@enlt-bakusoku/functions 0.0.0-stage → 2.1.0
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.
- package/README.md +67 -2
- package/dist/index.d.ts +12 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +72 -0
- package/dist/index.js.map +1 -0
- package/dist/lib/catalog.d.ts +115 -0
- package/dist/lib/catalog.d.ts.map +1 -0
- package/dist/lib/catalog.js +273 -0
- package/dist/lib/catalog.js.map +1 -0
- package/dist/mail/create-mail-delivery-function.d.ts +50 -0
- package/dist/mail/create-mail-delivery-function.d.ts.map +1 -0
- package/dist/mail/create-mail-delivery-function.js +263 -0
- package/dist/mail/create-mail-delivery-function.js.map +1 -0
- package/dist/mail/queued-mail.d.ts +47 -0
- package/dist/mail/queued-mail.d.ts.map +1 -0
- package/dist/mail/queued-mail.js +74 -0
- package/dist/mail/queued-mail.js.map +1 -0
- package/dist/migrate/migration-batch.d.ts +14 -0
- package/dist/migrate/migration-batch.d.ts.map +1 -0
- package/dist/migrate/migration-batch.js +58 -0
- package/dist/migrate/migration-batch.js.map +1 -0
- package/dist/migrate/migration-plan.d.ts +21 -0
- package/dist/migrate/migration-plan.d.ts.map +1 -0
- package/dist/migrate/migration-plan.js +88 -0
- package/dist/migrate/migration-plan.js.map +1 -0
- package/dist/schedule/create-schedules.d.ts +37 -0
- package/dist/schedule/create-schedules.d.ts.map +1 -0
- package/dist/schedule/create-schedules.js +107 -0
- package/dist/schedule/create-schedules.js.map +1 -0
- package/dist/tasks/create-migration-recovery-schedule.d.ts +5 -0
- package/dist/tasks/create-migration-recovery-schedule.d.ts.map +1 -0
- package/dist/tasks/create-migration-recovery-schedule.js +17 -0
- package/dist/tasks/create-migration-recovery-schedule.js.map +1 -0
- package/dist/tasks/create-tasks-function.d.ts +67 -0
- package/dist/tasks/create-tasks-function.d.ts.map +1 -0
- package/dist/tasks/create-tasks-function.js +255 -0
- package/dist/tasks/create-tasks-function.js.map +1 -0
- package/dist/tasks/definitions.d.ts +16 -0
- package/dist/tasks/definitions.d.ts.map +1 -0
- package/dist/tasks/definitions.js +22 -0
- package/dist/tasks/definitions.js.map +1 -0
- package/dist/tasks/enqueue-task.d.ts +43 -0
- package/dist/tasks/enqueue-task.d.ts.map +1 -0
- package/dist/tasks/enqueue-task.js +61 -0
- package/dist/tasks/enqueue-task.js.map +1 -0
- package/dist/tasks/task-execution.d.ts +146 -0
- package/dist/tasks/task-execution.d.ts.map +1 -0
- package/dist/tasks/task-execution.js +788 -0
- package/dist/tasks/task-execution.js.map +1 -0
- package/dist/tasks/task-queue.d.ts +29 -0
- package/dist/tasks/task-queue.d.ts.map +1 -0
- package/dist/tasks/task-queue.js +61 -0
- package/dist/tasks/task-queue.js.map +1 -0
- package/package.json +64 -3
- package/scripts/generate-catalog.cjs +100 -0
- package/scripts/prepare-firebase-artifact.mjs +35 -0
|
@@ -0,0 +1,788 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.ExecutionConflictError = exports.EXECUTION_STATUS_LABELS = exports.ATTEMPT_LEASE_MS = exports.MAX_EXECUTION_ATTEMPTS = exports.MIGRATIONS_COLLECTION = exports.TASK_EXECUTIONS_COLLECTION = void 0;
|
|
4
|
+
exports.executionRef = executionRef;
|
|
5
|
+
exports.getMigrationPlanStatus = getMigrationPlanStatus;
|
|
6
|
+
exports.detectStalledMigrationPlan = detectStalledMigrationPlan;
|
|
7
|
+
exports.resolveStalledMigrationPlan = resolveStalledMigrationPlan;
|
|
8
|
+
exports.enqueueExecution = enqueueExecution;
|
|
9
|
+
exports.enqueueMigrationPlan = enqueueMigrationPlan;
|
|
10
|
+
exports.continueMigrationPlan = continueMigrationPlan;
|
|
11
|
+
exports.cancelExecution = cancelExecution;
|
|
12
|
+
exports.claimExecution = claimExecution;
|
|
13
|
+
exports.extendAttemptLease = extendAttemptLease;
|
|
14
|
+
exports.finishExecution = finishExecution;
|
|
15
|
+
exports.listExecutions = listExecutions;
|
|
16
|
+
exports.latestExecutions = latestExecutions;
|
|
17
|
+
exports.listMigrationStates = listMigrationStates;
|
|
18
|
+
exports.subjectName = subjectName;
|
|
19
|
+
const node_crypto_1 = require("node:crypto");
|
|
20
|
+
const node_util_1 = require("node:util");
|
|
21
|
+
const functions_1 = require("firebase-admin/functions");
|
|
22
|
+
const firestore_1 = require("firebase-admin/firestore");
|
|
23
|
+
const catalog_1 = require("../lib/catalog");
|
|
24
|
+
const migration_plan_1 = require("../migrate/migration-plan");
|
|
25
|
+
const task_queue_1 = require("./task-queue");
|
|
26
|
+
exports.TASK_EXECUTIONS_COLLECTION = 'bksk_task';
|
|
27
|
+
exports.MIGRATIONS_COLLECTION = 'bksk_migrations';
|
|
28
|
+
const ACTIVE_MIGRATION_PLAN = '_active-plan';
|
|
29
|
+
const MIGRATION_INACTIVITY_MS = 60 * 60000;
|
|
30
|
+
/** 一時失敗は初回を含めてこの回数まで。結果を確認できない上限到達は unknown。 */
|
|
31
|
+
exports.MAX_EXECUTION_ATTEMPTS = 3;
|
|
32
|
+
/** ハートビートが途切れた試行を、次の配送が引き継げるまでの猶予。 */
|
|
33
|
+
exports.ATTEMPT_LEASE_MS = 60000;
|
|
34
|
+
exports.EXECUTION_STATUS_LABELS = {
|
|
35
|
+
pending: '投入待ち',
|
|
36
|
+
accepted: '受付済み',
|
|
37
|
+
running: '実行中',
|
|
38
|
+
retrying: '再試行待ち',
|
|
39
|
+
succeeded: '完了',
|
|
40
|
+
failed: '失敗',
|
|
41
|
+
cancelled: '取消',
|
|
42
|
+
unknown: '結果不明(要確認)',
|
|
43
|
+
};
|
|
44
|
+
class ExecutionConflictError extends Error {
|
|
45
|
+
constructor(message, reason = 'request') {
|
|
46
|
+
super(message);
|
|
47
|
+
this.name = 'ExecutionConflictError';
|
|
48
|
+
this.reason = reason;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
exports.ExecutionConflictError = ExecutionConflictError;
|
|
52
|
+
/** 指定した実行 ID に対応する Firestore の台帳文書を参照する。 */
|
|
53
|
+
function executionRef(db, executionId) {
|
|
54
|
+
(0, catalog_1.assertCloudTaskId)(executionId);
|
|
55
|
+
return db.collection(exports.TASK_EXECUTIONS_COLLECTION).doc(executionId);
|
|
56
|
+
}
|
|
57
|
+
/** ロールバックの指定を判定し、省略時は適用として扱う。 */
|
|
58
|
+
function migrationDirection(payload) {
|
|
59
|
+
return payload.kind === 'migration' && payload.direction === 'down' ? 'down' : 'up';
|
|
60
|
+
}
|
|
61
|
+
/** 指定した版の適用状態を格納する Firestore 文書を参照する。 */
|
|
62
|
+
function migrationRef(db, migrationId) {
|
|
63
|
+
(0, catalog_1.assertMigrationId)(migrationId);
|
|
64
|
+
return db.collection(exports.MIGRATIONS_COLLECTION).doc(migrationId);
|
|
65
|
+
}
|
|
66
|
+
/** 版の ID と区別できる固定の文書で、適用とロールバックの受付を直列化する。 */
|
|
67
|
+
function migrationLockRef(db) {
|
|
68
|
+
return db.collection(exports.MIGRATIONS_COLLECTION).doc(ACTIVE_MIGRATION_PLAN);
|
|
69
|
+
}
|
|
70
|
+
/** 管理画面に、現在の計画と復旧に必要な情報を返す。 */
|
|
71
|
+
async function getMigrationPlanStatus() {
|
|
72
|
+
var _a;
|
|
73
|
+
const db = (0, firestore_1.getFirestore)();
|
|
74
|
+
const lock = (await migrationLockRef(db).get()).data();
|
|
75
|
+
return lock ? { ownerId: lock.ownerId, executionId: lock.executionId, recovery: (_a = lock.recovery) !== null && _a !== void 0 ? _a : null } : null;
|
|
76
|
+
}
|
|
77
|
+
/** 配信の再試行とは独立して、進まなくなった計画を復旧待ちにする。 */
|
|
78
|
+
async function detectStalledMigrationPlan() {
|
|
79
|
+
const db = (0, firestore_1.getFirestore)();
|
|
80
|
+
const ref = migrationLockRef(db);
|
|
81
|
+
return db.runTransaction(async (tx) => {
|
|
82
|
+
var _a;
|
|
83
|
+
const lock = (await tx.get(ref)).data();
|
|
84
|
+
if (!lock || lock.recovery)
|
|
85
|
+
return null;
|
|
86
|
+
const current = executionRef(db, lock.executionId);
|
|
87
|
+
const snapshot = await tx.get(current);
|
|
88
|
+
const record = snapshot.data();
|
|
89
|
+
const payload = record === null || record === void 0 ? void 0 : record.request.payload;
|
|
90
|
+
if (!record || (payload === null || payload === void 0 ? void 0 : payload.kind) !== 'migration') {
|
|
91
|
+
throw new Error(`Active migration execution is missing: ${lock.executionId}`);
|
|
92
|
+
}
|
|
93
|
+
// リース失効だけでは、ワーカーが終了したか分からない。最後の更新からも猶予を取る。
|
|
94
|
+
const lastUpdate = Date.parse(isoTime(record.updatedAt) || isoTime(snapshot.updateTime));
|
|
95
|
+
const lastActivity = Math.max(lastUpdate, (_a = record.leaseUntil) !== null && _a !== void 0 ? _a : 0);
|
|
96
|
+
if (!Number.isFinite(lastActivity) || lastActivity + MIGRATION_INACTIVITY_MS > Date.now())
|
|
97
|
+
return null;
|
|
98
|
+
const unstarted = record.status === 'pending' || record.status === 'accepted';
|
|
99
|
+
const requiresOutcome = record.status === 'running' || record.status === 'retrying' || record.status === 'unknown';
|
|
100
|
+
const recovery = {
|
|
101
|
+
migrationId: payload.migrationId,
|
|
102
|
+
direction: migrationDirection(payload),
|
|
103
|
+
requiresOutcome,
|
|
104
|
+
};
|
|
105
|
+
const root = executionRef(db, lock.ownerId);
|
|
106
|
+
const rootExists = root.id === current.id || (await tx.get(root)).exists;
|
|
107
|
+
if (rootExists && root.id !== current.id)
|
|
108
|
+
tx.update(root, { migrationPlanStopped: true });
|
|
109
|
+
tx.update(ref, { recovery });
|
|
110
|
+
tx.update(current, Object.assign({ migrationPlanStopped: true }, (unstarted || requiresOutcome ? {
|
|
111
|
+
status: unstarted ? 'cancelled' : 'unknown',
|
|
112
|
+
error: unstarted ? '実行が開始されないまま計画を停止しました。' : '計画が停止しました。実データで適用状態を確認してください。',
|
|
113
|
+
endedAt: firestore_1.FieldValue.serverTimestamp(),
|
|
114
|
+
updatedAt: firestore_1.FieldValue.serverTimestamp(),
|
|
115
|
+
leaseUntil: firestore_1.FieldValue.delete(),
|
|
116
|
+
} : {})));
|
|
117
|
+
return { ownerId: lock.ownerId, executionId: lock.executionId, recovery };
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
/** 管理者が確認した状態を反映し、停止した計画を閉じてロックを解除する。 */
|
|
121
|
+
async function resolveStalledMigrationPlan(input) {
|
|
122
|
+
const db = (0, firestore_1.getFirestore)();
|
|
123
|
+
const ref = migrationLockRef(db);
|
|
124
|
+
const current = executionRef(db, input.executionId);
|
|
125
|
+
await db.runTransaction(async (tx) => {
|
|
126
|
+
var _a;
|
|
127
|
+
const lock = (await tx.get(ref)).data();
|
|
128
|
+
const recovery = lock === null || lock === void 0 ? void 0 : lock.recovery;
|
|
129
|
+
if (!recovery || lock.executionId !== current.id) {
|
|
130
|
+
throw new ExecutionConflictError('復旧対象が変わりました。画面を再読み込みしてください。', 'recovery');
|
|
131
|
+
}
|
|
132
|
+
if (recovery.requiresOutcome && typeof input.applied !== 'boolean') {
|
|
133
|
+
throw new TypeError('確認した適用状態を指定してください。');
|
|
134
|
+
}
|
|
135
|
+
if (recovery.requiresOutcome) {
|
|
136
|
+
const migration = migrationRef(db, recovery.migrationId);
|
|
137
|
+
const state = (await tx.get(migration)).data();
|
|
138
|
+
if ((state === null || state === void 0 ? void 0 : state.status) === 'running' && state.executionId !== current.id) {
|
|
139
|
+
throw new ExecutionConflictError('適用状態が変わりました。画面を再読み込みしてください。', 'recovery');
|
|
140
|
+
}
|
|
141
|
+
if (!input.applied)
|
|
142
|
+
tx.delete(migration);
|
|
143
|
+
else if ((state === null || state === void 0 ? void 0 : state.status) !== 'succeeded') {
|
|
144
|
+
tx.set(migration, Object.assign(Object.assign({}, appliedMigration(state !== null && state !== void 0 ? state : { status: 'running', executionId: current.id })), { executedAt: (_a = state === null || state === void 0 ? void 0 : state.executedAt) !== null && _a !== void 0 ? _a : firestore_1.FieldValue.serverTimestamp() }));
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
tx.update(current, Object.assign(Object.assign({}, (recovery.requiresOutcome
|
|
148
|
+
? { status: input.applied === (recovery.direction === 'up') ? 'succeeded' : 'failed', error: firestore_1.FieldValue.delete() }
|
|
149
|
+
: {})), { message: recovery.requiresOutcome
|
|
150
|
+
? `管理者が${input.applied ? '適用済み' : '未適用'}を確認し、計画を終了しました。`
|
|
151
|
+
: '管理者が停止した計画を終了しました。', migrationResolution: Object.assign({ actorUid: input.actorUid, resolvedAt: firestore_1.FieldValue.serverTimestamp() }, (recovery.requiresOutcome ? { applied: input.applied } : {})) }));
|
|
152
|
+
tx.delete(ref);
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
/** 現在の実行が所有者の場合だけ、次の計画を受け付けられる状態に戻す。 */
|
|
156
|
+
function releaseMigrationLock(tx, ref, lock, executionId) {
|
|
157
|
+
if ((lock === null || lock === void 0 ? void 0 : lock.executionId) === executionId)
|
|
158
|
+
tx.delete(ref);
|
|
159
|
+
}
|
|
160
|
+
/** トランザクション内で、台帳文書を投入待ちとして作成する。 */
|
|
161
|
+
function createPendingExecution(tx, ref, request, target, migrationSteps) {
|
|
162
|
+
tx.create(ref, Object.assign(Object.assign({ request,
|
|
163
|
+
target, status: 'pending', attempts: 0 }, (migrationSteps ? { migrationSteps } : {})), { createdAt: firestore_1.FieldValue.serverTimestamp(), updatedAt: firestore_1.FieldValue.serverTimestamp() }));
|
|
164
|
+
}
|
|
165
|
+
/** 例外に指定のエラーコードが付いているか判定する。 */
|
|
166
|
+
function hasCode(error, code) {
|
|
167
|
+
return typeof error === 'object' && error !== null && 'code' in error && error.code === code;
|
|
168
|
+
}
|
|
169
|
+
/** 実行データを検証して台帳とキューで共通に使う形式に整える。 */
|
|
170
|
+
function normalizePayload(payload) {
|
|
171
|
+
if (payload.kind === 'migration') {
|
|
172
|
+
(0, catalog_1.assertMigrationId)(payload.migrationId);
|
|
173
|
+
const normalized = {
|
|
174
|
+
kind: 'migration',
|
|
175
|
+
migrationId: payload.migrationId,
|
|
176
|
+
direction: payload.direction === 'down' ? 'down' : 'up',
|
|
177
|
+
};
|
|
178
|
+
if (typeof payload.targetId === 'string') {
|
|
179
|
+
if (payload.targetId !== '') {
|
|
180
|
+
(0, catalog_1.assertMigrationId)(payload.targetId);
|
|
181
|
+
}
|
|
182
|
+
normalized.targetId = payload.targetId;
|
|
183
|
+
}
|
|
184
|
+
if (typeof payload.planId === 'string' && payload.planId !== '') {
|
|
185
|
+
(0, catalog_1.assertCloudTaskId)(payload.planId);
|
|
186
|
+
normalized.planId = payload.planId;
|
|
187
|
+
}
|
|
188
|
+
return normalized;
|
|
189
|
+
}
|
|
190
|
+
if (payload.kind === 'task') {
|
|
191
|
+
(0, catalog_1.assertTaskId)(payload.taskType);
|
|
192
|
+
let round;
|
|
193
|
+
try {
|
|
194
|
+
round = JSON.parse(JSON.stringify({
|
|
195
|
+
kind: 'task',
|
|
196
|
+
taskType: payload.taskType,
|
|
197
|
+
data: payload.data,
|
|
198
|
+
}));
|
|
199
|
+
}
|
|
200
|
+
catch (_a) {
|
|
201
|
+
throw new TypeError('Task data must be JSON serializable');
|
|
202
|
+
}
|
|
203
|
+
if (!round || round.kind !== 'task' || !('data' in round)) {
|
|
204
|
+
throw new TypeError('Task data must be JSON serializable');
|
|
205
|
+
}
|
|
206
|
+
return round;
|
|
207
|
+
}
|
|
208
|
+
throw new TypeError('Execution payload kind must be task or migration');
|
|
209
|
+
}
|
|
210
|
+
/** 実行依頼を比較・保存できる台帳の形式に変換する。 */
|
|
211
|
+
function storedRequest(input, payload) {
|
|
212
|
+
var _a, _b;
|
|
213
|
+
if (input.source !== 'manual' && input.source !== 'schedule' && input.source !== 'app') {
|
|
214
|
+
throw new TypeError('Execution source must be manual, schedule, or app');
|
|
215
|
+
}
|
|
216
|
+
return Object.assign(Object.assign({ executionId: input.executionId, payload, source: input.source }, (input.actorUid ? { actorUid: input.actorUid } : {})), { scheduleTime: (_b = (_a = input.scheduleTime) === null || _a === void 0 ? void 0 : _a.toISOString()) !== null && _b !== void 0 ? _b : null });
|
|
217
|
+
}
|
|
218
|
+
/**
|
|
219
|
+
* 台帳へ要求を書いてからキューへ積む。
|
|
220
|
+
* 同じ実行 ID かつ同じ要求は既存の実行を返す。内容が違えば競合。
|
|
221
|
+
* ワーカーが先に進めていても、投入側は状態を巻き戻さない。
|
|
222
|
+
*/
|
|
223
|
+
async function enqueueExecution(input, target = {}) {
|
|
224
|
+
const db = (0, firestore_1.getFirestore)();
|
|
225
|
+
const ref = executionRef(db, input.executionId);
|
|
226
|
+
const queueName = (0, task_queue_1.tasksQueueResourceName)(target.functionName, target.region);
|
|
227
|
+
const payload = normalizePayload(input.payload);
|
|
228
|
+
(0, catalog_1.assertScheduleWindow)(input.scheduleTime);
|
|
229
|
+
const request = storedRequest(input, payload);
|
|
230
|
+
// キュー登録より先に実行 ID を依頼に紐づけ、同じ ID の再送で依頼内容が変わることを防ぐ。
|
|
231
|
+
const status = await db.runTransaction(async (tx) => {
|
|
232
|
+
const existing = (await tx.get(ref)).data();
|
|
233
|
+
if (existing) {
|
|
234
|
+
if (!(0, node_util_1.isDeepStrictEqual)(existing.request, request) || existing.target !== queueName) {
|
|
235
|
+
throw new ExecutionConflictError('Execution ID is already bound to another request');
|
|
236
|
+
}
|
|
237
|
+
return existing.status;
|
|
238
|
+
}
|
|
239
|
+
createPendingExecution(tx, ref, request, queueName);
|
|
240
|
+
return 'pending';
|
|
241
|
+
});
|
|
242
|
+
return dispatchExecution(db, ref, request, queueName, status);
|
|
243
|
+
}
|
|
244
|
+
/** 予約された実行をキューに送り、競合があれば台帳の最新状態を返す。 */
|
|
245
|
+
async function dispatchExecution(db, ref, request, queueName, status) {
|
|
246
|
+
const { executionId, payload, scheduleTime } = request;
|
|
247
|
+
if (status !== 'pending') {
|
|
248
|
+
return { executionId, status };
|
|
249
|
+
}
|
|
250
|
+
const queue = (0, functions_1.getFunctions)().taskQueue(queueName);
|
|
251
|
+
try {
|
|
252
|
+
await queue.enqueue(Object.assign(Object.assign({}, payload), { executionId }), (0, task_queue_1.buildEnqueueOptions)(scheduleTime === null ? undefined : new Date(scheduleTime), executionId));
|
|
253
|
+
}
|
|
254
|
+
catch (error) {
|
|
255
|
+
if (!hasCode(error, 'functions/task-already-exists')) {
|
|
256
|
+
throw error;
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
// 登録中に実行や取り消しが先に確定した場合は、台帳の状態を優先する。
|
|
260
|
+
const acceptedStatus = await db.runTransaction(async (tx) => {
|
|
261
|
+
var _a;
|
|
262
|
+
const record = (await tx.get(ref)).data();
|
|
263
|
+
if (!record || record.status !== 'pending') {
|
|
264
|
+
return (_a = record === null || record === void 0 ? void 0 : record.status) !== null && _a !== void 0 ? _a : 'pending';
|
|
265
|
+
}
|
|
266
|
+
tx.update(ref, { status: 'accepted', updatedAt: firestore_1.FieldValue.serverTimestamp() });
|
|
267
|
+
return 'accepted';
|
|
268
|
+
});
|
|
269
|
+
if (acceptedStatus === 'cancelled') {
|
|
270
|
+
await deleteQueueTask(queueName, executionId);
|
|
271
|
+
}
|
|
272
|
+
return { executionId, status: acceptedStatus };
|
|
273
|
+
}
|
|
274
|
+
/** 適用順の確認、計画の予約、先頭の台帳作成を同じトランザクションで行う。 */
|
|
275
|
+
async function enqueueMigrationPlan(input) {
|
|
276
|
+
const { catalog, executionId, targetId, actorUid } = input;
|
|
277
|
+
const direction = input.direction === 'down' ? 'down' : 'up';
|
|
278
|
+
const db = (0, firestore_1.getFirestore)();
|
|
279
|
+
const ref = executionRef(db, executionId);
|
|
280
|
+
const lockRef = migrationLockRef(db);
|
|
281
|
+
const queueName = (0, task_queue_1.tasksQueueResourceName)();
|
|
282
|
+
const admission = await db.runTransaction(async (tx) => {
|
|
283
|
+
var _a;
|
|
284
|
+
const existing = (await tx.get(ref)).data();
|
|
285
|
+
const existingPayload = existing === null || existing === void 0 ? void 0 : existing.request.payload;
|
|
286
|
+
const existingSteps = (_a = existing === null || existing === void 0 ? void 0 : existing.migrationSteps) !== null && _a !== void 0 ? _a : ((existingPayload === null || existingPayload === void 0 ? void 0 : existingPayload.kind) === 'migration' ? remainingMigrationSteps(catalog.map(entry => entry.id), existingPayload) : []);
|
|
287
|
+
if (existing && ((existingPayload === null || existingPayload === void 0 ? void 0 : existingPayload.kind) !== 'migration'
|
|
288
|
+
|| existingPayload.planId !== executionId
|
|
289
|
+
|| existingPayload.targetId !== targetId
|
|
290
|
+
|| migrationDirection(existingPayload) !== direction
|
|
291
|
+
|| existing.request.source !== 'manual'
|
|
292
|
+
|| existing.request.actorUid !== (actorUid || undefined)
|
|
293
|
+
|| existing.target !== queueName)) {
|
|
294
|
+
throw new ExecutionConflictError('Execution ID is already bound to another request');
|
|
295
|
+
}
|
|
296
|
+
if (existing && existing.status !== 'pending') {
|
|
297
|
+
return { request: existing.request, steps: existingSteps, status: existing.status };
|
|
298
|
+
}
|
|
299
|
+
const lock = (await tx.get(lockRef)).data();
|
|
300
|
+
if (lock === null || lock === void 0 ? void 0 : lock.recovery)
|
|
301
|
+
throw new ExecutionConflictError('停止したマイグレーション計画の復旧が必要です。', 'recovery');
|
|
302
|
+
if (lock && (lock.ownerId !== executionId || lock.executionId !== executionId)) {
|
|
303
|
+
throw new ExecutionConflictError('別のマイグレーション計画が実行中です。', 'locked');
|
|
304
|
+
}
|
|
305
|
+
if (existing && lock) {
|
|
306
|
+
return { request: existing.request, steps: existingSteps, status: existing.status };
|
|
307
|
+
}
|
|
308
|
+
const states = await readMigrationStateMap(tx, db, catalog.map(entry => entry.id));
|
|
309
|
+
const { steps } = (0, migration_plan_1.planMigrationMove)({ catalog, states, direction, targetId });
|
|
310
|
+
const first = steps[0];
|
|
311
|
+
if (!first)
|
|
312
|
+
throw new TypeError('移動するマイグレーションがありません。');
|
|
313
|
+
for (const step of steps.slice(1))
|
|
314
|
+
(0, catalog_1.assertCloudTaskId)(`${executionId}_${step}`);
|
|
315
|
+
const payload = normalizePayload({ kind: 'migration', migrationId: first, direction, targetId, planId: executionId });
|
|
316
|
+
const request = storedRequest({ executionId, source: 'manual', actorUid, payload }, payload);
|
|
317
|
+
if (existing && !(0, node_util_1.isDeepStrictEqual)(existing.request, request)) {
|
|
318
|
+
throw new ExecutionConflictError('適用状態が変わったため、以前の計画を再投入できません。');
|
|
319
|
+
}
|
|
320
|
+
if (!existing)
|
|
321
|
+
createPendingExecution(tx, ref, request, queueName, steps);
|
|
322
|
+
tx.set(lockRef, { ownerId: executionId, executionId, steps });
|
|
323
|
+
return { request, steps, status: 'pending' };
|
|
324
|
+
});
|
|
325
|
+
const result = await dispatchExecution(db, ref, admission.request, queueName, admission.status);
|
|
326
|
+
return Object.assign(Object.assign({}, result), { steps: admission.steps });
|
|
327
|
+
}
|
|
328
|
+
/** 計画の先頭から到達点までの順序を、公開前に保存された実行から復元する。 */
|
|
329
|
+
function remainingMigrationSteps(catalogIds, payload) {
|
|
330
|
+
const first = catalogIds.indexOf(payload.migrationId);
|
|
331
|
+
if (first === -1 || payload.targetId === undefined)
|
|
332
|
+
return [];
|
|
333
|
+
if (migrationDirection(payload) === 'down') {
|
|
334
|
+
const target = payload.targetId === '' ? -1 : catalogIds.indexOf(payload.targetId);
|
|
335
|
+
if (target === -1 && payload.targetId !== '')
|
|
336
|
+
return [];
|
|
337
|
+
return catalogIds.slice(target + 1, first + 1).reverse();
|
|
338
|
+
}
|
|
339
|
+
return catalogIds.slice(first, catalogIds.indexOf(payload.targetId) + 1);
|
|
340
|
+
}
|
|
341
|
+
/** 計画のロックと同じトランザクションで、カタログに対応する適用状態を読み取る。 */
|
|
342
|
+
async function readMigrationStateMap(tx, db, ids) {
|
|
343
|
+
if (ids.length === 0)
|
|
344
|
+
return new Map();
|
|
345
|
+
const snapshots = await tx.getAll(...ids.map(id => migrationRef(db, id)));
|
|
346
|
+
return new Map(snapshots.map(snap => {
|
|
347
|
+
var _a;
|
|
348
|
+
const status = (_a = snap.data()) === null || _a === void 0 ? void 0 : _a.status;
|
|
349
|
+
return [snap.id, status === 'running' || status === 'succeeded' ? status : 'absent'];
|
|
350
|
+
}));
|
|
351
|
+
}
|
|
352
|
+
/** 成功した版の次を予約し、最終版なら計画のロックを解除する。 */
|
|
353
|
+
async function continueMigrationPlan(executionId, catalogIds) {
|
|
354
|
+
const db = (0, firestore_1.getFirestore)();
|
|
355
|
+
const lockRef = migrationLockRef(db);
|
|
356
|
+
const continuation = await db.runTransaction(async (tx) => {
|
|
357
|
+
var _a, _b, _c;
|
|
358
|
+
const record = (await tx.get(executionRef(db, executionId))).data();
|
|
359
|
+
const payload = record === null || record === void 0 ? void 0 : record.request.payload;
|
|
360
|
+
if ((record === null || record === void 0 ? void 0 : record.status) !== 'succeeded' || record.migrationPlanStopped || (payload === null || payload === void 0 ? void 0 : payload.kind) !== 'migration' || typeof payload.targetId !== 'string' || !payload.planId) {
|
|
361
|
+
return null;
|
|
362
|
+
}
|
|
363
|
+
const lock = (await tx.get(lockRef)).data();
|
|
364
|
+
if (lock === null || lock === void 0 ? void 0 : lock.recovery)
|
|
365
|
+
return null;
|
|
366
|
+
const root = payload.planId === executionId
|
|
367
|
+
? record
|
|
368
|
+
: (await tx.get(executionRef(db, payload.planId))).data();
|
|
369
|
+
if (root === null || root === void 0 ? void 0 : root.migrationPlanStopped)
|
|
370
|
+
return null;
|
|
371
|
+
const steps = (_b = (_a = record.migrationSteps) !== null && _a !== void 0 ? _a : ((lock === null || lock === void 0 ? void 0 : lock.ownerId) === payload.planId ? lock.steps : undefined)) !== null && _b !== void 0 ? _b : root === null || root === void 0 ? void 0 : root.migrationSteps;
|
|
372
|
+
const currentIndex = (_c = steps === null || steps === void 0 ? void 0 : steps.indexOf(payload.migrationId)) !== null && _c !== void 0 ? _c : -1;
|
|
373
|
+
const nextId = steps
|
|
374
|
+
? (currentIndex >= 0 ? steps[currentIndex + 1] : undefined)
|
|
375
|
+
: (0, migration_plan_1.nextMigrationStep)(catalogIds, payload.migrationId, migrationDirection(payload), payload.targetId);
|
|
376
|
+
if (!nextId) {
|
|
377
|
+
releaseMigrationLock(tx, lockRef, lock, executionId);
|
|
378
|
+
return null;
|
|
379
|
+
}
|
|
380
|
+
const nextExecutionId = `${payload.planId}_${nextId}`;
|
|
381
|
+
const ref = executionRef(db, nextExecutionId);
|
|
382
|
+
const request = Object.assign(Object.assign({}, record.request), { executionId: nextExecutionId, payload: Object.assign(Object.assign({}, payload), { migrationId: nextId }), scheduleTime: null });
|
|
383
|
+
const existing = (await tx.get(ref)).data();
|
|
384
|
+
if (existing && (!(0, node_util_1.isDeepStrictEqual)(existing.request, request) || existing.target !== record.target)) {
|
|
385
|
+
releaseMigrationLock(tx, lockRef, lock, executionId);
|
|
386
|
+
return { conflict: nextExecutionId };
|
|
387
|
+
}
|
|
388
|
+
if (existing && existing.status !== 'pending')
|
|
389
|
+
return null;
|
|
390
|
+
if (lock && (lock.ownerId !== payload.planId || (lock.executionId !== executionId && lock.executionId !== nextExecutionId))) {
|
|
391
|
+
throw new ExecutionConflictError('別のマイグレーション計画が実行中です。', 'locked');
|
|
392
|
+
}
|
|
393
|
+
if (!existing)
|
|
394
|
+
createPendingExecution(tx, ref, request, record.target);
|
|
395
|
+
tx.set(lockRef, Object.assign(Object.assign({}, lock), { ownerId: payload.planId, executionId: nextExecutionId }));
|
|
396
|
+
return { ref, request, target: record.target };
|
|
397
|
+
});
|
|
398
|
+
if (!continuation)
|
|
399
|
+
return;
|
|
400
|
+
if ('conflict' in continuation) {
|
|
401
|
+
console.warn('Migration plan could not enqueue the next version', continuation.conflict);
|
|
402
|
+
return;
|
|
403
|
+
}
|
|
404
|
+
await dispatchExecution(db, continuation.ref, continuation.request, continuation.target, 'pending');
|
|
405
|
+
}
|
|
406
|
+
/**
|
|
407
|
+
* 最初の開始が確定する前だけ取り消す。
|
|
408
|
+
* 開始と取消は同じ文書のトランザクションで先に確定した側を採用する。
|
|
409
|
+
*/
|
|
410
|
+
async function cancelExecution(executionId) {
|
|
411
|
+
const db = (0, firestore_1.getFirestore)();
|
|
412
|
+
const ref = executionRef(db, executionId);
|
|
413
|
+
const target = await db.runTransaction(async (tx) => {
|
|
414
|
+
const record = (await tx.get(ref)).data();
|
|
415
|
+
if (!record) {
|
|
416
|
+
return null;
|
|
417
|
+
}
|
|
418
|
+
if (record.status === 'cancelled') {
|
|
419
|
+
return record.target;
|
|
420
|
+
}
|
|
421
|
+
if (record.attempts !== 0 || (record.status !== 'pending' && record.status !== 'accepted')) {
|
|
422
|
+
throw new ExecutionConflictError('Execution cannot be cancelled after it has started', 'started');
|
|
423
|
+
}
|
|
424
|
+
const lockRef = migrationLockRef(db);
|
|
425
|
+
const lock = record.request.payload.kind === 'migration'
|
|
426
|
+
? (await tx.get(lockRef)).data()
|
|
427
|
+
: undefined;
|
|
428
|
+
tx.update(ref, {
|
|
429
|
+
status: 'cancelled',
|
|
430
|
+
endedAt: firestore_1.FieldValue.serverTimestamp(),
|
|
431
|
+
updatedAt: firestore_1.FieldValue.serverTimestamp(),
|
|
432
|
+
});
|
|
433
|
+
releaseMigrationLock(tx, lockRef, lock, executionId);
|
|
434
|
+
return record.target;
|
|
435
|
+
});
|
|
436
|
+
if (!target) {
|
|
437
|
+
return false;
|
|
438
|
+
}
|
|
439
|
+
await deleteQueueTask(target, executionId);
|
|
440
|
+
return true;
|
|
441
|
+
}
|
|
442
|
+
/** 取り消した実行のタスクをキューから削除し、削除時のエラーを扱う。 */
|
|
443
|
+
async function deleteQueueTask(target, executionId) {
|
|
444
|
+
try {
|
|
445
|
+
await (0, functions_1.getFunctions)().taskQueue(target).delete(executionId);
|
|
446
|
+
}
|
|
447
|
+
catch (error) {
|
|
448
|
+
if (!hasCode(error, 'functions/not-found') && !hasCode(error, 'not-found')) {
|
|
449
|
+
console.warn('Cancelled execution delivery could not be deleted', executionId, error);
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
/**
|
|
454
|
+
* 試行 ID と有効期限を記録してから処理する。
|
|
455
|
+
* 有効な試行がある間は、その試行が実行を持つ。期限切れで試行枠が残っていれば同じ ID で取り直す。
|
|
456
|
+
* マイグレーションは成功済みをスキップする。別の実行が持っている間は、先の実行に任せる。
|
|
457
|
+
*/
|
|
458
|
+
async function claimExecution(executionId, catalogIds = []) {
|
|
459
|
+
const db = (0, firestore_1.getFirestore)();
|
|
460
|
+
const ref = executionRef(db, executionId);
|
|
461
|
+
const attemptId = (0, node_crypto_1.randomUUID)();
|
|
462
|
+
return db.runTransaction(async (tx) => {
|
|
463
|
+
var _a, _b;
|
|
464
|
+
const snap = await tx.get(ref);
|
|
465
|
+
const record = snap.data();
|
|
466
|
+
if (!record) {
|
|
467
|
+
throw new Error('Execution ledger entry is missing');
|
|
468
|
+
}
|
|
469
|
+
const payload = record.request.payload;
|
|
470
|
+
const migrationId = payload.kind === 'migration' ? payload.migrationId : '';
|
|
471
|
+
const migration = migrationId ? migrationRef(db, migrationId) : null;
|
|
472
|
+
const migrationSnap = migration ? await tx.get(migration) : null;
|
|
473
|
+
const migrationRecord = migrationSnap === null || migrationSnap === void 0 ? void 0 : migrationSnap.data();
|
|
474
|
+
if (record.status === 'cancelled'
|
|
475
|
+
|| record.status === 'succeeded'
|
|
476
|
+
|| record.status === 'failed'
|
|
477
|
+
|| record.status === 'unknown') {
|
|
478
|
+
return null;
|
|
479
|
+
}
|
|
480
|
+
const now = Date.now();
|
|
481
|
+
if (record.status === 'running' && ((_a = record.leaseUntil) !== null && _a !== void 0 ? _a : 0) > now) {
|
|
482
|
+
throw new ExecutionConflictError('Execution attempt is already in progress', 'locked');
|
|
483
|
+
}
|
|
484
|
+
const lockRef = migrationLockRef(db);
|
|
485
|
+
const lock = migration ? (await tx.get(lockRef)).data() : undefined;
|
|
486
|
+
if (lock === null || lock === void 0 ? void 0 : lock.recovery)
|
|
487
|
+
throw new ExecutionConflictError('停止したマイグレーション計画の復旧が必要です。', 'recovery');
|
|
488
|
+
const ownerId = payload.kind === 'migration' ? (_b = payload.planId) !== null && _b !== void 0 ? _b : executionId : executionId;
|
|
489
|
+
if (lock && (lock.ownerId !== ownerId || lock.executionId !== executionId)) {
|
|
490
|
+
throw new ExecutionConflictError('別のマイグレーション計画が実行中です。', 'locked');
|
|
491
|
+
}
|
|
492
|
+
const direction = migrationDirection(payload);
|
|
493
|
+
if (direction === 'down') {
|
|
494
|
+
const ownsRollback = (migrationRecord === null || migrationRecord === void 0 ? void 0 : migrationRecord.status) === 'running'
|
|
495
|
+
&& migrationRecord.executionId === executionId
|
|
496
|
+
&& migrationRecord.direction === 'down';
|
|
497
|
+
if (!ownsRollback && (migrationRecord === null || migrationRecord === void 0 ? void 0 : migrationRecord.status) !== 'succeeded') {
|
|
498
|
+
tx.update(ref, {
|
|
499
|
+
status: 'failed',
|
|
500
|
+
error: '適用されていないためロールバックできません',
|
|
501
|
+
endedAt: firestore_1.FieldValue.serverTimestamp(),
|
|
502
|
+
updatedAt: firestore_1.FieldValue.serverTimestamp(),
|
|
503
|
+
leaseUntil: firestore_1.FieldValue.delete(),
|
|
504
|
+
});
|
|
505
|
+
releaseMigrationLock(tx, lockRef, lock, executionId);
|
|
506
|
+
return null;
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
else if ((migrationRecord === null || migrationRecord === void 0 ? void 0 : migrationRecord.status) === 'succeeded') {
|
|
510
|
+
if (!lock && payload.kind === 'migration' && payload.planId && payload.targetId !== undefined) {
|
|
511
|
+
tx.set(lockRef, { ownerId, executionId });
|
|
512
|
+
}
|
|
513
|
+
tx.update(ref, {
|
|
514
|
+
status: 'succeeded',
|
|
515
|
+
message: '実行済みのためスキップしました',
|
|
516
|
+
endedAt: firestore_1.FieldValue.serverTimestamp(),
|
|
517
|
+
updatedAt: firestore_1.FieldValue.serverTimestamp(),
|
|
518
|
+
});
|
|
519
|
+
return null;
|
|
520
|
+
}
|
|
521
|
+
if ((migrationRecord === null || migrationRecord === void 0 ? void 0 : migrationRecord.status) === 'running'
|
|
522
|
+
&& migrationRecord.executionId !== executionId) {
|
|
523
|
+
throw new ExecutionConflictError('Migration is already running', 'locked');
|
|
524
|
+
}
|
|
525
|
+
// 処理結果を確定できないまま試行枠を使い切った場合は、結果不明として記録する。
|
|
526
|
+
if (record.attempts >= exports.MAX_EXECUTION_ATTEMPTS) {
|
|
527
|
+
tx.update(ref, {
|
|
528
|
+
status: 'unknown',
|
|
529
|
+
error: '試行上限に達しましたが、結果を確認できません',
|
|
530
|
+
endedAt: firestore_1.FieldValue.serverTimestamp(),
|
|
531
|
+
updatedAt: firestore_1.FieldValue.serverTimestamp(),
|
|
532
|
+
leaseUntil: firestore_1.FieldValue.delete(),
|
|
533
|
+
});
|
|
534
|
+
// マイグレーションの結果を確認できるまで、実行中の印とロックを残す。
|
|
535
|
+
if (migration && !lock)
|
|
536
|
+
tx.set(lockRef, { ownerId, executionId });
|
|
537
|
+
return null;
|
|
538
|
+
}
|
|
539
|
+
const position = migration ? catalogIds.indexOf(migrationId) : -1;
|
|
540
|
+
if (position >= 0 && !(lock === null || lock === void 0 ? void 0 : lock.steps)) {
|
|
541
|
+
// 旧版ですでにキューに載った実行は、現在の適用順を起動時にも確認する。
|
|
542
|
+
const states = await readMigrationStateMap(tx, db, catalogIds.filter(id => id !== migrationId));
|
|
543
|
+
if ([...states.values()].includes('running')) {
|
|
544
|
+
throw new ExecutionConflictError('別のマイグレーションが実行中です。', 'locked');
|
|
545
|
+
}
|
|
546
|
+
const ordered = direction === 'up'
|
|
547
|
+
? catalogIds.slice(0, position).every(id => states.get(id) === 'succeeded')
|
|
548
|
+
: catalogIds.slice(position + 1).every(id => states.get(id) === 'absent');
|
|
549
|
+
if (!ordered) {
|
|
550
|
+
tx.update(ref, {
|
|
551
|
+
status: 'failed',
|
|
552
|
+
error: '適用順が変わったため、マイグレーションを実行できません。',
|
|
553
|
+
endedAt: firestore_1.FieldValue.serverTimestamp(),
|
|
554
|
+
updatedAt: firestore_1.FieldValue.serverTimestamp(),
|
|
555
|
+
leaseUntil: firestore_1.FieldValue.delete(),
|
|
556
|
+
});
|
|
557
|
+
if (migration && (migrationRecord === null || migrationRecord === void 0 ? void 0 : migrationRecord.executionId) === executionId && migrationRecord.status === 'running') {
|
|
558
|
+
restoreOrClearMigration(tx, migration, payload, migrationRecord);
|
|
559
|
+
}
|
|
560
|
+
releaseMigrationLock(tx, lockRef, lock, executionId);
|
|
561
|
+
return null;
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
const attempts = record.attempts + 1;
|
|
565
|
+
tx.update(ref, Object.assign(Object.assign({ status: 'running', attempts,
|
|
566
|
+
attemptId, leaseUntil: now + exports.ATTEMPT_LEASE_MS }, (attempts === 1 ? { startedAt: firestore_1.FieldValue.serverTimestamp() } : {})), { updatedAt: firestore_1.FieldValue.serverTimestamp() }));
|
|
567
|
+
if (migration) {
|
|
568
|
+
if (!lock)
|
|
569
|
+
tx.set(lockRef, { ownerId, executionId });
|
|
570
|
+
tx.set(migration, runningMigration(executionId, direction, migrationRecord));
|
|
571
|
+
}
|
|
572
|
+
return { attemptId, attempts, request: record.request };
|
|
573
|
+
});
|
|
574
|
+
}
|
|
575
|
+
/** 台帳上で実行中の試行 ID が一致する場合に有効期限を延長する。 */
|
|
576
|
+
async function extendAttemptLease(executionId, attemptId) {
|
|
577
|
+
const db = (0, firestore_1.getFirestore)();
|
|
578
|
+
const ref = executionRef(db, executionId);
|
|
579
|
+
await db.runTransaction(async (tx) => {
|
|
580
|
+
const record = (await tx.get(ref)).data();
|
|
581
|
+
if ((record === null || record === void 0 ? void 0 : record.status) !== 'running' || record.attemptId !== attemptId) {
|
|
582
|
+
return;
|
|
583
|
+
}
|
|
584
|
+
tx.update(ref, {
|
|
585
|
+
leaseUntil: Date.now() + exports.ATTEMPT_LEASE_MS,
|
|
586
|
+
updatedAt: firestore_1.FieldValue.serverTimestamp(),
|
|
587
|
+
});
|
|
588
|
+
});
|
|
589
|
+
}
|
|
590
|
+
/**
|
|
591
|
+
* 台帳の現在の試行 ID と一致するときだけ結果を確定する。
|
|
592
|
+
* 適用成功は `bksk_migrations` に記録し、ロールバック成功時は適用記録を削除する。
|
|
593
|
+
*/
|
|
594
|
+
async function finishExecution(executionId, attemptId, status, detail) {
|
|
595
|
+
const db = (0, firestore_1.getFirestore)();
|
|
596
|
+
const ref = executionRef(db, executionId);
|
|
597
|
+
return db.runTransaction(async (tx) => {
|
|
598
|
+
const record = (await tx.get(ref)).data();
|
|
599
|
+
if ((record === null || record === void 0 ? void 0 : record.status) !== 'running' || record.attemptId !== attemptId) {
|
|
600
|
+
return false;
|
|
601
|
+
}
|
|
602
|
+
const payload = record.request.payload;
|
|
603
|
+
const migrationId = payload.kind === 'migration' ? payload.migrationId : '';
|
|
604
|
+
const migration = migrationId ? migrationRef(db, migrationId) : null;
|
|
605
|
+
let current;
|
|
606
|
+
if (migration) {
|
|
607
|
+
current = (await tx.get(migration)).data();
|
|
608
|
+
if (current && current.executionId !== executionId) {
|
|
609
|
+
return false;
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
const lockRef = migrationLockRef(db);
|
|
613
|
+
const lock = migration ? (await tx.get(lockRef)).data() : undefined;
|
|
614
|
+
tx.update(ref, Object.assign(Object.assign(Object.assign({ status, leaseUntil: firestore_1.FieldValue.delete() }, (status === 'succeeded' ? { message: detail, error: firestore_1.FieldValue.delete() } : { error: detail })), (status === 'retrying' ? {} : { endedAt: firestore_1.FieldValue.serverTimestamp() })), { updatedAt: firestore_1.FieldValue.serverTimestamp() }));
|
|
615
|
+
if (!migration) {
|
|
616
|
+
return true;
|
|
617
|
+
}
|
|
618
|
+
const hasContinuation = payload.kind === 'migration' && payload.planId && payload.targetId !== undefined;
|
|
619
|
+
if (status === 'failed' || (status === 'succeeded' && !hasContinuation)) {
|
|
620
|
+
releaseMigrationLock(tx, lockRef, lock, executionId);
|
|
621
|
+
}
|
|
622
|
+
// ロールバック成功時は適用済みの記録を削除し、失敗が確定した場合は以前の適用状態に戻す。
|
|
623
|
+
if (status === 'succeeded' && migrationDirection(record.request.payload) === 'down') {
|
|
624
|
+
tx.delete(migration);
|
|
625
|
+
}
|
|
626
|
+
else if (status === 'succeeded') {
|
|
627
|
+
tx.set(migration, {
|
|
628
|
+
status: 'succeeded',
|
|
629
|
+
executionId,
|
|
630
|
+
direction: 'up',
|
|
631
|
+
executedAt: firestore_1.FieldValue.serverTimestamp(),
|
|
632
|
+
});
|
|
633
|
+
}
|
|
634
|
+
else if (status === 'failed' && migrationDirection(record.request.payload) === 'down' && current) {
|
|
635
|
+
tx.set(migration, appliedMigration(current));
|
|
636
|
+
}
|
|
637
|
+
else if (status === 'failed') {
|
|
638
|
+
tx.delete(migration);
|
|
639
|
+
}
|
|
640
|
+
return true;
|
|
641
|
+
});
|
|
642
|
+
}
|
|
643
|
+
/** 条件に一致する実行履歴を新しい順に取得する。 */
|
|
644
|
+
async function listExecutions(limit = 50, kind, subjectId) {
|
|
645
|
+
const size = Number.isInteger(limit) && limit > 0 ? Math.min(limit, 100) : 50;
|
|
646
|
+
const found = [];
|
|
647
|
+
await eachExecutionPage((summary) => {
|
|
648
|
+
if (kind && summary.kind !== kind) {
|
|
649
|
+
return true;
|
|
650
|
+
}
|
|
651
|
+
if (subjectId && summary.subjectId !== subjectId) {
|
|
652
|
+
return true;
|
|
653
|
+
}
|
|
654
|
+
found.push(summary);
|
|
655
|
+
return found.length < size;
|
|
656
|
+
});
|
|
657
|
+
return found;
|
|
658
|
+
}
|
|
659
|
+
/** 指定したタスクまたはマイグレーションごとに、作成時刻が最新の実行を返す。 */
|
|
660
|
+
async function latestExecutions(kind, subjectIds) {
|
|
661
|
+
const wanted = new Set(subjectIds);
|
|
662
|
+
const found = new Map();
|
|
663
|
+
if (wanted.size === 0) {
|
|
664
|
+
return [];
|
|
665
|
+
}
|
|
666
|
+
await eachExecutionPage((summary) => {
|
|
667
|
+
if (summary.kind === kind && wanted.has(summary.subjectId) && !found.has(summary.subjectId)) {
|
|
668
|
+
found.set(summary.subjectId, summary);
|
|
669
|
+
}
|
|
670
|
+
return found.size < wanted.size;
|
|
671
|
+
});
|
|
672
|
+
return [...found.values()];
|
|
673
|
+
}
|
|
674
|
+
/** 実行台帳を新しい順にページ単位で読み、指定された条件で読み取りを打ち切る。 */
|
|
675
|
+
async function eachExecutionPage(visit) {
|
|
676
|
+
const query = (0, firestore_1.getFirestore)()
|
|
677
|
+
.collection(exports.TASK_EXECUTIONS_COLLECTION)
|
|
678
|
+
.orderBy('createdAt', 'desc');
|
|
679
|
+
let last;
|
|
680
|
+
for (let page = 0; page < 8; page += 1) {
|
|
681
|
+
const snap = await (last ? query.startAfter(last) : query).limit(50).get();
|
|
682
|
+
if (snap.empty) {
|
|
683
|
+
return;
|
|
684
|
+
}
|
|
685
|
+
last = snap.docs[snap.docs.length - 1];
|
|
686
|
+
for (const doc of snap.docs) {
|
|
687
|
+
if (!visit(summarizeExecution(doc))) {
|
|
688
|
+
return;
|
|
689
|
+
}
|
|
690
|
+
}
|
|
691
|
+
if (snap.size < 50) {
|
|
692
|
+
return;
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
}
|
|
696
|
+
/** 実行中のマイグレーションの記録を作り、必要な場合は以前の適用情報を残す。 */
|
|
697
|
+
function runningMigration(executionId, direction, current) {
|
|
698
|
+
const appliedExecutionId = direction === 'down'
|
|
699
|
+
? (current === null || current === void 0 ? void 0 : current.status) === 'succeeded'
|
|
700
|
+
? current.executionId
|
|
701
|
+
: current === null || current === void 0 ? void 0 : current.appliedExecutionId
|
|
702
|
+
: undefined;
|
|
703
|
+
return Object.assign(Object.assign(Object.assign({ status: 'running', executionId,
|
|
704
|
+
direction }, (appliedExecutionId ? { appliedExecutionId } : {})), (direction === 'down' && (current === null || current === void 0 ? void 0 : current.executedAt) ? { executedAt: current.executedAt } : {})), { updatedAt: firestore_1.FieldValue.serverTimestamp() });
|
|
705
|
+
}
|
|
706
|
+
/** 実行中の記録から復元に使う適用済みの情報を組み立てる。 */
|
|
707
|
+
function appliedMigration(current) {
|
|
708
|
+
return Object.assign(Object.assign({ status: 'succeeded', executionId: (current === null || current === void 0 ? void 0 : current.appliedExecutionId) || (current === null || current === void 0 ? void 0 : current.executionId) || '', direction: 'up' }, ((current === null || current === void 0 ? void 0 : current.executedAt) ? { executedAt: current.executedAt } : {})), { updatedAt: firestore_1.FieldValue.serverTimestamp() });
|
|
709
|
+
}
|
|
710
|
+
/** 失敗したロールバックの適用状態を復元するか、実行中の記録を削除する。 */
|
|
711
|
+
function restoreOrClearMigration(tx, migration, payload, current) {
|
|
712
|
+
if (migrationDirection(payload) === 'down' && current.appliedExecutionId) {
|
|
713
|
+
tx.set(migration, appliedMigration(current));
|
|
714
|
+
return;
|
|
715
|
+
}
|
|
716
|
+
tx.delete(migration);
|
|
717
|
+
}
|
|
718
|
+
/** 台帳文書を管理画面向けの実行情報に変換する。 */
|
|
719
|
+
function summarizeExecution(doc) {
|
|
720
|
+
var _a, _b, _c, _d, _e, _f, _g;
|
|
721
|
+
const data = doc.data();
|
|
722
|
+
const payload = (_a = data.request) === null || _a === void 0 ? void 0 : _a.payload;
|
|
723
|
+
const kind = (payload === null || payload === void 0 ? void 0 : payload.kind) === 'migration' ? 'migration' : 'task';
|
|
724
|
+
const subjectId = kind === 'migration'
|
|
725
|
+
? payload && 'migrationId' in payload ? payload.migrationId : ''
|
|
726
|
+
: payload && 'taskType' in payload ? payload.taskType : '';
|
|
727
|
+
return {
|
|
728
|
+
id: doc.id,
|
|
729
|
+
kind,
|
|
730
|
+
subjectId,
|
|
731
|
+
status: data.status,
|
|
732
|
+
source: (_b = data.request) === null || _b === void 0 ? void 0 : _b.source,
|
|
733
|
+
actorUid: (_d = (_c = data.request) === null || _c === void 0 ? void 0 : _c.actorUid) !== null && _d !== void 0 ? _d : '',
|
|
734
|
+
scheduleTime: (_f = (_e = data.request) === null || _e === void 0 ? void 0 : _e.scheduleTime) !== null && _f !== void 0 ? _f : '',
|
|
735
|
+
startedAt: isoTime(data.startedAt),
|
|
736
|
+
endedAt: isoTime(data.endedAt),
|
|
737
|
+
attempts: (_g = data.attempts) !== null && _g !== void 0 ? _g : 0,
|
|
738
|
+
error: typeof data.error === 'string' ? data.error : '',
|
|
739
|
+
message: typeof data.message === 'string' ? data.message : '',
|
|
740
|
+
direction: (payload === null || payload === void 0 ? void 0 : payload.kind) === 'migration' ? migrationDirection(payload) : '',
|
|
741
|
+
};
|
|
742
|
+
}
|
|
743
|
+
/** 指定した版の適用状態を台帳から取得する。 */
|
|
744
|
+
async function listMigrationStates(ids) {
|
|
745
|
+
if (ids.length === 0) {
|
|
746
|
+
return [];
|
|
747
|
+
}
|
|
748
|
+
const db = (0, firestore_1.getFirestore)();
|
|
749
|
+
const refs = ids.map((id) => {
|
|
750
|
+
(0, catalog_1.assertMigrationId)(id);
|
|
751
|
+
return db.collection(exports.MIGRATIONS_COLLECTION).doc(id);
|
|
752
|
+
});
|
|
753
|
+
const snaps = await db.getAll(...refs);
|
|
754
|
+
return snaps.map((snap) => {
|
|
755
|
+
var _a;
|
|
756
|
+
const status = (_a = snap.data()) === null || _a === void 0 ? void 0 : _a.status;
|
|
757
|
+
return {
|
|
758
|
+
id: snap.id,
|
|
759
|
+
status: status === 'running' || status === 'succeeded' ? status : 'absent',
|
|
760
|
+
};
|
|
761
|
+
});
|
|
762
|
+
}
|
|
763
|
+
/** 実行種別とタスクまたはマイグレーションの ID から対象を表すキーを作る。 */
|
|
764
|
+
function subjectName(summary, tasks, migrations) {
|
|
765
|
+
var _a, _b;
|
|
766
|
+
const list = summary.kind === 'migration' ? migrations : tasks;
|
|
767
|
+
return (_b = (_a = list.find((item) => item.id === summary.subjectId)) === null || _a === void 0 ? void 0 : _a.name) !== null && _b !== void 0 ? _b : summary.subjectId;
|
|
768
|
+
}
|
|
769
|
+
/** 文字列や Firestore のタイムスタンプを扱い、表示用の日時文字列を返す。 */
|
|
770
|
+
function isoTime(value) {
|
|
771
|
+
if (typeof value === 'string') {
|
|
772
|
+
return value;
|
|
773
|
+
}
|
|
774
|
+
if (value instanceof Date) {
|
|
775
|
+
return value.toISOString();
|
|
776
|
+
}
|
|
777
|
+
if (typeof value === 'object' && value !== null && 'toDate' in value) {
|
|
778
|
+
const toDate = value.toDate;
|
|
779
|
+
if (typeof toDate === 'function') {
|
|
780
|
+
const date = toDate.call(value);
|
|
781
|
+
if (date instanceof Date && !Number.isNaN(date.getTime())) {
|
|
782
|
+
return date.toISOString();
|
|
783
|
+
}
|
|
784
|
+
}
|
|
785
|
+
}
|
|
786
|
+
return '';
|
|
787
|
+
}
|
|
788
|
+
//# sourceMappingURL=task-execution.js.map
|