Skip to content

Commit

Permalink
feat: metadata upstream passing
Browse files Browse the repository at this point in the history
  • Loading branch information
Vilsol committed Dec 9, 2023
1 parent 1336ae0 commit b68bc87
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 1 deletion.
3 changes: 2 additions & 1 deletion src/microservice/transport/provider/grpc/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { Logger } from 'winston';
import type { Server as GRPCServer, ServiceImplementation } from 'nice-grpc';
import type { CompatServiceDefinition } from 'nice-grpc/lib/service-definitions';
import { createServer } from 'nice-grpc';
import { loggingMiddleware, tracingMiddleware, WithRequestID } from './middlewares';
import { loggingMiddleware, metaMiddleware, tracingMiddleware, WithRequestID } from './middlewares';

/**
* Name of the transport
Expand Down Expand Up @@ -50,6 +50,7 @@ export class Server {

this.server = createServer()
.use(tracingMiddleware)
.use(metaMiddleware)
.use(loggingMiddleware(this.logger));

this.name = NAME;
Expand Down
36 changes: 36 additions & 0 deletions src/microservice/transport/provider/grpc/middlewares.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import { CallContext, ServerError, ServerMiddlewareCall } from 'nice-grpc';
import { isAbortError } from 'abort-controller-x';
import { Logger } from 'winston';
import { v1 as uuidv1 } from 'uuid';
import { metadataPassThrough } from '@restorecommerce/grpc-client/dist/middleware';
import { AsyncLocalStorage } from 'async_hooks';

const tracingHeader = 'x-request-id';

Expand Down Expand Up @@ -61,3 +63,37 @@ export const loggingMiddleware = (logger: Logger) => {
}
};
};


function bindAsyncGenerator<T = any, TReturn = any, TNext = any>(
store: AsyncLocalStorage<any>,
generator: AsyncGenerator<any, any, any>,
): AsyncGenerator<T, TReturn, TNext> {
const ctx = store.getStore();
return {
next: () => store.run(ctx, generator.next.bind(generator)),
return: (args) => store.run(ctx, generator.return.bind(generator), args),
throw: (args) => store.run(ctx, generator.throw.bind(generator), args),

[Symbol.asyncIterator]() {
return this;
},
};
}

export async function* metaMiddleware<Request, Response>(
call: ServerMiddlewareCall<Request, Response>,
context: CallContext,
) {
const mapped = {};
for (const [a, b] of context.metadata) {
mapped[a] = b;
}

const val = JSON.stringify(mapped);
metadataPassThrough.enterWith(val);

return yield* bindAsyncGenerator(metadataPassThrough, call.next(call.request, {
...context,
}));
}

0 comments on commit b68bc87

Please sign in to comment.