@unchainedshop/core-worker 3.0.0-alpha6 → 3.0.0-rc.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/lib/db/WorkQueueCollection.d.ts +26 -1
  2. package/lib/db/WorkQueueCollection.d.ts.map +1 -1
  3. package/lib/db/WorkQueueCollection.js +8 -0
  4. package/lib/db/WorkQueueCollection.js.map +1 -1
  5. package/lib/module/configureWorkerModule.d.ts +66 -54
  6. package/lib/module/configureWorkerModule.d.ts.map +1 -1
  7. package/lib/module/configureWorkerModule.js +54 -88
  8. package/lib/module/configureWorkerModule.js.map +1 -1
  9. package/lib/worker-index.d.ts +1 -9
  10. package/lib/worker-index.d.ts.map +1 -1
  11. package/lib/worker-index.js +1 -9
  12. package/lib/worker-index.js.map +1 -1
  13. package/package.json +13 -13
  14. package/src/db/WorkQueueCollection.ts +28 -1
  15. package/src/module/configureWorkerModule.ts +145 -171
  16. package/src/worker-index.ts +1 -10
  17. package/tsconfig.json +5 -7
  18. package/lib/director/WorkStatus.d.ts +0 -8
  19. package/lib/director/WorkStatus.d.ts.map +0 -1
  20. package/lib/director/WorkStatus.js +0 -9
  21. package/lib/director/WorkStatus.js.map +0 -1
  22. package/lib/director/WorkerAdapter.d.ts +0 -15
  23. package/lib/director/WorkerAdapter.d.ts.map +0 -1
  24. package/lib/director/WorkerAdapter.js +0 -11
  25. package/lib/director/WorkerAdapter.js.map +0 -1
  26. package/lib/director/WorkerDirector.d.ts +0 -27
  27. package/lib/director/WorkerDirector.d.ts.map +0 -1
  28. package/lib/director/WorkerDirector.js +0 -72
  29. package/lib/director/WorkerDirector.js.map +0 -1
  30. package/lib/director/WorkerEventTypes.d.ts +0 -8
  31. package/lib/director/WorkerEventTypes.d.ts.map +0 -1
  32. package/lib/director/WorkerEventTypes.js +0 -9
  33. package/lib/director/WorkerEventTypes.js.map +0 -1
  34. package/lib/schedulers/FailedRescheduler.d.ts +0 -16
  35. package/lib/schedulers/FailedRescheduler.d.ts.map +0 -1
  36. package/lib/schedulers/FailedRescheduler.js +0 -45
  37. package/lib/schedulers/FailedRescheduler.js.map +0 -1
  38. package/lib/types.d.ts +0 -20
  39. package/lib/types.d.ts.map +0 -1
  40. package/lib/types.js +0 -2
  41. package/lib/types.js.map +0 -1
  42. package/lib/workers/BaseWorker.d.ts +0 -34
  43. package/lib/workers/BaseWorker.d.ts.map +0 -1
  44. package/lib/workers/BaseWorker.js +0 -81
  45. package/lib/workers/BaseWorker.js.map +0 -1
  46. package/lib/workers/EventListenerWorker.d.ts +0 -6
  47. package/lib/workers/EventListenerWorker.d.ts.map +0 -1
  48. package/lib/workers/EventListenerWorker.js +0 -46
  49. package/lib/workers/EventListenerWorker.js.map +0 -1
  50. package/lib/workers/IntervalWorker.d.ts +0 -10
  51. package/lib/workers/IntervalWorker.d.ts.map +0 -1
  52. package/lib/workers/IntervalWorker.js +0 -38
  53. package/lib/workers/IntervalWorker.js.map +0 -1
  54. package/src/director/WorkStatus.ts +0 -7
  55. package/src/director/WorkerAdapter.ts +0 -28
  56. package/src/director/WorkerDirector.ts +0 -120
  57. package/src/director/WorkerEventTypes.ts +0 -7
  58. package/src/schedulers/FailedRescheduler.ts +0 -83
  59. package/src/types.ts +0 -20
  60. package/src/workers/BaseWorker.ts +0 -125
  61. package/src/workers/EventListenerWorker.ts +0 -61
  62. package/src/workers/IntervalWorker.ts +0 -56
