-
Notifications
You must be signed in to change notification settings - Fork 97
Expand file tree
/
Copy pathregistration_impl.ts
More file actions
760 lines (733 loc) · 25.7 KB
/
registration_impl.ts
File metadata and controls
760 lines (733 loc) · 25.7 KB
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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
import {
ConvexError,
convexToJson,
GenericValidator,
jsonToConvex,
v,
Validator,
Value,
} from "../../values/index.js";
import { GenericDataModel } from "../data_model.js";
import {
ActionBuilder,
DefaultFunctionArgs,
FunctionVisibility,
GenericActionCtx,
GenericMutationCtx,
GenericQueryCtx,
MutationBuilder,
PublicHttpAction,
QueryBuilder,
RegisteredAction,
RegisteredMutation,
RegisteredQuery,
} from "../registration.js";
import { setupActionCalls } from "./actions_impl.js";
import { setupActionVectorSearch } from "./vector_search_impl.js";
import { setupAuth } from "./authentication_impl.js";
import { setupReader, setupWriter } from "./database_impl.js";
import { QueryImpl, QueryInitializerImpl } from "./query_impl.js";
import {
setupActionScheduler,
setupMutationScheduler,
} from "./scheduler_impl.js";
import {
setupStorageActionWriter,
setupStorageReader,
setupStorageWriter,
} from "./storage_impl.js";
import { parseArgs } from "../../common/index.js";
import { performAsyncSyscall } from "./syscall.js";
import { asObjectValidator } from "../../values/validator.js";
import { getFunctionAddress } from "../components/paths.js";
import {
setupQueryMeta,
setupMutationMeta,
setupActionMeta,
} from "./meta_impl.js";
async function invokeMutation<
F extends (ctx: GenericMutationCtx<GenericDataModel>, ...args: any) => any,
>(func: F, argsStr: string, visibility: FunctionVisibility) {
// TODO(presley): Change the function signature and propagate the requestId from Rust.
// Ok, to mock it out for now, since queries are only running in V8.
const requestId = "";
const args = jsonToConvex(JSON.parse(argsStr));
const mutationCtx = {
db: setupWriter(),
auth: setupAuth(requestId),
storage: setupStorageWriter(requestId),
scheduler: setupMutationScheduler(),
meta: setupMutationMeta(visibility),
runQuery: (reference: any, args?: any) => runUdf("query", reference, args),
runSnapshotQuery: (reference: any, args?: any) =>
runUdf("snapshotQuery", reference, args),
runMutation: (reference: any, args?: any) =>
runUdf("mutation", reference, args),
};
const result = await invokeFunction(func, mutationCtx, args as any);
validateReturnValue(result);
return JSON.stringify(convexToJson(result === undefined ? null : result));
}
export function validateReturnValue(v: any) {
if (v instanceof QueryInitializerImpl || v instanceof QueryImpl) {
throw new Error(
"Return value is a Query. Results must be retrieved with `.collect()`, `.take(n), `.unique()`, or `.first()`.",
);
}
}
export async function invokeFunction<
Ctx,
Args extends any[],
F extends (ctx: Ctx, ...args: Args) => any,
>(func: F, ctx: Ctx, args: Args) {
let result;
try {
result = await Promise.resolve(func(ctx, ...args));
} catch (thrown: unknown) {
throw serializeConvexErrorData(thrown);
}
return result;
}
function dontCallDirectly(
funcType: string,
handler: (ctx: any, args: any) => any,
): unknown {
return (ctx: any, args: any) => {
globalThis.console.warn(
"Convex functions should not directly call other Convex functions. Consider calling a helper function instead. " +
`e.g. \`export const foo = ${funcType}(...); await foo(ctx);\` is not supported. ` +
"See https://docs.convex.dev/production/best-practices/#use-helper-functions-to-write-shared-code",
);
return handler(ctx, args);
};
}
// Keep in sync with node executor
function serializeConvexErrorData(thrown: unknown) {
if (
typeof thrown === "object" &&
thrown !== null &&
Symbol.for("ConvexError") in thrown
) {
const error = thrown as ConvexError<any>;
error.data = JSON.stringify(
convexToJson(error.data === undefined ? null : error.data),
);
(error as any).ConvexErrorSymbol = Symbol.for("ConvexError");
return error;
} else {
return thrown;
}
}
/**
* Guard against Convex functions accidentally getting included in a browser bundle.
* Convex functions may include secret logic or credentials that should not be
* send to untrusted clients (browsers).
*/
function assertNotBrowser() {
if (
typeof window === "undefined" ||
(window as any).__convexAllowFunctionsInBrowser
) {
return;
}
// JSDom doesn't count, developers are allowed to use JSDom in Convex functions.
const isRealBrowser =
Object.getOwnPropertyDescriptor(globalThis, "window")
?.get?.toString()
.includes("[native code]") ?? false;
if (isRealBrowser) {
// eslint-disable-next-line no-console
console.error(
"Convex functions should not be imported in the browser. This will throw an error in future versions of `convex`. If this is a false negative, please report it to Convex support.",
);
}
}
type FunctionDefinition =
| ((ctx: any, args: DefaultFunctionArgs) => any)
| {
args?: GenericValidator | Record<string, GenericValidator>;
returns?: GenericValidator | Record<string, GenericValidator>;
handler: (ctx: any, args: DefaultFunctionArgs) => any;
};
function strictReplacer(key: string, value: any) {
if (value === undefined) {
throw new Error(
`A validator is undefined for field "${key}". ` +
`This is often caused by circular imports. ` +
`See https://docs.convex.dev/error#undefined-validator for details.`,
);
}
return value;
}
function exportArgs(functionDefinition: FunctionDefinition) {
return () => {
let args: GenericValidator = v.any();
if (
typeof functionDefinition === "object" &&
functionDefinition.args !== undefined
) {
args = asObjectValidator(functionDefinition.args);
}
return JSON.stringify(args.json, strictReplacer);
};
}
function exportReturns(functionDefinition: FunctionDefinition) {
return () => {
let returns: Validator<any, any, any> | undefined;
if (
typeof functionDefinition === "object" &&
functionDefinition.returns !== undefined
) {
returns = asObjectValidator(functionDefinition.returns);
}
return JSON.stringify(returns ? returns.json : null, strictReplacer);
};
}
/**
* Define a mutation in this Convex app's public API.
*
* You should generally use the `mutation` function from
* `"./_generated/server"`.
*
* Mutations can read from and write to the database, and are accessible from
* the client. They run **transactionally**, all database reads and writes
* within a single mutation are atomic and isolated from other mutations.
*
* @example
* ```typescript
* import { mutation } from "./_generated/server";
* import { v } from "convex/values";
*
* export const createTask = mutation({
* args: { text: v.string() },
* returns: v.id("tasks"),
* handler: async (ctx, args) => {
* const taskId = await ctx.db.insert("tasks", {
* text: args.text,
* completed: false,
* });
* return taskId;
* },
* });
* ```
*
* **Best practice:** Always include `args` and `returns` validators on all
* mutations. If the function doesn't return a value, use `returns: v.null()`.
* Argument validation is critical for security since public mutations are
* exposed to the internet.
*
* **Common mistake:** Mutations cannot call third-party APIs or use `fetch`.
* They must be deterministic. Use actions for external API calls.
*
* **Common mistake:** Do not use `mutation` for sensitive internal functions
* that should not be called by clients. Use `internalMutation` instead.
*
* @param func - The mutation function. It receives a {@link GenericMutationCtx} as its first argument.
* @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.
*
* @see https://docs.convex.dev/functions/mutation-functions
* @public
*/
export const mutationGeneric: MutationBuilder<any, "public"> = ((
functionDefinition: FunctionDefinition,
) => {
const handler = (
typeof functionDefinition === "function"
? functionDefinition
: functionDefinition.handler
) as (ctx: GenericMutationCtx<any>, args: any) => any;
const func = dontCallDirectly("mutation", handler) as RegisteredMutation<
"public",
any,
any
>;
assertNotBrowser();
func.isMutation = true;
func.isPublic = true;
func.invokeMutation = (argsStr) => invokeMutation(handler, argsStr, "public");
func.exportArgs = exportArgs(functionDefinition);
func.exportReturns = exportReturns(functionDefinition);
func._handler = handler;
return func;
}) as MutationBuilder<any, "public">;
/**
* Define a mutation that is only accessible from other Convex functions (but not from the client).
*
* You should generally use the `internalMutation` function from
* `"./_generated/server"`.
*
* Internal mutations can read from and write to the database but are **not**
* exposed as part of your app's public API. They can only be called by other
* Convex functions using `ctx.runMutation` or by the scheduler. Like public
* mutations, they run transactionally.
*
* @example
* ```typescript
* import { internalMutation } from "./_generated/server";
* import { v } from "convex/values";
*
* // This mutation can only be called from other Convex functions:
* export const markTaskCompleted = internalMutation({
* args: { taskId: v.id("tasks") },
* returns: v.null(),
* handler: async (ctx, args) => {
* await ctx.db.patch("tasks", args.taskId, { completed: true });
* return null;
* },
* });
* ```
*
* **Best practice:** Use `internalMutation` for any mutation that should not
* be directly callable by clients, such as write-back functions from actions
* or scheduled background work. Reference it via the `internal` object:
* `await ctx.runMutation(internal.myModule.markTaskCompleted, { taskId })`.
*
* @param func - The mutation function. It receives a {@link GenericMutationCtx} as its first argument.
* @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.
*
* @see https://docs.convex.dev/functions/internal-functions
* @public
*/
export const internalMutationGeneric: MutationBuilder<any, "internal"> = ((
functionDefinition: FunctionDefinition,
) => {
const handler = (
typeof functionDefinition === "function"
? functionDefinition
: functionDefinition.handler
) as (ctx: GenericMutationCtx<any>, args: any) => any;
const func = dontCallDirectly(
"internalMutation",
handler,
) as RegisteredMutation<"internal", any, any>;
assertNotBrowser();
func.isMutation = true;
func.isInternal = true;
func.invokeMutation = (argsStr) =>
invokeMutation(handler, argsStr, "internal");
func.exportArgs = exportArgs(functionDefinition);
func.exportReturns = exportReturns(functionDefinition);
func._handler = handler;
return func;
}) as MutationBuilder<any, "internal">;
async function invokeQuery<
F extends (ctx: GenericQueryCtx<GenericDataModel>, ...args: any) => any,
>(func: F, argsStr: string, visibility: FunctionVisibility) {
// TODO(presley): Change the function signature and propagate the requestId from Rust.
// Ok, to mock it out for now, since queries are only running in V8.
const requestId = "";
const args = jsonToConvex(JSON.parse(argsStr));
const queryCtx = {
db: setupReader(),
auth: setupAuth(requestId),
storage: setupStorageReader(requestId),
meta: setupQueryMeta(visibility),
runQuery: (reference: any, args?: any) => runUdf("query", reference, args),
};
const result = await invokeFunction(func, queryCtx, args as any);
validateReturnValue(result);
return JSON.stringify(convexToJson(result === undefined ? null : result));
}
/**
* Define a query in this Convex app's public API.
*
* You should generally use the `query` function from
* `"./_generated/server"`.
*
* Queries can read from the database and are accessible from the client. They
* are **reactive**, when used with `useQuery` in React, the component
* automatically re-renders whenever the underlying data changes. Queries
* cannot modify the database.
* Query results are automatically cached by the Convex client and kept
* consistent via WebSocket subscriptions.
*
*
* @example
* ```typescript
* import { query } from "./_generated/server";
* import { v } from "convex/values";
*
* export const listTasks = query({
* args: { completed: v.optional(v.boolean()) },
* returns: v.array(v.object({
* _id: v.id("tasks"),
* _creationTime: v.number(),
* text: v.string(),
* completed: v.boolean(),
* })),
* handler: async (ctx, args) => {
* if (args.completed !== undefined) {
* return await ctx.db
* .query("tasks")
* .withIndex("by_completed", (q) => q.eq("completed", args.completed))
* .collect();
* }
* return await ctx.db.query("tasks").collect();
* },
* });
* ```
*
* **Best practice:** Always include `args` and `returns` validators. Use
* `.withIndex()` instead of `.filter()` for efficient database queries.
* Queries should be fast since they run on every relevant data change.
*
* **Common mistake:** Queries are pure reads, they cannot write to the
* database, call external APIs, or schedule functions. Use actions for HTTP
* calls and mutations for database writes and scheduling.
*
* @param func - The query function. It receives a {@link GenericQueryCtx} as its first argument.
* @returns The wrapped query. Include this as an `export` to name it and make it accessible.
*
* @see https://docs.convex.dev/functions/query-functions
* @public
*/
export const queryGeneric: QueryBuilder<any, "public"> = ((
functionDefinition: FunctionDefinition,
) => {
const handler = (
typeof functionDefinition === "function"
? functionDefinition
: functionDefinition.handler
) as (ctx: GenericQueryCtx<any>, args: any) => any;
const func = dontCallDirectly("query", handler) as RegisteredQuery<
"public",
any,
any
>;
assertNotBrowser();
func.isQuery = true;
func.isPublic = true;
func.invokeQuery = (argsStr) => invokeQuery(handler, argsStr, "public");
func.exportArgs = exportArgs(functionDefinition);
func.exportReturns = exportReturns(functionDefinition);
func._handler = handler;
return func;
}) as QueryBuilder<any, "public">;
/**
* Define a query that is only accessible from other Convex functions (but not from the client).
*
* You should generally use the `internalQuery` function from
* `"./_generated/server"`.
*
* Internal queries can read from the database but are **not** exposed as part
* of your app's public API. They can only be called by other Convex functions
* using `ctx.runQuery`. This is useful for loading data in actions or for
* helper queries that shouldn't be client-facing.
*
* @example
* ```typescript
* import { internalQuery } from "./_generated/server";
* import { v } from "convex/values";
*
* // Only callable from other Convex functions:
* export const getUser = internalQuery({
* args: { userId: v.id("users") },
* returns: v.union(
* v.object({
* _id: v.id("users"),
* _creationTime: v.number(),
* name: v.string(),
* email: v.string(),
* }),
* v.null(),
* ),
* handler: async (ctx, args) => {
* return await ctx.db.get("users", args.userId);
* },
* });
* ```
*
* **Best practice:** Use `internalQuery` for data-loading in actions via
* `ctx.runQuery(internal.myModule.getUser, { userId })`.
*
* @param func - The query function. It receives a {@link GenericQueryCtx} as its first argument.
* @returns The wrapped query. Include this as an `export` to name it and make it accessible.
*
* @see https://docs.convex.dev/functions/internal-functions
* @public
*/
export const internalQueryGeneric: QueryBuilder<any, "internal"> = ((
functionDefinition: FunctionDefinition,
) => {
const handler = (
typeof functionDefinition === "function"
? functionDefinition
: functionDefinition.handler
) as (ctx: GenericQueryCtx<any>, args: any) => any;
const func = dontCallDirectly("internalQuery", handler) as RegisteredQuery<
"internal",
any,
any
>;
assertNotBrowser();
func.isQuery = true;
func.isInternal = true;
func.invokeQuery = (argsStr) =>
invokeQuery(handler as any, argsStr, "internal");
func.exportArgs = exportArgs(functionDefinition);
func.exportReturns = exportReturns(functionDefinition);
func._handler = handler;
return func;
}) as QueryBuilder<any, "internal">;
async function invokeAction<
F extends (ctx: GenericActionCtx<GenericDataModel>, ...args: any) => any,
>(func: F, requestId: string, argsStr: string, visibility: FunctionVisibility) {
const args = jsonToConvex(JSON.parse(argsStr));
const calls = setupActionCalls(requestId);
const ctx = {
...calls,
auth: setupAuth(requestId),
scheduler: setupActionScheduler(requestId),
storage: setupStorageActionWriter(requestId),
vectorSearch: setupActionVectorSearch(requestId) as any,
meta: setupActionMeta(visibility),
};
const result = await invokeFunction(func, ctx, args as any);
return JSON.stringify(convexToJson(result === undefined ? null : result));
}
/**
* Define an action in this Convex app's public API.
*
* Actions can call third-party APIs, use Node.js libraries, and perform other
* side effects. Unlike queries and mutations, actions do **not** have direct
* database access (`ctx.db` is not available). Instead, use `ctx.runQuery`
* and `ctx.runMutation` to read and write data.
*
* You should generally use the `action` function from
* `"./_generated/server"`.
*
* Actions are accessible from the client and run outside of the database
* transaction, so they are not atomic. They are best for integrating with
* external services.
*
* @example
* ```typescript
* // Add "use node"; at the top of the file if using Node.js built-in modules.
* import { action } from "./_generated/server";
* import { v } from "convex/values";
* import { internal } from "./_generated/api";
*
* export const generateSummary = action({
* args: { text: v.string() },
* returns: v.string(),
* handler: async (ctx, args) => {
* // Call an external API:
* const response = await fetch("https://api.example.com/summarize", {
* method: "POST",
* body: JSON.stringify({ text: args.text }),
* });
* const { summary } = await response.json();
*
* // Write results back via a mutation:
* await ctx.runMutation(internal.myModule.saveSummary, {
* text: args.text,
* summary,
* });
*
* return summary;
* },
* });
* ```
*
* **Best practice:** Minimize the number of `ctx.runQuery` and
* `ctx.runMutation` calls from actions. Each call is a separate transaction,
* so splitting logic across multiple calls introduces the risk of race
* conditions. Try to batch reads/writes into single query/mutation calls.
*
* **`"use node"` runtime:** Actions run in Convex's default JavaScript
* runtime, which supports `fetch` and most NPM packages. Only add
* `"use node";` at the top of the file if a third-party library specifically
* requires Node.js built-in APIs, it is a last resort, not the default.
* Node.js actions have slower cold starts, and **only actions can be defined
* in `"use node"` files** (no queries or mutations), so prefer the default
* runtime whenever possible.
*
* **Common mistake:** Do not try to access `ctx.db` in an action, it is
* not available. Use `ctx.runQuery` and `ctx.runMutation` instead.
*
* @param func - The function. It receives a {@link GenericActionCtx} as its first argument.
* @returns The wrapped function. Include this as an `export` to name it and make it accessible.
*
* @see https://docs.convex.dev/functions/actions
* @public
*/
export const actionGeneric: ActionBuilder<any, "public"> = ((
functionDefinition: FunctionDefinition,
) => {
const handler = (
typeof functionDefinition === "function"
? functionDefinition
: functionDefinition.handler
) as (ctx: GenericActionCtx<any>, args: any) => any;
const func = dontCallDirectly("action", handler) as RegisteredAction<
"public",
any,
any
>;
assertNotBrowser();
func.isAction = true;
func.isPublic = true;
func.invokeAction = (requestId, argsStr) =>
invokeAction(handler, requestId, argsStr, "public");
func.exportArgs = exportArgs(functionDefinition);
func.exportReturns = exportReturns(functionDefinition);
func._handler = handler;
return func;
}) as ActionBuilder<any, "public">;
/**
* Define an action that is only accessible from other Convex functions (but not from the client).
*
* You should generally use the `internalAction` function from
* `"./_generated/server"`.
*
* Internal actions behave like public actions (they can call external APIs and
* use Node.js libraries) but are **not** exposed in your app's public API. They
* can only be called by other Convex functions using `ctx.runAction` or via the
* scheduler.
*
* @example
* ```typescript
* import { internalAction } from "./_generated/server";
* import { v } from "convex/values";
*
* export const sendEmail = internalAction({
* args: { to: v.string(), subject: v.string(), body: v.string() },
* returns: v.null(),
* handler: async (ctx, args) => {
* // Call an external email service (fetch works in the default runtime):
* await fetch("https://api.email-service.com/send", {
* method: "POST",
* headers: { "Content-Type": "application/json" },
* body: JSON.stringify(args),
* });
* return null;
* },
* });
* ```
*
* **Best practice:** Use `internalAction` for background work scheduled from
* mutations: `await ctx.scheduler.runAfter(0, internal.myModule.sendEmail, { ... })`.
* Only use `ctx.runAction` from another action if you need to cross runtimes
* (e.g., default Convex runtime to Node.js). Otherwise, extract shared code
* into a helper function.
*
* **`"use node"` runtime:** Only add `"use node";` at the top of the file
* as a last resort when a third-party library requires Node.js APIs. Node.js
* actions have slower cold starts, and **only actions can be defined in
* `"use node"` files** (no queries or mutations).
*
* @param func - The function. It receives a {@link GenericActionCtx} as its first argument.
* @returns The wrapped function. Include this as an `export` to name it and make it accessible.
*
* @see https://docs.convex.dev/functions/internal-functions
* @public
*/
export const internalActionGeneric: ActionBuilder<any, "internal"> = ((
functionDefinition: FunctionDefinition,
) => {
const handler = (
typeof functionDefinition === "function"
? functionDefinition
: functionDefinition.handler
) as (ctx: GenericActionCtx<any>, args: any) => any;
const func = dontCallDirectly("internalAction", handler) as RegisteredAction<
"internal",
any,
any
>;
assertNotBrowser();
func.isAction = true;
func.isInternal = true;
func.invokeAction = (requestId, argsStr) =>
invokeAction(handler, requestId, argsStr, "internal");
func.exportArgs = exportArgs(functionDefinition);
func.exportReturns = exportReturns(functionDefinition);
func._handler = handler;
return func;
}) as ActionBuilder<any, "internal">;
async function invokeHttpAction<
F extends (ctx: GenericActionCtx<GenericDataModel>, request: Request) => any,
>(func: F, request: Request) {
// TODO(presley): Change the function signature and propagate the requestId from Rust.
// Ok, to mock it out for now, since http endpoints are only running in V8.
const requestId = "";
const calls = setupActionCalls(requestId);
const ctx = {
...calls,
auth: setupAuth(requestId),
storage: setupStorageActionWriter(requestId),
scheduler: setupActionScheduler(requestId),
vectorSearch: setupActionVectorSearch(requestId) as any,
meta: setupActionMeta("public"),
};
return await invokeFunction(func, ctx, [request]);
}
/**
* Define a Convex HTTP action.
*
* HTTP actions handle raw HTTP requests and return HTTP responses. They are
* registered by routing URL paths to them in `convex/http.ts` using
* {@link HttpRouter}. Like regular actions, they can call external APIs and
* use `ctx.runQuery` / `ctx.runMutation` but do not have direct `ctx.db` access.
*
* @example
* ```typescript
* // convex/http.ts
* import { httpRouter } from "convex/server";
* import { httpAction } from "./_generated/server";
*
* const http = httpRouter();
*
* http.route({
* path: "/api/webhook",
* method: "POST",
* handler: httpAction(async (ctx, request) => {
* const body = await request.json();
* // Process the webhook payload...
* return new Response(JSON.stringify({ ok: true }), {
* status: 200,
* headers: { "Content-Type": "application/json" },
* });
* }),
* });
*
* export default http;
* ```
*
* **Best practice:** HTTP actions are registered at the exact path specified.
* For example, `path: "/api/webhook"` registers at `/api/webhook`.
*
* @param func - The function. It receives a {@link GenericActionCtx} as its first argument, and a `Request` object
* as its second.
* @returns The wrapped function. Route a URL path to this function in `convex/http.ts`.
*
* @see https://docs.convex.dev/functions/http-actions
* @public
*/
export const httpActionGeneric = (
func: (
ctx: GenericActionCtx<GenericDataModel>,
request: Request,
) => Promise<Response>,
): PublicHttpAction => {
const q = dontCallDirectly("httpAction", func) as PublicHttpAction;
assertNotBrowser();
q.isHttp = true;
q.invokeHttpAction = (request) => invokeHttpAction(func as any, request);
q._handler = func;
return q;
};
async function runUdf(
udfType: "query" | "mutation" | "snapshotQuery",
f: any,
args?: Record<string, Value>,
): Promise<any> {
const queryArgs = parseArgs(args);
const syscallArgs = {
udfType,
args: convexToJson(queryArgs),
...getFunctionAddress(f),
};
const result = await performAsyncSyscall("1.0/runUdf", syscallArgs);
return jsonToConvex(result);
}