@chevre/domain 25.2.0-alpha.46 → 25.2.0-alpha.47

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,65 @@
1
+ import type { Connection, UpdateWriteOpResult } from 'mongoose';
2
+ import { factory } from '../factory';
3
+ import { IModel } from './mongoose/schemas/task';
4
+ import type { IExecutableTask } from '../taskSettings';
5
+ /**
6
+ * タスクリポジトリ
7
+ */
8
+ export declare class AsyncActionRepo {
9
+ readonly taskModel: IModel;
10
+ constructor(connection: Connection);
11
+ /**
12
+ * Readyタスクをひとつ追加する
13
+ */
14
+ addReadyAsyncAction(params: Pick<factory.task.IAttributes<factory.taskName>, 'data' | 'expires' | 'name' | 'project' | 'remainingNumberOfTries' | 'runsAt'> & {
15
+ alternateName?: never;
16
+ identifier?: never;
17
+ expires: Date;
18
+ }): Promise<{
19
+ id: string;
20
+ }>;
21
+ /**
22
+ * Ready -> remainingNumberOfTriesが1減る
23
+ */
24
+ executeAsyncActionById(params: {
25
+ id: string;
26
+ status: factory.taskStatus.Ready;
27
+ executor: {
28
+ name: string;
29
+ };
30
+ expires?: Date;
31
+ }): Promise<IExecutableTask<factory.taskName> | null>;
32
+ /**
33
+ * Readyのままで期限切れのタスクをExpiredに変更する
34
+ */
35
+ makeExpiredMany(params: {
36
+ expiresLt: Date;
37
+ }): Promise<UpdateWriteOpResult>;
38
+ abortMany(params: {
39
+ intervalInMinutes: number;
40
+ name: {
41
+ $in?: factory.taskName[];
42
+ };
43
+ }): Promise<UpdateWriteOpResult>;
44
+ /**
45
+ * タスクIDから実行結果とステータスを保管する
46
+ * Abortedの場合、dateAbortedもセットする
47
+ */
48
+ setExecutionResultAndStatus(params: {
49
+ /**
50
+ * タスクID
51
+ */
52
+ id: string;
53
+ }, update: {
54
+ status: factory.taskStatus.Executed | factory.taskStatus.Aborted;
55
+ executionResult: factory.task.IExecutionResult;
56
+ }): Promise<void>;
57
+ /**
58
+ * 不要なタスクを削除する
59
+ */
60
+ deleteRunsAtPassedCertainPeriod(params: {
61
+ runsAt: {
62
+ $lt: Date;
63
+ };
64
+ }): Promise<import("mongodb").DeleteResult>;
65
+ }
@@ -0,0 +1,156 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.AsyncActionRepo = void 0;
7
+ const moment_1 = __importDefault(require("moment"));
8
+ const factory_1 = require("../factory");
9
+ const settings_1 = require("../settings");
10
+ const task_1 = require("./mongoose/schemas/task");
11
+ const executableTaskProjection = {
12
+ _id: 0,
13
+ id: { $toString: '$_id' },
14
+ // 必要最低限にprojection(2024-04-23~)
15
+ data: 1,
16
+ name: 1,
17
+ status: 1,
18
+ numberOfTried: 1,
19
+ project: 1,
20
+ remainingNumberOfTries: 1,
21
+ runsAt: 1,
22
+ expires: 1
23
+ };
24
+ /**
25
+ * タスクリポジトリ
26
+ */
27
+ class AsyncActionRepo {
28
+ taskModel;
29
+ constructor(connection) {
30
+ this.taskModel = connection.model(task_1.modelName, (0, task_1.createSchema)());
31
+ }
32
+ /**
33
+ * Readyタスクをひとつ追加する
34
+ */
35
+ async addReadyAsyncAction(
36
+ // resolve uniqueness of identifier(2025-03-27~)
37
+ params) {
38
+ const { expires } = params;
39
+ if (!(expires instanceof Date)) {
40
+ throw new factory_1.factory.errors.Argument('expires', 'must be Date');
41
+ }
42
+ const savingTask = {
43
+ ...params,
44
+ remainingNumberOfTries: 1, // リトライはありえないので、1で固定
45
+ status: factory_1.factory.taskStatus.Ready,
46
+ numberOfTried: 0,
47
+ executionResults: []
48
+ };
49
+ const result = await this.taskModel.insertMany(savingTask, { rawResult: true });
50
+ const id = result.insertedIds?.[0]?.toHexString();
51
+ if (typeof id !== 'string') {
52
+ throw new factory_1.factory.errors.Internal('task not saved');
53
+ }
54
+ return { id };
55
+ }
56
+ /**
57
+ * Ready -> remainingNumberOfTriesが1減る
58
+ */
59
+ async executeAsyncActionById(params) {
60
+ const now = new Date();
61
+ const doc = await this.taskModel.findOneAndUpdate({
62
+ _id: { $eq: params.id },
63
+ status: { $eq: params.status },
64
+ runsAt: { $lt: now },
65
+ ...(params.expires instanceof Date) ? { expires: { $gt: now } } : undefined
66
+ }, {
67
+ $set: {
68
+ status: factory_1.factory.taskStatus.Running, // 実行中に変更
69
+ lastTriedAt: now,
70
+ executor: params.executor
71
+ },
72
+ $inc: {
73
+ remainingNumberOfTries: -1, // 残りトライ可能回数減らす
74
+ numberOfTried: 1 // トライ回数増やす
75
+ }
76
+ }, { new: true, projection: executableTaskProjection })
77
+ .setOptions({ maxTimeMS: settings_1.MONGO_MAX_TIME_MS })
78
+ .lean() // lean(2024-09-26~)
79
+ .exec();
80
+ if (doc === null) {
81
+ return null;
82
+ }
83
+ return doc;
84
+ }
85
+ /**
86
+ * Readyのままで期限切れのタスクをExpiredに変更する
87
+ */
88
+ async makeExpiredMany(params) {
89
+ const { expiresLt } = params;
90
+ if (!(expiresLt instanceof Date)) {
91
+ throw new factory_1.factory.errors.Argument('expiresLt', 'must be Date');
92
+ }
93
+ return this.taskModel.updateMany({
94
+ status: { $eq: factory_1.factory.taskStatus.Ready },
95
+ expires: { $exists: true, $lt: expiresLt }
96
+ }, {
97
+ $set: {
98
+ status: factory_1.factory.taskStatus.Expired
99
+ }
100
+ })
101
+ .exec();
102
+ }
103
+ async abortMany(params) {
104
+ const lastTriedAtShoudBeLessThan = (0, moment_1.default)()
105
+ .add(-params.intervalInMinutes, 'minutes')
106
+ .toDate();
107
+ return this.taskModel.updateMany({
108
+ status: { $eq: factory_1.factory.taskStatus.Running },
109
+ lastTriedAt: {
110
+ $type: 'date',
111
+ $lt: lastTriedAtShoudBeLessThan
112
+ },
113
+ remainingNumberOfTries: { $eq: 0 },
114
+ ...(Array.isArray(params.name.$in)) ? { name: { $in: params.name.$in } } : undefined
115
+ }, {
116
+ $set: {
117
+ status: factory_1.factory.taskStatus.Aborted,
118
+ dateAborted: new Date()
119
+ }
120
+ })
121
+ .exec();
122
+ }
123
+ /**
124
+ * タスクIDから実行結果とステータスを保管する
125
+ * Abortedの場合、dateAbortedもセットする
126
+ */
127
+ async setExecutionResultAndStatus(params, update) {
128
+ const { id } = params;
129
+ const { status, executionResult } = update;
130
+ await this.taskModel.updateOne({ _id: { $eq: id } }, {
131
+ $set: {
132
+ status,
133
+ ...(status === factory_1.factory.taskStatus.Aborted) ? { dateAborted: executionResult.endDate } : undefined // 2025-08-04~
134
+ },
135
+ $push: { executionResults: executionResult }
136
+ })
137
+ .exec();
138
+ }
139
+ /**
140
+ * 不要なタスクを削除する
141
+ */
142
+ async deleteRunsAtPassedCertainPeriod(params) {
143
+ return this.taskModel.deleteMany({
144
+ runsAt: { $lt: params.runsAt.$lt },
145
+ status: {
146
+ $in: [
147
+ factory_1.factory.taskStatus.Aborted,
148
+ factory_1.factory.taskStatus.Executed,
149
+ factory_1.factory.taskStatus.Expired
150
+ ]
151
+ }
152
+ })
153
+ .exec();
154
+ }
155
+ }
156
+ exports.AsyncActionRepo = AsyncActionRepo;
@@ -15,6 +15,7 @@ import type { CheckMovieTicketActionRepo } from './repo/action/checkMovieTicket'
15
15
  import type { CheckThingActionRepo } from './repo/action/checkThing';
