@unchainedshop/core-worker 5.0.0-alpha.11 → 5.0.0-alpha.14

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.
@@ -1,5 +1,10 @@
1
1
  import { type TimestampFields } from '@unchainedshop/mongodb';
2
2
  import { type mongodb } from '@unchainedshop/mongodb';
3
+ export declare const WORK_RETENTION_SECONDS: number;
4
+ export declare const computeWorkExpiry: ({ created, scheduled, }: {
5
+ created?: Date;
6
+ scheduled?: Date | null;
7
+ }) => Date;
3
8
  export declare const WorkStatus: {
4
9
  readonly NEW: "NEW";
5
10
  readonly ALLOCATED: "ALLOCATED";
@@ -25,5 +30,6 @@ export type Work = {
25
30
  worker?: string | null;
26
31
  autoscheduled?: boolean;
27
32
  scheduleId?: string;
33
+ expires?: Date;
28
34
  } & TimestampFields;
29
35
  export declare const WorkQueueCollection: (db: mongodb.Db) => Promise<mongodb.Collection<Work>>;
@@ -1,6 +1,14 @@
1
1
  import {} from '@unchainedshop/mongodb';
2
2
  import { buildDbIndexes } from '@unchainedshop/mongodb';
3
3
  const ONE_DAY_IN_SECONDS = 86400;
4
+ export const WORK_RETENTION_SECONDS = 30 * ONE_DAY_IN_SECONDS;
5
+ export const computeWorkExpiry = ({ created, scheduled, }) => {
6
+ const times = [created, scheduled]
7
+ .map((date) => (date ? new Date(date).getTime() : NaN))
8
+ .filter(Number.isFinite);
9
+ const latest = times.length ? Math.max(...times) : Date.now();
10
+ return new Date(latest + WORK_RETENTION_SECONDS * 1000);
11
+ };
4
12
  export const WorkStatus = {
5
13
  NEW: 'NEW',
6
14
  ALLOCATED: 'ALLOCATED',
@@ -26,10 +34,8 @@ export const WorkQueueCollection = async (db) => {
26
34
  },
27
35
  ]);
