@gaganref/confect-test 10.3.1-fork.87 → 10.3.1-fork.89

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/dist/internal/Attempt.d.ts +77 -0
  2. package/dist/internal/Attempt.d.ts.map +1 -0
  3. package/dist/internal/Attempt.js +154 -0
  4. package/dist/internal/Attempt.js.map +1 -0
  5. package/dist/internal/ConvexTest.d.ts +34 -0
  6. package/dist/internal/ConvexTest.d.ts.map +1 -0
  7. package/dist/internal/ConvexTest.js +59 -0
  8. package/dist/internal/ConvexTest.js.map +1 -0
  9. package/dist/internal/Execution.d.ts +167 -0
  10. package/dist/internal/Execution.d.ts.map +1 -0
  11. package/dist/internal/Execution.js +790 -0
  12. package/dist/internal/Execution.js.map +1 -0
  13. package/dist/internal/Globals.d.ts +11 -0
  14. package/dist/internal/Globals.d.ts.map +1 -0
  15. package/dist/internal/Globals.js +76 -0
  16. package/dist/internal/Globals.js.map +1 -0
  17. package/dist/internal/Invocation.d.ts +57 -0
  18. package/dist/internal/Invocation.d.ts.map +1 -0
  19. package/dist/internal/Invocation.js +145 -0
  20. package/dist/internal/Invocation.js.map +1 -0
  21. package/dist/internal/Kernel.d.ts +93 -0
  22. package/dist/internal/Kernel.d.ts.map +1 -0
  23. package/dist/internal/Kernel.js +91 -0
  24. package/dist/internal/Kernel.js.map +1 -0
  25. package/dist/internal/KernelQuery.d.ts +55 -0
  26. package/dist/internal/KernelQuery.d.ts.map +1 -0
  27. package/dist/internal/KernelQuery.js +205 -0
  28. package/dist/internal/KernelQuery.js.map +1 -0
  29. package/dist/internal/KernelRefusal.d.ts +77 -0
  30. package/dist/internal/KernelRefusal.d.ts.map +1 -0
  31. package/dist/internal/KernelRefusal.js +73 -0
  32. package/dist/internal/KernelRefusal.js.map +1 -0
  33. package/dist/internal/KernelValues.d.ts +136 -0
  34. package/dist/internal/KernelValues.d.ts.map +1 -0
  35. package/dist/internal/KernelValues.js +266 -0
  36. package/dist/internal/KernelValues.js.map +1 -0
  37. package/dist/internal/ReadSet.d.ts +55 -0
  38. package/dist/internal/ReadSet.d.ts.map +1 -0
  39. package/dist/internal/ReadSet.js +29 -0
  40. package/dist/internal/ReadSet.js.map +1 -0
  41. package/package.json +3 -3
  42. package/src/internal/Attempt.ts +185 -0
  43. package/src/internal/ConvexTest.ts +118 -0
  44. package/src/internal/Execution.ts +1430 -0
  45. package/src/internal/Globals.ts +93 -0
  46. package/src/internal/Invocation.ts +291 -0
  47. package/src/internal/Kernel.ts +190 -0
  48. package/src/internal/KernelQuery.ts +405 -0
  49. package/src/internal/KernelRefusal.ts +88 -0
  50. package/src/internal/KernelValues.ts +725 -0
  51. package/src/internal/ReadSet.ts +108 -0
