@chevre/domain 22.11.0-alpha.27 → 22.11.0-alpha.29

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 moment from 'moment';
3
+ import * as mongoose from 'mongoose';
4
+
5
+ import { chevre } from '../../../../lib/index';
6
+
7
+ // tslint:disable-next-line:max-func-body-length
8
+ async function main() {
9
+ await mongoose.connect(<string>process.env.MONGOLAB_URI, { autoIndex: false });
10
+
11
+ const taskRepo = await chevre.repository.Task.createInstance(mongoose.connection);
12
+
13
+ const aggregateDate = new Date();
14
+ const runsFrom: Date = moment(aggregateDate)
15
+ .utc()
16
+ // .tz('Asia/Tokyo')
17
+ .add(-1, 'days')
18
+ .startOf('days')
19
+ .toDate();
20
+ const runsThrough: Date = moment(aggregateDate)
21
+ .utc()
22
+ // .tz('Asia/Tokyo')
23
+ .add(-1, 'days')
24
+ .endOf('days')
25
+ .toDate();
26
+
27
+ const result = await taskRepo.aggregateTask({
28
+ project: {
29
+ id: { $ne: 'sskts-development' }
30
+ },
31
+ runsFrom,
32
+ runsThrough
33
+ });
34
+ console.dir(result, { depth: null });
35
+ }
36
+
37
+ main()
38
+ .then(() => {
39
+ console.log('success!');
40
+ })
41
+ .catch(console.error);
@@ -25,7 +25,15 @@ async function main() {
25
25
  }
26
26
  }],
27
27
  informTaskNames: [
28
- chevre.factory.taskName.Pay
28
+ chevre.factory.taskName.Pay,
29
+ chevre.factory.taskName.InvalidatePaymentUrl,
30
+ chevre.factory.taskName.Refund,
31
+ chevre.factory.taskName.VoidPayment
32
+ // chevre.factory.taskName.ConfirmReserveTransaction
33
+ ],
34
+ informTaskStatuses: [
35
+ chevre.factory.taskStatus.Aborted
36
+ // chevre.factory.taskStatus.Running
29
37
  ]
30
38
  }
31
39
  }
@@ -20,29 +20,43 @@ interface IReadyTask {
20
20
  expires?: Date;
21
21
  executionResult?: never;
22
22
  }
23
+ /**
24
+ * タスク名不明の遅延実行中タスク
25
+ */
23
26
  interface IRunningTask {
24
27
  id: string;
25
28
  status: factory.taskStatus.Running;
26
- remainingNumberOfTries?: never;
27
29
  name?: never;
30
+ remainingNumberOfTries?: never;
28
31
  expires?: never;
29
32
  executionResult?: never;
30
33
  }
31
34
  /**
32
- * 実行されたタスクイベント
35
+ * タスク名指定での遅延実行中タスク
36
+ */
37
+ interface IRunningTaskByName {
38
+ id: string;
39
+ status: factory.taskStatus.Running;
40
+ name: factory.taskName;
41
+ remainingNumberOfTries?: never;
42
+ expires?: never;
43
+ executionResult?: never;
44
+ }
45
+ /**
46
+ * 実行後失敗したタスクイベント
33
47
  */
34
48
  interface IExecutedTask {
35
49
  id: string;
36
- status: factory.taskStatus.Executed | factory.taskStatus.Running | factory.taskStatus.Aborted;
50
+ status: factory.taskStatus.Running | factory.taskStatus.Aborted;
51
+ name: factory.taskName;
37
52
  executionResult: factory.task.IExecutionResult;
38
53
  /**
39
54
  * 実行されたタスクの残り試行回数
40
55
  */
41
56
  remainingNumberOfTries: number;
42
- name: factory.taskName;
43
57
  expires?: never;
44
58
  }