28
36
  await buildDbIndexes(WorkQueue, [
29
- {
30
- index: { created: -1 },
31
- options: { expireAfterSeconds: 30 * ONE_DAY_IN_SECONDS },
32
- },
37
+ { index: { expires: 1 }, options: { expireAfterSeconds: 0 } },
38
+ { index: { created: 1 } },
33
39
  { index: { scheduled: 1, type: 1 } },
34
40
  { index: { type: 1 } },
35
41
  { index: { originalWorkId: 1 } },
@@ -0,0 +1,2 @@
1
+ import type { MigrationRepository } from '@unchainedshop/mongodb';
2
+ export default function migrateWorkQueueExpiry(repository: MigrationRepository): void;
@@ -0,0 +1,35 @@
1
+ import { WORK_RETENTION_SECONDS, WorkQueueCollection } from "../db/WorkQueueCollection.js";
2
+ export default function migrateWorkQueueExpiry(repository) {
3
+ repository?.register({
4
+ id: 20261104120100,
5
+ name: 'Expire work 30 days after it was created or is scheduled, whichever is later',
6
+ up: async ({ logger }) => {
7
+ const WorkQueue = await WorkQueueCollection(repository.db);
8
+ const { modifiedCount } = await WorkQueue.updateMany({ expires: { $exists: false } }, [
9
+ {
10
+ $set: {
11
+ expires: {
12
+ $add: [
13
+ { $ifNull: [{ $max: ['$created', '$scheduled'] }, '$$NOW'] },
14
+ WORK_RETENTION_SECONDS * 1000,
15
+ ],
16
+ },
17
+ },
18
+ },
19
+ ]);
20
+ const legacyTTLIndexNames = (await WorkQueue.indexes())
21
+ .filter(({ key, expireAfterSeconds }) => expireAfterSeconds !== undefined && Object.keys(key).join() === 'created')
22
+ .map(({ name }) => name);
23
+ for (const name of legacyTTLIndexNames) {
24
+ try {
25
+ await WorkQueue.dropIndex(name);
26
+ }
27
+ catch (error) {
28
+ if (error?.codeName !== 'IndexNotFound')
29
+ throw error;
30
+ }
31
+ }
32
+ logger?.info(`Work queue expiry: ${modifiedCount} work item(s) got an expiry, dropped TTL index(es) on created: ${legacyTTLIndexNames.join(', ') || 'none'}`);
33
+ },
34
+ });
35
+ }
@@ -61,14 +61,15 @@ export declare const buildQuerySelector: ({ created, scheduled, types, status, w
61
61
  worker?: mongodb.Condition<string | null | undefined>;
62
62
  input?: mongodb.Condition<Record<string, any>> | undefined;
63
63
  type?: mongodb.Condition<string> | undefined;
64
+ expires?: mongodb.Condition<Date | undefined>;
64
65
  started?: mongodb.Condition<Date | undefined>;
65
66
  finished?: mongodb.Condition<Date | undefined>;
66
67
  priority?: mongodb.Condition<number> | undefined;
67
68
  retries?: mongodb.Condition<number> | undefined;
68
- scheduleId?: mongodb.Condition<string | undefined>;
69
69
  result?: any;
70
70
  success?: mongodb.Condition<boolean | undefined>;
71
71
  autoscheduled?: mongodb.Condition<boolean | undefined>;
72
+ scheduleId?: mongodb.Condition<string | undefined>;
72
73
  updated?: mongodb.Condition<Date | undefined>;
73
74
  deleted?: mongodb.Condition<Date | null | undefined>;
74
75
  _id?: mongodb.Condition<string> | undefined;
@@ -86,7 +87,7 @@ export declare const buildQuerySelector: ({ created, scheduled, types, status, w
86
87
  created?: mongodb.Condition<Date> | undefined;
87
88
  scheduled?: mongodb.Condition<Date> | undefined;
88
89
  };
89
- export declare const configureWorkerModule: ({ db, options }: ModuleInput<WorkerSettingsOptions>) => Promise<{
90
+ export declare const configureWorkerModule: ({ db, options, migrationRepository, }: ModuleInput<WorkerSettingsOptions>) => Promise<{
90
91
  workerId: string;
91
92
  activeWorkTypes: () => Promise<string[]>;
92
93
  findWork: (params: {
@@ -3,7 +3,8 @@ import { createLogger } from '@unchainedshop/logger';
3
3
  import { generateDbFilterById, buildSortOptions, generateDbObjectId, } from '@unchainedshop/mongodb';
4
4
  import { emit, registerEvents } from '@unchainedshop/events';
5
5
  import { buildObfuscatedFieldsFilter, SortDirection, } from '@unchainedshop/utils';
6
- import { WorkQueueCollection, WorkStatus } from "../db/WorkQueueCollection.js";
6
+ import { computeWorkExpiry, WorkQueueCollection, WorkStatus, } from "../db/WorkQueueCollection.js";
7
+ import migrateWorkQueueExpiry from "../migrations/20261104120100-work-queue-expires.js";
7
8
  const { UNCHAINED_WORKER_ID = os.hostname() } = process.env;
8
9
  export const DIRECTOR_MARKED_FAILED_ERROR = 'DIRECTOR_MARKED_FAILED';
9
10
  const logger = createLogger('unchained:core-worker');
@@ -108,7 +109,8 @@ const normalizeWorkQueueAggregateResult = (data = []) => {
108
109
  return workStatistics;
109
110
  });
110
111
  };
111
- export const configureWorkerModule = async ({ db, options }) => {
112
+ export const configureWorkerModule = async ({ db, options, migrationRepository, }) => {
113
+ migrateWorkQueueExpiry(migrationRepository);
112
114
  registerEvents(Object.values(WorkerEventTypes));
113
115
  const WorkQueue = await WorkQueueCollection(db);
114
116
  const removePrivateFields = buildObfuscatedFieldsFilter(options?.blacklistedVariables);
@@ -253,6 +255,7 @@ export const configureWorkerModule = async ({ db, options }) => {
253
255
  input: input || {},
254
256
  priority,
255
257
  scheduled: scheduled || created,
258
+ expires: computeWorkExpiry({ created, scheduled }),
256
259
  originalWorkId,
257
260
  retries,
258
261
  worker,
@@ -279,6 +282,7 @@ export const configureWorkerModule = async ({ db, options }) => {
279
282
  $set: {
280
283
  updated: new Date(),
281
284
  scheduled,
285
+ expires: computeWorkExpiry({ created: currentWork.created, scheduled }),
282
286
  },
283
287
  }, { returnDocument: 'after' });
284
288
  if (!work)
@@ -333,6 +337,7 @@ export const configureWorkerModule = async ({ db, options }) => {
333
337
  scheduled,
334
338
  type,
335
339
  created,
340
+ expires: computeWorkExpiry({ created, scheduled }),
336
341
  autoscheduled: true,
337
342
  priority,
338
343
  },
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@unchainedshop/core-worker",
3
3
  "description": "Background job and task queue module for the Unchained Engine",
4
- "version": "5.0.0-alpha.11",
4
+ "version": "5.0.0-alpha.14",
5
5
  "files": [
6
6
  "lib"
7
7
  ],
@@ -38,10 +38,10 @@
38
38
  },
39
39
  "homepage": "https://github.com/unchainedshop/unchained#readme",
40
40
  "dependencies": {
41
- "@unchainedshop/events": "^5.0.0-alpha.11",
42
- "@unchainedshop/logger": "^5.0.0-alpha.11",
43
- "@unchainedshop/mongodb": "^5.0.0-alpha.11",
44
- "@unchainedshop/utils": "^5.0.0-alpha.11"
41
+ "@unchainedshop/events": "^5.0.0-alpha.14",
42
+ "@unchainedshop/logger": "^5.0.0-alpha.14",
43
+ "@unchainedshop/mongodb": "^5.0.0-alpha.14",
44
+ "@unchainedshop/utils": "^5.0.0-alpha.14"
45
45
  },
46
46
  "devDependencies": {
47
47
  "@types/node": "^26.2.0",