@@ -0,0 +1,185 @@
1
+ // oxlint-disable-next-line effecttsgo/node-builtin-import -- The drain waits a real turn of the event loop. Fake timers in a test replace the global `setImmediate`, not this one.
2
+ import { setImmediate } from "node:timers/promises";
3
+ import type { Attempt as AttemptNumber } from "./Invocation.js";
4
+ import * as Kernel from "./Kernel.js";
5
+ import type { DocumentId, StoredDocument } from "./KernelValues.js";
6
+ import { tableNameFromId } from "./KernelValues.js";
7
+ import type * as ReadSet from "./ReadSet.js";
8
+
9
+ /**
10
+ * Pending writes, keyed by component path, then document ID. `null` deletes.
11
+ */
12
+ type Overlay = Map<string, Map<DocumentId, StoredDocument | null>>;
13
+
14
+ /**
15
+ * How long one frame takes syscalls: those it has running, those it has
16
+ * started, and whether it still takes them.
17
+ */
18
+ interface Life {
19
+ running: number;
20
+ started: number;
21
+ open: boolean;
22
+ }
23
+
24
+ /**
25
+ * One frame of an attempt at a query or mutation: the committed state the
26
+ * attempt started from, its caller's frame and its own pending writes. The
27
+ * outermost frame belongs to the top-level function. Each nested mutation opens
28
+ * a child frame, which merges into its caller's frame when it returns and is
29
+ * dropped when it fails. Reads belong to the whole attempt and are never
30
+ * dropped: a failed nested mutation's reads stay in the attempt.
31
+ *
32
+ * Each frame has its own lifetime. A frame takes reads and writes until it is
33
+ * closed. A mutation's frame closes once its function has returned and no
34
+ * syscall it started is still running, so a write a detached fiber makes after
35
+ * the handler settled still lands in it, as on the binary. A nested mutation's
36
+ * frame closes before it merges into its caller's, so no write reaches it after
37
+ * its writes became its caller's.
38
+ *
39
+ * A frame belongs to one invocation, which alone writes to it, so a caller's
40
+ * write made while its nested mutation is in flight stays the caller's.
41
+ * `Kernel.apply` publishes the outermost frame's writes.
42
+ */
43
+ export class KernelAttempt {
44
+ private readonly overlay: Overlay = new Map();
45
+ private readonly life: Life = { running: 0, started: 0, open: true };
46
+ private readonly allReads: Array<ReadSet.Read>;
47
+
48
+ constructor(
49
+ readonly snapshot: Kernel.State,
50
+ readonly number: AttemptNumber = 1,
51
+ private readonly parent?: KernelAttempt,
52
+ ) {
53
+ this.allReads = parent?.allReads ?? [];
54
+ }
55
+
56
+ get reads(): ReadonlyArray<ReadSet.Read> {
57
+ return this.allReads;
58
+ }
59
+
60
+ get closed(): boolean {
61
+ return !this.life.open;
62
+ }
63
+
64
+ readDocument(componentPath: string, id: DocumentId) {
65
+ this.allReads.push({ kind: "document", componentPath, id });
66
+ }
67
+
68
+ /**
69
+ * Record a read of an interval. The returned function advances how far the
70
+ * query examined it.
71
+ */
72
+ readInterval(
73
+ read: Omit<ReadSet.IntervalRead, "through">,
74
+ ): (through: ReadSet.Key | "end") => void {
75
+ const interval: ReadSet.IntervalRead = { ...read, through: null };
76
+ this.allReads.push(interval);
77
+ return (through) => {
78
+ interval.through = through;
79
+ };
80
+ }
81
+
82
+ /**
83
+ * A syscall began. `end` runs when it settles.
84
+ */
85
+ begin(): () => void {
86
+ const life = this.life;
87
+ life.running++;
88
+ life.started++;
89
+ return () => {
90
+ life.running--;
91
+ };
92
+ }
93
+
94
+ /**
95
+ * Resolves once a whole turn of the event loop passes with no syscall of this
96
+ * frame running or started. A nested call is a syscall of its caller's frame
97
+ * until it has drained.
98
+ */
99
+ drained(): Promise<void> {
100
+ const before = this.life.started;
101
+ return setImmediate().then(() =>
102
+ this.life.running === 0 && this.life.started === before
103
+ ? undefined
104
+ : this.drained(),
105
+ );
106
+ }
107
+
108
+ close() {
109
+ this.life.open = false;
110
+ }
111
+
112
+ /**
113
+ * The pending writes this frame sees, from the outermost frame to this one.
114
+ */
115
+ private overlays(): Array<Overlay> {
116
+ return this.parent === undefined
117
+ ? [this.overlay]
118
+ : [...this.parent.overlays(), this.overlay];
119
+ }
120
+
121
+ get(componentPath: string, id: DocumentId): StoredDocument | null {
122
+ for (const overlay of this.overlays().toReversed()) {
123
+ const write = overlay.get(componentPath)?.get(id);
124
+ if (write !== undefined) return write;
125
+ }
126
+ return Kernel.get(this.snapshot, componentPath, id)?.doc ?? null;
127
+ }
128
+
129
+ /**
130
+ * The table as this frame sees it, committed rows under every pending write
131
+ * from the outermost frame to this one.
132
+ */
133
+ scan(componentPath: string, tableName: string): Array<StoredDocument> {
134
+ const ids = new Set<DocumentId>();
135
+ for (const row of Kernel.rows(this.snapshot, componentPath, tableName))
136
+ ids.add(row.doc._id);
137
+ for (const overlay of this.overlays())
138
+ for (const id of overlay.get(componentPath)?.keys() ?? [])
139
+ if (tableNameFromId(id) === tableName) ids.add(id);
140
+ const docs: Array<StoredDocument> = [];
141
+ for (const id of ids) {
142
+ const doc = this.get(componentPath, id);
143
+ if (doc !== null) docs.push(doc);
144
+ }
145
+ return docs;
146
+ }
147
+
148
+ write(componentPath: string, id: DocumentId, doc: StoredDocument | null) {
149
+ const writes = this.overlay.get(componentPath) ?? new Map();
150
+ this.overlay.set(componentPath, writes);
151
+ writes.set(id, doc);
152
+ }
153
+
154
+ /**
155
+ * A nested mutation begins, in a frame of its own. Dropping a failed one is
156
+ * forgetting it.
157
+ */
158
+ child(): KernelAttempt {
159
+ return new KernelAttempt(this.snapshot, this.number, this);
160
+ }
161
+
162
+ /**
163
+ * A nested mutation returned and its frame closed. Its writes become its
164
+ * caller's.
165
+ */
166
+ merge() {
167
+ if (this.parent === undefined) {
168
+ throw new Error("The outermost frame of an attempt has no caller.");
169
+ }
170
+ if (this.life.open) {
171
+ throw new Error("A nested mutation's frame merges only once closed.");
172
+ }
173
+ for (const [componentPath, writes] of this.overlay)
174
+ for (const [id, doc] of writes) this.parent.write(componentPath, id, doc);
175
+ }
176
+
177
+ /**
178
+ * The outermost frame's writes, for `Kernel.apply`.
179
+ */
180
+ writes(): Array<Kernel.Write> {
181
+ return Array.from(this.overlay, ([componentPath, writes]) =>
182
+ Array.from(writes, ([id, doc]) => ({ componentPath, id, doc })),
183
+ ).flat();
184
+ }
185
+ }
@@ -0,0 +1,118 @@
1
+ import type {
2
+ GenericSchema,
3
+ SchemaDefinition,
4
+ UserIdentity,
5
+ } from "convex/server";
6
+ import { componentsGeneric } from "convex/server";
7
+ import * as Execution from "./Execution.js";
8
+ import type * as Kernel from "./Kernel.js";
9
+ import * as KernelRefusal from "./KernelRefusal.js";
10
+
11
+ type Modules = Record<string, () => Promise<any>>;
12
+
13
+ /**
14
+ * What the kernel adds to convex-test's surface, typed. The shim itself returns
15
+ * `any`, as convex-test's callers expect.
16
+ */
17
+ export interface KernelControls {
18
+ readonly query: (reference: any, args?: any) => Promise<any>;
19
+ readonly mutation: (reference: any, args?: any) => Promise<any>;
20
+ readonly action: (reference: any, args?: any) => Promise<any>;
21
+ readonly prepare: (
22
+ reference: any,
23
+ args?: any,
24
+ ) => Promise<Execution.HeldAttempt>;
25
+ readonly apply: (id: string) => Promise<Execution.KernelApply>;
26
+ readonly held: () => ReadonlyArray<Execution.HeldAttempt>;
27
+ }
28
+
29
+ const isSchemaDefinition = (
30
+ value: unknown,
31
+ ): value is SchemaDefinition<GenericSchema, boolean> =>
32
+ value !== null &&
33
+ typeof value === "object" &&
34
+ "tables" in value &&
35
+ typeof (value as { tables: unknown }).tables === "object";
36
+
37
+ const accessor = (world: Execution.World, caller: Execution.Caller): any => ({
38
+ query: (reference: any, args?: any) => world.query(caller, reference, args),
39
+ mutation: (reference: any, args?: any) =>
40
+ world.mutation(caller, reference, args),
41
+ action: (reference: any, args?: any) => world.action(caller, reference, args),
42
+ prepare: (reference: any, args?: any) =>
43
+ world.prepare(caller, reference, args),
44
+ apply: (id: string) => world.apply(id),
45
+ held: () => world.held(),
46
+ run: (handler: (ctx: any) => any) => world.run(caller, "", handler),
47
+ runInComponent: (componentPath: string, handler: (ctx: any) => any) =>
48
+ world.run(caller, componentPath, handler),
49
+ withIdentity: (identity: Partial<UserIdentity>) =>
50
+ accessor(world, Execution.withIdentity(caller, identity)),
51
+ withRequestMetadata: (metadata: {
52
+ readonly ip?: string | null;
53
+ readonly userAgent?: string | null;
54
+ }) =>
55
+ accessor(world, {
56
+ ...caller,
57
+ ip: metadata.ip ?? null,
58
+ userAgent: metadata.userAgent ?? null,
59
+ }),
60
+ fetch: () => Promise.reject(KernelRefusal.rowPending("HTTP routes", 6)),
61
+ jwks: () => Promise.reject(KernelRefusal.rowPending("JWT verification", 6)),
62
+ finishInProgressScheduledFunctions: () =>
63
+ Promise.reject(KernelRefusal.rowPending("the scheduler", 5)),
64
+ finishAllScheduledFunctions: () =>
65
+ Promise.reject(KernelRefusal.rowPending("the scheduler", 5)),
66
+ });
67
+
68
+ /**
69
+ * The test kernel under convex-test's `convexTest` signature. The fork's kernel
70
+ * lane aliases `convex-test` to this module, so every suite that calls
71
+ * `convexTest` directly, and `TestConfect` itself, runs on the kernel.
72
+ *
73
+ * Beyond convex-test, `prepare` runs a mutation to its commit point and holds
74
+ * it, and `apply` validates and publishes a held attempt. `mutation` applies
75
+ * each attempt it prepares at once and prepares the next on a conflict, up to
76
+ * attempt 5. `runtime` supplies the clock and commit timestamps.
77
+ */
78
+ export function convexTest(
79
+ schemaOrOptions?:
80
+ | SchemaDefinition<GenericSchema, boolean>
81
+ | {
82
+ readonly schema?: SchemaDefinition<GenericSchema, boolean>;
83
+ readonly modules?: Modules;
84
+ readonly transactionLimits?: unknown;
85
+ readonly runtime?: Kernel.KernelRuntime;
86
+ },
87
+ modules?: Modules,
88
+ ): any {
89
+ let schema: SchemaDefinition<GenericSchema, boolean> | undefined;
90
+ let runtime: Kernel.KernelRuntime | undefined;
91
+ if (isSchemaDefinition(schemaOrOptions)) {
92
+ schema = schemaOrOptions;
93
+ } else if (schemaOrOptions !== undefined) {
94
+ if (schemaOrOptions.transactionLimits !== undefined) {
95
+ throw KernelRefusal.rowPending("transaction limits", 6);
96
+ }
97
+ schema = schemaOrOptions.schema;
98
+ modules = schemaOrOptions.modules;
99
+ runtime = schemaOrOptions.runtime;
100
+ }
101
+ if (modules === undefined) {
102
+ throw new Error(
103
+ "The test kernel needs the modules map: pass `import.meta.glob(...)` as the second argument.",
104
+ );
105
+ }
106
+ const world = new Execution.World(schema, modules, runtime);
107
+ return {
108
+ ...accessor(world, Execution.anonymous),
109
+ registerComponent: (
110
+ componentPath: string,
111
+ componentSchema: SchemaDefinition<GenericSchema, boolean>,
112
+ componentModules: Modules,
113
+ ) => {
114
+ world.register(componentPath, componentSchema, componentModules);
115
+ return (componentsGeneric() as any)[componentPath];
116
+ },
117
+ };
118
+ }