45
- type IChangedTask = IReadyTask | IRunningTask | IExecutedTask;
59
+ type IChangedTask = IReadyTask | IRunningTask | IRunningTaskByName | IExecutedTask;
46
60
  type IOperationExecute<T> = (settings: IExecuteSettings) => Promise<T>;
47
61
  type INextFunction = (task: IExecutedTask) => IOperationExecute<void>;
48
62
  type IOnTaskStatusChangedListener = (task: IChangedTask, next?: INextFunction) => void;
@@ -54,4 +68,4 @@ declare class TaskEventEmitter extends EventEmitter {
54
68
  emitTaskStatusChanged(task: IChangedTask, next?: INextFunction): void;
55
69
  }
56
70
  declare const taskEventEmitter: TaskEventEmitter;
57
- export { IChangedTask, IReadyTask, IRunningTask, IExecutedTask, IExecuteSettings, INextFunction, IOnTaskStatusChangedListener, taskEventEmitter };
71
+ export { IChangedTask, IReadyTask, IRunningTask, IRunningTaskByName, IExecutedTask, IExecuteSettings, INextFunction, IOnTaskStatusChangedListener, taskEventEmitter };
@@ -22,6 +22,10 @@ interface IOnTaskStatusChanged {
22
22
  * 分析連携するtaskNameリスト
23
23
  */
24
24
  informTaskNames?: factory.taskName[];
25
+ /**
26
+ * 分析連携するtaskStatusリスト
27
+ */
28
+ informTaskStatuses?: factory.taskStatus[];
25
29
  }
26
30
  interface IOnEventChanged {
27
31
  informEvent2agg?: factory.project.IInformParams[];
@@ -496,10 +496,21 @@ class TaskRepo {
496
496
  // tslint:disable-next-line:no-null-keyword
497
497
  return null;
498
498
  }
499
- task_1.taskEventEmitter.emitTaskStatusChanged({
500
- id: doc.id,
501
- status: factory.taskStatus.Running
502
- }, (typeof next === 'function') ? next : undefined);
499
+ let changedTask;
500
+ if (typeof nameEq === 'string') {
501
+ changedTask = {
502
+ id: doc.id,
503
+ status: factory.taskStatus.Running,
504
+ name: nameEq
505
+ };
506
+ }
507
+ else {
508
+ changedTask = {
509
+ id: doc.id,
510
+ status: factory.taskStatus.Running
511
+ };
512
+ }
513
+ task_1.taskEventEmitter.emitTaskStatusChanged(changedTask, (typeof next === 'function') ? next : undefined);
503
514
  return doc;
504
515
  });
505
516
  }
@@ -639,8 +650,10 @@ class TaskRepo {
639
650
  .exec();
640
651
  // emit event(2025-05-26~)
641
652
  if (typeof next === 'function') {
642
- const changedTask = { id, name, status, remainingNumberOfTries, executionResult };
643
- task_1.taskEventEmitter.emitTaskStatusChanged(changedTask, next);
653
+ if (status !== factory.taskStatus.Executed) {
654
+ const changedTask = { id, name, status, remainingNumberOfTries, executionResult };
655
+ task_1.taskEventEmitter.emitTaskStatusChanged(changedTask, next);
656
+ }
644
657
  }
645
658
  });
646
659
  }
