Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Always include builtInMiddleware in custom middleware types #332

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
90 changes: 5 additions & 85 deletions packages/inngest/src/components/Inngest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import {
import { fixEventKeyMissingSteps, prettyError } from "../helpers/errors";
import { stringify } from "../helpers/strings";
import { type ExclusiveKeys, type SendEventPayload } from "../helpers/types";
import { DefaultLogger, ProxyLogger, type Logger } from "../middleware/logger";
import { DefaultLogger, type Logger } from "../middleware/logger";
import {
sendEventResponseSchema,
type ClientOptions,
Expand All @@ -29,9 +29,10 @@ import {
import { type EventSchemas } from "./EventSchemas";
import { InngestFunction } from "./InngestFunction";
import {
InngestMiddleware,
builtInMiddleware,
getHookStack,
type ExtendWithMiddleware,
type InngestMiddleware,
type MiddlewareOptions,
type MiddlewareRegisterFn,
type MiddlewareRegisterReturn,
Expand Down Expand Up @@ -479,11 +480,7 @@ export class Inngest<TOpts extends ClientOptions = ClientOptions> {
TTriggerName,
TShimmedFns,
ExtendWithMiddleware<
[
typeof builtInMiddleware,
NonNullable<TOpts["middleware"]>,
TMiddleware
],
[NonNullable<TOpts["middleware"]>, TMiddleware],
FailureEventArgs<EventsFromOpts<TOpts>[TTriggerName]>
>
>;
Expand All @@ -502,13 +499,7 @@ export class Inngest<TOpts extends ClientOptions = ClientOptions> {
EventsFromOpts<TOpts>,
TTriggerName,
TShimmedFns,
ExtendWithMiddleware<
[
typeof builtInMiddleware,
NonNullable<TOpts["middleware"]>,
TMiddleware
]
>
ExtendWithMiddleware<[NonNullable<TOpts["middleware"]>, TMiddleware]>
>
): InngestFunction<
TOpts,
Expand Down Expand Up @@ -545,74 +536,3 @@ export class Inngest<TOpts extends ClientOptions = ClientOptions> {
);
}
}

/**
* Default middleware that is included in every client, placed after the user's
* middleware on the client but before function-level middleware.
*
* It is defined here to ensure that comments are included in the generated TS
* definitions. Without this, we infer the stack of built-in middleware without
* comments, losing a lot of value.
*
* If this is moved, please ensure that using this package in another project
* can correctly access comments on mutated input and output.
*/
const builtInMiddleware = (<T extends MiddlewareStack>(m: T): T => m)([
new InngestMiddleware({
name: "Inngest: Logger",
init({ client }) {
return {
onFunctionRun(arg) {
const { ctx } = arg;
const metadata = {
runID: ctx.runId,
eventName: ctx.event.name,
functionName: arg.fn.name,
};

let providedLogger: Logger = client["logger"];
// create a child logger if the provided logger has child logger implementation
try {
if ("child" in providedLogger) {
type ChildLoggerFn = (
metadata: Record<string, unknown>
) => Logger;
providedLogger = (providedLogger.child as ChildLoggerFn)(
metadata
);
}
} catch (err) {
console.error('failed to create "childLogger" with error: ', err);
// no-op
}
const logger = new ProxyLogger(providedLogger);

return {
transformInput() {
return {
ctx: {
/**
* The passed in logger from the user.
* Defaults to a console logger if not provided.
*/
logger: logger as Logger,
},
};
},
beforeExecution() {
logger.enable();
},
transformOutput({ result: { error } }) {
if (error) {
logger.error(error);
}
},
async beforeResponse() {
await logger.flush();
},
};
},
};
},
}),
]);
93 changes: 86 additions & 7 deletions packages/inngest/src/components/InngestMiddleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
type ObjectAssign,
type PartialK,
} from "../helpers/types";
import { ProxyLogger, type Logger } from "../middleware/logger";
import {
type BaseContext,
type ClientOptions,
Expand Down Expand Up @@ -384,10 +385,13 @@ type MiddlewareRunArgs = Readonly<{
*/
ctx: Record<string, unknown> &
Readonly<
BaseContext<
ClientOptions,
string,
Record<string, (...args: unknown[]) => unknown>
ExtendWithMiddleware<
[],
BaseContext<
ClientOptions,
string,
Record<string, (...args: unknown[]) => unknown>
>
>
>;

Expand Down Expand Up @@ -504,13 +508,17 @@ type GetMiddlewareRunInputMutation<
export type ExtendWithMiddleware<
TMiddlewareStacks extends MiddlewareStack[],
// eslint-disable-next-line @typescript-eslint/ban-types
TContext = {}
TContext = {},
TAllMiddlewareStacks extends MiddlewareStack[] = [
typeof builtInMiddleware,
...TMiddlewareStacks
]
> = ObjectAssign<
{
[K in keyof TMiddlewareStacks]: MiddlewareStackRunInputMutation<
[K in keyof TAllMiddlewareStacks]: MiddlewareStackRunInputMutation<
// eslint-disable-next-line @typescript-eslint/ban-types
{},
TMiddlewareStacks[K]
TAllMiddlewareStacks[K]
>;
},
TContext
Expand All @@ -528,3 +536,74 @@ export type MiddlewareStackRunInputMutation<
},
TContext
>;

/**
* Default middleware that is included in every client, placed after the user's
* middleware on the client but before function-level middleware.
*
* It is defined here to ensure that comments are included in the generated TS
* definitions. Without this, we infer the stack of built-in middleware without
* comments, losing a lot of value.
*
* If this is moved, please ensure that using this package in another project
* can correctly access comments on mutated input and output.
*/
export const builtInMiddleware = (<T extends MiddlewareStack>(m: T): T => m)([
new InngestMiddleware({
name: "Inngest: Logger",
init({ client }) {
return {
onFunctionRun(arg) {
const { ctx } = arg;
const metadata = {
runID: ctx.runId,
eventName: ctx.event.name,
functionName: arg.fn.name,
};

let providedLogger: Logger = client["logger"];
// create a child logger if the provided logger has child logger implementation
try {
if ("child" in providedLogger) {
type ChildLoggerFn = (
metadata: Record<string, unknown>
) => Logger;
providedLogger = (providedLogger.child as ChildLoggerFn)(
metadata
);
}
} catch (err) {
console.error('failed to create "childLogger" with error: ', err);
// no-op
}
const logger = new ProxyLogger(providedLogger);

return {
transformInput() {
return {
ctx: {
/**
* The passed in logger from the user.
* Defaults to a console logger if not provided.
*/
logger: logger as Logger,
},
};
},
beforeExecution() {
logger.enable();
},
transformOutput({ result: { error } }) {
if (error) {
logger.error(error);
}
},
async beforeResponse() {
await logger.flush();
},
};
},
};
},
}),
]);
Loading