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

INN-2882 Add selective header forwarding when sending events #520

Merged
merged 14 commits into from
Apr 23, 2024
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
16 changes: 15 additions & 1 deletion packages/inngest/src/components/Inngest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -350,6 +350,20 @@ export class Inngest<TClientOpts extends ClientOptions = ClientOptions> {
public async send<Payload extends SendEventPayload<GetEvents<this>>>(
payload: Payload
): Promise<SendEventOutput<TClientOpts>> {
return this._send({ payload });
}

/**
* Internal method for sending an event, used to allow Inngest internals to
* further customize the request sent to an Inngest Server.
*/
private async _send<Payload extends SendEventPayload<GetEvents<this>>>({
payload,
headers,
}: {
payload: Payload;
headers?: Record<string, string>;
}): Promise<SendEventOutput<TClientOpts>> {
const hooks = await getHookStack(
this.middleware,
"onSendEvent",
Expand Down Expand Up @@ -462,7 +476,7 @@ export class Inngest<TClientOpts extends ClientOptions = ClientOptions> {
const response = await this.fetch(url, {
method: "POST",
body: stringify(payloads),
headers: { ...this.headers },
headers: { ...this.headers, ...headers },
});

let body: SendEventResponse | undefined;
Expand Down
27 changes: 27 additions & 0 deletions packages/inngest/src/components/InngestCommHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -722,12 +722,35 @@ export class InngestCommHandler<
(await getQuerystring("processing run request", queryKeys.StepId)) ||
null;

const headersToForward = [
headerKeys.TraceParent,
headerKeys.TraceState,
];

const headers = await headersToForward.reduce<
Promise<Record<string, string>>
>(async (acc, header) => {
const value = await actions.headers(
`fetching ${header} for forwarding`,
header
);
if (value) {
return {
...(await acc),
[header]: value,
};
}

return acc;
}, Promise.resolve({}));
jpwilliams marked this conversation as resolved.
Show resolved Hide resolved

const { version, result } = this.runStep({
functionId: fnId,
data: body,
stepId,
timer,
reqArgs,
headers,
});
const stepOutput = await result;

Expand Down Expand Up @@ -901,12 +924,14 @@ export class InngestCommHandler<
data,
timer,
reqArgs,
headers,
}: {
functionId: string;
stepId: string | null;
data: unknown;
timer: ServerTiming;
reqArgs: unknown[];
headers: Record<string, string>;
}): { version: ExecutionVersion; result: Promise<ExecutionResult> } {
const fn = this.fns[functionId];
if (!fn) {
Expand Down Expand Up @@ -972,6 +997,7 @@ export class InngestCommHandler<
isFailureHandler: fn.onFailure,
stepCompletionOrder: ctx?.stack?.stack ?? [],
reqArgs,
headers,
},
};
},
Expand Down Expand Up @@ -1007,6 +1033,7 @@ export class InngestCommHandler<
disableImmediateExecution: ctx?.disable_immediate_execution,
stepCompletionOrder: ctx?.stack?.stack ?? [],
reqArgs,
headers,
},
};
},
Expand Down
2 changes: 2 additions & 0 deletions packages/inngest/src/components/InngestFunction.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,7 @@ describe("runFn", () => {
stepState: {},
stepCompletionOrder: [],
reqArgs: [],
headers: {},
},
});

Expand Down Expand Up @@ -200,6 +201,7 @@ describe("runFn", () => {
runId: "run",
stepCompletionOrder: [],
reqArgs: [],
headers: {},
},
});

Expand Down
7 changes: 6 additions & 1 deletion packages/inngest/src/components/InngestStepTools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import {
} from "./Inngest";
import { InngestFunction } from "./InngestFunction";
import { InngestFunctionReference } from "./InngestFunctionReference";
import { type InngestExecution } from "./execution/InngestExecution";

