@terreno/admin-backend 57.16.1 → 57.17.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.
@@ -272,6 +272,131 @@ describe("admin/script durable job adapter", () => {
272
272
  expect(refreshed?.error).toInclude("Script not found");
273
273
  });
274
274
 
275
+ it("does not run the durable handler for a task that already started", async () => {
276
+ let calls = 0;
277
+ const countingScript: AdminScriptJobTarget = {
278
+ name: "counting",
279
+ runner: async (wetRun: boolean) => {
280
+ calls += 1;
281
+ return {results: [`wetRun=${wetRun} call=${calls}`], success: true};
282
+ },
283
+ };
284
+ const handler = getAdminScriptHandler(() => countingScript);
285
+ const task = await BackgroundTask.create({
286
+ isDryRun: false,
287
+ logs: [],
288
+ status: "running",
289
+ taskType: "counting",
290
+ });
291
+
292
+ await expect(
293
+ handler(
294
+ {args: {}, scriptName: "counting", taskId: String(task._id), wetRun: true},
295
+ mockJobContext
296
+ )
297
+ ).rejects.toThrow("already started");
298
+ expect(calls).toBe(0);
299
+ expect((await BackgroundTask.findById(task._id))?.status).toBe("running");
300
+ });
301
+
302
+ it("skips the durable handler quietly for a task cancelled before it started", async () => {
303
+ let calls = 0;
304
+ const countingScript: AdminScriptJobTarget = {
305
+ name: "counting",
306
+ runner: async () => {
307
+ calls += 1;
308
+ return {results: [], success: true};
309
+ },
310
+ };
311
+ const handler = getAdminScriptHandler(() => countingScript);
312
+ const task = await BackgroundTask.create({
313
+ isDryRun: false,
314
+ logs: [],
315
+ status: "cancelled",
316
+ taskType: "counting",
317
+ });
318
+
319
+ await handler(
320
+ {args: {}, scriptName: "counting", taskId: String(task._id), wetRun: true},
321
+ mockJobContext
322
+ );
323
+ expect(calls).toBe(0);
324
+ expect((await BackgroundTask.findById(task._id))?.status).toBe("cancelled");
325
+ });
326
+
327
+ it("still runs the in-process script path for a task created as running", async () => {
328
+ const task = await BackgroundTask.create({
329
+ isDryRun: true,
330
+ logs: [],
331
+ status: "running",
332
+ taskType: "echo",
333
+ });
334
+ const {args} = createScriptArgs({values: {}});
335
+ await runRegisteredScriptTask({
336
+ args,
337
+ script: echoScript,
338
+ taskId: String(task._id),
339
+ wetRun: false,
340
+ });
341
+ const refreshed = await BackgroundTask.findById(task._id);
342
+ expect(refreshed?.status).toBe("completed");
343
+ expect(refreshed?.result).toContain("dry");
344
+ });
345
+
346
+ it("runs a wet script once when a duplicate dispatch arrives after the lock TTL", async () => {
347
+ let calls = 0;
348
+ let concurrent = 0;
349
+ let maxConcurrent = 0;
350
+ const slowScript: AdminScriptJobTarget = {
351
+ name: "slow-wet",
352
+ runner: async (wetRun: boolean) => {
353
+ calls += 1;
354
+ const call = calls;
355
+ concurrent += 1;
356
+ maxConcurrent = Math.max(maxConcurrent, concurrent);
357
+ if (call === 1) {
358
+ await Bun.sleep(400);
359
+ }
360
+ concurrent -= 1;
361
+ return {results: [`wetRun=${wetRun} call=${call}`], success: true};
362
+ },
363
+ };
364
+ const jobsApp = new JobsApp({lockTtlMs: 100});
365
+ defineAdminScriptJob(jobsApp, (name) => (name === "slow-wet" ? slowScript : undefined));
366
+ const app = getBaseServer();
367
+ jobsApp.register(app);
368
+
369
+ const task = await BackgroundTask.create({
370
+ isDryRun: false,
371
+ logs: [],
372
+ status: "pending",
373
+ taskType: "slow-wet",
374
+ });
375
+ const enqueued = await tryEnqueueAdminScriptJob({
376
+ args: {},
377
+ scriptName: "slow-wet",
378
+ taskId: String(task._id),
379
+ wetRun: true,
380
+ });
381
+ const jobId = String(enqueued?.id);
382
+
383
+ const first = jobsApp.executeQueuedJob(jobId);
384
+ await Bun.sleep(30);
385
+ const withinTtl = await jobsApp.executeQueuedJob(jobId);
386
+ await Bun.sleep(170);
387
+ const afterTtl = await jobsApp.executeQueuedJob(jobId);
388
+ const firstOutcome = await first;
389
+
390
+ expect(withinTtl.kind).toBe("conflict");
391
+ expect(afterTtl.kind).toBe("conflict");
392
+ expect(firstOutcome.kind).toBe("executed");
393
+ expect(calls).toBe(1);
394
+ expect(maxConcurrent).toBe(1);
395
+ const refreshed = await BackgroundTask.findById(task._id);
396
+ expect(refreshed?.status).toBe("completed");
397
+ expect(refreshed?.result).toEqual(["wetRun=true call=1"]);
398
+ });
399
+
275
400
  it("cancels the matching job row for a script task", async () => {
276
401
  const jobsApp = new JobsApp({pollIntervalMs: 50});
277
402
  defineAdminScriptJob(jobsApp, (name) => (name === "echo" ? echoScript : undefined));
@@ -91,22 +91,29 @@ const isAbortLike = (error: unknown): boolean => {
91
91
  return error.name === "AbortError" || error.name === "TaskCancelledError";
92
92
  };
93
93
 
94
+ /**
95
+ * Run an admin script against its BackgroundTask row. `requirePending` makes the run conditional
96
+ * on winning the task's pending -> running transition, so a durable job delivered twice never
97
+ * starts the script twice. The in-process path creates its task already running and omits it.
98
+ */
94
99
  export const runRegisteredScriptTask = async ({
95
100
  args,
101
+ requirePending = false,
96
102
  script,
97
103
  signal,
98
104
  taskId,
99
105
  wetRun,
100
106
  }: {
101
107
  args: ScriptArgs;
108
+ requirePending?: boolean;
102
109
  script: AdminScriptJobTarget;
103
110
  signal?: AbortSignal;
104
111
  taskId: string;
105
112
  wetRun: boolean;
106
113
  }): Promise<void> => {
107
114
  const now = DateTime.now().toJSDate();
108
- await BackgroundTask.findOneAndUpdate(
109
- {_id: taskId, status: {$in: ["pending", "running"]}},
115
+ const started = await BackgroundTask.findOneAndUpdate(
116
+ {_id: taskId, status: requirePending ? "pending" : {$in: ["pending", "running"]}},
110
117
  {
111
118
  $set: {
112
119
  progress: {message: "Starting...", percentage: 0, stage: "Running"},
@@ -116,6 +123,18 @@ export const runRegisteredScriptTask = async ({
116
123
  }
117
124
  );
118
125
 
126
+ if (!started && requirePending) {
127
+ const current = await BackgroundTask.findById(taskId);
128
+ if (current?.status === "cancelled") {
129
+ return;
130
+ }
131
+ throw new APIError({
132
+ detail: `Task ${taskId} is ${current?.status ?? "missing"}`,
133
+ status: 409,
134
+ title: "Admin script task already started",
135
+ });
136
+ }
137
+
119
138
  const ctx: ScriptContext = {
120
139
  addLog: async (level, message) => {
121
140
  const current = await BackgroundTask.findById(taskId);
@@ -217,6 +236,7 @@ const createAdminScriptHandler = (
217
236
 
218
237
  await runRegisteredScriptTask({
219
238
  args,
239
+ requirePending: true,
220
240
  script,
221
241
  signal: ctx.signal,
222
242
  taskId: parsed.taskId,
@@ -85,11 +85,13 @@ const productSyncOptions = {
85
85
  };
86
86
 
87
87
  const buildHarness = ({
88
+ adminModelOverrides,
88
89
  grants,
89
90
  onAdminAudit,
90
91
  productHookTracker,
91
92
  resolvePermissions,
92
93
  }: {
94
+ adminModelOverrides?: Partial<AdminModelConfig>;
93
95
  grants: Record<string, string[]>;
94
96
  onAdminAudit?: (event: AdminAuditEvent) => void | Promise<void>;
95
97
  productHookTracker?: {postUpdateCalls: number; preCreateCalls: number; preUpdateCalls: number};
@@ -152,6 +154,7 @@ const buildHarness = ({
152
154
  isOwned: adminOwnedBy("ownerId"),
153
155
  resource: "adminWindowTodo",
154
156
  },
157
+ ...adminModelOverrides,
155
158
  },
156
159
  ],
157
160
  onAdminAudit,
@@ -648,3 +651,123 @@ describe("admin window org-scoped mutation membership", () => {
648
651
  expect(afterSyncAttempt?.title).toBe("REST ok");
649
652
  });
650
653
  });
654
+
655
+ describe("admin window sync mutation row scope", () => {
656
+ let agent: TestAgent;
657
+ let actorId: string;
658
+ let otherOwnerId: string;
659
+
660
+ beforeEach(async () => {
661
+ await setupDb();
662
+ otherOwnerId = new mongoose.Types.ObjectId().toHexString();
663
+ const app = buildHarness({
664
+ adminModelOverrides: {
665
+ permissions: {delete: true, update: true},
666
+ queryFilter: (user, query): Record<string, unknown> => ({
667
+ ...(query ?? {}),
668
+ ownerId: String(user?.id),
669
+ }),
670
+ },
671
+ grants: {admin: ["access"], adminWindowTodo: ["read", "write"]},
672
+ });
673
+ agent = await authAsUser(app, "admin");
674
+ const actor = await findOneOrNoneFor(UserModel, {email: "admin@example.com"});
675
+ actorId = String(actor?._id);
676
+ });
677
+
678
+ afterEach(async () => {
679
+ clearSyncRegistry();
680
+ await WindowTodoModel.deleteMany({});
681
+ });
682
+
683
+ it("nacks update and delete of rows outside the AdminApp row scope", async () => {
684
+ const theirs = await WindowTodoModel.create({ownerId: otherOwnerId, title: "Theirs"});
685
+ const theirsToo = await WindowTodoModel.create({ownerId: otherOwnerId, title: "TheirsToo"});
686
+
687
+ const updateRes = await agent
688
+ .post("/sync/mutate")
689
+ .send(
690
+ adminWindowMutate({
691
+ baseVersion: theirs._syncSeq ?? 1,
692
+ collection: "window-todos",
693
+ data: {title: "overwritten"},
694
+ id: theirs._id,
695
+ mutationId: "admin-row-scope-update",
696
+ operation: "update",
697
+ })
698
+ )
699
+ .expect(403);
700
+ expect(updateRes.body.nack.code).toBe("unauthorized");
701
+
702
+ await agent
703
+ .post("/sync/mutate")
704
+ .send(
705
+ adminWindowMutate({
706
+ collection: "window-todos",
707
+ id: theirsToo._id,
708
+ mutationId: "admin-row-scope-delete",
709
+ operation: "delete",
710
+ })
711
+ )
712
+ .expect(403);
713
+
714
+ const batchRes = await agent
715
+ .post("/sync/mutate/batch")
716
+ .send({
717
+ mutations: [
718
+ adminWindowMutate({
719
+ baseVersion: theirs._syncSeq ?? 1,
720
+ collection: "window-todos",
721
+ data: {title: "batch overwritten"},
722
+ id: theirs._id,
723
+ mutationId: "admin-row-scope-batch",
724
+ operation: "update",
725
+ }),
726
+ ],
727
+ })
728
+ .expect(200);
729
+ expect(batchRes.body.results[0].type).toBe("nack");
730
+
731
+ const reloaded = await WindowTodoModel.findById(theirs._id).lean();
732
+ expect(reloaded?.title).toBe("Theirs");
733
+ const stillThere = await WindowTodoModel.findById(theirsToo._id).lean();
734
+ expect(stillThere?.deleted).not.toBe(true);
735
+ });
736
+
737
+ it("acks in-scope writes and nacks an update that moves a row out of scope", async () => {
738
+ const mine = await WindowTodoModel.create({ownerId: actorId, title: "Mine"});
739
+
740
+ await agent
741
+ .post("/sync/mutate")
742
+ .send(
743
+ adminWindowMutate({
744
+ baseVersion: mine._syncSeq ?? 1,
745
+ collection: "window-todos",
746
+ data: {title: "Mine edited"},
747
+ id: mine._id,
748
+ mutationId: "admin-row-scope-own-update",
749
+ operation: "update",
750
+ })
751
+ )
752
+ .expect(200);
753
+
754
+ const current = await WindowTodoModel.findById(mine._id).lean();
755
+ await agent
756
+ .post("/sync/mutate")
757
+ .send(
758
+ adminWindowMutate({
759
+ baseVersion: current?._syncSeq ?? 2,
760
+ collection: "window-todos",
761
+ data: {ownerId: otherOwnerId},
762
+ id: mine._id,
763
+ mutationId: "admin-row-scope-move",
764
+ operation: "update",
765
+ })
766
+ )
767
+ .expect(403);
768
+
769
+ const after = await WindowTodoModel.findById(mine._id).lean();
770
+ expect(after?.ownerId).toBe(actorId);
771
+ expect(after?.title).toBe("Mine edited");
772
+ });
773
+ });