@@ -1,83 +0,0 @@
1
- import { log } from '@unchainedshop/logger';
2
- import { subscribe } from '@unchainedshop/events';
3
- import { WorkerEventTypes } from '../director/WorkerEventTypes.js';
4
- import { UnchainedCore } from '@unchainedshop/core';
5
- import { WorkData } from '../worker-index.js';
6
- import { Work } from '../types.js';
7
-
8
- export interface FailedReschedulerParams {
9
- retryInput?: (
10
- workData: WorkData,
11
- priorInput: Record<string, any>,
12
- ) => Promise<Record<string, any> | null>;
13
- }
14
-
15
- export type IScheduler<P> = {
16
- key: string;
17
- label: string;
18
- version: string;
19
-
20
- actions: (
21
- params: P,
22
- unchainedAPI: UnchainedCore,
23
- ) => {
24
- start: () => void;
25
- stop: () => void;
26
- };
27
- };
28
-
29
- export const FailedRescheduler: IScheduler<FailedReschedulerParams> = {
30
- key: 'shop.unchained.scheduler.failed',
31
- label: 'Reschedule failed works',
32
- version: '1.0.0',
33
-
34
- actions: ({ retryInput }, unchainedAPI) => {
35
- const handleFinishedWork = async ({ payload: work }: { payload: Work }) => {
36
- if (!work.success && work.retries > 0) {
37
- const now = new Date();
38
- const workDelayMs = work.scheduled.getTime() - work.created.getTime();
39
-
40
- // In short: Double the delay of the old work or delay for 5 seconds
41
- const scheduled =
42
- workDelayMs > 1000
43
- ? new Date(now.getTime() + workDelayMs * 2)
44
- : new Date(now.setSeconds(now.getSeconds() + 5));
45
-
46
- log(
47
- `${FailedRescheduler.key} -> Reschedule failed work ${work._id} ${
48
- work.type
49
- } for ${scheduled.toISOString()} (in ${Math.round(workDelayMs / 1000)}). Remaining retries: ${
50
- work.retries
51
- }`,
52
- );
53
-
54
- const workData: WorkData = {
55
- type: work.type,
56
- priority: work.priority,
57
- originalWorkId: work.originalWorkId || work._id,
58
- retries: work.retries - 1,
59
- timeout: work.timeout,
60
- scheduled,
61
- };
62
-
63
- if (retryInput) {
64
- workData.input = await retryInput(workData, work.input);
65
- } else {
66
- workData.input = work.input;
67
- }
68
-
69
- unchainedAPI.modules.worker.addWork(workData);
70
- }
71
- };
72
-
73
- return {
74
- start() {
75
- subscribe<Work>(WorkerEventTypes.FINISHED, handleFinishedWork);
76
- },
77
-
78
- stop() {
79
- /* */
80
- },
81
- };
82
- },
83
- };
package/src/types.ts DELETED
@@ -1,20 +0,0 @@
1
- import type { TimestampFields } from '@unchainedshop/mongodb';
2
-
3
- export type Work = {
4
- _id?: string;
5
- priority: number;
6
- retries: number;
7
- scheduled: Date;
8
- type: string;
9
- input: Record<string, any>;
10
- error?: any;
11
- finished?: Date;
12
- originalWorkId?: string;
13
- result?: any;
14
- started?: Date;
15
- success?: boolean;
16
- timeout?: number;
17
- worker?: string;
18
- autoscheduled?: boolean;
19
- scheduleId?: string;
20
- } & TimestampFields;
@@ -1,125 +0,0 @@
1
- import later from '@breejs/later';
2
- import { log } from '@unchainedshop/logger';
3
- import { WorkerDirector } from '../director/WorkerDirector.js';
4
- import { UnchainedCore } from '@unchainedshop/core';
5
- import { Work } from '../types.js';
6
-
7
- export type WorkData = Pick<
8
- Partial<Work>,
9
- 'input' | 'originalWorkId' | 'priority' | 'retries' | 'timeout' | 'scheduled' | 'worker' | 'scheduleId'
10
- > & { type: string };
11
-
12
- export type IWorker<P extends { workerId?: string }> = {
13
- key: string;
14
- label: string;
15
- version: string;
16
- type: string;
17
- external: boolean;
18
-
19
- getFloorDate: (date?: Date) => Date;
20
-
21
- actions: (
22
- params: P,
23
- unchainedAPI: UnchainedCore,
24
- ) => {
25
- autorescheduleTypes: (options: { referenceDate: Date }) => Promise<Array<Work | null>>;
26
- process: (options: { maxWorkItemCount?: number; referenceDate?: Date }) => Promise<void>;
27
- reset: () => Promise<void>;
28
- start: () => void;
29
- stop: () => void;
30
- };
31
- };
32
-
33
- interface WorkerParams {
34
- workerId?: string;
35
- worker: IWorker<any>;
36
- }
37
-
38
- export const BaseWorker: IWorker<WorkerParams> = {
39
- key: 'shop.unchained.worker.base',
40
- label: 'Base worker. Do not use this directly.',
41
- version: '1.0.0',
42
- type: 'BASE',
43
- external: false,
44
-
45
- getFloorDate: (date = new Date()) => {
46
- const floored = new Date(Math.floor(date.getTime() / 1000) * 1000);
47
- return floored;
48
- },
49
-
50
- actions: ({ workerId, worker }: WorkerParams, unchainedAPI) => {
51
- log(`${worker.key} -> Initialized ${worker.type}`);
52
-
53
- const workerActions = {
54
- start() {
55
- throw new Error(`Not implemented on ${this.constructor.key}`);
56
- },
57
-
58
- stop() {
59
- throw new Error(`Not implemented on ${this.constructor.key}`);
60
- },
61
-
62
- reset: async (referenceDate = new Date()) => {
63
- await unchainedAPI.modules.worker.markOldWorkAsFailed({
64
- types: WorkerDirector.getActivePluginTypes({ external: false }),
65
- worker: workerId,
66
- referenceDate,
67
- });
68
- },
69
-
70
- autorescheduleTypes: async ({ referenceDate }) => {
71
- return Promise.all(
72
- WorkerDirector.getAutoSchedules().map(async ([scheduleId, workConfig]) => {
73
- if (!workConfig.schedule) {
74
- await unchainedAPI.modules.worker.ensureNoWork({
75
- type: workConfig.type,
76
- priority: workConfig.priority || 0,
77
- scheduleId,
78
- });
79
- return null;
80
- }
81
-
82
- const fixedSchedule = { ...workConfig.schedule };
83
- fixedSchedule.schedules[0].s = [0]; // ignore seconds, always run on second 0
84
- const nextDate = later.schedule(fixedSchedule).next(1, referenceDate);
85
- nextDate.setMilliseconds(0);
86
- const workData: WorkData = {
87
- type: workConfig.type,
88
- scheduleId,
89
- scheduled: nextDate,
90
- timeout: workConfig.timeout,
91
- priority: workConfig.priority || 0,
92
- retries: workConfig.retries || 0,
93
- };
94
- if (workConfig.input) {
95
- workData.input = await workConfig.input(workData);
96
- // A work input fn can skip auto scheduling a new record
97
- // when it explicitly returns a falsish input instead of a dictionary
98
- if (!workData.input) return null;
99
- }
100
- return unchainedAPI.modules.worker.ensureOneWork(workData);
101
- }),
102
- );
103
- },
104
-
105
- process: async ({ maxWorkItemCount, referenceDate }) => {
106
- await workerActions.autorescheduleTypes({
107
- referenceDate,
108
- });
109
-
110
- const processRecursively = async (recursionCounter = 0) => {
111
- if (maxWorkItemCount && maxWorkItemCount < recursionCounter) return null;
112
- const doneWork = await unchainedAPI.modules.worker.processNextWork(unchainedAPI, workerId);
113
- if (doneWork) return processRecursively(recursionCounter + 1);
114
- return null;
115
- };
116
-
117
- await processRecursively();
118
- },
119
- };
120
-
121
- workerActions.reset();
122
-
123
- return workerActions;
124
- },
125
- };
@@ -1,61 +0,0 @@
1
- import { subscribe } from '@unchainedshop/events';
2
- import { WorkerEventTypes } from '../director/WorkerEventTypes.js';
3
- import { BaseWorker, IWorker } from './BaseWorker.js';
4
-
5
- function debounce<T extends (...args: any) => any>(func: T, wait) {
6
- let timeout;
7
- return (...args) => {
8
- clearTimeout(timeout);
9
- timeout = setTimeout(() => {
10
- timeout = null;
11
- func(...args);
12
- }, wait);
13
- };
14
- }
15
-
16
- export interface EventListenerWorkerParams {
17
- workerId?: string;
18
- }
19
-
20
- export const EventListenerWorker: IWorker<EventListenerWorkerParams> = {
21
- ...BaseWorker,
22
-
23
- key: 'shop.unchained.worker.event-listener',
24
- label: 'Allocates work on events. This worker does not make sense on multiple containers.',
25
- version: '1.0.0',
26
- type: 'EVENT_LISTENER',
27
-
28
- actions: ({ workerId }, unchainedAPI) => {
29
- const baseWorkerActions = BaseWorker.actions(
30
- { workerId, worker: EventListenerWorker },
31
- unchainedAPI,
32
- );
33
-
34
- // Debounce in the event of many work queue events conflicting with each other
35
- const processWorkQueue = debounce<() => Promise<void>>(async () => {
36
- await baseWorkerActions.process({
37
- maxWorkItemCount: 1, // only one work item at a time, else we could end up in a loop
38
- referenceDate: EventListenerWorker.getFloorDate(),
39
- });
40
- }, 300);
41
-
42
- return {
43
- ...baseWorkerActions,
44
-
45
- start() {
46
- subscribe(WorkerEventTypes.ADDED, processWorkQueue);
47
- subscribe(WorkerEventTypes.FINISHED, processWorkQueue);
48
-
49
- setTimeout(async () => {
50
- await baseWorkerActions.autorescheduleTypes({
51
- referenceDate: EventListenerWorker.getFloorDate(),
52
- });
53
- }, 300);
54
- },
55
-
56
- stop() {
57
- /* */
58
- },
59
- };
60
- },
61
- };
@@ -1,56 +0,0 @@
1
- import later from '@breejs/later';
2
- import { BaseWorker, IWorker } from './BaseWorker.js';
3
- import { WorkerSchedule } from '../worker-index.js';
4
-
5
- const { NODE_ENV } = process.env;
6
-
7
- export interface IntervalWorkerParams {
8
- workerId?: string;
9
- batchCount?: number;
10
- schedule?: WorkerSchedule | string;
11
- }
12
-
13
- const defaultSchedule = later.parse.text(
14
- NODE_ENV !== 'production' ? 'every 2 seconds' : 'every 30 seconds',
15
- ) as WorkerSchedule;
16
-
17
- export const scheduleToInterval = (scheduleRaw: WorkerSchedule | string) => {
18
- const referenceDate = new Date(1000);
19
- const schedule = typeof scheduleRaw === 'string' ? later.parse.text(scheduleRaw) : scheduleRaw;
20
- const [one, two] = later.schedule(schedule).next(2, referenceDate);
21
- const diff = new Date(two).getTime() - new Date(one).getTime();
22
- return Math.min(1000 * 60 * 60, diff); // at least once every hour!
23
- };
24
-
25
- export const IntervalWorker: IWorker<IntervalWorkerParams> = {
26
- ...BaseWorker,
27
-
28
- key: 'shop.unchained.worker.cron',
29
- label: 'Allocates work on fixed intervals with native node setInterval',
30
- version: '1.0.0',
31
- type: 'CRON',
32
-
33
- actions: ({ workerId, batchCount = 0, schedule = defaultSchedule }, unchainedAPI) => {
34
- const baseWorkerActions = BaseWorker.actions({ workerId, worker: IntervalWorker }, unchainedAPI);
35
-
36
- const intervalDelay = scheduleToInterval(schedule);
37
- let intervalHandle: NodeJS.Timeout;
38
-
39
- return {
40
- ...baseWorkerActions,
41
-
42
- start() {
43
- intervalHandle = setInterval(() => {
44
- baseWorkerActions.process({
45
- maxWorkItemCount: batchCount,
46
- referenceDate: IntervalWorker.getFloorDate(),
47
- });
48
- }, intervalDelay);
49
- },
50
-
51
- stop() {
52
- clearInterval(intervalHandle);
53
- },
54
- };
55
- },
56
- };