@terreno/api 56.0.0-beta.2 → 57.0.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/dist/realtime/changeStreamWatcher.d.ts +1 -1
- package/dist/realtime/changeStreamWatcher.js +0 -2
- package/dist/sync/registry.d.ts +4 -4
- package/dist/sync/socketHandlers.d.ts +1 -1
- package/package.json +3 -3
- package/src/permissions.middleware.test.ts +73 -81
- package/src/plugins.test.ts +50 -29
- package/src/realtime/changeStreamWatcher.ts +1 -4
- package/src/sync/registry.ts +5 -7
- package/src/sync/socketHandlers.ts +1 -3
- package/src/sync/syncSeqPlugin.test.ts +446 -0
|
@@ -1,6 +1,4 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
-
// noExplicitAny: change stream and socket handlers use dynamic document shapes
|
|
3
|
-
// biome-ignore-all lint/suspicious/noExplicitAny: change stream and socket handlers use dynamic document shapes
|
|
4
2
|
var __assign = (this && this.__assign) || function () {
|
|
5
3
|
__assign = Object.assign || function(t) {
|
|
6
4
|
for (var s, i = 1, n = arguments.length; i < n; i++) {
|
package/dist/sync/registry.d.ts
CHANGED
|
@@ -16,7 +16,7 @@ export interface SyncRegistryEntry {
|
|
|
16
16
|
/** Sync configuration from modelRouter options */
|
|
17
17
|
config: SyncConfig;
|
|
18
18
|
/** Full modelRouter options (for responseHandler, permissions, etc.) */
|
|
19
|
-
options: ModelRouterOptions<
|
|
19
|
+
options: ModelRouterOptions<unknown>;
|
|
20
20
|
}
|
|
21
21
|
/**
|
|
22
22
|
* Enqueue an index-creation promise for `ensureSyncIndexes()` to await at startup. Used by
|
|
@@ -33,11 +33,11 @@ export declare const trackSyncIndexCreation: (promise: Promise<void>) => void;
|
|
|
33
33
|
* - `syncPlugin` is required so every write stamps a per-stream `_syncSeq`;
|
|
34
34
|
* - owner/tenant scope fields must exist on the schema.
|
|
35
35
|
*/
|
|
36
|
-
export declare const registerSync: ({ model, routePath, config, options, }: {
|
|
37
|
-
model: Model<
|
|
36
|
+
export declare const registerSync: <T>({ model, routePath, config, options, }: {
|
|
37
|
+
model: Model<T>;
|
|
38
38
|
routePath: string;
|
|
39
39
|
config: SyncConfig;
|
|
40
|
-
options: ModelRouterOptions<
|
|
40
|
+
options: ModelRouterOptions<T>;
|
|
41
41
|
}) => void;
|
|
42
42
|
/**
|
|
43
43
|
* C8: await every enqueued sync index creation — per-model snapshot indexes from
|
|
@@ -40,7 +40,7 @@ export interface SyncSocketLike extends SocketWithDecodedToken {
|
|
|
40
40
|
join: (room: string) => Promise<void> | void;
|
|
41
41
|
leave: (room: string) => Promise<void> | void;
|
|
42
42
|
emit: (event: string, payload: unknown) => void;
|
|
43
|
-
on: (event: string, handler: (...args:
|
|
43
|
+
on: (event: string, handler: (...args: never[]) => void | Promise<void>) => void;
|
|
44
44
|
}
|
|
45
45
|
/**
|
|
46
46
|
* Install the sync socket handlers on a single socket. Wired into RealtimeApp's
|
package/package.json
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
"@asteasolutions/zod-to-openapi": "^8.5.0",
|
|
8
8
|
"@sentry/bun": "^10.39.0",
|
|
9
9
|
"@sentry/profiling-node": "^10.25.0",
|
|
10
|
-
"@terreno/test": "
|
|
10
|
+
"@terreno/test": "57.0.0",
|
|
11
11
|
"@types/qs": "^6.14.0",
|
|
12
12
|
"ajv": "8.20.0",
|
|
13
13
|
"ajv-formats": "^3.0.1",
|
|
@@ -47,7 +47,7 @@
|
|
|
47
47
|
"description": "Styled after the Django & Django REST Framework, a batteries-include framework for building REST APIs with Node/Express/Mongoose.",
|
|
48
48
|
"devDependencies": {
|
|
49
49
|
"@biomejs/biome": "^2.3.6",
|
|
50
|
-
"@terreno/syncdb": "
|
|
50
|
+
"@terreno/syncdb": "57.0.0",
|
|
51
51
|
"@types/bcrypt": "^6.0.0",
|
|
52
52
|
"@types/bun": "^1.3.8",
|
|
53
53
|
"@types/cors": "^2.8.17",
|
|
@@ -123,5 +123,5 @@
|
|
|
123
123
|
"updateSnapshot": "bun test --update-snapshots"
|
|
124
124
|
},
|
|
125
125
|
"types": "dist/index.d.ts",
|
|
126
|
-
"version": "
|
|
126
|
+
"version": "57.0.0"
|
|
127
127
|
}
|
|
@@ -1,11 +1,17 @@
|
|
|
1
|
-
// noExplicitAny: test mock typing
|
|
2
|
-
// biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
|
|
3
1
|
import {describe, expect, it, mock} from "bun:test";
|
|
4
2
|
import type express from "express";
|
|
3
|
+
import type {Model} from "mongoose";
|
|
5
4
|
|
|
6
5
|
import {APIError} from "./errors";
|
|
7
6
|
import {Permissions, permissionMiddleware} from "./permissions";
|
|
8
7
|
|
|
8
|
+
interface MockDoc {
|
|
9
|
+
archived?: boolean;
|
|
10
|
+
deleted?: boolean;
|
|
11
|
+
disabled?: boolean;
|
|
12
|
+
foo?: string;
|
|
13
|
+
}
|
|
14
|
+
|
|
9
15
|
describe("permissionMiddleware", () => {
|
|
10
16
|
const allPermissions = {
|
|
11
17
|
create: [Permissions.IsAny],
|
|
@@ -24,171 +30,157 @@ describe("permissionMiddleware", () => {
|
|
|
24
30
|
} as unknown as express.Request;
|
|
25
31
|
};
|
|
26
32
|
|
|
27
|
-
|
|
33
|
+
const buildModel = ({
|
|
34
|
+
exec = mock(async (): Promise<MockDoc | null> => null),
|
|
35
|
+
hiddenDoc = null,
|
|
36
|
+
}: {
|
|
37
|
+
exec?: () => Promise<MockDoc | null>;
|
|
38
|
+
hiddenDoc?: MockDoc | null;
|
|
39
|
+
} = {}) => {
|
|
28
40
|
const model = {
|
|
29
|
-
collection: {findOne: mock(async () =>
|
|
30
|
-
findById: mock(() => ({exec
|
|
41
|
+
collection: {findOne: mock(async () => hiddenDoc)},
|
|
42
|
+
findById: mock(() => ({exec})),
|
|
31
43
|
modelName: "MockModel",
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
|
|
44
|
+
};
|
|
45
|
+
return {model, modelAsMongoose: model as unknown as Model<MockDoc>};
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
const buildNext = () => mock((_error?: unknown) => {});
|
|
49
|
+
|
|
50
|
+
const firstError = (next: ReturnType<typeof buildNext>): APIError => {
|
|
51
|
+
const [error] = next.mock.calls[0];
|
|
52
|
+
if (!(error instanceof APIError)) {
|
|
53
|
+
throw new Error(`Expected next to be called with an APIError, got ${String(error)}`);
|
|
54
|
+
}
|
|
55
|
+
return error;
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
it("calls next immediately for OPTIONS requests", async () => {
|
|
59
|
+
const {model, modelAsMongoose} = buildModel();
|
|
60
|
+
const middleware = permissionMiddleware(modelAsMongoose, {permissions: allPermissions});
|
|
61
|
+
const next = buildNext();
|
|
35
62
|
|
|
36
|
-
await middleware(buildReq({method: "OPTIONS"}), {} as express.Response, next
|
|
63
|
+
await middleware(buildReq({method: "OPTIONS"}), {} as express.Response, next);
|
|
37
64
|
|
|
38
65
|
expect(next).toHaveBeenCalledTimes(1);
|
|
39
|
-
expect(
|
|
66
|
+
expect(next.mock.calls[0]).toEqual([]);
|
|
40
67
|
expect(model.findById).toHaveBeenCalledTimes(0);
|
|
41
68
|
});
|
|
42
69
|
|
|
43
70
|
it("returns APIError for unsupported HTTP methods", async () => {
|
|
44
|
-
const
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
modelName: "MockModel",
|
|
48
|
-
} as any;
|
|
49
|
-
const middleware = permissionMiddleware(model, {permissions: allPermissions});
|
|
50
|
-
const next = mock(() => {});
|
|
71
|
+
const {modelAsMongoose} = buildModel();
|
|
72
|
+
const middleware = permissionMiddleware(modelAsMongoose, {permissions: allPermissions});
|
|
73
|
+
const next = buildNext();
|
|
51
74
|
|
|
52
|
-
await middleware(buildReq({method: "TRACE"}), {} as express.Response, next
|
|
75
|
+
await middleware(buildReq({method: "TRACE"}), {} as express.Response, next);
|
|
53
76
|
|
|
54
77
|
expect(next).toHaveBeenCalledTimes(1);
|
|
55
|
-
const
|
|
56
|
-
expect(error).toBeInstanceOf(APIError);
|
|
78
|
+
const error = firstError(next);
|
|
57
79
|
expect(error.status).toBe(405);
|
|
58
80
|
expect(error.title).toContain("Method TRACE not allowed");
|
|
59
81
|
});
|
|
60
82
|
|
|
61
83
|
it("wraps query execution failures in a 500 APIError", async () => {
|
|
62
|
-
const exec = mock(async () => {
|
|
84
|
+
const exec = mock(async (): Promise<MockDoc | null> => {
|
|
63
85
|
throw new Error("query failed");
|
|
64
86
|
});
|
|
65
|
-
const
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
modelName: "MockModel",
|
|
69
|
-
} as any;
|
|
70
|
-
const middleware = permissionMiddleware(model, {permissions: allPermissions});
|
|
71
|
-
const next = mock(() => {});
|
|
87
|
+
const {modelAsMongoose} = buildModel({exec});
|
|
88
|
+
const middleware = permissionMiddleware(modelAsMongoose, {permissions: allPermissions});
|
|
89
|
+
const next = buildNext();
|
|
72
90
|
|
|
73
91
|
await middleware(
|
|
74
92
|
buildReq({method: "GET", params: {id: "507f1f77bcf86cd799439011"}}),
|
|
75
93
|
{} as express.Response,
|
|
76
|
-
next
|
|
94
|
+
next
|
|
77
95
|
);
|
|
78
96
|
|
|
79
97
|
expect(exec).toHaveBeenCalledTimes(1);
|
|
80
|
-
const
|
|
81
|
-
expect(error).toBeInstanceOf(APIError);
|
|
98
|
+
const error = firstError(next);
|
|
82
99
|
expect(error.status).toBe(500);
|
|
83
100
|
expect(error.title).toBe("GET error");
|
|
84
101
|
expect(error.detail).toContain("GET failed on 507f1f77bcf86cd799439011");
|
|
85
102
|
});
|
|
86
103
|
|
|
87
104
|
it("returns plain not found when document does not exist", async () => {
|
|
88
|
-
const
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
modelName: "MockModel",
|
|
92
|
-
} as any;
|
|
93
|
-
const middleware = permissionMiddleware(model, {permissions: allPermissions});
|
|
94
|
-
const next = mock(() => {});
|
|
105
|
+
const {modelAsMongoose} = buildModel();
|
|
106
|
+
const middleware = permissionMiddleware(modelAsMongoose, {permissions: allPermissions});
|
|
107
|
+
const next = buildNext();
|
|
95
108
|
|
|
96
109
|
await middleware(
|
|
97
110
|
buildReq({method: "GET", params: {id: "507f1f77bcf86cd799439011"}}),
|
|
98
111
|
{} as express.Response,
|
|
99
|
-
next
|
|
112
|
+
next
|
|
100
113
|
);
|
|
101
114
|
|
|
102
|
-
const
|
|
103
|
-
expect(error).toBeInstanceOf(APIError);
|
|
115
|
+
const error = firstError(next);
|
|
104
116
|
expect(error.status).toBe(404);
|
|
105
117
|
expect(error.title).toBe("Document not found");
|
|
106
118
|
expect(error.detail).toContain("507f1f77bcf86cd799439011");
|
|
107
119
|
});
|
|
108
120
|
|
|
109
121
|
it("returns hidden reason metadata when document is deleted", async () => {
|
|
110
|
-
const
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
modelName: "MockModel",
|
|
114
|
-
} as any;
|
|
115
|
-
const middleware = permissionMiddleware(model, {permissions: allPermissions});
|
|
116
|
-
const next = mock(() => {});
|
|
122
|
+
const {modelAsMongoose} = buildModel({hiddenDoc: {deleted: true}});
|
|
123
|
+
const middleware = permissionMiddleware(modelAsMongoose, {permissions: allPermissions});
|
|
124
|
+
const next = buildNext();
|
|
117
125
|
|
|
118
126
|
await middleware(
|
|
119
127
|
buildReq({method: "GET", params: {id: "507f1f77bcf86cd799439011"}}),
|
|
120
128
|
{} as express.Response,
|
|
121
|
-
next
|
|
129
|
+
next
|
|
122
130
|
);
|
|
123
131
|
|
|
124
|
-
const
|
|
125
|
-
expect(error).toBeInstanceOf(APIError);
|
|
132
|
+
const error = firstError(next);
|
|
126
133
|
expect(error.status).toBe(404);
|
|
127
134
|
expect(error.meta).toEqual({deleted: "true"});
|
|
128
135
|
expect(error.disableExternalErrorTracking).toBe(true);
|
|
129
136
|
});
|
|
130
137
|
|
|
131
138
|
it("returns hidden reason metadata when document is disabled", async () => {
|
|
132
|
-
const
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
modelName: "MockModel",
|
|
136
|
-
} as any;
|
|
137
|
-
const middleware = permissionMiddleware(model, {permissions: allPermissions});
|
|
138
|
-
const next = mock(() => {});
|
|
139
|
+
const {modelAsMongoose} = buildModel({hiddenDoc: {disabled: true}});
|
|
140
|
+
const middleware = permissionMiddleware(modelAsMongoose, {permissions: allPermissions});
|
|
141
|
+
const next = buildNext();
|
|
139
142
|
|
|
140
143
|
await middleware(
|
|
141
144
|
buildReq({method: "GET", params: {id: "507f1f77bcf86cd799439011"}}),
|
|
142
145
|
{} as express.Response,
|
|
143
|
-
next
|
|
146
|
+
next
|
|
144
147
|
);
|
|
145
148
|
|
|
146
|
-
const
|
|
147
|
-
expect(error).toBeInstanceOf(APIError);
|
|
149
|
+
const error = firstError(next);
|
|
148
150
|
expect(error.status).toBe(404);
|
|
149
151
|
expect(error.meta).toEqual({disabled: "true"});
|
|
150
152
|
expect(error.disableExternalErrorTracking).toBe(true);
|
|
151
153
|
});
|
|
152
154
|
|
|
153
155
|
it("returns hidden reason metadata when document is archived", async () => {
|
|
154
|
-
const
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
modelName: "MockModel",
|
|
158
|
-
} as any;
|
|
159
|
-
const middleware = permissionMiddleware(model, {permissions: allPermissions});
|
|
160
|
-
const next = mock(() => {});
|
|
156
|
+
const {modelAsMongoose} = buildModel({hiddenDoc: {archived: true}});
|
|
157
|
+
const middleware = permissionMiddleware(modelAsMongoose, {permissions: allPermissions});
|
|
158
|
+
const next = buildNext();
|
|
161
159
|
|
|
162
160
|
await middleware(
|
|
163
161
|
buildReq({method: "GET", params: {id: "507f1f77bcf86cd799439011"}}),
|
|
164
162
|
{} as express.Response,
|
|
165
|
-
next
|
|
163
|
+
next
|
|
166
164
|
);
|
|
167
165
|
|
|
168
|
-
const
|
|
169
|
-
expect(error).toBeInstanceOf(APIError);
|
|
166
|
+
const error = firstError(next);
|
|
170
167
|
expect(error.status).toBe(404);
|
|
171
168
|
expect(error.meta).toEqual({archived: "true"});
|
|
172
169
|
expect(error.disableExternalErrorTracking).toBe(true);
|
|
173
170
|
});
|
|
174
171
|
|
|
175
172
|
it("returns plain not found when hidden document has no reason", async () => {
|
|
176
|
-
const
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
modelName: "MockModel",
|
|
180
|
-
} as any;
|
|
181
|
-
const middleware = permissionMiddleware(model, {permissions: allPermissions});
|
|
182
|
-
const next = mock(() => {});
|
|
173
|
+
const {modelAsMongoose} = buildModel({hiddenDoc: {foo: "bar"}});
|
|
174
|
+
const middleware = permissionMiddleware(modelAsMongoose, {permissions: allPermissions});
|
|
175
|
+
const next = buildNext();
|
|
183
176
|
|
|
184
177
|
await middleware(
|
|
185
178
|
buildReq({method: "GET", params: {id: "507f1f77bcf86cd799439011"}}),
|
|
186
179
|
{} as express.Response,
|
|
187
|
-
next
|
|
180
|
+
next
|
|
188
181
|
);
|
|
189
182
|
|
|
190
|
-
const
|
|
191
|
-
expect(error).toBeInstanceOf(APIError);
|
|
183
|
+
const error = firstError(next);
|
|
192
184
|
expect(error.status).toBe(404);
|
|
193
185
|
expect(error.title).toBe("Document not found");
|
|
194
186
|
});
|
package/src/plugins.test.ts
CHANGED
|
@@ -1,13 +1,18 @@
|
|
|
1
|
-
// noExplicitAny: test mock typing
|
|
2
|
-
// biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
|
|
3
1
|
import {beforeEach, describe, expect, it, setSystemTime} from "bun:test";
|
|
4
2
|
import {assert} from "chai";
|
|
5
3
|
import type express from "express";
|
|
6
|
-
import {
|
|
4
|
+
import {
|
|
5
|
+
type DateSchemaDefinition,
|
|
6
|
+
type Document,
|
|
7
|
+
type HydratedDocument,
|
|
8
|
+
type Model,
|
|
9
|
+
model,
|
|
10
|
+
Schema,
|
|
11
|
+
} from "mongoose";
|
|
7
12
|
import supertest from "supertest";
|
|
8
13
|
import type TestAgent from "supertest/lib/agent";
|
|
9
14
|
import {modelRouter} from "./api";
|
|
10
|
-
import {addAuthRoutes, setupAuth} from "./auth";
|
|
15
|
+
import {type UserModel as AuthUserModel, addAuthRoutes, setupAuth} from "./auth";
|
|
11
16
|
import {type APIErrorConstructor, InternalServerError, isAPIError, NotFoundError} from "./errors";
|
|
12
17
|
import {Permissions} from "./permissions";
|
|
13
18
|
import {
|
|
@@ -37,17 +42,31 @@ interface Stuff extends IsDeleted {
|
|
|
37
42
|
|
|
38
43
|
interface StuffModelType extends Model<Stuff> {
|
|
39
44
|
findOneOrNone(
|
|
40
|
-
query: Record<string,
|
|
45
|
+
query: Record<string, unknown>,
|
|
41
46
|
errorArgs?: Partial<APIErrorConstructor>
|
|
42
47
|
): Promise<(Document & Stuff) | null>;
|
|
43
48
|
findExactlyOne(
|
|
44
|
-
query: Record<string,
|
|
49
|
+
query: Record<string, unknown>,
|
|
45
50
|
errorArgs?: Partial<APIErrorConstructor>
|
|
46
51
|
): Promise<Document & Stuff>;
|
|
52
|
+
upsert(
|
|
53
|
+
conditions: Record<string, unknown>,
|
|
54
|
+
update: Record<string, unknown>
|
|
55
|
+
): Promise<Document & Stuff>;
|
|
47
56
|
}
|
|
48
57
|
|
|
58
|
+
const expectApiError = (error: unknown) => {
|
|
59
|
+
if (!isAPIError(error)) {
|
|
60
|
+
throw error;
|
|
61
|
+
}
|
|
62
|
+
return error;
|
|
63
|
+
};
|
|
64
|
+
|
|
49
65
|
const stuffSchema = new Schema<Stuff>({
|
|
50
|
-
date: {
|
|
66
|
+
date: {
|
|
67
|
+
description: "The date associated with this item",
|
|
68
|
+
type: DateOnly as unknown as DateSchemaDefinition,
|
|
69
|
+
},
|
|
51
70
|
name: {description: "The name of the item", type: String},
|
|
52
71
|
ownerId: {description: "The user who owns this item", type: String},
|
|
53
72
|
});
|
|
@@ -63,7 +82,7 @@ const StuffModel = model<Stuff>("Stuff", stuffSchema) as unknown as StuffModelTy
|
|
|
63
82
|
describe("baseUserPlugin", () => {
|
|
64
83
|
it("adds admin and email fields to the schema", () => {
|
|
65
84
|
const testSchema = new Schema({});
|
|
66
|
-
baseUserPlugin(testSchema
|
|
85
|
+
baseUserPlugin(testSchema);
|
|
67
86
|
|
|
68
87
|
const adminPath = testSchema.path("admin");
|
|
69
88
|
expect(adminPath).toBeDefined();
|
|
@@ -142,7 +161,7 @@ describe("isDeleted", () => {
|
|
|
142
161
|
});
|
|
143
162
|
|
|
144
163
|
describe("findOneOrNone", () => {
|
|
145
|
-
let things:
|
|
164
|
+
let things: HydratedDocument<Stuff>;
|
|
146
165
|
|
|
147
166
|
beforeEach(async () => {
|
|
148
167
|
await StuffModel.deleteMany({});
|
|
@@ -183,8 +202,8 @@ describe("findOneOrNone", () => {
|
|
|
183
202
|
await fn();
|
|
184
203
|
// If the promise doesn't reject, the test should fail
|
|
185
204
|
throw new Error("Expected promise to reject");
|
|
186
|
-
} catch (
|
|
187
|
-
|
|
205
|
+
} catch (caught: unknown) {
|
|
206
|
+
const error = expectApiError(caught);
|
|
188
207
|
expect(error.title).toBe("Oh no!");
|
|
189
208
|
expect(error.status).toBe(400);
|
|
190
209
|
expect(error.detail).toBe(
|
|
@@ -215,7 +234,7 @@ describe("findOneOrNoneFor", () => {
|
|
|
215
234
|
});
|
|
216
235
|
|
|
217
236
|
describe("when the schema has the findOneOrNone plugin", () => {
|
|
218
|
-
let things:
|
|
237
|
+
let things: HydratedDocument<Stuff>;
|
|
219
238
|
|
|
220
239
|
beforeEach(async () => {
|
|
221
240
|
[things] = await Promise.all([
|
|
@@ -247,7 +266,8 @@ describe("findOneOrNoneFor", () => {
|
|
|
247
266
|
try {
|
|
248
267
|
await fn();
|
|
249
268
|
throw new Error("Expected promise to reject");
|
|
250
|
-
} catch (
|
|
269
|
+
} catch (caught: unknown) {
|
|
270
|
+
const error = expectApiError(caught);
|
|
251
271
|
expect(error.title).toBe("Oh no!");
|
|
252
272
|
expect(error.status).toBe(400);
|
|
253
273
|
}
|
|
@@ -255,7 +275,7 @@ describe("findOneOrNoneFor", () => {
|
|
|
255
275
|
});
|
|
256
276
|
|
|
257
277
|
describe("when the schema does NOT have the findOneOrNone plugin", () => {
|
|
258
|
-
let bareThings:
|
|
278
|
+
let bareThings: HydratedDocument<BareThing>;
|
|
259
279
|
|
|
260
280
|
beforeEach(async () => {
|
|
261
281
|
[bareThings] = await Promise.all([
|
|
@@ -272,7 +292,7 @@ describe("findOneOrNoneFor", () => {
|
|
|
272
292
|
it("returns a single match", async () => {
|
|
273
293
|
const result = await findOneOrNoneFor(BareThingModel, {name: "Things"});
|
|
274
294
|
expect(result).not.toBeNull();
|
|
275
|
-
expect(
|
|
295
|
+
expect(result?._id?.toString()).toBe(bareThings._id?.toString());
|
|
276
296
|
});
|
|
277
297
|
|
|
278
298
|
it("throws when multiple documents match", async () => {
|
|
@@ -287,7 +307,8 @@ describe("findOneOrNoneFor", () => {
|
|
|
287
307
|
try {
|
|
288
308
|
await fn();
|
|
289
309
|
throw new Error("Expected promise to reject");
|
|
290
|
-
} catch (
|
|
310
|
+
} catch (caught: unknown) {
|
|
311
|
+
const error = expectApiError(caught);
|
|
291
312
|
expect(error.title).toBe("Oh no!");
|
|
292
313
|
expect(error.status).toBe(400);
|
|
293
314
|
}
|
|
@@ -296,7 +317,7 @@ describe("findOneOrNoneFor", () => {
|
|
|
296
317
|
});
|
|
297
318
|
|
|
298
319
|
describe("findExactlyOne", () => {
|
|
299
|
-
let things:
|
|
320
|
+
let things: HydratedDocument<Stuff>;
|
|
300
321
|
|
|
301
322
|
beforeEach(async () => {
|
|
302
323
|
await StuffModel.deleteMany({});
|
|
@@ -354,8 +375,8 @@ describe("findExactlyOne", () => {
|
|
|
354
375
|
await fn();
|
|
355
376
|
// If the promise doesn't reject, the test should fail
|
|
356
377
|
throw new Error("Expected promise to reject");
|
|
357
|
-
} catch (
|
|
358
|
-
|
|
378
|
+
} catch (caught: unknown) {
|
|
379
|
+
const error = expectApiError(caught);
|
|
359
380
|
expect(error.title).toBe("Oh no!");
|
|
360
381
|
expect(error.status).toBe(400);
|
|
361
382
|
expect(error.detail).toBe(
|
|
@@ -373,7 +394,7 @@ describe("upsertPlugin", () => {
|
|
|
373
394
|
});
|
|
374
395
|
|
|
375
396
|
it("creates a new document when none exists", async () => {
|
|
376
|
-
const result = await
|
|
397
|
+
const result = await StuffModel.upsert({name: "NewThing"}, {ownerId: "456"});
|
|
377
398
|
expect(result.name).toBe("NewThing");
|
|
378
399
|
expect(result.ownerId).toBe("456");
|
|
379
400
|
|
|
@@ -388,7 +409,7 @@ describe("upsertPlugin", () => {
|
|
|
388
409
|
ownerId: "123",
|
|
389
410
|
});
|
|
390
411
|
|
|
391
|
-
const result = await
|
|
412
|
+
const result = await StuffModel.upsert({name: "ExistingThing"}, {ownerId: "789"});
|
|
392
413
|
|
|
393
414
|
expect(result._id.toString()).toBe(initial._id.toString());
|
|
394
415
|
expect(result.ownerId).toBe("789");
|
|
@@ -404,7 +425,7 @@ describe("upsertPlugin", () => {
|
|
|
404
425
|
StuffModel.create({name: "Thing2", ownerId: "123"}),
|
|
405
426
|
]);
|
|
406
427
|
|
|
407
|
-
const fn = () =>
|
|
428
|
+
const fn = () => StuffModel.upsert({ownerId: "123"}, {name: "Updated"});
|
|
408
429
|
await expect(fn()).rejects.toThrow(/^upsert find query returned multiple documents$/);
|
|
409
430
|
try {
|
|
410
431
|
await fn();
|
|
@@ -421,7 +442,7 @@ describe("upsertPlugin", () => {
|
|
|
421
442
|
});
|
|
422
443
|
|
|
423
444
|
it("combines conditions and update data for new documents", async () => {
|
|
424
|
-
const result = await
|
|
445
|
+
const result = await StuffModel.upsert({name: "TestCondition"}, {ownerId: "999"});
|
|
425
446
|
|
|
426
447
|
expect(result.name).toBe("TestCondition");
|
|
427
448
|
expect(result.ownerId).toBe("999");
|
|
@@ -491,7 +512,7 @@ describe("excludeArchivedPlugin", () => {
|
|
|
491
512
|
});
|
|
492
513
|
|
|
493
514
|
describe("TypeScript return types", () => {
|
|
494
|
-
let _things:
|
|
515
|
+
let _things: HydratedDocument<Stuff>;
|
|
495
516
|
|
|
496
517
|
beforeEach(async () => {
|
|
497
518
|
await StuffModel.deleteMany({});
|
|
@@ -550,12 +571,12 @@ describe("DateOnly", () => {
|
|
|
550
571
|
it("throws error with invalid date", async () => {
|
|
551
572
|
try {
|
|
552
573
|
await StuffModel.create({
|
|
553
|
-
date: "foo" as
|
|
574
|
+
date: "foo" as unknown as Date,
|
|
554
575
|
name: "Things",
|
|
555
576
|
ownerId: "123",
|
|
556
577
|
});
|
|
557
|
-
} catch (error:
|
|
558
|
-
expect(error.message).toMatch(/Cast to DateOnly failed/);
|
|
578
|
+
} catch (error: unknown) {
|
|
579
|
+
expect((error as Error).message).toMatch(/Cast to DateOnly failed/);
|
|
559
580
|
return;
|
|
560
581
|
}
|
|
561
582
|
throw new Error("Expected error was not thrown");
|
|
@@ -599,8 +620,8 @@ describe("DateOnly", () => {
|
|
|
599
620
|
beforeEach(async () => {
|
|
600
621
|
await setupDb();
|
|
601
622
|
app = getBaseServer();
|
|
602
|
-
setupAuth(app, UserModel as
|
|
603
|
-
addAuthRoutes(app, UserModel as
|
|
623
|
+
setupAuth(app, UserModel as unknown as AuthUserModel);
|
|
624
|
+
addAuthRoutes(app, UserModel as unknown as AuthUserModel);
|
|
604
625
|
app.use(
|
|
605
626
|
"/stuff",
|
|
606
627
|
modelRouter(StuffModel, {
|
|
@@ -1,6 +1,3 @@
|
|
|
1
|
-
// noExplicitAny: change stream and socket handlers use dynamic document shapes
|
|
2
|
-
// biome-ignore-all lint/suspicious/noExplicitAny: change stream and socket handlers use dynamic document shapes
|
|
3
|
-
|
|
4
1
|
import * as Sentry from "@sentry/bun";
|
|
5
2
|
import type express from "express";
|
|
6
3
|
import {DateTime} from "luxon";
|
|
@@ -195,7 +192,7 @@ const getSocketsInRoom = (io: Server, room: string): RealtimeSocketWithAuth[] =>
|
|
|
195
192
|
*/
|
|
196
193
|
export interface AuthorizedEmitEntry {
|
|
197
194
|
modelName: string;
|
|
198
|
-
options: {permissions: {read: PermissionMethod<
|
|
195
|
+
options: {permissions: {read: PermissionMethod<unknown>[]}};
|
|
199
196
|
}
|
|
200
197
|
|
|
201
198
|
const canReadDocument = async (
|
package/src/sync/registry.ts
CHANGED
|
@@ -1,5 +1,3 @@
|
|
|
1
|
-
// noExplicitAny: model router options are generic across all models
|
|
2
|
-
// biome-ignore-all lint/suspicious/noExplicitAny: model router options are generic across all models
|
|
3
1
|
import type {Model} from "mongoose";
|
|
4
2
|
import type {ModelRouterOptions} from "../api";
|
|
5
3
|
import {logger} from "../logger";
|
|
@@ -21,7 +19,7 @@ export interface SyncRegistryEntry {
|
|
|
21
19
|
/** Sync configuration from modelRouter options */
|
|
22
20
|
config: SyncConfig;
|
|
23
21
|
/** Full modelRouter options (for responseHandler, permissions, etc.) */
|
|
24
|
-
options: ModelRouterOptions<
|
|
22
|
+
options: ModelRouterOptions<unknown>;
|
|
25
23
|
}
|
|
26
24
|
|
|
27
25
|
const syncRegistry: SyncRegistryEntry[] = [];
|
|
@@ -57,16 +55,16 @@ export const trackSyncIndexCreation = (promise: Promise<void>): void => {
|
|
|
57
55
|
* - `syncPlugin` is required so every write stamps a per-stream `_syncSeq`;
|
|
58
56
|
* - owner/tenant scope fields must exist on the schema.
|
|
59
57
|
*/
|
|
60
|
-
export const registerSync = ({
|
|
58
|
+
export const registerSync = <T>({
|
|
61
59
|
model,
|
|
62
60
|
routePath,
|
|
63
61
|
config,
|
|
64
62
|
options,
|
|
65
63
|
}: {
|
|
66
|
-
model: Model<
|
|
64
|
+
model: Model<T>;
|
|
67
65
|
routePath: string;
|
|
68
66
|
config: SyncConfig;
|
|
69
|
-
options: ModelRouterOptions<
|
|
67
|
+
options: ModelRouterOptions<T>;
|
|
70
68
|
}): void => {
|
|
71
69
|
const name = model.modelName;
|
|
72
70
|
const deletedPath = model.schema.path("deleted");
|
|
@@ -112,7 +110,7 @@ export const registerSync = ({
|
|
|
112
110
|
collectionTag,
|
|
113
111
|
config,
|
|
114
112
|
modelName: name,
|
|
115
|
-
options
|
|
113
|
+
options: options as unknown as ModelRouterOptions<unknown>,
|
|
116
114
|
routePath,
|
|
117
115
|
});
|
|
118
116
|
|
|
@@ -1,5 +1,3 @@
|
|
|
1
|
-
// noExplicitAny: Socket.io handler signatures require dynamic args
|
|
2
|
-
// biome-ignore-all lint/suspicious/noExplicitAny: Socket.io handler signatures require dynamic args
|
|
3
1
|
import type {Server} from "socket.io";
|
|
4
2
|
|
|
5
3
|
import type {User} from "../auth";
|
|
@@ -61,7 +59,7 @@ export interface SyncSocketLike extends SocketWithDecodedToken {
|
|
|
61
59
|
join: (room: string) => Promise<void> | void;
|
|
62
60
|
leave: (room: string) => Promise<void> | void;
|
|
63
61
|
emit: (event: string, payload: unknown) => void;
|
|
64
|
-
on: (event: string, handler: (...args:
|
|
62
|
+
on: (event: string, handler: (...args: never[]) => void | Promise<void>) => void;
|
|
65
63
|
}
|
|
66
64
|
|
|
67
65
|
/**
|
|
@@ -0,0 +1,446 @@
|
|
|
1
|
+
import {beforeAll, beforeEach, describe, expect, it} from "bun:test";
|
|
2
|
+
import {type Model, model, Schema} from "mongoose";
|
|
3
|
+
import type {ModelRouterOptions} from "../api";
|
|
4
|
+
import {createdUpdatedPlugin, type IsDeleted, isDeletedPlugin} from "../plugins";
|
|
5
|
+
import {setupDb} from "../tests";
|
|
6
|
+
import {SyncCounter, SyncScopeMove} from "./models";
|
|
7
|
+
import {clearSyncRegistry, registerSync} from "./registry";
|
|
8
|
+
import {syncPlugin} from "./syncSeqPlugin";
|
|
9
|
+
import type {SyncConfig} from "./types";
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Failure-path coverage for the `_syncSeq` plugin: the guards and recovery branches that
|
|
13
|
+
* the happy-path suites (sync.test, syncFrontier.test, syncPhaseC.test) never reach —
|
|
14
|
+
* schema contract violations, unregistered models, `$eq`/`$in` `_id` filters, confirm and
|
|
15
|
+
* release failures, reaped-claim re-stamping, and the non-tenant scope kinds
|
|
16
|
+
* (custom resolver / broadcast) on the query-write path.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
interface SeqTenantThing extends IsDeleted {
|
|
20
|
+
_id: string;
|
|
21
|
+
name: string;
|
|
22
|
+
orgId?: string;
|
|
23
|
+
_syncSeq?: number;
|
|
24
|
+
_syncPrevStream?: string | null;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
interface SeqCustomThing extends IsDeleted {
|
|
28
|
+
_id: string;
|
|
29
|
+
name: string;
|
|
30
|
+
workspaceId: string;
|
|
31
|
+
_syncSeq?: number;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
interface SeqBroadcastThing extends IsDeleted {
|
|
35
|
+
_id: string;
|
|
36
|
+
name: string;
|
|
37
|
+
_syncSeq?: number;
|
|
38
|
+
_syncPrevStream?: string | null;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const tenantSchema = new Schema<SeqTenantThing>({
|
|
42
|
+
name: {description: "The name of the thing", required: true, type: String},
|
|
43
|
+
orgId: {description: "The organization this thing belongs to", type: String},
|
|
44
|
+
});
|
|
45
|
+
tenantSchema.plugin(isDeletedPlugin);
|
|
46
|
+
tenantSchema.plugin(createdUpdatedPlugin);
|
|
47
|
+
tenantSchema.plugin(syncPlugin);
|
|
48
|
+
// Registered AFTER syncPlugin so the save fails once its seq is claimed and registered —
|
|
49
|
+
// the window the error middleware releases the claim in.
|
|
50
|
+
tenantSchema.pre("save", function () {
|
|
51
|
+
if (this.name === "kaboom") {
|
|
52
|
+
throw new Error("simulated post-claim save failure");
|
|
53
|
+
}
|
|
54
|
+
});
|
|
55
|
+
const TenantModel = model<SeqTenantThing>("SeqPluginTenantThing", tenantSchema);
|
|
56
|
+
|
|
57
|
+
const customSchema = new Schema<SeqCustomThing>({
|
|
58
|
+
name: {description: "The name of the thing", required: true, type: String},
|
|
59
|
+
workspaceId: {description: "The workspace this thing belongs to", required: true, type: String},
|
|
60
|
+
});
|
|
61
|
+
customSchema.plugin(isDeletedPlugin);
|
|
62
|
+
customSchema.plugin(createdUpdatedPlugin);
|
|
63
|
+
customSchema.plugin(syncPlugin);
|
|
64
|
+
const CustomModel = model<SeqCustomThing>("SeqPluginCustomThing", customSchema);
|
|
65
|
+
|
|
66
|
+
const broadcastSchema = new Schema<SeqBroadcastThing>({
|
|
67
|
+
name: {description: "The name of the thing", required: true, type: String},
|
|
68
|
+
});
|
|
69
|
+
broadcastSchema.plugin(isDeletedPlugin);
|
|
70
|
+
broadcastSchema.plugin(createdUpdatedPlugin);
|
|
71
|
+
broadcastSchema.plugin(syncPlugin);
|
|
72
|
+
const BroadcastModel = model<SeqBroadcastThing>("SeqPluginBroadcastThing", broadcastSchema);
|
|
73
|
+
|
|
74
|
+
/** Carries syncPlugin but is never registered: every hook must no-op on it. */
|
|
75
|
+
const unregisteredSchema = new Schema<SeqBroadcastThing>({
|
|
76
|
+
name: {description: "The name of the thing", required: true, type: String},
|
|
77
|
+
});
|
|
78
|
+
unregisteredSchema.plugin(isDeletedPlugin);
|
|
79
|
+
unregisteredSchema.plugin(createdUpdatedPlugin);
|
|
80
|
+
unregisteredSchema.plugin(syncPlugin);
|
|
81
|
+
const UnregisteredModel = model<SeqBroadcastThing>(
|
|
82
|
+
"SeqPluginUnregisteredThing",
|
|
83
|
+
unregisteredSchema
|
|
84
|
+
);
|
|
85
|
+
|
|
86
|
+
const stubOptions = {
|
|
87
|
+
permissions: {create: [], delete: [], list: [], read: [], update: []},
|
|
88
|
+
} as unknown as ModelRouterOptions<SeqTenantThing>;
|
|
89
|
+
|
|
90
|
+
const TENANT_TAG = "seqPluginTenantThings";
|
|
91
|
+
const CUSTOM_TAG = "seqPluginCustomThings";
|
|
92
|
+
const BROADCAST_TAG = "seqPluginBroadcastThings";
|
|
93
|
+
|
|
94
|
+
type LooseUpdateOne = (
|
|
95
|
+
filter: Record<string, unknown>,
|
|
96
|
+
update: Record<string, unknown>,
|
|
97
|
+
options?: Record<string, unknown>
|
|
98
|
+
) => Promise<{modifiedCount?: number}>;
|
|
99
|
+
|
|
100
|
+
type LooseFindOneAndUpdate = (
|
|
101
|
+
filter: Record<string, unknown>,
|
|
102
|
+
update: unknown,
|
|
103
|
+
options?: Record<string, unknown>
|
|
104
|
+
) => Promise<unknown>;
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Make the pending-claim `$pull` that `confirmSyncSeqs`/`releaseSyncSeqs` issue either
|
|
108
|
+
* throw or report "nothing cleared" (the reaped-lease signature), optionally only for one
|
|
109
|
+
* stream. Returns the restore function.
|
|
110
|
+
*/
|
|
111
|
+
const stubPendingPull = ({
|
|
112
|
+
behavior,
|
|
113
|
+
stream,
|
|
114
|
+
}: {
|
|
115
|
+
behavior: "throw" | "reaped";
|
|
116
|
+
stream?: string;
|
|
117
|
+
}): (() => void) => {
|
|
118
|
+
const original = SyncCounter.updateOne.bind(SyncCounter) as unknown as LooseUpdateOne;
|
|
119
|
+
const stub = (async (
|
|
120
|
+
filter: Record<string, unknown>,
|
|
121
|
+
update: Record<string, unknown>,
|
|
122
|
+
options?: Record<string, unknown>
|
|
123
|
+
) => {
|
|
124
|
+
const isPull = Boolean(update) && Object.hasOwn(update, "$pull");
|
|
125
|
+
if (isPull && (!stream || filter.stream === stream)) {
|
|
126
|
+
if (behavior === "throw") {
|
|
127
|
+
throw new Error("simulated pending-claim $pull failure");
|
|
128
|
+
}
|
|
129
|
+
const result = await original(filter, update, options);
|
|
130
|
+
return {...result, modifiedCount: 0};
|
|
131
|
+
}
|
|
132
|
+
return original(filter, update, options);
|
|
133
|
+
}) as unknown as typeof SyncCounter.updateOne;
|
|
134
|
+
Object.assign(SyncCounter, {updateOne: stub});
|
|
135
|
+
return () => {
|
|
136
|
+
Object.assign(SyncCounter, {updateOne: original});
|
|
137
|
+
};
|
|
138
|
+
};
|
|
139
|
+
|
|
140
|
+
/** Make a seq claim fail, optionally only for one stream. Returns the restore function. */
|
|
141
|
+
const stubClaimFailure = ({stream}: {stream?: string}): (() => void) => {
|
|
142
|
+
const original = SyncCounter.findOneAndUpdate.bind(
|
|
143
|
+
SyncCounter
|
|
144
|
+
) as unknown as LooseFindOneAndUpdate;
|
|
145
|
+
const stub = (async (
|
|
146
|
+
filter: Record<string, unknown>,
|
|
147
|
+
update: unknown,
|
|
148
|
+
options?: Record<string, unknown>
|
|
149
|
+
) => {
|
|
150
|
+
if (!stream || filter.stream === stream) {
|
|
151
|
+
throw new Error("simulated claim failure");
|
|
152
|
+
}
|
|
153
|
+
return original(filter, update, options);
|
|
154
|
+
}) as unknown as typeof SyncCounter.findOneAndUpdate;
|
|
155
|
+
Object.assign(SyncCounter, {findOneAndUpdate: stub});
|
|
156
|
+
return () => {
|
|
157
|
+
Object.assign(SyncCounter, {findOneAndUpdate: original});
|
|
158
|
+
};
|
|
159
|
+
};
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* Replace the raw-collection `updateOne` the reaped-claim re-stamp uses, so it can be made
|
|
163
|
+
* to match nothing or throw. Returns the restore function.
|
|
164
|
+
*/
|
|
165
|
+
const stubRawUpdateOne = <T>({
|
|
166
|
+
behavior,
|
|
167
|
+
model: target,
|
|
168
|
+
}: {
|
|
169
|
+
behavior: "noMatch" | "throw";
|
|
170
|
+
model: Model<T>;
|
|
171
|
+
}): (() => void) => {
|
|
172
|
+
const collection = target.collection;
|
|
173
|
+
const original = collection.updateOne.bind(collection) as unknown as LooseUpdateOne;
|
|
174
|
+
// Only the re-stamp writes `{$set: {_syncSeq}}` and nothing else; Mongoose's own
|
|
175
|
+
// `doc.save()` goes through the same collection method and must still land.
|
|
176
|
+
const isRestamp = (update: Record<string, unknown>): boolean => {
|
|
177
|
+
const set = update.$set;
|
|
178
|
+
if (Object.keys(update).length !== 1 || typeof set !== "object" || set === null) {
|
|
179
|
+
return false;
|
|
180
|
+
}
|
|
181
|
+
const keys = Object.keys(set);
|
|
182
|
+
return keys.length === 1 && keys[0] === "_syncSeq";
|
|
183
|
+
};
|
|
184
|
+
const stub = (async (
|
|
185
|
+
filter: Record<string, unknown>,
|
|
186
|
+
update: Record<string, unknown>,
|
|
187
|
+
options?: Record<string, unknown>
|
|
188
|
+
) => {
|
|
189
|
+
if (!isRestamp(update)) {
|
|
190
|
+
return original(filter, update, options);
|
|
191
|
+
}
|
|
192
|
+
if (behavior === "throw") {
|
|
193
|
+
throw new Error("simulated re-stamp failure");
|
|
194
|
+
}
|
|
195
|
+
return {matchedCount: 0, modifiedCount: 0};
|
|
196
|
+
}) as unknown as typeof collection.updateOne;
|
|
197
|
+
Object.assign(collection, {updateOne: stub});
|
|
198
|
+
return () => {
|
|
199
|
+
Object.assign(collection, {updateOne: original});
|
|
200
|
+
};
|
|
201
|
+
};
|
|
202
|
+
|
|
203
|
+
describe("syncPlugin schema contract", () => {
|
|
204
|
+
it("throws when the schema disabled its versionKey", () => {
|
|
205
|
+
const schema = new Schema(
|
|
206
|
+
{name: {description: "The name of the thing", type: String}},
|
|
207
|
+
{versionKey: false}
|
|
208
|
+
);
|
|
209
|
+
expect(() => schema.plugin(syncPlugin)).toThrow(/requires a versionKey/);
|
|
210
|
+
});
|
|
211
|
+
});
|
|
212
|
+
|
|
213
|
+
describe("syncPlugin on an unregistered model", () => {
|
|
214
|
+
beforeAll(async () => {
|
|
215
|
+
await setupDb();
|
|
216
|
+
clearSyncRegistry();
|
|
217
|
+
});
|
|
218
|
+
|
|
219
|
+
beforeEach(async () => {
|
|
220
|
+
await UnregisteredModel.collection.deleteMany({});
|
|
221
|
+
});
|
|
222
|
+
|
|
223
|
+
it("stamps nothing and blocks nothing: save, hydration, query-write and insertMany all no-op", async () => {
|
|
224
|
+
const doc = await UnregisteredModel.create({name: "unstamped"});
|
|
225
|
+
expect(doc._syncSeq).toBeUndefined();
|
|
226
|
+
// post("init") must bail out without resolving a stream for an unregistered model.
|
|
227
|
+
const hydrated = await UnregisteredModel.findById(doc._id);
|
|
228
|
+
expect(hydrated?._syncSeq).toBeUndefined();
|
|
229
|
+
// A non-_id query-write is only rejected for registered models.
|
|
230
|
+
await UnregisteredModel.updateOne({name: "unstamped"}, {$set: {name: "renamed"}});
|
|
231
|
+
expect((await UnregisteredModel.findById(doc._id))?.name).toBe("renamed");
|
|
232
|
+
const inserted = await UnregisteredModel.insertMany([{name: "a"}, {name: "b"}]);
|
|
233
|
+
expect(inserted).toHaveLength(2);
|
|
234
|
+
expect(inserted.every((entry) => entry._syncSeq === undefined)).toBe(true);
|
|
235
|
+
});
|
|
236
|
+
});
|
|
237
|
+
|
|
238
|
+
describe("syncPlugin write-path failure and recovery branches", () => {
|
|
239
|
+
beforeAll(async () => {
|
|
240
|
+
await setupDb();
|
|
241
|
+
await SyncCounter.ensureIndexes();
|
|
242
|
+
clearSyncRegistry();
|
|
243
|
+
registerSync({
|
|
244
|
+
config: {scope: {field: "orgId", type: "tenant"}} as SyncConfig,
|
|
245
|
+
model: TenantModel,
|
|
246
|
+
options: stubOptions,
|
|
247
|
+
routePath: `/${TENANT_TAG}`,
|
|
248
|
+
});
|
|
249
|
+
registerSync({
|
|
250
|
+
config: {
|
|
251
|
+
scope: (doc: Record<string, unknown>) => String(doc.workspaceId),
|
|
252
|
+
snapshotFilter: () => ({}),
|
|
253
|
+
} as SyncConfig,
|
|
254
|
+
model: CustomModel,
|
|
255
|
+
options: stubOptions,
|
|
256
|
+
routePath: `/${CUSTOM_TAG}`,
|
|
257
|
+
});
|
|
258
|
+
registerSync({
|
|
259
|
+
config: {scope: {type: "broadcast"}} as SyncConfig,
|
|
260
|
+
model: BroadcastModel,
|
|
261
|
+
options: stubOptions,
|
|
262
|
+
routePath: `/${BROADCAST_TAG}`,
|
|
263
|
+
});
|
|
264
|
+
});
|
|
265
|
+
|
|
266
|
+
beforeEach(async () => {
|
|
267
|
+
// deleteMany is blocked on synced models; clear via the native collections.
|
|
268
|
+
await TenantModel.collection.deleteMany({});
|
|
269
|
+
await CustomModel.collection.deleteMany({});
|
|
270
|
+
await BroadcastModel.collection.deleteMany({});
|
|
271
|
+
await SyncCounter.deleteMany({});
|
|
272
|
+
await SyncScopeMove.deleteMany({});
|
|
273
|
+
});
|
|
274
|
+
|
|
275
|
+
// ── m9: single-`_id` filter shapes ────────────────────────────────────────
|
|
276
|
+
it("accepts an `_id: {$eq}` filter and rejects `_id: {$in}` and a null `_id`", async () => {
|
|
277
|
+
const doc = await TenantModel.create({name: "n", orgId: "org1"});
|
|
278
|
+
const createSeq = doc._syncSeq as number;
|
|
279
|
+
await TenantModel.updateOne({_id: {$eq: doc._id}}, {$set: {name: "eq-renamed"}});
|
|
280
|
+
const reloaded = await TenantModel.findById(doc._id);
|
|
281
|
+
expect(reloaded?.name).toBe("eq-renamed");
|
|
282
|
+
expect(reloaded?._syncSeq).toBe(createSeq + 1);
|
|
283
|
+
|
|
284
|
+
await expect(
|
|
285
|
+
TenantModel.updateOne({_id: {$in: [doc._id]}}, {$set: {name: "x"}}).exec()
|
|
286
|
+
).rejects.toThrow(/must target a single document by _id/);
|
|
287
|
+
await expect(TenantModel.updateOne({_id: null}, {$set: {name: "x"}}).exec()).rejects.toThrow(
|
|
288
|
+
/must target a single document by _id/
|
|
289
|
+
);
|
|
290
|
+
});
|
|
291
|
+
|
|
292
|
+
// ── C1: confirm failures never fail the user's write ──────────────────────
|
|
293
|
+
it("a confirm failure after save is logged, not surfaced", async () => {
|
|
294
|
+
const doc = await TenantModel.create({name: "n", orgId: "org1"});
|
|
295
|
+
const restore = stubPendingPull({behavior: "throw"});
|
|
296
|
+
try {
|
|
297
|
+
doc.name = "renamed";
|
|
298
|
+
await doc.save();
|
|
299
|
+
} finally {
|
|
300
|
+
restore();
|
|
301
|
+
}
|
|
302
|
+
expect((await TenantModel.findById(doc._id))?.name).toBe("renamed");
|
|
303
|
+
});
|
|
304
|
+
|
|
305
|
+
it("a confirm failure after a query write is logged, not surfaced", async () => {
|
|
306
|
+
const doc = await TenantModel.create({name: "n", orgId: "org1"});
|
|
307
|
+
const restore = stubPendingPull({behavior: "throw"});
|
|
308
|
+
try {
|
|
309
|
+
await TenantModel.updateOne({_id: doc._id}, {$set: {name: "renamed"}});
|
|
310
|
+
} finally {
|
|
311
|
+
restore();
|
|
312
|
+
}
|
|
313
|
+
expect((await TenantModel.findById(doc._id))?.name).toBe("renamed");
|
|
314
|
+
});
|
|
315
|
+
|
|
316
|
+
it("a confirm failure after insertMany is logged, not surfaced", async () => {
|
|
317
|
+
const restore = stubPendingPull({behavior: "throw"});
|
|
318
|
+
try {
|
|
319
|
+
await TenantModel.insertMany([
|
|
320
|
+
{name: "im-1", orgId: "org1"},
|
|
321
|
+
{name: "im-2", orgId: "org1"},
|
|
322
|
+
]);
|
|
323
|
+
} finally {
|
|
324
|
+
restore();
|
|
325
|
+
}
|
|
326
|
+
const docs = await TenantModel.find({orgId: "org1"});
|
|
327
|
+
expect(docs).toHaveLength(2);
|
|
328
|
+
expect(docs.every((entry) => typeof entry._syncSeq === "number")).toBe(true);
|
|
329
|
+
});
|
|
330
|
+
|
|
331
|
+
it("insertMany of an empty batch claims nothing", async () => {
|
|
332
|
+
await TenantModel.insertMany([]);
|
|
333
|
+
expect(await SyncCounter.countDocuments({})).toBe(0);
|
|
334
|
+
});
|
|
335
|
+
|
|
336
|
+
// ── Task 9.13: a failed save releases its claim ───────────────────────────
|
|
337
|
+
it("a release failure after a failed save is logged, not surfaced", async () => {
|
|
338
|
+
const restore = stubPendingPull({behavior: "throw"});
|
|
339
|
+
try {
|
|
340
|
+
await expect(TenantModel.create({name: "kaboom", orgId: "org1"})).rejects.toThrow(
|
|
341
|
+
/simulated post-claim save failure/
|
|
342
|
+
);
|
|
343
|
+
} finally {
|
|
344
|
+
restore();
|
|
345
|
+
}
|
|
346
|
+
expect(await TenantModel.collection.countDocuments({})).toBe(0);
|
|
347
|
+
});
|
|
348
|
+
|
|
349
|
+
// ── Task 9.17: reaped-claim re-stamping ───────────────────────────────────
|
|
350
|
+
it("a re-stamp that matches no document releases its claim and leaves the doc below the frontier", async () => {
|
|
351
|
+
const doc = await TenantModel.create({name: "n", orgId: "org1"});
|
|
352
|
+
const claimedSeq = doc._syncSeq as number;
|
|
353
|
+
const restorePull = stubPendingPull({behavior: "reaped"});
|
|
354
|
+
const restoreRaw = stubRawUpdateOne({behavior: "noMatch", model: TenantModel});
|
|
355
|
+
try {
|
|
356
|
+
doc.name = "renamed";
|
|
357
|
+
await doc.save();
|
|
358
|
+
} finally {
|
|
359
|
+
restoreRaw();
|
|
360
|
+
restorePull();
|
|
361
|
+
}
|
|
362
|
+
// The re-stamp never landed, so the in-memory doc keeps the seq its own save stamped.
|
|
363
|
+
expect(doc._syncSeq).toBe(claimedSeq + 1);
|
|
364
|
+
});
|
|
365
|
+
|
|
366
|
+
it("a re-stamp whose own confirm is reaped keeps the new seq on the document", async () => {
|
|
367
|
+
const doc = await TenantModel.create({name: "n", orgId: "org1"});
|
|
368
|
+
const savedSeq = doc._syncSeq as number;
|
|
369
|
+
const restore = stubPendingPull({behavior: "reaped"});
|
|
370
|
+
try {
|
|
371
|
+
doc.name = "renamed";
|
|
372
|
+
await doc.save();
|
|
373
|
+
} finally {
|
|
374
|
+
restore();
|
|
375
|
+
}
|
|
376
|
+
const reStamped = doc._syncSeq as number;
|
|
377
|
+
expect(reStamped).toBeGreaterThan(savedSeq + 1);
|
|
378
|
+
expect((await TenantModel.findById(doc._id))?._syncSeq).toBe(reStamped);
|
|
379
|
+
});
|
|
380
|
+
|
|
381
|
+
it("a re-stamp that throws leaves the document's own seq in place", async () => {
|
|
382
|
+
const doc = await TenantModel.create({name: "n", orgId: "org1"});
|
|
383
|
+
const claimedSeq = doc._syncSeq as number;
|
|
384
|
+
const restorePull = stubPendingPull({behavior: "reaped"});
|
|
385
|
+
const restoreRaw = stubRawUpdateOne({behavior: "throw", model: TenantModel});
|
|
386
|
+
try {
|
|
387
|
+
doc.name = "renamed";
|
|
388
|
+
await doc.save();
|
|
389
|
+
} finally {
|
|
390
|
+
restoreRaw();
|
|
391
|
+
restorePull();
|
|
392
|
+
}
|
|
393
|
+
expect(doc._syncSeq).toBe(claimedSeq + 1);
|
|
394
|
+
});
|
|
395
|
+
|
|
396
|
+
// ── C4: scope-move marker failures ────────────────────────────────────────
|
|
397
|
+
it("a scope-move marker whose seq claim fails writes no marker and never fails the move", async () => {
|
|
398
|
+
const doc = await TenantModel.create({name: "n", orgId: "org1"});
|
|
399
|
+
const restore = stubClaimFailure({stream: `${TENANT_TAG}|tenant:org1`});
|
|
400
|
+
try {
|
|
401
|
+
doc.orgId = "org2";
|
|
402
|
+
await doc.save();
|
|
403
|
+
} finally {
|
|
404
|
+
restore();
|
|
405
|
+
}
|
|
406
|
+
expect(await SyncScopeMove.countDocuments({entityId: String(doc._id)})).toBe(0);
|
|
407
|
+
expect((await TenantModel.findById(doc._id))?.orgId).toBe("org2");
|
|
408
|
+
});
|
|
409
|
+
|
|
410
|
+
it("a scope-move marker whose confirm fails still writes the marker", async () => {
|
|
411
|
+
const doc = await TenantModel.create({name: "n", orgId: "org1"});
|
|
412
|
+
const restore = stubPendingPull({behavior: "throw", stream: `${TENANT_TAG}|tenant:org1`});
|
|
413
|
+
try {
|
|
414
|
+
doc.orgId = "org2";
|
|
415
|
+
await doc.save();
|
|
416
|
+
} finally {
|
|
417
|
+
restore();
|
|
418
|
+
}
|
|
419
|
+
const markers = await SyncScopeMove.find({entityId: String(doc._id)});
|
|
420
|
+
expect(markers).toHaveLength(1);
|
|
421
|
+
expect(markers[0].fromStream).toBe(`${TENANT_TAG}|tenant:org1`);
|
|
422
|
+
});
|
|
423
|
+
|
|
424
|
+
// ── query-write scope resolution for non-tenant scope kinds ───────────────
|
|
425
|
+
it("a custom scope resolver resolves the query-write's stream from the merged document", async () => {
|
|
426
|
+
const doc = await CustomModel.create({name: "n", workspaceId: "w1"});
|
|
427
|
+
await CustomModel.updateOne({_id: doc._id}, {$set: {workspaceId: "w2"}});
|
|
428
|
+
const reloaded = await CustomModel.findById(doc._id);
|
|
429
|
+
expect(reloaded?._syncSeq).toBe(1);
|
|
430
|
+
const markers = await SyncScopeMove.find({entityId: String(doc._id)});
|
|
431
|
+
expect(markers).toHaveLength(1);
|
|
432
|
+
expect(markers[0].fromStream).toBe(`${CUSTOM_TAG}|custom:w1`);
|
|
433
|
+
expect(markers[0].toStream).toBe(`${CUSTOM_TAG}|custom:w2`);
|
|
434
|
+
});
|
|
435
|
+
|
|
436
|
+
it("a broadcast scope stamps the single all-stream and never reports a move", async () => {
|
|
437
|
+
const doc = await BroadcastModel.create({name: "n"});
|
|
438
|
+
await BroadcastModel.updateOne({_id: doc._id}, {$set: {name: "renamed"}});
|
|
439
|
+
const reloaded = await BroadcastModel.findById(doc._id);
|
|
440
|
+
expect(reloaded?._syncSeq).toBe((doc._syncSeq as number) + 1);
|
|
441
|
+
expect(reloaded?._syncPrevStream ?? null).toBeNull();
|
|
442
|
+
expect(await SyncScopeMove.countDocuments({})).toBe(0);
|
|
443
|
+
const counter = await SyncCounter.findOne({stream: `${BROADCAST_TAG}|all`});
|
|
444
|
+
expect(counter?.seq).toBe(2);
|
|
445
|
+
});
|
|
446
|
+
});
|