@@ -762,10 +775,10 @@ class TaskRepo {
762
775
  factory.taskStatus.Aborted
763
776
  ].map((taskStatus) => __awaiter(this, void 0, void 0, function* () {
764
777
  var _a, _b;
765
- const matchConditions = Object.assign({ runsAt: {
778
+ const matchConditions = Object.assign({ status: { $eq: taskStatus }, runsAt: {
766
779
  $gte: params.runsFrom,
767
780
  $lte: params.runsThrough
768
- }, status: { $eq: taskStatus } }, (typeof ((_b = (_a = params.project) === null || _a === void 0 ? void 0 : _a.id) === null || _b === void 0 ? void 0 : _b.$ne) === 'string')
781
+ } }, (typeof ((_b = (_a = params.project) === null || _a === void 0 ? void 0 : _a.id) === null || _b === void 0 ? void 0 : _b.$ne) === 'string')
769
782
  ? { 'project.id': { $ne: params.project.id.$ne } }
770
783
  : undefined);
771
784
  return this.agggregateByStatus({ matchConditions, status: taskStatus });
@@ -778,7 +791,7 @@ class TaskRepo {
778
791
  return __awaiter(this, void 0, void 0, function* () {
779
792
  const matchConditions = params.matchConditions;
780
793
  const taskStatus = params.status;
781
- const aggregations = yield this.taskModel.aggregate([
794
+ const aggregate1 = this.taskModel.aggregate([
782
795
  {
783
796
  $match: matchConditions
784
797
  },
@@ -808,8 +821,11 @@ class TaskRepo {
808
821
  minLatency: '$minLatency'
809
822
  }
810
823
  }
811
- ])
812
- .exec();
824
+ ]);
825
+ // const explainResult = await aggregate1.explain();
826
+ // console.dir(explainResult, { depth: null });
827
+ // return;
828
+ const aggregations = yield aggregate1.exec();
813
829
  // tslint:disable-next-line:no-magic-numbers
814
830
  const percents = [50, 95, 99];
815
831
  if (aggregations.length === 0) {
@@ -836,7 +852,7 @@ class TaskRepo {
836
852
  rank: Math.floor(aggregations[0].taskCount * percentile / 100)
837
853
  };
838
854
  });
839
- const aggregations2 = yield this.taskModel.aggregate([
855
+ const aggregate2 = this.taskModel.aggregate([
840
856
  {
841
857
  $match: matchConditions
842
858
  },
@@ -866,8 +882,8 @@ class TaskRepo {
866
882
  })
867
883
  }
868
884
  }
869
- ])
870
- .exec();
885
+ ]);
886
+ const aggregations2 = yield aggregate2.exec();
871
887
  return {
872
888
  status: taskStatus,
873
889
  aggregation: Object.assign(Object.assign({}, aggregations[0]), aggregations2[0])
@@ -323,7 +323,7 @@ class TransactionRepo {
323
323
  .lean() // 2024-08-26~
324
324
  .exec();
325
325
  if (doc === null) {
326
- throw new factory.errors.NotFound(this.transactionModel.modelName);
326
+ throw new factory.errors.NotFound(this.transactionModel.modelName, `${params.typeOf} not found`);
327
327
  }
328
328
  return doc;
329
329
  });
@@ -371,7 +371,7 @@ class TransactionRepo {
371
371
  .lean() // 2024-08-26~
372
372
  .exec();
373
373
  if (doc === null) {
374
- throw new factory.errors.NotFound(this.transactionModel.modelName);
374
+ throw new factory.errors.NotFound(this.transactionModel.modelName, `${params.typeOf} ${factory.transactionStatusType.InProgress} not found`);
375
375
  }
376
376
  return doc;
377
377
  });
@@ -389,7 +389,7 @@ class TransactionRepo {
389
389
  .lean() // 2024-08-26~
390
390
  .exec();
391
391
  if (doc === null) {
392
- throw new factory.errors.NotFound(this.transactionModel.modelName);
392
+ throw new factory.errors.NotFound(this.transactionModel.modelName, `${factory.transactionType.PlaceOrder} ${factory.transactionStatusType.InProgress} not found`);
393
393
  }
394
394
  return doc.object.paymentMethods;
395
395
  });
@@ -407,7 +407,7 @@ class TransactionRepo {
407
407
  .lean() // 2024-08-26~
408
408
  .exec();
409
409
  if (doc === null) {
410
- throw new factory.errors.NotFound(this.transactionModel.modelName);
410
+ throw new factory.errors.NotFound(this.transactionModel.modelName, `${factory.transactionType.PlaceOrder} ${factory.transactionStatusType.InProgress} not found`);
411
411
  }
412
412
  return doc.object.orderNumber;
413
413
  });
