@spinajs/tasks 2.0.553 → 2.0.555

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,18 +1,48 @@
1
1
  export declare const TASK_COMMAND = "task:command";
2
- interface TaskOptions {
2
+ export interface TaskOptions {
3
+ /**
4
+ * Allow several runs of the same task at once, e.g. a long run that overlaps the next start.
5
+ */
3
6
  taskStacking: boolean;
7
+ /**
8
+ * Lifetime of the task mutex in ms, renewed every lockTtl / 3 while the task runs, so a
9
+ * crashed process frees the task after at most lockTtl. 0 = never expires.
10
+ */
11
+ lockTtl: number;
4
12
  }
13
+ export declare const DEFAULT_TASK_OPTIONS: TaskOptions;
14
+ export interface TaskDeclaration {
15
+ name: string;
16
+ description: string;
17
+ options: TaskOptions;
18
+ /** The class that declares the method (the constructor itself for a static method). */
19
+ target: Function;
20
+ isStatic: boolean;
21
+ propertyKey: string | symbol;
22
+ /** The undecorated method. */
23
+ method: (...args: any[]) => unknown;
24
+ }
25
+ export interface RunTaskOptions {
26
+ /** false: skip the task mutex, its heartbeat and the in-process guard (the caller holds a lock of its own). */
27
+ lock: boolean;
28
+ /** true: rethrow the task's error after history is written, instead of resolving with `{ error: true }`. */
29
+ rethrow: boolean;
30
+ }
31
+ export declare function getTaskDeclarations(name?: string): TaskDeclaration[];
5
32
  /**
6
- * Cli command, wrapper for lib commander. For more docs on command options & args check
7
- * https://github.com/tj/commander.js
8
- *
9
- * It allows to use all features that spinajs provides eg. DI, logging, intl support etc.
10
- * inside command functions without hassle.
33
+ * Runs a task method with the `@Task` bookkeeping: `__tasks` state, a `__task_history` row and
34
+ * TaskSuccess / TaskFailed. The decorator calls it with `{ lock: true, rethrow: false }`.
35
+ */
36
+ export declare function runTask(decl: TaskDeclaration, thisArg: unknown, args: unknown[], opts: RunTaskOptions): Promise<unknown>;
37
+ /**
38
+ * Marks a method as a task: records runs in `__tasks` / `__task_history`, emits
39
+ * TaskSuccess / TaskFailed and, unless `taskStacking` is set, lets only one run
40
+ * happen at a time across all processes sharing the database. The declaration is
41
+ * also recorded, so `@spinajs/scheduler` can schedule the method by task name.
11
42
  *
12
- * @param nameAndArgs - name of command with optional args defined
13
- * @param description - short description
14
- * @param opts - additional options, see https://github.com/tj/commander.js
43
+ * @param taskName - unique task name
44
+ * @param description - short description
45
+ * @param opts - see {@link TaskOptions}, defaults to {@link DEFAULT_TASK_OPTIONS}
15
46
  */
16
- export declare function Task(taskName: string, description: string, opts?: TaskOptions): (_target: any, _propertyKey: string | symbol, descriptor: PropertyDescriptor) => void;
17
- export {};
47
+ export declare function Task(taskName: string, description: string, opts?: Partial<TaskOptions>): (target: any, propertyKey: string | symbol, descriptor: PropertyDescriptor) => void;
18
48
  //# sourceMappingURL=decorators.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"decorators.d.ts","sourceRoot":"","sources":["../../src/decorators.ts"],"names":[],"mappings":"AAUA,eAAO,MAAM,YAAY,iBAAiB,CAAC;AAE3C,UAAU,WAAW;IAInB,YAAY,EAAE,OAAO,CAAC;CACvB;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,IAAI,CAAC,QAAQ,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,WAAW,aAIlD,GAAG,gBAAgB,MAAM,GAAG,MAAM,cAAc,kBAAkB,UA4E7F"}
1
+ {"version":3,"file":"decorators.d.ts","sourceRoot":"","sources":["../../src/decorators.ts"],"names":[],"mappings":"AAUA,eAAO,MAAM,YAAY,iBAAiB,CAAC;AAE3C,MAAM,WAAW,WAAW;IAC1B;;OAEG;IACH,YAAY,EAAE,OAAO,CAAC;IAEtB;;;OAGG;IACH,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,eAAO,MAAM,oBAAoB,EAAE,WAGlC,CAAC;AAqDF,MAAM,WAAW,eAAe;IAC9B,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,CAAC;IACpB,OAAO,EAAE,WAAW,CAAC;IACrB,uFAAuF;IACvF,MAAM,EAAE,QAAQ,CAAC;IACjB,QAAQ,EAAE,OAAO,CAAC;IAClB,WAAW,EAAE,MAAM,GAAG,MAAM,CAAC;IAC7B,8BAA8B;IAC9B,MAAM,EAAE,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,OAAO,CAAC;CACrC;AAED,MAAM,WAAW,cAAc;IAC7B,+GAA+G;IAC/G,IAAI,EAAE,OAAO,CAAC;IACd,4GAA4G;IAC5G,OAAO,EAAE,OAAO,CAAC;CAClB;AAID,wBAAgB,mBAAmB,CAAC,IAAI,CAAC,EAAE,MAAM,GAAG,eAAe,EAAE,CAKpE;AAQD;;;GAGG;AACH,wBAAsB,OAAO,CAC3B,IAAI,EAAE,eAAe,EACrB,OAAO,EAAE,OAAO,EAChB,IAAI,EAAE,OAAO,EAAE,EACf,IAAI,EAAE,cAAc,GACnB,OAAO,CAAC,OAAO,CAAC,CAsFlB;AAED;;;;;;;;;GASG;AACH,wBAAgB,IAAI,CAAC,QAAQ,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,OAAO,CAAC,WAAW,CAAC,YAK5D,GAAG,eAAe,MAAM,GAAG,MAAM,cAAc,kBAAkB,UAiB3F"}
@@ -1,6 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.TASK_COMMAND = void 0;
3
+ exports.DEFAULT_TASK_OPTIONS = exports.TASK_COMMAND = void 0;
4
+ exports.getTaskDeclarations = getTaskDeclarations;
5
+ exports.runTask = runTask;
4
6
  exports.Task = Task;
5
7
  const threading_1 = require("@spinajs/threading");
6
8
  const util_1 = require("@spinajs/util");
@@ -11,87 +13,181 @@ const __task_history_js_1 = require("./models/__task_history.js");
11
13
  const TaskSuccess_js_1 = require("./events/TaskSuccess.js");
12
14
  const TaskFailed_js_1 = require("./events/TaskFailed.js");
13
15
  exports.TASK_COMMAND = 'task:command';
16
+ exports.DEFAULT_TASK_OPTIONS = {
17
+ taskStacking: false,
18
+ lockTtl: 60000,
19
+ };
20
+ // The mutex is re-entrant per tenant and the default tenant is per process,
21
+ // so overlapping runs inside one process are excluded here, not by the mutex.
22
+ const runningInProcess = new Set();
23
+ async function lockTask(name, opts, log) {
24
+ if (opts.taskStacking) {
25
+ return async () => { };
26
+ }
27
+ if (runningInProcess.has(name)) {
28
+ log.warn(`Task ${name} is already running in this process`);
29
+ return null;
30
+ }
31
+ runningInProcess.add(name);
32
+ const mutexName = `task-${name}`;
33
+ try {
34
+ const lock = await (0, threading_1.mutex_acquire)({ Name: mutexName, ttl: opts.lockTtl });
35
+ if (!lock.Locked) {
36
+ runningInProcess.delete(name);
37
+ log.warn(`Cannot acquire mutex for task ${name}, already locked !`);
38
+ return null;
39
+ }
40
+ }
41
+ catch (err) {
42
+ runningInProcess.delete(name);
43
+ throw err;
44
+ }
45
+ const heartbeat = opts.lockTtl > 0
46
+ ? setInterval(() => {
47
+ (0, threading_1.mutex_renew)({ Name: mutexName, ttl: opts.lockTtl })
48
+ .then((renewed) => {
49
+ if (!renewed) {
50
+ log.warn(`Task ${name} lost its mutex, another process may run it now`);
51
+ }
52
+ })
53
+ .catch((err) => log.error(err, `Cannot renew mutex for task ${name}`));
54
+ }, Math.max(1, Math.floor(opts.lockTtl / 3)))
55
+ : undefined;
56
+ return async () => {
57
+ clearInterval(heartbeat);
58
+ runningInProcess.delete(name);
59
+ await (0, threading_1.mutex_release)({ Name: mutexName });
60
+ };
61
+ }
62
+ const declarations = new Map();
63
+ function getTaskDeclarations(name) {
64
+ if (name !== undefined) {
65
+ return [...(declarations.get(name) ?? [])];
66
+ }
67
+ return [...declarations.values()].flat();
68
+ }
69
+ function errorMessage(err) {
70
+ return err?.message ?? String(err);
71
+ }
72
+ const NO_LOCK = () => Promise.resolve();
14
73
  /**
15
- * Cli command, wrapper for lib commander. For more docs on command options & args check
16
- * https://github.com/tj/commander.js
17
- *
18
- * It allows to use all features that spinajs provides eg. DI, logging, intl support etc.
19
- * inside command functions without hassle.
74
+ * Runs a task method with the `@Task` bookkeeping: `__tasks` state, a `__task_history` row and
75
+ * TaskSuccess / TaskFailed. The decorator calls it with `{ lock: true, rethrow: false }`.
76
+ */
77
+ async function runTask(decl, thisArg, args, opts) {
78
+ const log = di_1.DI.resolve('__log__', ['TASKS']);
79
+ log.info(`Executing task ${decl.name} ...`);
80
+ let task;
81
+ let unlock;
82
+ try {
83
+ task = await __task_js_1.__task.getOrCreate(null, {
84
+ Name: decl.name,
85
+ Description: decl.description,
86
+ State: 'stopped',
87
+ });
88
+ const lock = opts.lock ? await lockTask(decl.name, decl.options, log) : NO_LOCK;
89
+ if (!lock) {
90
+ return undefined;
91
+ }
92
+ unlock = lock;
93
+ try {
94
+ task.State = 'running';
95
+ task.LastRunAt = luxon_1.DateTime.now();
96
+ await task.update();
97
+ }
98
+ catch (err) {
99
+ await unlock();
100
+ throw err;
101
+ }
102
+ }
103
+ catch (err) {
104
+ log.error(err, `Cannot start task ${decl.name}`);
105
+ throw err;
106
+ }
107
+ let taskResult = null;
108
+ let failure = null;
109
+ const start = luxon_1.DateTime.now();
110
+ try {
111
+ try {
112
+ taskResult = await decl.method.apply(thisArg, args);
113
+ }
114
+ catch (err) {
115
+ failure = { error: err };
116
+ log.error(err, `Cannot execute task ${decl.name}`);
117
+ taskResult = {
118
+ error: true,
119
+ message: errorMessage(err),
120
+ };
121
+ }
122
+ // An emit failure (queue outage) is logged only: it must not turn a run whose side effects
123
+ // already happened into a failure that a caller would retry.
124
+ try {
125
+ if (failure) {
126
+ await TaskFailed_js_1.TaskFailed.emit({
127
+ TaskName: decl.name,
128
+ Reason: errorMessage(failure.error),
129
+ });
130
+ }
131
+ else {
132
+ await TaskSuccess_js_1.TaskSuccess.emit({
133
+ TaskName: decl.name,
134
+ });
135
+ log.success(`Task ${decl.name} executed !`);
136
+ }
137
+ }
138
+ catch (emitErr) {
139
+ log.error(emitErr, `Cannot emit ${failure ? 'TaskFailed' : 'TaskSuccess'} for ${decl.name}`);
140
+ }
141
+ }
142
+ finally {
143
+ try {
144
+ await unlock();
145
+ await task.update({
146
+ State: 'stopped',
147
+ });
148
+ await __task_history_js_1.__task_history.insert({
149
+ TaskId: task.Id,
150
+ Result: taskResult,
151
+ Duration: luxon_1.DateTime.now().diff(start).milliseconds,
152
+ });
153
+ }
154
+ catch (err) {
155
+ log.error(err, `Cannot finalize task`);
156
+ }
157
+ }
158
+ if (failure && opts.rethrow) {
159
+ throw failure.error;
160
+ }
161
+ return taskResult;
162
+ }
163
+ /**
164
+ * Marks a method as a task: records runs in `__tasks` / `__task_history`, emits
165
+ * TaskSuccess / TaskFailed and, unless `taskStacking` is set, lets only one run
166
+ * happen at a time across all processes sharing the database. The declaration is
167
+ * also recorded, so `@spinajs/scheduler` can schedule the method by task name.
20
168
  *
21
- * @param nameAndArgs - name of command with optional args defined
22
- * @param description - short description
23
- * @param opts - additional options, see https://github.com/tj/commander.js
169
+ * @param taskName - unique task name
170
+ * @param description - short description
171
+ * @param opts - see {@link TaskOptions}, defaults to {@link DEFAULT_TASK_OPTIONS}
24
172
  */
25
173
  function Task(taskName, description, opts) {
26
174
  const _name = (0, util_1._check_arg)((0, util_1._trim)(), (0, util_1._non_empty)())(taskName, 'Task name is empty');
27
175
  const _description = (0, util_1._check_arg)((0, util_1._trim)(), (0, util_1._non_empty)())(description, 'Task description is empty');
28
- return function (_target, _propertyKey, descriptor) {
29
- const oldFunction = descriptor.value;
30
- descriptor.value = async function (...args) {
31
- const log = di_1.DI.resolve('__log__', ['TASKS']);
32
- log.info(`Executing task ${_name} ...`);
33
- try {
34
- const task = await __task_js_1.__task.getOrCreate(null, {
35
- Name: _name,
36
- Description: _description,
37
- State: 'stopped',
38
- });
39
- if (!opts.taskStacking) {
40
- const lock = await (0, threading_1.mutex_acquire)({
41
- Name: `task-${_name}`,
42
- });
43
- if (!lock.Locked) {
44
- log.warn(`Cannot acquire mutex for task ${_name}, already locked !`);
45
- return;
46
- }
47
- }
48
- task.State = 'running';
49
- task.LastRunAt = luxon_1.DateTime.now();
50
- await task.update();
51
- let taskResult = null;
52
- const start = luxon_1.DateTime.now();
53
- try {
54
- taskResult = await oldFunction.apply(this, args);
55
- await TaskSuccess_js_1.TaskSuccess.emit({
56
- TaskName: taskName,
57
- });
58
- log.success(`Task ${taskName} executed !`);
59
- }
60
- catch (err) {
61
- log.error(err, `Cannot execute task ${taskName}`);
62
- taskResult = {
63
- error: true,
64
- message: err.Message,
65
- };
66
- await TaskFailed_js_1.TaskFailed.emit({
67
- TaskName: taskName,
68
- Reason: err.Message,
69
- });
70
- }
71
- finally {
72
- try {
73
- await (0, threading_1.mutex_release)({
74
- Name: `task-${name}`,
75
- });
76
- await task.update({
77
- State: 'stopped',
78
- });
79
- await __task_history_js_1.__task_history.insert({
80
- TaskId: task.Id,
81
- Result: taskResult,
82
- Duration: luxon_1.DateTime.now().diff(start).milliseconds,
83
- });
84
- }
85
- catch (err) {
86
- log.error(err, `Cannot finalize task`);
87
- }
88
- return taskResult;
89
- }
90
- }
91
- catch (err) {
92
- log.error(err, `Cannot start task ${taskName}`);
93
- throw err;
94
- }
176
+ const _opts = { ...exports.DEFAULT_TASK_OPTIONS, ...opts };
177
+ return function (target, propertyKey, descriptor) {
178
+ const isStatic = typeof target === 'function';
179
+ const decl = {
180
+ name: _name,
181
+ description: _description,
182
+ options: _opts,
183
+ target: isStatic ? target : target.constructor,
184
+ isStatic,
185
+ propertyKey,
186
+ method: descriptor.value,
187
+ };
188
+ declarations.set(_name, [...(declarations.get(_name) ?? []), decl]);
189
+ descriptor.value = function (...args) {
190
+ return runTask(decl, this, args, { lock: true, rethrow: false });
95
191
  };
96
192
  };
97
193
  }
@@ -1 +1 @@
1
- {"version":3,"file":"decorators.js","sourceRoot":"","sources":["../../src/decorators.ts"],"names":[],"mappings":";;;;AAAA,kDAAkE;AAClE,wCAA8D;AAC9D,oCAAiC;AACjC,kDAA4C;AAC5C,iCAAiC;AACjC,kEAA4D;AAE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,CAAC,CAAC,QAAQ,EAAE,oBAAoB,CAAC,CAAC;IACxF,MAAM,YAAY,GAAW,IAAA,iBAAU,EAAC,IAAA,YAAK,GAAE,EAAE,IAAA,iBAAU,GAAE,CAAC,CAAC,WAAW,EAAE,2BAA2B,CAAC,CAAC;IACzG,MAAM,KAAK,GAAgB,EAAE,GAAG,QAAA,oBAAoB,EAAE,GAAG,IAAI,EAAE,CAAC;IAEhE,OAAO,UAAU,MAAW,EAAE,WAA4B,EAAE,UAA8B;QACxF,MAAM,QAAQ,GAAG,OAAO,MAAM,KAAK,UAAU,CAAC;QAC9C,MAAM,IAAI,GAAoB;YAC5B,IAAI,EAAE,KAAK;YACX,WAAW,EAAE,YAAY;YACzB,OAAO,EAAE,KAAK;YACd,MAAM,EAAE,QAAQ,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,WAAW;YAC9C,QAAQ;YACR,WAAW;YACX,MAAM,EAAE,UAAU,CAAC,KAAK;SACzB,CAAC;QACF,YAAY,CAAC,GAAG,CAAC,KAAK,EAAE,CAAC,GAAG,CAAC,YAAY,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC,EAAE,IAAI,CAAC,CAAC,CAAC;QAEpE,UAAU,CAAC,KAAK,GAAG,UAAU,GAAG,IAAW;YACzC,OAAO,OAAO,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC,CAAC;QACnE,CAAC,CAAC;IACJ,CAAC,CAAC;AACJ,CAAC"}
@@ -1,18 +1,48 @@
1
1
  export declare const TASK_COMMAND = "task:command";
2
- interface TaskOptions {
2
+ export interface TaskOptions {
3
+ /**
4
+ * Allow several runs of the same task at once, e.g. a long run that overlaps the next start.
5
+ */
3
6
  taskStacking: boolean;
7
+ /**
8
+ * Lifetime of the task mutex in ms, renewed every lockTtl / 3 while the task runs, so a
9
+ * crashed process frees the task after at most lockTtl. 0 = never expires.
10
+ */
11
+ lockTtl: number;
4
12
  }
13
+ export declare const DEFAULT_TASK_OPTIONS: TaskOptions;
14
+ export interface TaskDeclaration {
15
+ name: string;
16
+ description: string;
17
+ options: TaskOptions;
18
+ /** The class that declares the method (the constructor itself for a static method). */
19
+ target: Function;
20
+ isStatic: boolean;
21
+ propertyKey: string | symbol;
22
+ /** The undecorated method. */
23
+ method: (...args: any[]) => unknown;
24
+ }
25
+ export interface RunTaskOptions {
26
+ /** false: skip the task mutex, its heartbeat and the in-process guard (the caller holds a lock of its own). */
27
+ lock: boolean;
28
+ /** true: rethrow the task's error after history is written, instead of resolving with `{ error: true }`. */
29
+ rethrow: boolean;
30
+ }
31
+ export declare function getTaskDeclarations(name?: string): TaskDeclaration[];
5
32
  /**
6
- * Cli command, wrapper for lib commander. For more docs on command options & args check
7
- * https://github.com/tj/commander.js
8
- *
9
- * It allows to use all features that spinajs provides eg. DI, logging, intl support etc.
10
- * inside command functions without hassle.
33
+ * Runs a task method with the `@Task` bookkeeping: `__tasks` state, a `__task_history` row and
34
+ * TaskSuccess / TaskFailed. The decorator calls it with `{ lock: true, rethrow: false }`.
35
+ */
36
+ export declare function runTask(decl: TaskDeclaration, thisArg: unknown, args: unknown[], opts: RunTaskOptions): Promise<unknown>;
37
+ /**
38
+ * Marks a method as a task: records runs in `__tasks` / `__task_history`, emits
39
+ * TaskSuccess / TaskFailed and, unless `taskStacking` is set, lets only one run
40
+ * happen at a time across all processes sharing the database. The declaration is
41
+ * also recorded, so `@spinajs/scheduler` can schedule the method by task name.
11
42
  *
12
- * @param nameAndArgs - name of command with optional args defined
13
- * @param description - short description
14
- * @param opts - additional options, see https://github.com/tj/commander.js
43
+ * @param taskName - unique task name
44
+ * @param description - short description
45
+ * @param opts - see {@link TaskOptions}, defaults to {@link DEFAULT_TASK_OPTIONS}
15
46
  */
16
- export declare function Task(taskName: string, description: string, opts?: TaskOptions): (_target: any, _propertyKey: string | symbol, descriptor: PropertyDescriptor) => void;
17
- export {};
47
+ export declare function Task(taskName: string, description: string, opts?: Partial<TaskOptions>): (target: any, propertyKey: string | symbol, descriptor: PropertyDescriptor) => void;
18
48
  //# sourceMappingURL=decorators.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"decorators.d.ts","sourceRoot":"","sources":["../../src/decorators.ts"],"names":[],"mappings":"AAUA,eAAO,MAAM,YAAY,iBAAiB,CAAC;AAE3C,UAAU,WAAW;IAInB,YAAY,EAAE,OAAO,CAAC;CACvB;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,IAAI,CAAC,QAAQ,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,WAAW,aAIlD,GAAG,gBAAgB,MAAM,GAAG,MAAM,cAAc,kBAAkB,UA4E7F"}
1
+ {"version":3,"file":"decorators.d.ts","sourceRoot":"","sources":["../../src/decorators.ts"],"names":[],"mappings":"AAUA,eAAO,MAAM,YAAY,iBAAiB,CAAC;AAE3C,MAAM,WAAW,WAAW;IAC1B;;OAEG;IACH,YAAY,EAAE,OAAO,CAAC;IAEtB;;;OAGG;IACH,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,eAAO,MAAM,oBAAoB,EAAE,WAGlC,CAAC;AAqDF,MAAM,WAAW,eAAe;IAC9B,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,CAAC;IACpB,OAAO,EAAE,WAAW,CAAC;IACrB,uFAAuF;IACvF,MAAM,EAAE,QAAQ,CAAC;IACjB,QAAQ,EAAE,OAAO,CAAC;IAClB,WAAW,EAAE,MAAM,GAAG,MAAM,CAAC;IAC7B,8BAA8B;IAC9B,MAAM,EAAE,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,OAAO,CAAC;CACrC;AAED,MAAM,WAAW,cAAc;IAC7B,+GAA+G;IAC/G,IAAI,EAAE,OAAO,CAAC;IACd,4GAA4G;IAC5G,OAAO,EAAE,OAAO,CAAC;CAClB;AAID,wBAAgB,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