export interface FoundStep extends HashedOp {
hashedId: string;
Expand Down Expand Up @@ -123,6 +124,7 @@ export const createStepTools = <
TTriggers extends TriggersFromClient<TClient> = TriggersFromClient<TClient>,
>(
client: TClient,
execution: InngestExecution,
stepHandler: StepHandler
) => {
/**
Expand Down Expand Up @@ -201,7 +203,10 @@ export const createStepTools = <
{
nonStepExecuteInline: true,
fn: (idOrOptions, payload) => {
return client.send(payload);
return client["_send"]({
payload,
headers: execution["options"]["headers"],
});
},
}
),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,11 @@ export interface InngestExecutionOptions {
data: Omit<Context.Any, "step">;
stepState: Record<string, MemoizedOp>;
stepCompletionOrder: string[];

/**
* Headers to be sent with any request to Inngest during this execution.
*/
headers: Record<string, string>;
requestedRunStep?: string;
timer?: ServerTiming;
isFailureHandler?: boolean;
Expand All @@ -68,7 +73,6 @@ export class InngestExecution {
protected debug: Debugger;

constructor(protected options: InngestExecutionOptions) {
this.options = options;
this.debug = Debug(debugPrefix).extend(this.options.runId);
}
}
Expand Down
2 changes: 1 addition & 1 deletion packages/inngest/src/components/execution/v0.ts
Original file line number Diff line number Diff line change
Expand Up @@ -417,7 +417,7 @@ export class V0InngestExecution
});
};

const step = createStepTools(this.options.client, stepHandler);
const step = createStepTools(this.options.client, this, stepHandler);

let fnArg = {
...(this.options.data as { event: EventPayload }),
Expand Down
2 changes: 1 addition & 1 deletion packages/inngest/src/components/execution/v1.ts
Original file line number Diff line number Diff line change
Expand Up @@ -859,7 +859,7 @@ class V1InngestExecution extends InngestExecution implements IInngestExecution {
return promise;
};

return createStepTools(this.options.client, stepHandler);
return createStepTools(this.options.client, this, stepHandler);
}

private getUserFnToRun(): Handler.Any {
Expand Down
2 changes: 2 additions & 0 deletions packages/inngest/src/helpers/consts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,8 @@ export enum headerKeys {
RetryAfter = "retry-after",
InngestServerKind = "x-inngest-server-kind",
InngestExpectedServerKind = "x-inngest-expected-server-kind",
TraceParent = "traceparent",
TraceState = "tracestate",
}

export const defaultInngestApiBaseUrl = "https://api.inngest.com/";
Expand Down
29 changes: 27 additions & 2 deletions packages/inngest/src/test/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ import {
} from "@local/components/InngestStepTools";
import {
ExecutionVersion,
IInngestExecution,
InngestExecution,
InngestExecutionOptions,
PREFERRED_EXECUTION_VERSION,
} from "@local/components/execution/InngestExecution";
Expand Down Expand Up @@ -64,9 +66,31 @@ export const createClient = <T extends ConstructorParameters<typeof Inngest>>(
export const testClientId = "__test_client__";

export const getStepTools = (
client: Inngest.Any = createClient({ id: testClientId })
client: Inngest.Any = createClient({ id: testClientId }),
executionOptions: Partial<InngestExecutionOptions> = {}
) => {
const step = createStepTools(client, ({ args, matchOp }) => {
const execution = client
.createFunction({ id: "test" }, { event: "test" }, () => undefined)
["createExecution"]({
version: PREFERRED_EXECUTION_VERSION,
partialOptions: {
data: fromPartial({
event: { name: "foo", data: {} },
}),
runId: "run",
stepState: {},
stepCompletionOrder: [],
isFailureHandler: false,
requestedRunStep: undefined,
timer: new ServerTiming(),
disableImmediateExecution: false,
reqArgs: [],
headers: {},
...executionOptions,
},
}) as IInngestExecution & InngestExecution;

const step = createStepTools(client, execution, ({ args, matchOp }) => {
const stepOptions = getStepOptions(args[0]);
return Promise.resolve(matchOp(stepOptions, ...args.slice(1)));
});
Expand Down Expand Up @@ -106,6 +130,7 @@ export const runFnWithStack = (
timer: new ServerTiming(),
disableImmediateExecution: opts?.disableImmediateExecution,
reqArgs: [],
headers: {},
},
});

Expand Down