@@ -425,7 +425,7 @@ class TransactionRepo {
425
425
  .lean() // 2024-08-26~
426
426
  .exec();
427
427
  if (doc === null) {
428
- throw new factory.errors.NotFound(this.transactionModel.modelName);
428
+ throw new factory.errors.NotFound(this.transactionModel.modelName, `${factory.transactionType.PlaceOrder} ${params.status.$in.join(' or ')} not found`);
429
429
  }
430
430
  return doc.object.confirmationNumber;
431
431
  });
@@ -448,7 +448,7 @@ class TransactionRepo {
448
448
  .lean()
449
449
  .exec();
450
450
  if (doc === null) {
451
- throw new factory.errors.NotFound(this.transactionModel.modelName);
451
+ throw new factory.errors.NotFound(this.transactionModel.modelName, `${params.typeOf} ${factory.transactionStatusType.InProgress} not found`);
452
452
  }
453
453
  });
454
454
  }
@@ -471,7 +471,7 @@ class TransactionRepo {
471
471
  .lean()
472
472
  .exec();
473
473
  if (doc === null) {
474
- throw new factory.errors.NotFound(this.transactionModel.modelName);
474
+ throw new factory.errors.NotFound(this.transactionModel.modelName, `${params.typeOf} ${factory.transactionStatusType.InProgress} not found`);
475
475
  }
476
476
  });
477
477
  }
@@ -494,7 +494,7 @@ class TransactionRepo {
494
494
  .lean()
495
495
  .exec();
496
496
  if (doc === null) {
497
- throw new factory.errors.NotFound(this.transactionModel.modelName);
497
+ throw new factory.errors.NotFound(this.transactionModel.modelName, `${params.typeOf} ${factory.transactionStatusType.InProgress} not found`);
498
498
  }
499
499
  });
500
500
  }
@@ -538,7 +538,7 @@ class TransactionRepo {
538
538
  .isSameOrBefore(moment(endDate))) {
539
539
  throw new factory.errors.Argument('Transaction id', 'potentially expired');
540
540
  }
541
- throw new factory.errors.NotFound(this.transactionModel.modelName);
541
+ throw new factory.errors.NotFound(this.transactionModel.modelName, `${params.typeOf} ${factory.transactionStatusType.InProgress} not found`);
542
542
  }
543
543
  }