16
16
  import type { PayActionRepo } from './repo/action/pay';
17
17
  import type { RefundActionRepo } from './repo/action/refund';
18
+ import type { AsyncActionRepo } from './repo/asyncAction';
18
19
  import type { AdditionalPropertyRepo } from './repo/additionalProperty';
19
20
  import type { AggregateActionRepo } from './repo/aggregateAction';
20
21
  import type { AggregateOfferRepo } from './repo/aggregateOffer';
@@ -470,6 +471,10 @@ export type Task = TaskRepo;
470
471
  export declare namespace Task {
471
472
  function createInstance(...params: ConstructorParameters<typeof TaskRepo>): Promise<TaskRepo>;
472
473
  }
474
+ export type AsyncAction = AsyncActionRepo;
475
+ export declare namespace AsyncAction {
476
+ function createInstance(...params: ConstructorParameters<typeof AsyncActionRepo>): Promise<AsyncActionRepo>;
477
+ }
473
478
  export type Ticket = TicketRepo;
474
479
  export declare namespace Ticket {
475
480
  function createInstance(...params: ConstructorParameters<typeof TicketRepo>): Promise<TicketRepo>;
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.place = exports.Person = exports.PendingReservation = exports.PaymentServiceProvider = exports.PaymentServiceChannel = exports.PaymentService = exports.Passport = exports.OwnershipInfo = exports.OrderNumber = exports.OrderInTransaction = exports.Order = exports.Offer = exports.OfferItemCondition = exports.OfferCatalogItem = exports.OfferCatalog = exports.NoteAboutOrder = exports.Note = exports.MovieTicketType = exports.Message = exports.MerchantReturnPolicy = exports.MemberProgram = exports.Member = exports.Issuer = exports.IdentityProvider = exports.Identity = exports.EventSeries = exports.EventSellerMakesOffer = exports.EventOffer = exports.Event = exports.EmailMessage = exports.CustomerType = exports.Customer = exports.Credentials = exports.CreativeWork = exports.ConfirmationNumber = exports.Authorization = exports.CategoryCode = exports.assetTransaction = exports.AssetTransaction = exports.Aggregation = exports.AggregateReservation = exports.AggregateOrder = exports.AggregateOffer = exports.AggregateAction = exports.AdditionalProperty = exports.action = exports.Action = exports.AccountTitle = exports.AccountingReport = exports.AcceptedOffer = void 0;
4
- exports.WebSite = exports.rateLimit = exports.TransactionProcess = exports.TransactionNumber = exports.transaction = exports.Transaction = exports.Ticket = exports.Task = exports.StockHolder = exports.setting = exports.Setting = exports.ServiceAvailableHour = exports.SellerReturnPolicy = exports.SellerPaymentAccepted = exports.SellerMakesOffer = exports.Seller = exports.Schedule = exports.Role = exports.ReserveInterface = exports.Reservation = exports.ProjectMakesOffer = exports.Project = exports.ProductHasOfferCatalog = exports.Product = exports.PriceSpecification = exports.PotentialAction = void 0;
4
+ exports.WebSite = exports.rateLimit = exports.TransactionProcess = exports.TransactionNumber = exports.transaction = exports.Transaction = exports.Ticket = exports.AsyncAction = exports.Task = exports.StockHolder = exports.setting = exports.Setting = exports.ServiceAvailableHour = exports.SellerReturnPolicy = exports.SellerPaymentAccepted = exports.SellerMakesOffer = exports.Seller = exports.Schedule = exports.Role = exports.ReserveInterface = exports.Reservation = exports.ProjectMakesOffer = exports.Project = exports.ProductHasOfferCatalog = exports.Product = exports.PriceSpecification = exports.PotentialAction = void 0;
5
5
  var AcceptedOffer;
6
6
  (function (AcceptedOffer) {
7
7
  let repo;
@@ -989,6 +989,17 @@ var Task;
989
989
  }
990
990
  Task.createInstance = createInstance;
991
991
  })(Task || (exports.Task = Task = {}));
