@terreno/syncdb 57.0.0-beta.1 → 57.2.0
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.
- package/README.md +33 -0
- package/dist/client.d.ts +5 -0
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +64 -1
- package/dist/client.js.map +1 -1
- package/dist/client.test.js +73 -1
- package/dist/client.test.js.map +1 -1
- package/dist/codegen/cli.d.ts +3 -0
- package/dist/codegen/cli.d.ts.map +1 -0
- package/dist/codegen/cli.js +47 -0
- package/dist/codegen/cli.js.map +1 -0
- package/dist/codegen/cli.test.d.ts +2 -0
- package/dist/codegen/cli.test.d.ts.map +1 -0
- package/dist/codegen/cli.test.js +54 -0
- package/dist/codegen/cli.test.js.map +1 -0
- package/dist/codegen/discoverCollections.d.ts +6 -0
- package/dist/codegen/discoverCollections.d.ts.map +1 -0
- package/dist/codegen/discoverCollections.js +111 -0
- package/dist/codegen/discoverCollections.js.map +1 -0
- package/dist/codegen/emitSdk.d.ts +12 -0
- package/dist/codegen/emitSdk.d.ts.map +1 -0
- package/dist/codegen/emitSdk.js +94 -0
- package/dist/codegen/emitSdk.js.map +1 -0
- package/dist/codegen/emitTypes.d.ts +6 -0
- package/dist/codegen/emitTypes.d.ts.map +1 -0
- package/dist/codegen/emitTypes.js +43 -0
- package/dist/codegen/emitTypes.js.map +1 -0
- package/dist/codegen/generate.d.ts +5 -0
- package/dist/codegen/generate.d.ts.map +1 -0
- package/dist/codegen/generate.js +47 -0
- package/dist/codegen/generate.js.map +1 -0
- package/dist/codegen/generate.test.d.ts +2 -0
- package/dist/codegen/generate.test.d.ts.map +1 -0
- package/dist/codegen/generate.test.js +192 -0
- package/dist/codegen/generate.test.js.map +1 -0
- package/dist/codegen/hookNames.d.ts +17 -0
- package/dist/codegen/hookNames.d.ts.map +1 -0
- package/dist/codegen/hookNames.js +27 -0
- package/dist/codegen/hookNames.js.map +1 -0
- package/dist/codegen/loadSpec.d.ts +3 -0
- package/dist/codegen/loadSpec.d.ts.map +1 -0
- package/dist/codegen/loadSpec.js +16 -0
- package/dist/codegen/loadSpec.js.map +1 -0
- package/dist/codegen/safeIdentifiers.d.ts +7 -0
- package/dist/codegen/safeIdentifiers.d.ts.map +1 -0
- package/dist/codegen/safeIdentifiers.js +15 -0
- package/dist/codegen/safeIdentifiers.js.map +1 -0
- package/dist/codegen/safeIdentifiers.test.d.ts +2 -0
- package/dist/codegen/safeIdentifiers.test.d.ts.map +1 -0
- package/dist/codegen/safeIdentifiers.test.js +25 -0
- package/dist/codegen/safeIdentifiers.test.js.map +1 -0
- package/dist/codegen/types.d.ts +69 -0
- package/dist/codegen/types.d.ts.map +1 -0
- package/dist/codegen/types.js +2 -0
- package/dist/codegen/types.js.map +1 -0
- package/dist/crypto/keyProviders.test.js +2 -2
- package/dist/crypto/keyProviders.test.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/maxAttempts.d.ts +7 -0
- package/dist/maxAttempts.d.ts.map +1 -0
- package/dist/maxAttempts.js +15 -0
- package/dist/maxAttempts.js.map +1 -0
- package/dist/mutations/outbox.d.ts +5 -0
- package/dist/mutations/outbox.d.ts.map +1 -1
- package/dist/mutations/outbox.js +10 -2
- package/dist/mutations/outbox.js.map +1 -1
- package/dist/mutations/outbox.test.js +36 -0
- package/dist/mutations/outbox.test.js.map +1 -1
- package/dist/react/collectionHooks.d.ts +43 -0
- package/dist/react/collectionHooks.d.ts.map +1 -0
- package/dist/react/collectionHooks.js +51 -0
- package/dist/react/collectionHooks.js.map +1 -0
- package/dist/react/collectionHooks.test.d.ts +2 -0
- package/dist/react/collectionHooks.test.d.ts.map +1 -0
- package/dist/react/collectionHooks.test.js +150 -0
- package/dist/react/collectionHooks.test.js.map +1 -0
- package/dist/react/hooks.d.ts +4 -0
- package/dist/react/hooks.d.ts.map +1 -1
- package/dist/react/hooks.js +20 -3
- package/dist/react/hooks.js.map +1 -1
- package/dist/react/hooks.test.js +3 -4
- package/dist/react/hooks.test.js.map +1 -1
- package/dist/react/index.d.ts +1 -0
- package/dist/react/index.d.ts.map +1 -1
- package/dist/react/index.js +1 -0
- package/dist/react/index.js.map +1 -1
- package/dist/storage/idb.test.js +3 -1
- package/dist/storage/idb.test.js.map +1 -1
- package/dist/storage/schema.d.ts.map +1 -1
- package/dist/storage/schema.js +1 -0
- package/dist/storage/schema.js.map +1 -1
- package/dist/storage/types.d.ts +2 -0
- package/dist/storage/types.d.ts.map +1 -1
- package/dist/sync/replayCoordinator.d.ts.map +1 -1
- package/dist/sync/replayCoordinator.js +4 -2
- package/dist/sync/replayCoordinator.js.map +1 -1
- package/dist/sync/replayCoordinator.test.js +52 -1
- package/dist/sync/replayCoordinator.test.js.map +1 -1
- package/dist/sync/socketTransport.d.ts +9 -2
- package/dist/sync/socketTransport.d.ts.map +1 -1
- package/dist/sync/socketTransport.js +21 -3
- package/dist/sync/socketTransport.js.map +1 -1
- package/dist/sync/socketTransport.test.js +50 -2
- package/dist/sync/socketTransport.test.js.map +1 -1
- package/dist/sync/transport.d.ts +7 -1
- package/dist/sync/transport.d.ts.map +1 -1
- package/dist/sync/transport.js.map +1 -1
- package/dist/testing/fakeTransport.d.ts +3 -1
- package/dist/testing/fakeTransport.d.ts.map +1 -1
- package/dist/testing/fakeTransport.js +12 -0
- package/dist/testing/fakeTransport.js.map +1 -1
- package/dist/types.d.ts +17 -0
- package/dist/types.d.ts.map +1 -1
- package/package.json +7 -2
- package/src/client.test.ts +88 -1
- package/src/client.ts +74 -0
- package/src/codegen/cli.test.ts +61 -0
- package/src/codegen/cli.ts +52 -0
- package/src/codegen/discoverCollections.ts +159 -0
- package/src/codegen/emitSdk.ts +113 -0
- package/src/codegen/emitTypes.ts +46 -0
- package/src/codegen/fixtures/openapi.example.json +94 -0
- package/src/codegen/generate.test.ts +216 -0
- package/src/codegen/generate.ts +52 -0
- package/src/codegen/hookNames.ts +41 -0
- package/src/codegen/loadSpec.ts +18 -0
- package/src/codegen/safeIdentifiers.test.ts +32 -0
- package/src/codegen/safeIdentifiers.ts +17 -0
- package/src/codegen/types.ts +70 -0
- package/src/crypto/keyProviders.test.ts +2 -2
- package/src/index.ts +1 -0
- package/src/maxAttempts.ts +14 -0
- package/src/mutations/outbox.test.ts +39 -0
- package/src/mutations/outbox.ts +15 -2
- package/src/react/collectionHooks.test.tsx +189 -0
- package/src/react/collectionHooks.ts +103 -0
- package/src/react/hooks.test.tsx +3 -4
- package/src/react/hooks.ts +40 -9
- package/src/react/index.ts +1 -0
- package/src/storage/idb.test.ts +3 -1
- package/src/storage/schema.ts +1 -0
- package/src/storage/types.ts +2 -0
- package/src/sync/replayCoordinator.test.ts +61 -0
- package/src/sync/replayCoordinator.ts +4 -2
- package/src/sync/socketTransport.test.ts +53 -2
- package/src/sync/socketTransport.ts +29 -2
- package/src/sync/transport.ts +7 -0
- package/src/testing/fakeTransport.ts +15 -0
- package/src/types.ts +18 -0
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
export const toPascalCase = (value: string): string =>
|
|
2
|
+
value
|
|
3
|
+
.split(/[-_/]/g)
|
|
4
|
+
.filter(Boolean)
|
|
5
|
+
.map((part) => part.charAt(0).toUpperCase() + part.slice(1))
|
|
6
|
+
.join("");
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Friendly generated names (IP decision: no collision with RTK codegen).
|
|
10
|
+
* Collection `todos`, entity `Todo` → useTodos / useTodo / useCreateTodo / …
|
|
11
|
+
*/
|
|
12
|
+
export const friendlyHookNames = ({
|
|
13
|
+
collection,
|
|
14
|
+
entityName,
|
|
15
|
+
}: {
|
|
16
|
+
collection: string;
|
|
17
|
+
entityName: string;
|
|
18
|
+
}): {
|
|
19
|
+
list: string;
|
|
20
|
+
read: string;
|
|
21
|
+
create: string;
|
|
22
|
+
update: string;
|
|
23
|
+
remove: string;
|
|
24
|
+
} => {
|
|
25
|
+
const plural = toPascalCase(collection);
|
|
26
|
+
return {
|
|
27
|
+
create: `useCreate${entityName}`,
|
|
28
|
+
list: `use${plural}`,
|
|
29
|
+
read: `use${entityName}`,
|
|
30
|
+
remove: `useDelete${entityName}`,
|
|
31
|
+
update: `useUpdate${entityName}`,
|
|
32
|
+
};
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
export const refName = (ref: string | undefined): string | undefined => {
|
|
36
|
+
if (!ref) {
|
|
37
|
+
return undefined;
|
|
38
|
+
}
|
|
39
|
+
const match = ref.match(/\/([^/]+)$/);
|
|
40
|
+
return match?.[1];
|
|
41
|
+
};
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import {readFile} from "node:fs/promises";
|
|
2
|
+
|
|
3
|
+
import type {OpenApiDocument} from "./types";
|
|
4
|
+
|
|
5
|
+
export const loadSpec = async (schema: string): Promise<OpenApiDocument> => {
|
|
6
|
+
if (!schema) {
|
|
7
|
+
throw new Error("Missing --schema (OpenAPI URL or JSON file path)");
|
|
8
|
+
}
|
|
9
|
+
if (/^https?:\/\//.test(schema)) {
|
|
10
|
+
const response = await fetch(schema);
|
|
11
|
+
if (!response.ok) {
|
|
12
|
+
throw new Error(`Failed to fetch OpenAPI spec from ${schema}: ${response.status}`);
|
|
13
|
+
}
|
|
14
|
+
return (await response.json()) as OpenApiDocument;
|
|
15
|
+
}
|
|
16
|
+
const raw = await readFile(schema, "utf8");
|
|
17
|
+
return JSON.parse(raw) as OpenApiDocument;
|
|
18
|
+
};
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import {describe, expect, it} from "bun:test";
|
|
2
|
+
|
|
3
|
+
import {assertTsIdentifier, emitTsPropertyKey, emitTsString} from "./safeIdentifiers";
|
|
4
|
+
|
|
5
|
+
describe("assertTsIdentifier", () => {
|
|
6
|
+
it("accepts TypeScript identifiers", () => {
|
|
7
|
+
expect(assertTsIdentifier({label: "name", value: "Todo"})).toBe("Todo");
|
|
8
|
+
expect(assertTsIdentifier({label: "name", value: "_id"})).toBe("_id");
|
|
9
|
+
});
|
|
10
|
+
|
|
11
|
+
it("rejects quote and statement injection", () => {
|
|
12
|
+
expect(() =>
|
|
13
|
+
assertTsIdentifier({label: "collection", value: 'todos"; process.exit(1); //'})
|
|
14
|
+
).toThrow(/not a TypeScript identifier/);
|
|
15
|
+
});
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
describe("emitTsString", () => {
|
|
19
|
+
it("JSON-escapes quotes so they cannot close a generated string", () => {
|
|
20
|
+
expect(emitTsString('todos"; process.exit(1); //')).toBe('"todos\\"; process.exit(1); //"');
|
|
21
|
+
});
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
describe("emitTsPropertyKey", () => {
|
|
25
|
+
it("emits bare identifiers", () => {
|
|
26
|
+
expect(emitTsPropertyKey("title")).toBe("title");
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
it("quotes keys that are not identifiers", () => {
|
|
30
|
+
expect(emitTsPropertyKey('foo"; bar')).toBe('"foo\\"; bar"');
|
|
31
|
+
});
|
|
32
|
+
});
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
const TS_IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
|
|
2
|
+
|
|
3
|
+
export const assertTsIdentifier = ({label, value}: {label: string; value: string}): string => {
|
|
4
|
+
if (!TS_IDENTIFIER.test(value)) {
|
|
5
|
+
throw new Error(`Invalid ${label}: ${JSON.stringify(value)} is not a TypeScript identifier`);
|
|
6
|
+
}
|
|
7
|
+
return value;
|
|
8
|
+
};
|
|
9
|
+
|
|
10
|
+
export const emitTsString = (value: string): string => JSON.stringify(value);
|
|
11
|
+
|
|
12
|
+
export const emitTsPropertyKey = (key: string): string => {
|
|
13
|
+
if (TS_IDENTIFIER.test(key)) {
|
|
14
|
+
return key;
|
|
15
|
+
}
|
|
16
|
+
return JSON.stringify(key);
|
|
17
|
+
};
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
export interface TerrenoSyncExtension {
|
|
2
|
+
collection: string;
|
|
3
|
+
scope: string;
|
|
4
|
+
}
|
|
5
|
+
|
|
6
|
+
export interface OpenApiSchema {
|
|
7
|
+
type?: string;
|
|
8
|
+
format?: string;
|
|
9
|
+
enum?: Array<string | number | boolean>;
|
|
10
|
+
properties?: Record<string, OpenApiSchema>;
|
|
11
|
+
required?: string[];
|
|
12
|
+
items?: OpenApiSchema;
|
|
13
|
+
$ref?: string;
|
|
14
|
+
additionalProperties?: boolean | OpenApiSchema;
|
|
15
|
+
allOf?: OpenApiSchema[];
|
|
16
|
+
oneOf?: OpenApiSchema[];
|
|
17
|
+
anyOf?: OpenApiSchema[];
|
|
18
|
+
description?: string;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface OpenApiOperation {
|
|
22
|
+
"x-terreno-sync"?: TerrenoSyncExtension;
|
|
23
|
+
requestBody?: {
|
|
24
|
+
content?: Record<string, {schema?: OpenApiSchema}>;
|
|
25
|
+
};
|
|
26
|
+
responses?: Record<
|
|
27
|
+
string,
|
|
28
|
+
{
|
|
29
|
+
content?: Record<string, {schema?: OpenApiSchema}>;
|
|
30
|
+
}
|
|
31
|
+
>;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface OpenApiPathItem {
|
|
35
|
+
get?: OpenApiOperation;
|
|
36
|
+
post?: OpenApiOperation;
|
|
37
|
+
patch?: OpenApiOperation;
|
|
38
|
+
put?: OpenApiOperation;
|
|
39
|
+
delete?: OpenApiOperation;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export interface OpenApiDocument {
|
|
43
|
+
paths?: Record<string, OpenApiPathItem>;
|
|
44
|
+
components?: {schemas?: Record<string, OpenApiSchema>};
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export interface DiscoveredCollection {
|
|
48
|
+
collection: string;
|
|
49
|
+
entityName: string;
|
|
50
|
+
entitySchema: OpenApiSchema;
|
|
51
|
+
createName: string;
|
|
52
|
+
createSchema: OpenApiSchema;
|
|
53
|
+
updateName: string;
|
|
54
|
+
updateSchema: OpenApiSchema;
|
|
55
|
+
retries?: boolean | number;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export interface CodegenConfigFile {
|
|
59
|
+
overrides?: Record<string, {retries?: boolean | number}>;
|
|
60
|
+
exportName?: string;
|
|
61
|
+
sdkImportPath?: string;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export interface GenerateArgs {
|
|
65
|
+
schema: string;
|
|
66
|
+
out: string;
|
|
67
|
+
collections?: string[];
|
|
68
|
+
config?: CodegenConfigFile;
|
|
69
|
+
format: boolean;
|
|
70
|
+
}
|
|
@@ -140,7 +140,7 @@ describe("createServerKeyProvider", () => {
|
|
|
140
140
|
fetchKeyMaterial: async () =>
|
|
141
141
|
Buffer.from(crypto.getRandomValues(new Uint8Array(16))).toString("base64"),
|
|
142
142
|
});
|
|
143
|
-
expect(provider.getKey({userId: "u1"})).rejects.toThrow("32 bytes");
|
|
143
|
+
await expect(provider.getKey({userId: "u1"})).rejects.toThrow("32 bytes");
|
|
144
144
|
});
|
|
145
145
|
|
|
146
146
|
it("does not poison future attempts after a failed fetch", async () => {
|
|
@@ -156,7 +156,7 @@ describe("createServerKeyProvider", () => {
|
|
|
156
156
|
return material;
|
|
157
157
|
},
|
|
158
158
|
});
|
|
159
|
-
expect(provider.getKey({userId: "u1"})).rejects.toThrow("network unavailable");
|
|
159
|
+
await expect(provider.getKey({userId: "u1"})).rejects.toThrow("network unavailable");
|
|
160
160
|
shouldFail = false;
|
|
161
161
|
const key = await provider.getKey({userId: "u1"});
|
|
162
162
|
expect(key.type).toBe("secret");
|
package/src/index.ts
CHANGED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Map the codegen/factory `retries` option onto `MutateArgs.maxAttempts`.
|
|
3
|
+
* `false` → 1 attempt (fail fast); a number → that many error-nack attempts;
|
|
4
|
+
* omitted/`true` → engine default (`MAX_ERROR_NACK_ATTEMPTS`).
|
|
5
|
+
*/
|
|
6
|
+
export const retriesToMaxAttempts = (retries?: boolean | number): number | undefined => {
|
|
7
|
+
if (retries === false) {
|
|
8
|
+
return 1;
|
|
9
|
+
}
|
|
10
|
+
if (typeof retries === "number") {
|
|
11
|
+
return retries;
|
|
12
|
+
}
|
|
13
|
+
return undefined;
|
|
14
|
+
};
|
|
@@ -76,6 +76,27 @@ describe("enqueue / getMutation", () => {
|
|
|
76
76
|
expect(outbox.getMutation({mutationId: "m1"})?.baseVersion).toBeUndefined();
|
|
77
77
|
});
|
|
78
78
|
|
|
79
|
+
it("persists optional maxAttempts on the outbox row", () => {
|
|
80
|
+
const outbox = makeOutbox();
|
|
81
|
+
const mutation = outbox.enqueue({
|
|
82
|
+
args: {title: "Buy milk"},
|
|
83
|
+
collection: "todos",
|
|
84
|
+
entityId: "t1",
|
|
85
|
+
maxAttempts: 1,
|
|
86
|
+
mutationId: "m-max",
|
|
87
|
+
operation: "update",
|
|
88
|
+
userId: "user-1",
|
|
89
|
+
});
|
|
90
|
+
expect(mutation.maxAttempts).toBe(1);
|
|
91
|
+
expect(outbox.getMutation({mutationId: "m-max"})?.maxAttempts).toBe(1);
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
it("leaves maxAttempts undefined when not provided", () => {
|
|
95
|
+
const outbox = makeOutbox();
|
|
96
|
+
const mutation = enqueueDefault(outbox, {mutationId: "m1"});
|
|
97
|
+
expect(mutation.maxAttempts).toBeUndefined();
|
|
98
|
+
});
|
|
99
|
+
|
|
79
100
|
it("returns undefined for a missing mutation", () => {
|
|
80
101
|
const outbox = makeOutbox();
|
|
81
102
|
expect(outbox.getMutation({mutationId: "nope"})).toBeUndefined();
|
|
@@ -245,6 +266,24 @@ describe("state machine transitions", () => {
|
|
|
245
266
|
expect(outbox.getMutation({mutationId: retry.mutationId})?.baseVersion).toBe(3);
|
|
246
267
|
});
|
|
247
268
|
|
|
269
|
+
it("requeue copies maxAttempts onto the cloned row", () => {
|
|
270
|
+
const outbox = makeOutbox();
|
|
271
|
+
outbox.enqueue({
|
|
272
|
+
args: {title: "Buy milk"},
|
|
273
|
+
collection: "todos",
|
|
274
|
+
entityId: "t1",
|
|
275
|
+
maxAttempts: 1,
|
|
276
|
+
mutationId: "m1",
|
|
277
|
+
operation: "update",
|
|
278
|
+
userId: "user-1",
|
|
279
|
+
});
|
|
280
|
+
outbox.markInFlight({mutationId: "m1"});
|
|
281
|
+
outbox.markConflicted({mutationId: "m1"});
|
|
282
|
+
const retry = outbox.requeue({mutationId: "m1"});
|
|
283
|
+
expect(retry.maxAttempts).toBe(1);
|
|
284
|
+
expect(outbox.getMutation({mutationId: retry.mutationId})?.maxAttempts).toBe(1);
|
|
285
|
+
});
|
|
286
|
+
|
|
248
287
|
it("requeue preserves the original FIFO position", () => {
|
|
249
288
|
const outbox = makeOutbox();
|
|
250
289
|
enqueueDefault(outbox, {entityId: "t1", mutationId: "m1"});
|
package/src/mutations/outbox.ts
CHANGED
|
@@ -44,6 +44,7 @@ const rowToMutation = (mutationId: string, row: Partial<OutboxRow>): OutboxMutat
|
|
|
44
44
|
createdAt: row.createdAt ?? "",
|
|
45
45
|
entityId: row.entityId ?? "",
|
|
46
46
|
errorNackCount: row.errorNackCount ?? 0,
|
|
47
|
+
maxAttempts: typeof row.maxAttempts === "number" ? row.maxAttempts : undefined,
|
|
47
48
|
mutationId,
|
|
48
49
|
operation: (row.operation ?? "update") as SyncMutationOperation,
|
|
49
50
|
status: (row.status ?? "queued") as OutboxStatus,
|
|
@@ -58,6 +59,11 @@ export interface EnqueueArgs {
|
|
|
58
59
|
args: Record<string, unknown>;
|
|
59
60
|
/** The seq the client last saw for the entity (LWW conflict detection). */
|
|
60
61
|
baseVersion?: number;
|
|
62
|
+
/**
|
|
63
|
+
* Optional error-nack retry budget. Missing cell keeps the engine default
|
|
64
|
+
* (`MAX_ERROR_NACK_ATTEMPTS`). `1` fails after a single error nack.
|
|
65
|
+
*/
|
|
66
|
+
maxAttempts?: number;
|
|
61
67
|
/** The user this mutation belongs to; replay skips mutations from other users. */
|
|
62
68
|
userId: string;
|
|
63
69
|
/** Optional explicit id (defaults to a generated UUID; useful in tests). */
|
|
@@ -246,6 +252,9 @@ export const createOutbox = ({
|
|
|
246
252
|
if (args.baseVersion !== undefined) {
|
|
247
253
|
row.baseVersion = args.baseVersion;
|
|
248
254
|
}
|
|
255
|
+
if (args.maxAttempts !== undefined) {
|
|
256
|
+
row.maxAttempts = args.maxAttempts;
|
|
257
|
+
}
|
|
249
258
|
store.raw.setRow(OUTBOX_TABLE, mutationId, row as unknown as Row);
|
|
250
259
|
return rowToMutation(mutationId, row);
|
|
251
260
|
};
|
|
@@ -332,8 +341,9 @@ export const createOutbox = ({
|
|
|
332
341
|
if (from !== "conflicted") {
|
|
333
342
|
throw new Error(`Illegal outbox transition "${from}" → "queued" (mutation ${mutationId})`);
|
|
334
343
|
}
|
|
335
|
-
// Clone under a fresh id (
|
|
336
|
-
//
|
|
344
|
+
// Clone under a fresh id (reset attempt/error-nack counters, keep the original
|
|
345
|
+
// FIFO position and per-mutation retry cap) and drop the spent row — its
|
|
346
|
+
// mutationId is burned on the server's idempotency ledger.
|
|
337
347
|
const retryId = generateMutationId();
|
|
338
348
|
const retryRow: OutboxRow = {
|
|
339
349
|
args: row.args ?? "{}",
|
|
@@ -351,6 +361,9 @@ export const createOutbox = ({
|
|
|
351
361
|
if (retryBaseVersion !== undefined) {
|
|
352
362
|
retryRow.baseVersion = retryBaseVersion;
|
|
353
363
|
}
|
|
364
|
+
if (typeof row.maxAttempts === "number") {
|
|
365
|
+
retryRow.maxAttempts = row.maxAttempts;
|
|
366
|
+
}
|
|
354
367
|
store.raw.setRow(OUTBOX_TABLE, retryId, retryRow as unknown as Row);
|
|
355
368
|
store.raw.delRow(OUTBOX_TABLE, mutationId);
|
|
356
369
|
return rowToMutation(retryId, retryRow);
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
import {describe, expect, it} from "bun:test";
|
|
2
|
+
import {act, renderHook} from "@testing-library/react-native";
|
|
3
|
+
import React from "react";
|
|
4
|
+
|
|
5
|
+
import {createSyncDb, type SyncDb} from "../client";
|
|
6
|
+
import {retriesToMaxAttempts} from "../maxAttempts";
|
|
7
|
+
import {memoryPersisterFactory} from "../persisters/memoryPersister";
|
|
8
|
+
import {OUTBOX_TABLE} from "../storage/types";
|
|
9
|
+
import {createFakeTransport} from "../testing/fakeTransport";
|
|
10
|
+
import type {AuthProvider} from "../types";
|
|
11
|
+
import {createCollectionHooks} from "./collectionHooks";
|
|
12
|
+
import {SyncDbProvider} from "./provider";
|
|
13
|
+
|
|
14
|
+
interface TodoData {
|
|
15
|
+
title: string;
|
|
16
|
+
completed?: boolean;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
interface CreateTodo {
|
|
20
|
+
title: string;
|
|
21
|
+
completed?: boolean;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
let nameCounter = 0;
|
|
25
|
+
const uniqueName = (): string => {
|
|
26
|
+
nameCounter += 1;
|
|
27
|
+
return `collection-hooks-test-${nameCounter}`;
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
const makeAuthProvider = (userId: string): AuthProvider => {
|
|
31
|
+
const listeners = new Set<() => void>();
|
|
32
|
+
return {
|
|
33
|
+
getToken: async () => "token",
|
|
34
|
+
getUserId: async () => userId,
|
|
35
|
+
onAuthChange: (callback: () => void): (() => void) => {
|
|
36
|
+
listeners.add(callback);
|
|
37
|
+
return () => {
|
|
38
|
+
listeners.delete(callback);
|
|
39
|
+
};
|
|
40
|
+
},
|
|
41
|
+
};
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
interface Harness {
|
|
45
|
+
client: SyncDb;
|
|
46
|
+
wrapper: React.FC<{children: React.ReactNode}>;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const setup = async (): Promise<Harness> => {
|
|
50
|
+
const transport = createFakeTransport();
|
|
51
|
+
const client = createSyncDb({
|
|
52
|
+
authProvider: makeAuthProvider("u1"),
|
|
53
|
+
collections: ["todos"],
|
|
54
|
+
name: uniqueName(),
|
|
55
|
+
persisterFactory: memoryPersisterFactory,
|
|
56
|
+
reconcileIntervalMs: 0,
|
|
57
|
+
transport,
|
|
58
|
+
});
|
|
59
|
+
await client.start();
|
|
60
|
+
await client.reconcile();
|
|
61
|
+
await client.replayOutbox();
|
|
62
|
+
const wrapper: React.FC<{children: React.ReactNode}> = ({children}) => (
|
|
63
|
+
<SyncDbProvider client={client}>{children}</SyncDbProvider>
|
|
64
|
+
);
|
|
65
|
+
return {client, wrapper};
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
const todoHooks = createCollectionHooks<TodoData, CreateTodo, Partial<CreateTodo>>({
|
|
69
|
+
collection: "todos",
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
describe("retriesToMaxAttempts", () => {
|
|
73
|
+
it("maps false to a single attempt", () => {
|
|
74
|
+
expect(retriesToMaxAttempts(false)).toBe(1);
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
it("maps a number through", () => {
|
|
78
|
+
expect(retriesToMaxAttempts(3)).toBe(3);
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
it("omits the engine default when retries is undefined or true", () => {
|
|
82
|
+
expect(retriesToMaxAttempts(undefined)).toBeUndefined();
|
|
83
|
+
expect(retriesToMaxAttempts(true)).toBeUndefined();
|
|
84
|
+
});
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
describe("createCollectionHooks", () => {
|
|
88
|
+
it("list/read/create/update/delete match direct hook behavior", async () => {
|
|
89
|
+
const {client, wrapper} = await setup();
|
|
90
|
+
const hooks = createCollectionHooks<TodoData, CreateTodo, Partial<CreateTodo>>({
|
|
91
|
+
collection: "todos",
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
const {result, unmount} = renderHook(
|
|
95
|
+
() => {
|
|
96
|
+
const list = hooks.useListQuery();
|
|
97
|
+
const [create] = hooks.useCreateMutation();
|
|
98
|
+
const [update] = hooks.useUpdateMutation();
|
|
99
|
+
const [remove] = hooks.useDeleteMutation();
|
|
100
|
+
return {create, list, remove, update};
|
|
101
|
+
},
|
|
102
|
+
{wrapper}
|
|
103
|
+
);
|
|
104
|
+
|
|
105
|
+
let createdId = "";
|
|
106
|
+
act(() => {
|
|
107
|
+
createdId = result.current.create({data: {title: "from factory"}}).id;
|
|
108
|
+
});
|
|
109
|
+
expect(result.current.list.data).toEqual([{title: "from factory"}]);
|
|
110
|
+
|
|
111
|
+
const {result: readResult} = renderHook(() => hooks.useReadQuery(createdId), {wrapper});
|
|
112
|
+
expect(readResult.current.data?.title).toBe("from factory");
|
|
113
|
+
expect(readResult.current.isPending).toBe(true);
|
|
114
|
+
|
|
115
|
+
act(() => {
|
|
116
|
+
result.current.update({data: {completed: true}, id: createdId});
|
|
117
|
+
});
|
|
118
|
+
expect(readResult.current.data?.completed).toBe(true);
|
|
119
|
+
|
|
120
|
+
act(() => {
|
|
121
|
+
result.current.remove({id: createdId});
|
|
122
|
+
});
|
|
123
|
+
expect(result.current.list.data).toEqual([]);
|
|
124
|
+
|
|
125
|
+
unmount();
|
|
126
|
+
await act(async () => {
|
|
127
|
+
await client.stop();
|
|
128
|
+
});
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
it("useListQuery returns list data matching useQuery", async () => {
|
|
132
|
+
const {client, wrapper} = await setup();
|
|
133
|
+
client.mutate({collection: "todos", data: {title: "A"}, operation: "create"});
|
|
134
|
+
const {result} = renderHook(() => todoHooks.useListQuery(), {wrapper});
|
|
135
|
+
expect(result.current.data).toHaveLength(1);
|
|
136
|
+
expect(result.current.data[0]?.title).toBe("A");
|
|
137
|
+
await act(async () => {
|
|
138
|
+
await client.stop();
|
|
139
|
+
});
|
|
140
|
+
});
|
|
141
|
+
|
|
142
|
+
it("useReadQuery returns entity data for an id", async () => {
|
|
143
|
+
const {client, wrapper} = await setup();
|
|
144
|
+
const {id} = client.mutate({
|
|
145
|
+
collection: "todos",
|
|
146
|
+
data: {title: "Read me"},
|
|
147
|
+
operation: "create",
|
|
148
|
+
});
|
|
149
|
+
const {result} = renderHook(() => todoHooks.useReadQuery(id), {wrapper});
|
|
150
|
+
expect(result.current.data?.title).toBe("Read me");
|
|
151
|
+
await act(async () => {
|
|
152
|
+
await client.stop();
|
|
153
|
+
});
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
it("useCreateMutation returns a one-element trigger tuple", async () => {
|
|
157
|
+
const {client, wrapper} = await setup();
|
|
158
|
+
const {result} = renderHook(() => todoHooks.useCreateMutation(), {wrapper});
|
|
159
|
+
expect(result.current).toHaveLength(1);
|
|
160
|
+
const [createTodo] = result.current;
|
|
161
|
+
const created = createTodo({data: {title: "New"}});
|
|
162
|
+
expect(created.id.length).toBeGreaterThan(0);
|
|
163
|
+
expect(created.mutationId.length).toBeGreaterThan(0);
|
|
164
|
+
await act(async () => {
|
|
165
|
+
await client.stop();
|
|
166
|
+
});
|
|
167
|
+
});
|
|
168
|
+
|
|
169
|
+
it("threads retries: false onto the outbox row as maxAttempts: 1", async () => {
|
|
170
|
+
const {client, wrapper} = await setup();
|
|
171
|
+
const hooks = createCollectionHooks<TodoData, CreateTodo>({
|
|
172
|
+
collection: "todos",
|
|
173
|
+
retries: false,
|
|
174
|
+
});
|
|
175
|
+
const {result, unmount} = renderHook(() => hooks.useCreateMutation(), {wrapper});
|
|
176
|
+
const [create] = result.current;
|
|
177
|
+
let mutationId = "";
|
|
178
|
+
act(() => {
|
|
179
|
+
mutationId = create({data: {title: "once"}}).mutationId;
|
|
180
|
+
});
|
|
181
|
+
expect(client.outbox.getMutation({mutationId})?.maxAttempts).toBe(1);
|
|
182
|
+
const row = client.store.raw.getRow(OUTBOX_TABLE, mutationId) as {maxAttempts?: number};
|
|
183
|
+
expect(row.maxAttempts).toBe(1);
|
|
184
|
+
unmount();
|
|
185
|
+
await act(async () => {
|
|
186
|
+
await client.stop();
|
|
187
|
+
});
|
|
188
|
+
});
|
|
189
|
+
});
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Typed per-collection hook factory used by generated SDKs and hand-written
|
|
3
|
+
* custom hooks. Mirrors RTK Query's `injectEndpoints` pattern: generated code
|
|
4
|
+
* and app code both call this factory; the generated file only renames the
|
|
5
|
+
* returned hooks to friendly collection-specific names.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import {useCallback, useMemo} from "react";
|
|
9
|
+
|
|
10
|
+
import {retriesToMaxAttempts} from "../maxAttempts";
|
|
11
|
+
import type {UseEntityResult, UseQueryOptions} from "./hooks";
|
|
12
|
+
import {useEntity, useMutate, useQuery} from "./hooks";
|
|
13
|
+
|
|
14
|
+
export interface CollectionHooksConfig {
|
|
15
|
+
collection: string;
|
|
16
|
+
/**
|
|
17
|
+
* `false` → 1 attempt (fail fast); a number → that many error-nack attempts;
|
|
18
|
+
* omitted → engine default (`MAX_ERROR_NACK_ATTEMPTS`).
|
|
19
|
+
*/
|
|
20
|
+
retries?: boolean | number;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export type MutationTrigger<TArgs> = (args: TArgs) => {mutationId: string; id: string};
|
|
24
|
+
|
|
25
|
+
export interface CollectionHooks<TData, TCreate, TUpdate> {
|
|
26
|
+
/** List query (RTK: useGet{Path}Query). */
|
|
27
|
+
useListQuery: (options?: UseQueryOptions<TData>) => {data: TData[]};
|
|
28
|
+
/** Single-entity read (RTK: useGet{Path}ByIdQuery). */
|
|
29
|
+
useReadQuery: (id: string) => UseEntityResult<TData>;
|
|
30
|
+
/** Create (RTK: usePost{Path}Mutation). Optional `id` pins the client-minted entity id. */
|
|
31
|
+
useCreateMutation: () => [MutationTrigger<{data: TCreate; id?: string}>];
|
|
32
|
+
/** Update via merge — patch semantics (RTK: usePatch{Path}ByIdMutation). */
|
|
33
|
+
useUpdateMutation: () => [MutationTrigger<{id: string; data: TUpdate}>];
|
|
34
|
+
/** Soft delete (RTK: useDelete{Path}ByIdMutation). */
|
|
35
|
+
useDeleteMutation: () => [MutationTrigger<{id: string}>];
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export const createCollectionHooks = <
|
|
39
|
+
TData = Record<string, unknown>,
|
|
40
|
+
TCreate = Record<string, unknown>,
|
|
41
|
+
TUpdate = Partial<TCreate>,
|
|
42
|
+
>(
|
|
43
|
+
config: CollectionHooksConfig
|
|
44
|
+
): CollectionHooks<TData, TCreate, TUpdate> => {
|
|
45
|
+
const maxAttempts = retriesToMaxAttempts(config.retries);
|
|
46
|
+
|
|
47
|
+
const useListQuery = (options?: UseQueryOptions<TData>): {data: TData[]} => {
|
|
48
|
+
const data = useQuery<TData>(config.collection, options);
|
|
49
|
+
return {data};
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
const useReadQuery = (id: string): UseEntityResult<TData> =>
|
|
53
|
+
useEntity<TData>(config.collection, id);
|
|
54
|
+
|
|
55
|
+
const useCreateMutation = (): [MutationTrigger<{data: TCreate; id?: string}>] => {
|
|
56
|
+
const {create} = useMutate(config.collection);
|
|
57
|
+
const trigger = useCallback(
|
|
58
|
+
(args: {data: TCreate; id?: string}): {mutationId: string; id: string} =>
|
|
59
|
+
create({
|
|
60
|
+
data: args.data as unknown as Record<string, unknown>,
|
|
61
|
+
...(args.id !== undefined ? {id: args.id} : {}),
|
|
62
|
+
...(maxAttempts !== undefined ? {maxAttempts} : {}),
|
|
63
|
+
}),
|
|
64
|
+
[create]
|
|
65
|
+
);
|
|
66
|
+
return useMemo(() => [trigger], [trigger]);
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
const useUpdateMutation = (): [MutationTrigger<{id: string; data: TUpdate}>] => {
|
|
70
|
+
const {update} = useMutate(config.collection);
|
|
71
|
+
const trigger = useCallback(
|
|
72
|
+
(args: {id: string; data: TUpdate}): {mutationId: string; id: string} =>
|
|
73
|
+
update({
|
|
74
|
+
data: args.data as unknown as Record<string, unknown>,
|
|
75
|
+
id: args.id,
|
|
76
|
+
...(maxAttempts !== undefined ? {maxAttempts} : {}),
|
|
77
|
+
}),
|
|
78
|
+
[maxAttempts, update]
|
|
79
|
+
);
|
|
80
|
+
return useMemo(() => [trigger], [trigger]);
|
|
81
|
+
};
|
|
82
|
+
|
|
83
|
+
const useDeleteMutation = (): [MutationTrigger<{id: string}>] => {
|
|
84
|
+
const {remove} = useMutate(config.collection);
|
|
85
|
+
const trigger = useCallback(
|
|
86
|
+
(args: {id: string}): {mutationId: string; id: string} =>
|
|
87
|
+
remove({
|
|
88
|
+
id: args.id,
|
|
89
|
+
...(maxAttempts !== undefined ? {maxAttempts} : {}),
|
|
90
|
+
}),
|
|
91
|
+
[maxAttempts, remove]
|
|
92
|
+
);
|
|
93
|
+
return useMemo(() => [trigger], [trigger]);
|
|
94
|
+
};
|
|
95
|
+
|
|
96
|
+
return {
|
|
97
|
+
useCreateMutation,
|
|
98
|
+
useDeleteMutation,
|
|
99
|
+
useListQuery,
|
|
100
|
+
useReadQuery,
|
|
101
|
+
useUpdateMutation,
|
|
102
|
+
};
|
|
103
|
+
};
|
package/src/react/hooks.test.tsx
CHANGED
|
@@ -113,10 +113,9 @@ describe("useEntity", () => {
|
|
|
113
113
|
|
|
114
114
|
it("re-renders on a local write and reports the pending flag", async () => {
|
|
115
115
|
const {client, transport, wrapper} = await setup();
|
|
116
|
-
//
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
});
|
|
116
|
+
// Never ack so the optimistic pending flag stays observable. Do not throw:
|
|
117
|
+
// an unhandled sendMutation rejection leaks into other files under bun test.
|
|
118
|
+
transport.setDefaultResponder(() => new Promise(() => {}));
|
|
120
119
|
const {result} = renderHook(() => useEntity<TodoData>("todos", "t1"), {wrapper});
|
|
121
120
|
expect(result.current.data).toBeUndefined();
|
|
122
121
|
|