544
544
  transaction_1.transactionEventEmitter.emitTransactionStatusChanged({
@@ -914,7 +914,7 @@ class TransactionRepo {
914
914
  throw new factory.errors.Argument('Transaction id', 'Confirmed transaction unable to cancel');
915
915
  }
916
916
  else {
917
- throw new factory.errors.NotFound(this.transactionModel.modelName);
917
+ throw new factory.errors.NotFound(this.transactionModel.modelName, `${params.typeOf} ${factory.transactionStatusType.InProgress} not found`);
918
918
  }
919
919
  }
920
920
  transaction_1.transactionEventEmitter.emitTransactionStatusChanged({
@@ -1,7 +1,10 @@
1
1
  import * as factory from '../../../factory';
2
2
  import type { SettingRepo } from '../../../repo/setting';
3
3
  import type { IExecutableTask, TaskRepo } from '../../../repo/task';
4
- declare function informTaskIfNeeded(task: IExecutableTask<factory.taskName>): (repos: {
4
+ declare function informTaskIfNeeded(params: {
5
+ task: IExecutableTask<factory.taskName>;
6
+ executionEndDate: Date;
7
+ }): (repos: {
5
8
  setting: SettingRepo;
6
9
  task: TaskRepo;
7
10
  }) => Promise<void>;
@@ -13,66 +13,89 @@ exports.informTaskIfNeeded = informTaskIfNeeded;
13
13
  const createDebug = require("debug");
14
14
  const factory = require("../../../factory");
15
15
  const debug = createDebug('chevre-domain:service:taskHandler:onOperationFailed');
16
- function createInformTasks(task, setting) {
17
- var _a, _b;
18
- const taskRunsAt = new Date();
16
+ function createInformTasks(params) {
17
+ var _a, _b, _c;
18
+ const { task, setting, executionEndDate } = params;
19
19
  const informTask = (_a = setting === null || setting === void 0 ? void 0 : setting.onTaskStatusChanged) === null || _a === void 0 ? void 0 : _a.informTask;
20
20
  const informTaskNames = (_b = setting === null || setting === void 0 ? void 0 : setting.onTaskStatusChanged) === null || _b === void 0 ? void 0 : _b.informTaskNames;
21
+ const informTaskStatuses = (_c = setting === null || setting === void 0 ? void 0 : setting.onTaskStatusChanged) === null || _c === void 0 ? void 0 : _c.informTaskStatuses;
21
22
  const informTasks = [];
22
23
  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
24
+ if (Array.isArray(informTaskStatuses)) {
25
+ const { id, name, data, project, runsAt, remainingNumberOfTries } = task;
26
+ let task4inform;
27
+ if (remainingNumberOfTries <= 0) {
28
+ if (informTaskStatuses.includes(factory.taskStatus.Aborted)) {
29
+ const abortingTask = {
30
+ id, name, data, project, runsAt,
31
+ status: factory.taskStatus.Aborted,
32
+ typeOf: 'Task',
33
+ dateAborted: executionEndDate
48
34
  };
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
35
+ task4inform = abortingTask;
36
+ }
37
+ }
38
+ else {
39
+ if (informTaskStatuses.includes(factory.taskStatus.Running)) {
40
+ const runningTask = {
41
+ id, name, data, project, runsAt,
42
+ status: factory.taskStatus.Running,
43
+ typeOf: 'Task'
44
+ };
45
+ task4inform = runningTask;
46
+ }
47
+ }
48
+ if (task4inform !== undefined) {
49
+ const informIdentifier = `Task:${name}:${id}:${task4inform.status}`;
50
+ if (Array.isArray(informTask) && informTask.length > 0) {
51
+ informTask.forEach((informTaskParams) => {
52
+ var _a, _b;
53
+ if (typeof ((_a = informTaskParams.recipient) === null || _a === void 0 ? void 0 : _a.url) === 'string') {
54
+ const informActionAttributes = {
55
+ object: task4inform,
56
+ recipient: {
57
+ id: '',
58
+ name: String((_b = informTaskParams.recipient) === null || _b === void 0 ? void 0 : _b.name),
59
+ typeOf: factory.creativeWorkType.WebApplication
60
+ },
61
+ target: {
62
+ httpMethod: 'POST',
63
+ encodingType: factory.encodingFormat.Application.json,
64
+ typeOf: 'EntryPoint',
65
+ urlTemplate: informTaskParams.recipient.url
66
+ },
67
+ identifier: informIdentifier
68
+ };
69
+ const description = `inform aborting tasks to agg service: ${name} ${id} ${task4inform.status}`;
70
+ informTasks.push({
71
+ project,
72
+ name: factory.taskName.TriggerWebhook,
73
+ status: factory.taskStatus.Ready,
74
+ runsAt: executionEndDate,
75
+ remainingNumberOfTries: 10,
76
+ numberOfTried: 0,
77
+ executionResults: [],
78
+ data: informActionAttributes,
79
+ description
80
+ });
81
+ }
60
82
  });
61
83
  }
62
- });
84
+ }
63
85
  }
64
86
  }
65
87
  return informTasks;
66
88
  }
67
- function informTaskIfNeeded(task) {
89
+ function informTaskIfNeeded(params) {
68
90
  return (repos) => __awaiter(this, void 0, void 0, function* () {
69
- const isAborting = task.status === factory.taskStatus.Running && task.remainingNumberOfTries <= 0;
91
+ const { executionEndDate, task } = params;
92
+ const isAborting = task.status === factory.taskStatus.Running;
70
93
  const useInform = isAborting
71
94
  && task.name !== factory.taskName.HandleNotification // nameで絞る
72
95
  && task.name !== factory.taskName.TriggerWebhook;
73
96
  if (useInform) {
74
97
  const setting = yield repos.setting.findOne({ project: { id: { $eq: '*' } } }, ['onTaskStatusChanged']);
75
- const informTasks = createInformTasks(task, setting);
98
+ const informTasks = createInformTasks({ task, setting, executionEndDate });
76
99
  debug('informTaskIfNeeded: creating inform tasks...', JSON.stringify(informTasks));
77
100
  if (informTasks.length > 0) {
78
101
  yield repos.task.saveMany(informTasks, { emitImmediately: true });
@@ -12,6 +12,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.onOperationFailed = onOperationFailed;
13
13
  const factory = require("../../factory");
14
14
  const informTaskIfNeeded_1 = require("./onOperationFailed/informTaskIfNeeded");
15
+ const USE_INFORM_TASK_RUNNING = process.env.USE_INFORM_TASK_RUNNING === '1';
15
16
  /**
16
17
  * タスク実行失敗時処理
17
18
  */
@@ -22,12 +23,17 @@ function onOperationFailed(params) {
22
23
  if (typeof error !== 'object') {
23
24
  error = { message: String(error) };
24
25
  }
26
+ const endDate = new Date();
25
27
  // remainingNumberOfTries<=0ならAborted(2025-08-04~)
26
28
  const isRetryable = task.remainingNumberOfTries > 0;
27
29
  if (isRetryable) {
30
+ // 実験的に実行中タスク連携
31
+ if (USE_INFORM_TASK_RUNNING) {
32
+ yield (0, informTaskIfNeeded_1.informTaskIfNeeded)({ task, executionEndDate: endDate })(repos);
33
+ }
28
34
  const result = {
29
35
  executedAt: now,
30
- endDate: new Date(),
36
+ endDate,
31
37
  error: Object.assign(Object.assign({}, error), { code: error.code, message: error.message, name: error.name, stack: error.stack })
32
38
  };
33
39
  // 失敗してもここではステータスを戻さない(Runningのまま待機)
@@ -45,10 +51,10 @@ function onOperationFailed(params) {
45
51
  // 設定されたnameの場合連携する
46
52
  // もしここで連携タスク作成に失敗したとしても、再度Readyタスクとなりリトライされて、処理は冪等となる想定
47
53
  // 最終的に、連携タスクが作成され、実行中タスクがAbortedとなればよい
48
- yield (0, informTaskIfNeeded_1.informTaskIfNeeded)(task)(repos);
54
+ yield (0, informTaskIfNeeded_1.informTaskIfNeeded)({ task, executionEndDate: endDate })(repos);
49
55
  const result = {
50
56
  executedAt: now,
51
- endDate: new Date(),
57
+ endDate,
52
58
  error: Object.assign(Object.assign({}, error), { code: error.code, message: error.message, name: error.name, stack: error.stack })
53
59
  };
54
60
  yield repos.task.setExecutionResultAndStatus({
package/package.json CHANGED
@@ -11,7 +11,7 @@
11
11
  "dependencies": {
12
12
  "@aws-sdk/client-cognito-identity-provider": "3.600.0",
13
13
  "@aws-sdk/credential-providers": "3.600.0",
14
- "@chevre/factory": "4.396.0-alpha.3",
14
+ "@chevre/factory": "4.396.0-alpha.4",
15
15
  "@cinerino/sdk": "11.1.0",
16
16
  "@motionpicture/coa-service": "9.6.0",
17
17
  "@motionpicture/gmo-service": "5.3.0",
@@ -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.27"
118
+ "version": "22.11.0-alpha.29"
119
119
  }