-
Notifications
You must be signed in to change notification settings - Fork 34
/
Inngest.ts
442 lines (413 loc) · 12.5 KB
/
Inngest.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
import { z } from "zod";
import { envKeys } from "../helpers/consts";
import { devServerAvailable, devServerUrl } from "../helpers/devserver";
import {
devServerHost,
getFetch,
inngestHeaders,
isProd,
processEnv,
} from "../helpers/env";
import { fixEventKeyMissingSteps, prettyError } from "../helpers/errors";
import {
type PartialK,
type SendEventPayload,
type SingleOrArray,
type ValueOf,
} from "../helpers/types";
import {
type ClientOptions,
type EventNameFromTrigger,
type EventPayload,
type FailureEventArgs,
type FunctionOptions,
type Handler,
type ShimmedFns,
type TriggerOptions,
} from "../types";
import { InngestFunction } from "./InngestFunction";
/**
* Capturing the global type of fetch so that we can reliably access it below.
*/
type FetchT = typeof fetch;
/**
* A client used to interact with the Inngest API by sending or reacting to
* events.
*
* To provide event typing, make sure to pass in your generated event types as
* the first generic.
*
* ```ts
* const inngest = new Inngest<Events>({ name: "My App" });
*
* // or to provide custom events too
* const inngest = new Inngest<
* Events & {
* "app/user.created": {
* name: "app/user.created";
* data: {
* foo: boolean;
* };
* };
* }
* >({ name: "My App" });
* ```
*
* @public
*/
export class Inngest<
Events extends Record<string, EventPayload> = Record<string, EventPayload>
> {
/**
* The name of this instance, most commonly the name of the application it
* resides in.
*/
public readonly name: string;
/**
* Inngest event key, used to send events to Inngest Cloud.
*/
private eventKey = "";
/**
* Base URL for Inngest Cloud.
*/
public readonly inngestBaseUrl: URL;
/**
* The absolute URL of the Inngest Cloud API.
*/
private inngestApiUrl: URL = new URL(`e/${this.eventKey}`, "https://inn.gs/");
private readonly headers: Record<string, string>;
private readonly fetch: FetchT;
/**
* A client used to interact with the Inngest API by sending or reacting to
* events.
*
* To provide event typing, make sure to pass in your generated event types as
* the first generic.
*
* ```ts
* const inngest = new Inngest<Events>({ name: "My App" });
*
* // or to provide custom events too
* const inngest = new Inngest<
* Events & {
* "app/user.created": {
* name: "app/user.created";
* data: {
* foo: boolean;
* };
* };
* }
* >({ name: "My App" });
* ```
*/
constructor({
name,
eventKey,
inngestBaseUrl = "https://inn.gs/",
fetch,
env,
}: ClientOptions) {
if (!name) {
// TODO PrettyError
throw new Error("A name must be passed to create an Inngest instance.");
}
this.name = name;
this.inngestBaseUrl = new URL(inngestBaseUrl);
this.setEventKey(eventKey || processEnv(envKeys.EventKey) || "");
if (!this.eventKey) {
console.warn(
prettyError({
type: "warn",
whatHappened: "Could not find event key",
consequences:
"Sending events will throw in production unless an event key is added.",
toFixNow: fixEventKeyMissingSteps,
why: "We couldn't find an event key to use to send events to Inngest.",
otherwise:
"Create a new production event key at https://app.inngest.com/env/production/manage/keys.",
})
);
}
this.headers = inngestHeaders({
inngestEnv: env,
});
this.fetch = getFetch(fetch);
}
/**
* Given a response from Inngest, relay the error to the caller.
*/
#getResponseError(response: globalThis.Response, rawBody: unknown): Error {
let errorMessage = "Unknown error";
switch (response.status) {
case 401:
errorMessage = "Event key Not Found";
break;
case 400:
errorMessage = "Cannot process event payload";
break;
case 403:
errorMessage = "Forbidden";
break;
case 404:
errorMessage = "Event key not found";
break;
case 406:
errorMessage = `${JSON.stringify(rawBody)}`;
break;
case 409:
case 412:
errorMessage = "Event transformation failed";
break;
case 413:
errorMessage = "Event payload too large";
break;
case 500:
errorMessage = "Internal server error";
break;
}
return new Error(`Inngest API Error: ${response.status} ${errorMessage}`);
}
/**
* Set the event key for this instance of Inngest. This is useful if for some
* reason the key is not available at time of instantiation or present in the
* `INNGEST_EVENT_KEY` environment variable.
*/
public setEventKey(
/**
* Inngest event key, used to send events to Inngest Cloud. Use this is your
* key is for some reason not available at time of instantiation or present
* in the `INNGEST_EVENT_KEY` environment variable.
*/
eventKey: string
): void {
this.eventKey = eventKey;
this.inngestApiUrl = new URL(`e/${this.eventKey}`, this.inngestBaseUrl);
}
/**
* Send one or many events to Inngest. Takes a known event from this Inngest
* instance based on the given `name`.
*
* ```ts
* await inngest.send("app/user.created", { data: { id: 123 } });
* ```
*
* Returns a promise that will resolve if the event(s) were sent successfully,
* else throws with an error explaining what went wrong.
*
* If you wish to send an event with custom types (i.e. one that hasn't been
* generated), make sure to add it when creating your Inngest instance, like
* so:
*
* ```ts
* const inngest = new Inngest<Events & {
* "my/event": {
* name: "my/event";
* data: { bar: string; };
* }
* }>("My App", "API_KEY");
* ```
*/
public async send<Event extends keyof Events>(
name: Event,
payload: SingleOrArray<PartialK<Omit<Events[Event], "name" | "v">, "ts">>
): Promise<string[]>;
/**
* Send one or many events to Inngest. Takes an entire payload (including
* name) as each input.
*
* ```ts
* await inngest.send({ name: "app/user.created", data: { id: 123 } });
* ```
*
* Returns a promise that will resolve if the event(s) were sent successfully,
* else throws with an error explaining what went wrong.
*
* If you wish to send an event with custom types (i.e. one that hasn't been
* generated), make sure to add it when creating your Inngest instance, like
* so:
*
* ```ts
* const inngest = new Inngest<Events & {
* "my/event": {
* name: "my/event";
* data: { bar: string; };
* }
* }>("My App", "API_KEY");
* ```
*/
public async send<Payload extends SendEventPayload<Events>>(
payload: Payload
): Promise<string[]>;
public async send<Event extends keyof Events>(
nameOrPayload:
| Event
| SingleOrArray<
ValueOf<{
[K in keyof Events]: PartialK<Omit<Events[K], "v">, "ts">;
}>
>,
maybePayload?: SingleOrArray<
PartialK<Omit<Events[Event], "name" | "v">, "ts">
>
): Promise<string[]> {
if (!this.eventKey) {
throw new Error(
prettyError({
whatHappened: "Failed to send event",
consequences: "Your event or events were not sent to Inngest.",
why: "We couldn't find an event key to use to send events to Inngest.",
toFixNow: fixEventKeyMissingSteps,
})
);
}
let payloads: ValueOf<Events>[];
if (typeof nameOrPayload === "string") {
/**
* Add our payloads and ensure they all have a name.
*/
payloads = (Array.isArray(maybePayload)
? maybePayload
: maybePayload
? [maybePayload]
: []
).map((payload) => ({
...payload,
name: nameOrPayload,
})) as unknown as typeof payloads;
} else {
/**
* Grab our payloads straight from the args.
*/
payloads = (Array.isArray(nameOrPayload)
? nameOrPayload
: nameOrPayload
? [nameOrPayload]
: []) as unknown as typeof payloads;
}
/**
* It can be valid for a user to send an empty list of events; if this
* happens, show a warning that this may not be intended, but don't throw.
*/
if (!payloads.length) {
console.warn(
prettyError({
type: "warn",
whatHappened: "`inngest.send()` called with no events",
reassurance:
"This is not an error, but you may not have intended to do this.",
consequences:
"The returned promise will resolve, but no events have been sent to Inngest.",
stack: true,
})
);
return [];
}
// When sending events, check if the dev server is available. If so, use the
// dev server.
let url = this.inngestApiUrl.href;
if (!isProd()) {
const host = devServerHost();
// If the dev server host env var has been set we always want to use
// the dev server - even if it's down. Otherwise, optimistically use
// it for non-prod services.
if (host !== undefined || (await devServerAvailable(host, this.fetch))) {
url = devServerUrl(host, `e/${this.eventKey}`).href;
}
}
const response = await this.fetch(url, {
method: "POST",
body: JSON.stringify(payloads),
headers: { ...this.headers },
});
let rawBody: unknown;
try {
rawBody = await response.json();
const body = await z
.object({
ids: z.array(z.string()),
status: z.number().min(200).max(299),
})
.parseAsync(rawBody);
return body.ids;
} catch (err) {
throw this.#getResponseError(response, rawBody);
}
}
public createFunction<
TFns extends Record<string, unknown>,
TTrigger extends TriggerOptions<keyof Events & string>,
TShimmedFns extends Record<
string,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(...args: any[]) => any
> = ShimmedFns<TFns>,
TTriggerName extends keyof Events & string = EventNameFromTrigger<
Events,
TTrigger
>
>(
nameOrOpts:
| string
| (Omit<FunctionOptions<Events, TTriggerName>, "fns" | "onFailure"> & {
/**
* Pass in an object of functions that will be wrapped in Inngest
* tooling and passes to your handler. This wrapping ensures that each
* function is automatically separated and retried.
*
* @example
*
* Both examples behave the same; it's preference as to which you
* prefer.
*
* ```ts
* import { userDb } from "./db";
*
* // Specify `fns` and be able to use them in your Inngest function
* inngest.createFunction(
* { name: "Create user from PR", fns: { ...userDb } },
* { event: "github/pull_request" },
* async ({ fns: { createUser } }) => {
* await createUser("Alice");
* }
* );
*
* // Or always use `run()` to run inline steps and use them directly
* inngest.createFunction(
* { name: "Create user from PR" },
* { event: "github/pull_request" },
* async ({ step: { run } }) => {
* await run("createUser", () => userDb.createUser("Alice"));
* }
* );
* ```
*/
fns?: TFns;
/**
* Provide a function to be called if your function fails, meaning
* that it ran out of retries and was unable to complete successfully.
*
* This is useful for sending warning notifications or cleaning up
* after a failure and supports all the same functionality as a
* regular handler.
*/
onFailure?: Handler<
Events,
TTriggerName,
TShimmedFns,
FailureEventArgs<Events[TTriggerName]>
>;
}),
trigger: TTrigger,
handler: Handler<Events, TTriggerName, TShimmedFns>
): InngestFunction {
const opts = (
typeof nameOrOpts === "string" ? { name: nameOrOpts } : nameOrOpts
) as FunctionOptions<Events, keyof Events & string>;
return new InngestFunction(
this,
opts,
typeof trigger === "string" ? { event: trigger } : trigger,
handler as Handler<Events, keyof Events & string>
) as unknown as InngestFunction;
}
}