992
+ var AsyncAction;
993
+ (function (AsyncAction) {
994
+ let repo;
995
+ async function createInstance(...params) {
996
+ if (repo === undefined) {
997
+ repo = (await import('./repo/asyncAction.js')).AsyncActionRepo;
998
+ }
999
+ return new repo(...params);
1000
+ }
1001
+ AsyncAction.createInstance = createInstance;
1002
+ })(AsyncAction || (exports.AsyncAction = AsyncAction = {}));
992
1003
  var Ticket;
993
1004
  (function (Ticket) {
994
1005
  let repo;
@@ -12,11 +12,11 @@ const asyncActionHandler_1 = require("./asyncActionHandler");
12
12
  const debug = (0, debug_1.default)('chevre-domain:service:task');
13
13
  function executeAsyncActionById(params, next) {
14
14
  return async (settings) => {
15
- const taskRepo = new (await import('../repo/task.js')).TaskRepo(settings.connection);
15
+ const asyncActionRepo = new (await import('../repo/asyncAction.js')).AsyncActionRepo(settings.connection);
16
16
  const { id, status, executor, expires } = params;
17
17
  let task = null;
18
18
  try {
19
- task = await taskRepo.executeOneById({
19
+ task = await asyncActionRepo.executeAsyncActionById({
20
20
  id,
21
21
  status,
22
22
  executor: { name: executor.name },
@@ -1,7 +1,7 @@
1
- import type { IExecutedTask, INextFunction } from '../../eventEmitter/task';
1
+ import type { IExecutedTask } from '../../eventEmitter/task';
2
2
  import { factory } from '../../factory';
3
3
  import type { SettingRepo } from '../../repo/setting';
4
- import type { TaskRepo } from '../../repo/task';
4
+ import type { AsyncActionRepo } from '../../repo/asyncAction';
5
5
  import type { IExecutableTask } from '../../taskSettings';
6
6
  /**
7
7
  * タスク実行失敗時処理
@@ -10,10 +10,9 @@ declare function onOperationFailed(params: {
10
10
  task: IExecutableTask<factory.taskName>;
11
11
  now: Date;
12
12
  error: any;
13
- next?: INextFunction;
14
13
  }): (repos: {
15
14
  setting: SettingRepo;
16
- task: TaskRepo;
15
+ asyncAction: AsyncActionRepo;
17
16
  }) => Promise<{
18
17
  executedTask: IExecutedTask;
19
18
  }>;
@@ -8,77 +8,35 @@ const factory_1 = require("../../factory");
8
8
  function onOperationFailed(params) {
9
9
  return async (repos) => {
10
10
  let error = params.error;
11
- const { task, now, next } = params;
11
+ const { task, now } = params;
12
12
  if (typeof error !== 'object') {
13
13
  error = { message: String(error) };
14
14
  }
15
15
  const endDate = new Date();
16
- let executedTask;
17
- // remainingNumberOfTries<=0ならAborted(2025-08-04~)
18
- const isRetryable = task.remainingNumberOfTries > 0;
19
- if (isRetryable) {
20
- // 実験的に実行中タスク連携をしてみたが、ひとまず廃止(2026-07-01~)
21
- // if (USE_INFORM_TASK_RUNNING) {
22
- // await informTaskIfNeeded({ task, executionEndDate: endDate })(repos);
23
- // }
24
- const result = {
25
- executedAt: now,
26
- endDate,
27
- error: {
28
- ...error,
29
- code: error.code,
30
- message: error.message,
31
- name: error.name,
32
- stack: error.stack
33
- }
34
- };
35
- // 失敗してもここではステータスを戻さない(Runningのまま待機)
36
- await 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
- executedTask = {
45
- id: task.id,
46
- remainingNumberOfTries: task.remainingNumberOfTries,
47
- name: task.name,
48
- status: task.status,
49
- executionResult: result
50
- };
51
- }
52
- else {
53
- // one time taskは分析連携しない
54
- // await informTaskIfNeeded({ task, executionEndDate: endDate })(repos);
55
- const result = {
56
- executedAt: now,
57
- endDate,
58
- error: {
59
- ...error,
60
- code: error.code,
61
- message: error.message,
62
- name: error.name,
63
- stack: error.stack
64
- }
65
- };
66
- await repos.task.setExecutionResultAndStatus({
67
- id: task.id,
68
- remainingNumberOfTries: task.remainingNumberOfTries,
69
- name: task.name
70
- }, {
71
- status: factory_1.factory.taskStatus.Aborted,
72
- executionResult: result
73
- }, (typeof next === 'function') ? next : undefined);
74
- executedTask = {
75
- id: task.id,
76
- remainingNumberOfTries: task.remainingNumberOfTries,
77
- name: task.name,
78
- status: task.status,
79
- executionResult: result
80
- };
81
- }
16
+ // 非同期アクションはワンタイムタスクなのでリトライはありえない
17
+ // ワンタイムタスクは分析連携しない
18
+ const result = {
19
+ executedAt: now,
20
+ endDate,
21
+ error: {
22
+ ...error,
23
+ code: error.code,
24
+ message: error.message,
25
+ name: error.name,
26
+ stack: error.stack
27
+ }
28
+ };
29
+ await repos.asyncAction.setExecutionResultAndStatus({ id: task.id }, {
30
+ status: factory_1.factory.taskStatus.Aborted,
31
+ executionResult: result
32
+ });
33
+ const executedTask = {
34
+ id: task.id,
35
+ remainingNumberOfTries: task.remainingNumberOfTries,
36
+ name: task.name,
37
+ status: task.status,
38
+ executionResult: result
39
+ };
82
40
  return { executedTask };
83
41
  };
84
42
  }
@@ -23,7 +23,7 @@ function executeAsyncAction(task, next) {
23
23
  debug('executing an executableTask...', task, now);
24
24
  return async (settings, options) => {
25
25
  const settingRepo = new (await import('../repo/setting.js')).SettingRepo(settings.connection);
26
- const taskRepo = new (await import('../repo/task.js')).TaskRepo(settings.connection);
26
+ const asyncActionRepo = new (await import('../repo/asyncAction.js')).AsyncActionRepo(settings.connection);
27
27
  let executedTask;
28
28
  try {
29
29
  // 期限検証(2024-04-23~)
@@ -55,11 +55,7 @@ function executeAsyncAction(task, next) {
55
55
  }
56
56
  : ''
57
57
  };
58
- await taskRepo.setExecutionResultAndStatus({
59
- id: task.id,
60
- remainingNumberOfTries,
61
- name: task.name
62
- }, {
58
+ await asyncActionRepo.setExecutionResultAndStatus({ id: task.id }, {
63
59
  status: factory_1.factory.taskStatus.Executed,
64
60
  executionResult: result
65
61
  });
@@ -74,8 +70,7 @@ function executeAsyncAction(task, next) {
74
70
  catch (error) {
75
71
  const onOperationFailedResult = await (0, onOperationFailed_1.onOperationFailed)({
76
72
  task, now, error,
77
- // ...(typeof next === 'function') ? { next } : undefined // タスクステータス変更イベントを発生させない
78
- })({ setting: settingRepo, task: taskRepo });
73
+ })({ setting: settingRepo, asyncAction: asyncActionRepo });
79
74
  executedTask = onOperationFailedResult.executedTask;
80
75
  }
81
76
  finally {
package/package.json CHANGED
@@ -88,5 +88,5 @@
88
88
  "postversion": "git push origin --tags",
89
89
  "prepublishOnly": "npm run clean && npm run build"
90
90
  },
91
- "version": "25.2.0-alpha.46"
91
+ "version": "25.2.0-alpha.47"
92
92
  }