@chevre/domain 22.11.0-alpha.22 → 22.11.0-alpha.24

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.
@@ -0,0 +1,41 @@
1
+ // tslint:disable:no-console
2
+ import * as mongoose from 'mongoose';
3
+
4
+ import { chevre } from '../../../../lib/index';
5
+
6
+ // const project = { id: String(process.env.PROJECT_ID) };
7
+
8
+ mongoose.Model.on('index', (...args) => {
9
+ console.error('******** index event emitted. ********\n', args);
10
+ });
11
+
12
+ const excludedTaskNames = [
13
+ chevre.factory.taskName.DeleteTransaction,
14
+ chevre.factory.taskName.ImportEventCapacitiesFromCOA,
15
+ chevre.factory.taskName.ImportEventsFromCOA,
16
+ chevre.factory.taskName.AcceptCOAOffer,
17
+ chevre.factory.taskName.CheckMovieTicket,
18
+ chevre.factory.taskName.AuthorizePayment,
19
+ chevre.factory.taskName.PublishPaymentUrl
20
+ ];
21
+ async function main() {
22
+ await mongoose.connect(<string>process.env.MONGOLAB_URI, { autoIndex: false });
23
+
24
+ let allTaskNames = Object.values(chevre.factory.taskName);
25
+ allTaskNames = allTaskNames.filter((taskName) => !excludedTaskNames.includes(taskName));
26
+ console.log('allTaskNames:', allTaskNames, allTaskNames.length);
27
+ const taskRepo = await chevre.repository.Task.createInstance(mongoose.connection);
28
+
29
+ const result = await taskRepo.countPotentiallyRunning({
30
+ name: {
31
+ $in: allTaskNames
32
+ },
33
+ runsAt: { $lt: new Date() },
34
+ limit: 100
35
+ });
36
+ console.log('result:', result);
37
+ }
38
+
39
+ main()
40
+ .then()
41
+ .catch(console.error);
@@ -0,0 +1,50 @@
1
+ // tslint:disable:no-console
2
+ import * as mongoose from 'mongoose';
3
+
4
+ import { chevre } from '../../../../lib/index';
5
+
6
+ // const project = { id: String(process.env.PROJECT_ID) };
7
+
8
+ mongoose.Model.on('index', (...args) => {
9
+ console.error('******** index event emitted. ********\n', args);
10
+ });
11
+
12
+ async function main() {
13
+ await mongoose.connect(<string>process.env.MONGOLAB_URI, { autoIndex: false });
14
+
15
+ const taskRepo = await chevre.repository.Task.createInstance(mongoose.connection);
16
+
17
+ setInterval(
18
+ async () => {
19
+ const readyTasksCountResult = await taskRepo.count({
20
+ limit: 100,
21
+ status: { $eq: chevre.factory.taskStatus.Ready },
22
+ runsThrough: new Date()
23
+ });
24
+ console.log('readyTasksCountResult:', readyTasksCountResult);
25
+
26
+ const readyTasks = await taskRepo.projectFields(
27
+ {
28
+ limit: 10,
29
+ status: { $eq: chevre.factory.taskStatus.Ready },
30
+ runsThrough: new Date(),
31
+ name: { $nin: [chevre.factory.taskName.DeleteTransaction] }
32
+ },
33
+ ['name']
34
+ );
35
+ console.log('readyTasks:', readyTasks);
36
+
37
+ const runningTasksCountResult = await taskRepo.count({
38
+ limit: 100,
39
+ status: { $eq: chevre.factory.taskStatus.Running }
40
+ });
41
+ console.log('runningTasksCountResult:', runningTasksCountResult);
42
+ },
43
+ // tslint:disable-next-line:no-magic-numbers
44
+ 10000
45
+ );
46
+ }
47
+
48
+ main()
49
+ .then()
50
+ .catch(console.error);
@@ -103,7 +103,7 @@ export declare class TaskRepo {
103
103
  countPotentiallyRunning(params: {
104
104
  name?: {
105
105
  $eq?: factory.taskName;
106
- $nin?: factory.taskName[];
106
+ $in?: factory.taskName[];
107
107
  };
108
108
  runsAt: {
109
109
  $lt: Date;
@@ -118,7 +118,7 @@ export declare class TaskRepo {
118
118
  emitRunningIfExists(params: {
119
119
  name?: {
120
120
  $eq?: factory.taskName;
121
- $nin?: factory.taskName[];
121
+ $in?: factory.taskName[];
122
122
  };
123
123
  executor: {
124
124
  name: string;
@@ -127,7 +127,6 @@ export declare class TaskRepo {
127
127
  $lt: Date;
128
128
  };
129
129
  sort: {
130
- numberOfTried?: factory.sortType;
131
130
  runsAt: factory.sortType;
132
131
  };
133
132
  }, next?: INextFunction): Promise<Pick<factory.task.ITask<factory.taskName>, 'id' | 'name'> | null>;
@@ -31,7 +31,7 @@ const task_2 = require("./mongoose/schemas/task");
31
31
  * タスク実行時のソート条件
32
32
  */
33
33
  const sortOrder4executionOfTasks = {
34
- numberOfTried: factory.sortType.Ascending, // トライ回数の少なさ優先
34
+ // numberOfTried: factory.sortType.Ascending, // トライ回数の少なさ優先 // discontinue(2025-08-06~)
35
35
  runsAt: factory.sortType.Ascending // 実行予定日時の早さ優先
36
36
  };
37
37
  const executableTaskProjection = {
@@ -433,13 +433,14 @@ class TaskRepo {
433
433
  return __awaiter(this, void 0, void 0, function* () {
434
434
  const { runsAt, limit, name } = params;
435
435
  const nameEq = name === null || name === void 0 ? void 0 : name.$eq;
436
- const nameNin = name === null || name === void 0 ? void 0 : name.$nin;
436
+ // const nameNin = name?.$nin;
437
+ const nameIn = name === null || name === void 0 ? void 0 : name.$in;
437
438
  if (!(runsAt.$lt instanceof Date)) {
438
439
  throw new factory.errors.Argument('runsAt.$lt', 'must be Date');
439
440
  }
440
- const query = this.taskModel.countDocuments(Object.assign({ status: { $eq: factory.taskStatus.Ready }, runsAt: { $lt: params.runsAt.$lt } }, (typeof nameEq === 'string' || Array.isArray(nameNin))
441
+ const query = this.taskModel.countDocuments(Object.assign({ status: { $eq: factory.taskStatus.Ready }, runsAt: { $lt: params.runsAt.$lt } }, (typeof nameEq === 'string' || Array.isArray(nameIn))
441
442
  ? {
442
- name: Object.assign(Object.assign({}, (typeof nameEq === 'string') ? { $eq: nameEq } : undefined), (Array.isArray(nameNin)) ? { $nin: nameNin } : undefined)
443
+ name: Object.assign(Object.assign({}, (typeof nameEq === 'string') ? { $eq: nameEq } : undefined), (Array.isArray(nameIn)) ? { $in: nameIn } : undefined)
443
444
  }
444
445
  : undefined));
445
446
  if (typeof limit === 'number' && limit >= 0) {
@@ -466,10 +467,11 @@ class TaskRepo {
466
467
  name: 1
467
468
  };
468
469
  const nameEq = (_a = params.name) === null || _a === void 0 ? void 0 : _a.$eq;
469
- const nameNin = (_b = params.name) === null || _b === void 0 ? void 0 : _b.$nin;
470
- const doc = yield this.taskModel.findOneAndUpdate(Object.assign({ status: { $eq: factory.taskStatus.Ready }, runsAt: { $lt: params.runsAt.$lt } }, (typeof nameEq === 'string' || Array.isArray(nameNin))
470
+ // const nameNin = params.name?.$nin;
471
+ const nameIn = (_b = params.name) === null || _b === void 0 ? void 0 : _b.$in;
472
+ const doc = yield this.taskModel.findOneAndUpdate(Object.assign({ status: { $eq: factory.taskStatus.Ready }, runsAt: { $lt: params.runsAt.$lt } }, (typeof nameEq === 'string' || Array.isArray(nameIn))
471
473
  ? {
472
- name: Object.assign(Object.assign({}, (typeof nameEq === 'string') ? { $eq: nameEq } : undefined), (Array.isArray(nameNin)) ? { $nin: nameNin } : undefined)
474
+ name: Object.assign(Object.assign({}, (typeof nameEq === 'string') ? { $eq: nameEq } : undefined), (Array.isArray(nameIn)) ? { $in: nameIn } : undefined)
473
475
  }
474
476
  : undefined), {
475
477
  $set: {
@@ -0,0 +1,8 @@
1
+ import * as factory from '../../../factory';
2
+ import type { SettingRepo } from '../../../repo/setting';
3
+ import type { IExecutableTask, TaskRepo } from '../../../repo/task';
4
+ declare function informTaskIfNeeded(task: IExecutableTask<factory.taskName>): (repos: {
5
+ setting: SettingRepo;
6
+ task: TaskRepo;
7
+ }) => Promise<void>;
8
+ export { informTaskIfNeeded };
@@ -0,0 +1,82 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.informTaskIfNeeded = informTaskIfNeeded;
13
+ const createDebug = require("debug");
14
+ const factory = require("../../../factory");
15
+ const debug = createDebug('chevre-domain:service:taskHandler:onOperationFailed');
16
+ function createInformTasks(task, setting) {
17
+ var _a, _b;
18
+ const taskRunsAt = new Date();
19
+ const informTask = (_a = setting === null || setting === void 0 ? void 0 : setting.onTaskStatusChanged) === null || _a === void 0 ? void 0 : _a.informTask;
20
+ const informTaskNames = (_b = setting === null || setting === void 0 ? void 0 : setting.onTaskStatusChanged) === null || _b === void 0 ? void 0 : _b.informTaskNames;
21
+ const informTasks = [];
22
+ if (Array.isArray(informTaskNames) && informTaskNames.includes(task.name)) {
23
+ const { id, name, data, project, runsAt } = task;
24
+ const task4inform = {
25
+ id, name, data, project, runsAt,
26
+ status: factory.taskStatus.Aborted,
27
+ typeOf: 'Task'
28
+ };
29
+ const informIdentifier = `Task:${name}:${id}:${task4inform.status}`;
30
+ if (Array.isArray(informTask) && informTask.length > 0) {
31
+ informTask.forEach((informTaskParams) => {
32
+ var _a, _b;
33
+ if (typeof ((_a = informTaskParams.recipient) === null || _a === void 0 ? void 0 : _a.url) === 'string') {
34
+ const informActionAttributes = {
35
+ object: task4inform,
36
+ recipient: {
37
+ id: '',
38
+ name: String((_b = informTaskParams.recipient) === null || _b === void 0 ? void 0 : _b.name),
39
+ typeOf: factory.creativeWorkType.WebApplication
40
+ },
41
+ target: {
42
+ httpMethod: 'POST',
43
+ encodingType: factory.encodingFormat.Application.json,
44
+ typeOf: 'EntryPoint',
45
+ urlTemplate: informTaskParams.recipient.url
46
+ },
47
+ identifier: informIdentifier
48
+ };
49
+ const description = `inform aborting tasks to agg service: ${name} ${id}`;
50
+ informTasks.push({
51
+ project,
52
+ name: factory.taskName.TriggerWebhook,
53
+ status: factory.taskStatus.Ready,
54
+ runsAt: taskRunsAt,
55
+ remainingNumberOfTries: 10,
56
+ numberOfTried: 0,
57
+ executionResults: [],
58
+ data: informActionAttributes,
59
+ description
60
+ });
61
+ }
62
+ });
63
+ }
64
+ }
65
+ return informTasks;
66
+ }
67
+ function informTaskIfNeeded(task) {
68
+ return (repos) => __awaiter(this, void 0, void 0, function* () {
69
+ const isAborting = task.status === factory.taskStatus.Running && task.remainingNumberOfTries <= 0;
70
+ const useInform = isAborting
71
+ && task.name !== factory.taskName.HandleNotification // nameで絞る
72
+ && task.name !== factory.taskName.TriggerWebhook;
73
+ if (useInform) {
74
+ const setting = yield repos.setting.findOne({ project: { id: { $eq: '*' } } }, ['onTaskStatusChanged']);
75
+ const informTasks = createInformTasks(task, setting);
76
+ debug('informTaskIfNeeded: creating inform tasks...', JSON.stringify(informTasks));
77
+ if (informTasks.length > 0) {
78
+ yield repos.task.saveMany(informTasks, { emitImmediately: true });
79
+ }
80
+ }
81
+ });
82
+ }
@@ -0,0 +1,17 @@
1
+ import type { INextFunction } from '../../eventEmitter/task';
2
+ import * as factory from '../../factory';
3
+ import type { SettingRepo } from '../../repo/setting';
4
+ import type { IExecutableTask, TaskRepo } from '../../repo/task';
5
+ /**
6
+ * タスク実行失敗時処理
7
+ */
8
+ declare function onOperationFailed(params: {
9
+ task: IExecutableTask<factory.taskName>;
10
+ now: Date;
11
+ error: any;
12
+ next?: INextFunction;
13
+ }): (repos: {
14
+ setting: SettingRepo;
15
+ task: TaskRepo;
16
+ }) => Promise<void>;
17
+ export { onOperationFailed };
@@ -0,0 +1,64 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.onOperationFailed = onOperationFailed;
13
+ const factory = require("../../factory");
14
+ const informTaskIfNeeded_1 = require("./onOperationFailed/informTaskIfNeeded");
15
+ /**
16
+ * タスク実行失敗時処理
17
+ */
18
+ function onOperationFailed(params) {
19
+ return (repos) => __awaiter(this, void 0, void 0, function* () {
20
+ let error = params.error;
21
+ const { task, now, next } = params;
22
+ if (typeof error !== 'object') {
23
+ error = { message: String(error) };
24
+ }
25
+ // remainingNumberOfTries<=0ならAborted(2025-08-04~)
26
+ const isRetryable = task.remainingNumberOfTries > 0;
27
+ if (isRetryable) {
28
+ const result = {
29
+ executedAt: now,
30
+ endDate: new Date(),
31
+ error: Object.assign(Object.assign({}, error), { code: error.code, message: error.message, name: error.name, stack: error.stack })
32
+ };
33
+ // 失敗してもここではステータスを戻さない(Runningのまま待機)
34
+ yield repos.task.setExecutionResultAndStatus({
35
+ id: task.id,
36
+ remainingNumberOfTries: task.remainingNumberOfTries,
37
+ name: task.name
38
+ }, {
39
+ status: task.status,
40
+ executionResult: result
41
+ }, (typeof next === 'function') ? next : undefined);
42
+ }
43
+ else {
44
+ // 分析連携(2025-08-05~)
45
+ // 設定されたnameの場合連携する
46
+ // もしここで連携タスク作成に失敗したとしても、再度Readyタスクとなりリトライされて、処理は冪等となる想定
47
+ // 最終的に、連携タスクが作成され、実行中タスクがAbortedとなればよい
48
+ yield (0, informTaskIfNeeded_1.informTaskIfNeeded)(task)(repos);
49
+ const result = {
50
+ executedAt: now,
51
+ endDate: new Date(),
52
+ error: Object.assign(Object.assign({}, error), { code: error.code, message: error.message, name: error.name, stack: error.stack })
53
+ };
54
+ yield repos.task.setExecutionResultAndStatus({
55
+ id: task.id,
56
+ remainingNumberOfTries: task.remainingNumberOfTries,
57
+ name: task.name
58
+ }, {
59
+ status: factory.taskStatus.Aborted,
60
+ executionResult: result
61
+ }, (typeof next === 'function') ? next : undefined);
62
+ }
63
+ });
64
+ }
@@ -1,9 +1,9 @@
1
- import { SendGridCredentials } from '../credentials/sendGrid';
1
+ import type { SendGridCredentials } from '../credentials/sendGrid';
2
2
  import type { IExecuteSettings as IMinimumExecuteSettings, INextFunction } from '../eventEmitter/task';
3
3
  import * as factory from '../factory';
4
4
  import type { IExecutableTask, IExecutableTaskKeys } from '../repo/task';
5
- import { Settings } from '../settings';
6
- import { AggregationSettings } from '../settings/aggregation';
5
+ import type { Settings } from '../settings';
6
+ import type { AggregationSettings } from '../settings/aggregation';
7
7
  interface ICredentialSettings {
8
8
  sendGrid: SendGridCredentials;
9
9
  }
@@ -13,52 +13,8 @@ exports.executeTask = executeTask;
13
13
  const createDebug = require("debug");
14
14
  const moment = require("moment");
15
15
  const factory = require("../factory");
16
- const debug = createDebug('chevre-domain:service:task');
17
- /**
18
- * タスク実行失敗時処理
19
- */
20
- function onOperationFailed(params) {
21
- return (repos) => __awaiter(this, void 0, void 0, function* () {
22
- let error = params.error;
23
- const { task, now, next } = params;
24
- if (typeof error !== 'object') {
25
- error = { message: String(error) };
26
- }
27
- // remainingNumberOfTries<=0ならAborted(2025-08-04~)
28
- const isRetryable = task.remainingNumberOfTries > 0;
29
- if (isRetryable) {
30
- const result = {
31
- executedAt: now,
32
- endDate: new Date(),
33
- error: Object.assign(Object.assign({}, error), { code: error.code, message: error.message, name: error.name, stack: error.stack })
34
- };
35
- // 失敗してもここではステータスを戻さない(Runningのまま待機)
36
- yield repos.task.setExecutionResultAndStatus({
37
- id: task.id,
38
- remainingNumberOfTries: task.remainingNumberOfTries,
39
- name: task.name
40
- }, {
41
- status: task.status,
42
- executionResult: result
43
- }, (typeof next === 'function') ? next : undefined);
44
- }
45
- else {
46
- const result = {
47
- executedAt: now,
48
- endDate: new Date(),
49
- error: Object.assign(Object.assign({}, error), { code: error.code, message: error.message, name: error.name, stack: error.stack })
50
- };
51
- yield repos.task.setExecutionResultAndStatus({
52
- id: task.id,
53
- remainingNumberOfTries: task.remainingNumberOfTries,
54
- name: task.name
55
- }, {
56
- status: factory.taskStatus.Aborted,
57
- executionResult: result
58
- }, (typeof next === 'function') ? next : undefined);
59
- }
60
- });
61
- }
16
+ const onOperationFailed_1 = require("./taskHandler/onOperationFailed");
17
+ const debug = createDebug('chevre-domain:service:taskHandler');
62
18
  /**
63
19
  * タスクを実行する
64
20
  */
@@ -67,6 +23,7 @@ function executeTask(task, next) {
67
23
  const now = new Date();
68
24
  debug('executing an executableTask...', task, now);
69
25
  return (settings, options) => __awaiter(this, void 0, void 0, function* () {
26
+ const settingRepo = new (yield Promise.resolve().then(() => require('../repo/setting'))).SettingRepo(settings.connection);
70
27
  const taskRepo = new (yield Promise.resolve().then(() => require('../repo/task'))).TaskRepo(settings.connection);
71
28
  try {
72
29
  // 期限検証(2024-04-23~)
@@ -133,7 +90,7 @@ function executeTask(task, next) {
133
90
  }
134
91
  catch (error) {
135
92
  debug('service.task.execute throwed an error. task:', task.name, task.id, 'error:', error === null || error === void 0 ? void 0 : error.name, error === null || error === void 0 ? void 0 : error.message);
136
- yield onOperationFailed(Object.assign({ task, now, error }, (typeof next === 'function') ? { next } : undefined))({ task: taskRepo });
93
+ yield (0, onOperationFailed_1.onOperationFailed)(Object.assign({ task, now, error }, (typeof next === 'function') ? { next } : undefined))({ setting: settingRepo, task: taskRepo });
137
94
  }
138
95
  });
139
96
  }
package/package.json CHANGED
@@ -115,5 +115,5 @@
115
115
  "postversion": "git push origin --tags",
116
116
  "prepublishOnly": "npm run clean && npm run build && npm test && npm run doc"
117
117
  },
118
- "version": "22.11.0-alpha.22"
118
+ "version": "22.11.0-alpha.24"
119
119
  }