@webiny/data-migration 5.39.0-beta.1 → 5.39.0-beta.2
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/MigrationRunner.js +10 -14
- package/MigrationRunner.js.map +1 -1
- package/cli/CliMigrationRunReporter.js +3 -8
- package/cli/CliMigrationRunReporter.js.map +1 -1
- package/cli/InteractiveCliStatusReporter.js +2 -4
- package/cli/InteractiveCliStatusReporter.js.map +1 -1
- package/cli/LogReporter.js +1 -5
- package/cli/LogReporter.js.map +1 -1
- package/cli/LogStream.js +3 -9
- package/cli/LogStream.js.map +1 -1
- package/cli/MigrationRunner.d.ts +1 -1
- package/cli/MigrationRunner.js +24 -23
- package/cli/MigrationRunner.js.map +1 -1
- package/cli/NonInteractiveCliStatusReporter.js +2 -5
- package/cli/NonInteractiveCliStatusReporter.js.map +1 -1
- package/createTable.d.ts +4 -4
- package/createTable.js +6 -3
- package/createTable.js.map +1 -1
- package/handlers/createDdbEsProjectMigration.d.ts +3 -3
- package/handlers/createDdbEsProjectMigration.js +12 -16
- package/handlers/createDdbEsProjectMigration.js.map +1 -1
- package/handlers/createDdbProjectMigration.d.ts +2 -2
- package/handlers/createDdbProjectMigration.js +10 -14
- package/handlers/createDdbProjectMigration.js.map +1 -1
- package/package.json +11 -11
- package/repository/createStandardEntity.d.ts +49 -3
- package/repository/createStandardEntity.js +2 -2
- package/repository/createStandardEntity.js.map +1 -1
- package/repository/migrations.repository.d.ts +2 -2
- package/repository/migrations.repository.js +46 -35
- package/repository/migrations.repository.js.map +1 -1
package/MigrationRunner.js
CHANGED
|
@@ -1,12 +1,9 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
|
|
3
|
-
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
|
|
4
3
|
Object.defineProperty(exports, "__esModule", {
|
|
5
4
|
value: true
|
|
6
5
|
});
|
|
7
6
|
exports.MigrationRunner = void 0;
|
|
8
|
-
var _objectSpread2 = _interopRequireDefault(require("@babel/runtime/helpers/objectSpread2"));
|
|
9
|
-
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
|
|
10
7
|
var _semver = require("semver");
|
|
11
8
|
var _ioc = require("@webiny/ioc");
|
|
12
9
|
var _utils = require("@webiny/utils");
|
|
@@ -28,12 +25,8 @@ const shouldForceExecute = mig => {
|
|
|
28
25
|
class MigrationNotFinished extends Error {}
|
|
29
26
|
class MigrationInProgress extends Error {}
|
|
30
27
|
class MigrationRunner {
|
|
28
|
+
context = {};
|
|
31
29
|
constructor(repository, timeLimiter, migrations, logger) {
|
|
32
|
-
(0, _defineProperty2.default)(this, "logger", void 0);
|
|
33
|
-
(0, _defineProperty2.default)(this, "migrations", void 0);
|
|
34
|
-
(0, _defineProperty2.default)(this, "repository", void 0);
|
|
35
|
-
(0, _defineProperty2.default)(this, "timeLimiter", void 0);
|
|
36
|
-
(0, _defineProperty2.default)(this, "context", {});
|
|
37
30
|
this.repository = repository;
|
|
38
31
|
this.timeLimiter = timeLimiter;
|
|
39
32
|
this.migrations = migrations || [];
|
|
@@ -205,13 +198,15 @@ class MigrationRunner {
|
|
|
205
198
|
// Since we don't store migration descriptions to DB, we need to fetch them from actual migration objects.
|
|
206
199
|
const withDescriptions = lastRun.migrations.map(mig => {
|
|
207
200
|
const dataMigration = this.migrations.find(dm => dm.getId() === mig.id);
|
|
208
|
-
return
|
|
201
|
+
return {
|
|
202
|
+
...mig,
|
|
209
203
|
description: dataMigration ? dataMigration.getDescription() : "N/A"
|
|
210
|
-
}
|
|
204
|
+
};
|
|
211
205
|
});
|
|
212
|
-
return
|
|
206
|
+
return {
|
|
207
|
+
...lastRun,
|
|
213
208
|
migrations: withDescriptions
|
|
214
|
-
}
|
|
209
|
+
};
|
|
215
210
|
}
|
|
216
211
|
validateIds(migrations) {
|
|
217
212
|
const ids = new Set();
|
|
@@ -258,9 +253,10 @@ class MigrationRunner {
|
|
|
258
253
|
getOrCreateRunItem(run, migration) {
|
|
259
254
|
const existingItem = run.migrations.find(item => item.id === migration.getId());
|
|
260
255
|
if (existingItem) {
|
|
261
|
-
return
|
|
256
|
+
return {
|
|
257
|
+
...existingItem,
|
|
262
258
|
status: "running"
|
|
263
|
-
}
|
|
259
|
+
};
|
|
264
260
|
}
|
|
265
261
|
return {
|
|
266
262
|
id: migration.getId(),
|
package/MigrationRunner.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"names":["_semver","require","_ioc","_utils","_symbols","_createPinoLogger","getCurrentISOTime","Date","toISOString","getRunItemDuration","runItem","startedOn","finishedOn","getTime","shouldForceExecute","mig","key","getId","replace","process","env","MigrationNotFinished","Error","MigrationInProgress","MigrationRunner","constructor","repository","timeLimiter","migrations","logger","_defineProperty2","default","createPinoLogger","setContext","context","execute","projectVersion","isApplicable","lastRun","getOrCreateRun","validateIds","err","status","error","message","saveRun","latestMigration","listMigrations","limit","info","currentVersion","coerce","startingId","id","lastId","logMigration","description","reason","defaultIsApplicable","isMigrationApplicable","executableMigrations","filter","setRunItem","sort","a","b","length","shouldCreateCheckpoint","migration","getOrCreateRunItem","checkpoint","getCheckpoint","getChildLogger","forceExecute","runningOutOfTime","createCheckpoint","data","createCheckpointAndExit","shouldExecute","setRunItemAndSave","getDescription","name","stack","code","deleteCheckpoint","getStatus","getLastRun","withDescriptions","map","dataMigration","find","dm","_objectSpread2","ids","Set","endsWith","has","add","executeWithRetry","resolvedStatus","unresolvedStatus","includes","mdbid","run","existingItem","item","index","findIndex","push","slice","exports","makeInjectable","inject","MigrationRepositorySymbol","ExecutionTimeLimiterSymbol","MigrationSymbol","multi","optional","LoggerSymbol"],"sources":["MigrationRunner.ts"],"sourcesContent":["import { coerce } from \"semver\";\nimport { Logger } from \"@webiny/logger\";\nimport { inject, makeInjectable } from \"@webiny/ioc\";\nimport { executeWithRetry, mdbid } from \"@webiny/utils\";\nimport {\n MigrationRepositorySymbol,\n LoggerSymbol,\n MigrationSymbol,\n ExecutionTimeLimiterSymbol\n} from \"./symbols\";\nimport { createPinoLogger, getChildLogger } from \"./createPinoLogger\";\nimport {\n MigrationRepository,\n DataMigration,\n DataMigrationContext,\n ExecutionTimeLimiter,\n MigrationRun,\n MigrationStatus,\n MigrationRunItem\n} from \"~/types\";\n\nexport type IsMigrationApplicable = (migration: DataMigration) => boolean;\n\nconst getCurrentISOTime = () => {\n return new Date().toISOString();\n};\n\nconst getRunItemDuration = (runItem: MigrationRunItem) => {\n if (!runItem.startedOn || !runItem.finishedOn) {\n return \"N/A\";\n }\n\n return new Date(runItem.finishedOn).getTime() - new Date(runItem.startedOn).getTime();\n};\n\nconst shouldForceExecute = (mig: DataMigration) => {\n const key = `WEBINY_MIGRATION_FORCE_EXECUTE_${mig.getId().replace(/[\\.\\-]/g, \"_\")}`;\n\n return process.env[key] === \"true\";\n};\n\nclass MigrationNotFinished extends Error {}\nclass MigrationInProgress extends Error {}\n\nexport class MigrationRunner {\n private readonly logger: Logger;\n private readonly migrations: DataMigration[];\n private readonly repository: MigrationRepository;\n private readonly timeLimiter: ExecutionTimeLimiter;\n private context: Record<string, any> = {};\n\n constructor(\n repository: MigrationRepository,\n timeLimiter: ExecutionTimeLimiter,\n migrations: DataMigration[],\n logger: Logger | undefined\n ) {\n this.repository = repository;\n this.timeLimiter = timeLimiter;\n this.migrations = migrations || [];\n\n if (!logger) {\n logger = createPinoLogger();\n }\n this.logger = logger;\n }\n\n setContext(context: Record<string, any>) {\n this.context = context;\n }\n\n async execute(projectVersion: string, isApplicable?: IsMigrationApplicable) {\n const lastRun = await this.getOrCreateRun();\n\n try {\n this.validateIds(this.migrations);\n } catch (err) {\n lastRun.status = \"error\";\n lastRun.error = {\n message: err.message\n };\n await this.repository.saveRun(lastRun);\n return;\n }\n\n const [latestMigration] = await this.repository.listMigrations({ limit: 1 });\n\n this.logger.info(`Project version is %s.`, projectVersion);\n\n // Get current version, and coerce it to a valid SemVer.\n // With this, we can run migrations targeted for stable versions, released under a preid tag (e.g., `beta`).\n const currentVersion = coerce(projectVersion) + \"\";\n const startingId = latestMigration ? latestMigration.id : `${currentVersion}-000`;\n const lastId = `${currentVersion}-999`;\n\n // Create initial migration record.\n if (!latestMigration) {\n this.logger.info(\n `No migrations were ever executed. Creating initial migration record %s.`,\n startingId\n );\n await this.repository.logMigration({\n id: startingId,\n description: \"starting point for applicable migrations detection\",\n startedOn: getCurrentISOTime(),\n finishedOn: getCurrentISOTime(),\n reason: \"initial migration\"\n });\n } else {\n this.logger.info(`Latest migration ID is %s.`, latestMigration.id);\n }\n\n if (isApplicable) {\n this.logger.info(`Using custom \"isApplicable\" function.`);\n } else {\n this.logger.info(`Using migrations in the range of %s to %s.`, startingId, lastId);\n }\n\n const defaultIsApplicable: IsMigrationApplicable = mig => {\n return mig.getId() > startingId && mig.getId() <= lastId;\n };\n\n const isMigrationApplicable = isApplicable || defaultIsApplicable;\n\n const executableMigrations = this.migrations\n .filter(mig => {\n if (shouldForceExecute(mig)) {\n return true;\n }\n\n if (!isMigrationApplicable(mig)) {\n this.setRunItem(lastRun, {\n id: mig.getId(),\n status: \"not-applicable\"\n });\n\n return false;\n }\n return true;\n })\n .sort((a, b) => (a.getId() > b.getId() ? 1 : -1));\n\n this.logger.info(\n `Found %s applicable out of %s available migration(s).`,\n executableMigrations.length,\n this.migrations.length\n );\n\n // Are we're within the last 2 minutes of the execution time limit?\n const shouldCreateCheckpoint = () => {\n return this.timeLimiter() < 120000;\n };\n\n //\n for (const migration of executableMigrations) {\n const runItem = this.getOrCreateRunItem(lastRun, migration);\n const checkpoint = await this.repository.getCheckpoint(migration.getId());\n const logger = getChildLogger(this.logger, migration);\n\n if (checkpoint) {\n this.logger.info(checkpoint, `Found checkpoint ${migration.getId()}.`);\n }\n\n const context: DataMigrationContext = {\n projectVersion,\n logger,\n checkpoint,\n forceExecute: shouldForceExecute(migration),\n runningOutOfTime: shouldCreateCheckpoint,\n createCheckpoint: async (data: unknown) => {\n await this.createCheckpoint(migration, data);\n },\n createCheckpointAndExit: async (data: unknown) => {\n await this.createCheckpoint(migration, data);\n // We throw an error to break out of the migration execution completely.\n throw new MigrationNotFinished();\n }\n };\n try {\n const shouldExecute =\n checkpoint || shouldForceExecute(migration)\n ? true\n : await migration.shouldExecute(context);\n\n if (!shouldExecute) {\n this.logger.info(`Skipping migration %s.`, migration.getId());\n runItem.status = \"skipped\";\n\n await this.setRunItemAndSave(lastRun, runItem);\n\n await this.repository.logMigration({\n id: migration.getId(),\n description: migration.getDescription(),\n reason: \"skipped\"\n });\n\n continue;\n }\n\n lastRun.status = \"running\";\n runItem.status = \"running\";\n if (!runItem.startedOn) {\n runItem.startedOn = getCurrentISOTime();\n }\n await this.setRunItemAndSave(lastRun, runItem);\n this.logger.info(\n `Executing migration %s: %s`,\n migration.getId(),\n migration.getDescription()\n );\n await migration.execute(context);\n runItem.status = \"done\";\n } catch (err) {\n // If `MigrationNotFinished` was thrown, we will need to resume the migration.\n if (err instanceof MigrationNotFinished) {\n lastRun.status = \"pending\";\n runItem.status = \"pending\";\n return;\n }\n\n runItem.status = \"error\";\n lastRun.status = \"error\";\n lastRun.error = {\n name: err.name || \"Migration error\",\n message: err.message,\n stack: err.stack,\n data: err.data,\n code: err.code\n };\n this.logger.error(err, err.message);\n return;\n } finally {\n // We sum duration from the previous run with the current run.\n runItem.finishedOn = getCurrentISOTime();\n\n // Update run stats.\n await this.setRunItemAndSave(lastRun, runItem);\n\n this.logger.info(\n `Finished executing migration %s in %sms.`,\n migration.getId(),\n getRunItemDuration(runItem)\n );\n }\n\n await this.repository.logMigration({\n id: migration.getId(),\n description: migration.getDescription(),\n startedOn: runItem.startedOn,\n finishedOn: runItem.finishedOn,\n reason: \"executed\"\n });\n\n this.logger.info(`Deleting checkpoint ${migration.getId()}.`);\n await this.repository.deleteCheckpoint(migration.getId());\n }\n\n lastRun.status = \"done\";\n lastRun.finishedOn = getCurrentISOTime();\n await this.repository.saveRun(lastRun);\n\n this.logger.info(`Finished processing applicable migrations.`);\n }\n\n async getStatus(): Promise<MigrationStatus> {\n const lastRun = await this.repository.getLastRun();\n if (!lastRun) {\n throw new Error(`No migrations were ever executed!`);\n }\n\n // Since we don't store migration descriptions to DB, we need to fetch them from actual migration objects.\n const withDescriptions = lastRun.migrations.map(mig => {\n const dataMigration = this.migrations.find(dm => dm.getId() === mig.id);\n return {\n ...mig,\n description: dataMigration ? dataMigration.getDescription() : \"N/A\"\n };\n });\n\n return { ...lastRun, migrations: withDescriptions };\n }\n\n private validateIds(migrations: DataMigration[]) {\n const ids = new Set();\n for (const mig of migrations) {\n const id = mig.getId();\n if (id.endsWith(\"-000\")) {\n const error = new Error(`Migration ID must not end with \"000\": ${id}`);\n this.logger.error(error);\n throw error;\n }\n\n if (ids.has(id)) {\n const error = new Error(`Duplicate migration ID found: ${id}`);\n this.logger.error(error);\n throw error;\n }\n ids.add(id);\n }\n }\n\n private async createCheckpoint(migration: DataMigration, checkpoint: unknown) {\n this.logger.info(checkpoint, `Saving checkpoint ${migration.getId()}`);\n const execute = () => this.repository.createCheckpoint(migration.getId(), checkpoint);\n await executeWithRetry(execute);\n }\n\n private async getOrCreateRun() {\n const resolvedStatus: Array<MigrationRun[\"status\"]> = [\"done\", \"error\"];\n const unresolvedStatus: Array<MigrationRun[\"status\"]> = [\"init\", \"running\"];\n\n let lastRun = await this.repository.getLastRun();\n\n if (lastRun && unresolvedStatus.includes(lastRun.status)) {\n throw new MigrationInProgress(`Migration is already in progress (ID: ${lastRun.id})!`);\n }\n\n if (!lastRun || resolvedStatus.includes(lastRun.status)) {\n lastRun = {\n id: mdbid(),\n status: \"init\",\n startedOn: getCurrentISOTime(),\n finishedOn: \"\",\n migrations: [],\n context: this.context\n };\n\n await this.repository.saveRun(lastRun);\n }\n\n return lastRun;\n }\n\n private getOrCreateRunItem(run: MigrationRun, migration: DataMigration): MigrationRunItem {\n const existingItem = run.migrations.find(item => item.id === migration.getId());\n if (existingItem) {\n return {\n ...existingItem,\n status: \"running\"\n };\n }\n\n return {\n id: migration.getId(),\n status: \"running\"\n };\n }\n\n private setRunItem(run: MigrationRun, item: MigrationRunItem) {\n const index = run.migrations.findIndex(runItem => runItem.id === item.id);\n if (index < 0) {\n run.migrations.push(item);\n } else {\n run.migrations = [\n ...run.migrations.slice(0, index),\n item,\n ...run.migrations.slice(index + 1)\n ];\n }\n\n run.migrations = run.migrations.sort((a, b) => (a.id > b.id ? 1 : -1));\n }\n\n private async setRunItemAndSave(run: MigrationRun, item: MigrationRunItem) {\n this.setRunItem(run, item);\n await this.repository.saveRun(run);\n }\n}\n\nmakeInjectable(MigrationRunner, [\n inject(MigrationRepositorySymbol),\n inject(ExecutionTimeLimiterSymbol),\n inject(MigrationSymbol, { multi: true, optional: true }),\n inject(LoggerSymbol, { optional: true })\n]);\n"],"mappings":";;;;;;;;;AAAA,IAAAA,OAAA,GAAAC,OAAA;AAEA,IAAAC,IAAA,GAAAD,OAAA;AACA,IAAAE,MAAA,GAAAF,OAAA;AACA,IAAAG,QAAA,GAAAH,OAAA;AAMA,IAAAI,iBAAA,GAAAJ,OAAA;AAaA,MAAMK,iBAAiB,GAAGA,CAAA,KAAM;EAC5B,OAAO,IAAIC,IAAI,CAAC,CAAC,CAACC,WAAW,CAAC,CAAC;AACnC,CAAC;AAED,MAAMC,kBAAkB,GAAIC,OAAyB,IAAK;EACtD,IAAI,CAACA,OAAO,CAACC,SAAS,IAAI,CAACD,OAAO,CAACE,UAAU,EAAE;IAC3C,OAAO,KAAK;EAChB;EAEA,OAAO,IAAIL,IAAI,CAACG,OAAO,CAACE,UAAU,CAAC,CAACC,OAAO,CAAC,CAAC,GAAG,IAAIN,IAAI,CAACG,OAAO,CAACC,SAAS,CAAC,CAACE,OAAO,CAAC,CAAC;AACzF,CAAC;AAED,MAAMC,kBAAkB,GAAIC,GAAkB,IAAK;EAC/C,MAAMC,GAAG,GAAI,kCAAiCD,GAAG,CAACE,KAAK,CAAC,CAAC,CAACC,OAAO,CAAC,SAAS,EAAE,GAAG,CAAE,EAAC;EAEnF,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_ioc","_utils","_symbols","_createPinoLogger","getCurrentISOTime","Date","toISOString","getRunItemDuration","runItem","startedOn","finishedOn","getTime","shouldForceExecute","mig","key","getId","replace","process","env","MigrationNotFinished","Error","MigrationInProgress","MigrationRunner","context","constructor","repository","timeLimiter","migrations","logger","createPinoLogger","setContext","execute","projectVersion","isApplicable","lastRun","getOrCreateRun","validateIds","err","status","error","message","saveRun","latestMigration","listMigrations","limit","info","currentVersion","coerce","startingId","id","lastId","logMigration","description","reason","defaultIsApplicable","isMigrationApplicable","executableMigrations","filter","setRunItem","sort","a","b","length","shouldCreateCheckpoint","migration","getOrCreateRunItem","checkpoint","getCheckpoint","getChildLogger","forceExecute","runningOutOfTime","createCheckpoint","data","createCheckpointAndExit","shouldExecute","setRunItemAndSave","getDescription","name","stack","code","deleteCheckpoint","getStatus","getLastRun","withDescriptions","map","dataMigration","find","dm","ids","Set","endsWith","has","add","executeWithRetry","resolvedStatus","unresolvedStatus","includes","mdbid","run","existingItem","item","index","findIndex","push","slice","exports","makeInjectable","inject","MigrationRepositorySymbol","ExecutionTimeLimiterSymbol","MigrationSymbol","multi","optional","LoggerSymbol"],"sources":["MigrationRunner.ts"],"sourcesContent":["import { coerce } from \"semver\";\nimport { Logger } from \"@webiny/logger\";\nimport { inject, makeInjectable } from \"@webiny/ioc\";\nimport { executeWithRetry, mdbid } from \"@webiny/utils\";\nimport {\n MigrationRepositorySymbol,\n LoggerSymbol,\n MigrationSymbol,\n ExecutionTimeLimiterSymbol\n} from \"./symbols\";\nimport { createPinoLogger, getChildLogger } from \"./createPinoLogger\";\nimport {\n MigrationRepository,\n DataMigration,\n DataMigrationContext,\n ExecutionTimeLimiter,\n MigrationRun,\n MigrationStatus,\n MigrationRunItem\n} from \"~/types\";\n\nexport type IsMigrationApplicable = (migration: DataMigration) => boolean;\n\nconst getCurrentISOTime = () => {\n return new Date().toISOString();\n};\n\nconst getRunItemDuration = (runItem: MigrationRunItem) => {\n if (!runItem.startedOn || !runItem.finishedOn) {\n return \"N/A\";\n }\n\n return new Date(runItem.finishedOn).getTime() - new Date(runItem.startedOn).getTime();\n};\n\nconst shouldForceExecute = (mig: DataMigration) => {\n const key = `WEBINY_MIGRATION_FORCE_EXECUTE_${mig.getId().replace(/[\\.\\-]/g, \"_\")}`;\n\n return process.env[key] === \"true\";\n};\n\nclass MigrationNotFinished extends Error {}\nclass MigrationInProgress extends Error {}\n\nexport class MigrationRunner {\n private readonly logger: Logger;\n private readonly migrations: DataMigration[];\n private readonly repository: MigrationRepository;\n private readonly timeLimiter: ExecutionTimeLimiter;\n private context: Record<string, any> = {};\n\n constructor(\n repository: MigrationRepository,\n timeLimiter: ExecutionTimeLimiter,\n migrations: DataMigration[],\n logger: Logger | undefined\n ) {\n this.repository = repository;\n this.timeLimiter = timeLimiter;\n this.migrations = migrations || [];\n\n if (!logger) {\n logger = createPinoLogger();\n }\n this.logger = logger;\n }\n\n setContext(context: Record<string, any>) {\n this.context = context;\n }\n\n async execute(projectVersion: string, isApplicable?: IsMigrationApplicable) {\n const lastRun = await this.getOrCreateRun();\n\n try {\n this.validateIds(this.migrations);\n } catch (err) {\n lastRun.status = \"error\";\n lastRun.error = {\n message: err.message\n };\n await this.repository.saveRun(lastRun);\n return;\n }\n\n const [latestMigration] = await this.repository.listMigrations({ limit: 1 });\n\n this.logger.info(`Project version is %s.`, projectVersion);\n\n // Get current version, and coerce it to a valid SemVer.\n // With this, we can run migrations targeted for stable versions, released under a preid tag (e.g., `beta`).\n const currentVersion = coerce(projectVersion) + \"\";\n const startingId = latestMigration ? latestMigration.id : `${currentVersion}-000`;\n const lastId = `${currentVersion}-999`;\n\n // Create initial migration record.\n if (!latestMigration) {\n this.logger.info(\n `No migrations were ever executed. Creating initial migration record %s.`,\n startingId\n );\n await this.repository.logMigration({\n id: startingId,\n description: \"starting point for applicable migrations detection\",\n startedOn: getCurrentISOTime(),\n finishedOn: getCurrentISOTime(),\n reason: \"initial migration\"\n });\n } else {\n this.logger.info(`Latest migration ID is %s.`, latestMigration.id);\n }\n\n if (isApplicable) {\n this.logger.info(`Using custom \"isApplicable\" function.`);\n } else {\n this.logger.info(`Using migrations in the range of %s to %s.`, startingId, lastId);\n }\n\n const defaultIsApplicable: IsMigrationApplicable = mig => {\n return mig.getId() > startingId && mig.getId() <= lastId;\n };\n\n const isMigrationApplicable = isApplicable || defaultIsApplicable;\n\n const executableMigrations = this.migrations\n .filter(mig => {\n if (shouldForceExecute(mig)) {\n return true;\n }\n\n if (!isMigrationApplicable(mig)) {\n this.setRunItem(lastRun, {\n id: mig.getId(),\n status: \"not-applicable\"\n });\n\n return false;\n }\n return true;\n })\n .sort((a, b) => (a.getId() > b.getId() ? 1 : -1));\n\n this.logger.info(\n `Found %s applicable out of %s available migration(s).`,\n executableMigrations.length,\n this.migrations.length\n );\n\n // Are we're within the last 2 minutes of the execution time limit?\n const shouldCreateCheckpoint = () => {\n return this.timeLimiter() < 120000;\n };\n\n //\n for (const migration of executableMigrations) {\n const runItem = this.getOrCreateRunItem(lastRun, migration);\n const checkpoint = await this.repository.getCheckpoint(migration.getId());\n const logger = getChildLogger(this.logger, migration);\n\n if (checkpoint) {\n this.logger.info(checkpoint, `Found checkpoint ${migration.getId()}.`);\n }\n\n const context: DataMigrationContext = {\n projectVersion,\n logger,\n checkpoint,\n forceExecute: shouldForceExecute(migration),\n runningOutOfTime: shouldCreateCheckpoint,\n createCheckpoint: async (data: unknown) => {\n await this.createCheckpoint(migration, data);\n },\n createCheckpointAndExit: async (data: unknown) => {\n await this.createCheckpoint(migration, data);\n // We throw an error to break out of the migration execution completely.\n throw new MigrationNotFinished();\n }\n };\n try {\n const shouldExecute =\n checkpoint || shouldForceExecute(migration)\n ? true\n : await migration.shouldExecute(context);\n\n if (!shouldExecute) {\n this.logger.info(`Skipping migration %s.`, migration.getId());\n runItem.status = \"skipped\";\n\n await this.setRunItemAndSave(lastRun, runItem);\n\n await this.repository.logMigration({\n id: migration.getId(),\n description: migration.getDescription(),\n reason: \"skipped\"\n });\n\n continue;\n }\n\n lastRun.status = \"running\";\n runItem.status = \"running\";\n if (!runItem.startedOn) {\n runItem.startedOn = getCurrentISOTime();\n }\n await this.setRunItemAndSave(lastRun, runItem);\n this.logger.info(\n `Executing migration %s: %s`,\n migration.getId(),\n migration.getDescription()\n );\n await migration.execute(context);\n runItem.status = \"done\";\n } catch (err) {\n // If `MigrationNotFinished` was thrown, we will need to resume the migration.\n if (err instanceof MigrationNotFinished) {\n lastRun.status = \"pending\";\n runItem.status = \"pending\";\n return;\n }\n\n runItem.status = \"error\";\n lastRun.status = \"error\";\n lastRun.error = {\n name: err.name || \"Migration error\",\n message: err.message,\n stack: err.stack,\n data: err.data,\n code: err.code\n };\n this.logger.error(err, err.message);\n return;\n } finally {\n // We sum duration from the previous run with the current run.\n runItem.finishedOn = getCurrentISOTime();\n\n // Update run stats.\n await this.setRunItemAndSave(lastRun, runItem);\n\n this.logger.info(\n `Finished executing migration %s in %sms.`,\n migration.getId(),\n getRunItemDuration(runItem)\n );\n }\n\n await this.repository.logMigration({\n id: migration.getId(),\n description: migration.getDescription(),\n startedOn: runItem.startedOn,\n finishedOn: runItem.finishedOn,\n reason: \"executed\"\n });\n\n this.logger.info(`Deleting checkpoint ${migration.getId()}.`);\n await this.repository.deleteCheckpoint(migration.getId());\n }\n\n lastRun.status = \"done\";\n lastRun.finishedOn = getCurrentISOTime();\n await this.repository.saveRun(lastRun);\n\n this.logger.info(`Finished processing applicable migrations.`);\n }\n\n async getStatus(): Promise<MigrationStatus> {\n const lastRun = await this.repository.getLastRun();\n if (!lastRun) {\n throw new Error(`No migrations were ever executed!`);\n }\n\n // Since we don't store migration descriptions to DB, we need to fetch them from actual migration objects.\n const withDescriptions = lastRun.migrations.map(mig => {\n const dataMigration = this.migrations.find(dm => dm.getId() === mig.id);\n return {\n ...mig,\n description: dataMigration ? dataMigration.getDescription() : \"N/A\"\n };\n });\n\n return { ...lastRun, migrations: withDescriptions };\n }\n\n private validateIds(migrations: DataMigration[]) {\n const ids = new Set();\n for (const mig of migrations) {\n const id = mig.getId();\n if (id.endsWith(\"-000\")) {\n const error = new Error(`Migration ID must not end with \"000\": ${id}`);\n this.logger.error(error);\n throw error;\n }\n\n if (ids.has(id)) {\n const error = new Error(`Duplicate migration ID found: ${id}`);\n this.logger.error(error);\n throw error;\n }\n ids.add(id);\n }\n }\n\n private async createCheckpoint(migration: DataMigration, checkpoint: unknown) {\n this.logger.info(checkpoint, `Saving checkpoint ${migration.getId()}`);\n const execute = () => this.repository.createCheckpoint(migration.getId(), checkpoint);\n await executeWithRetry(execute);\n }\n\n private async getOrCreateRun() {\n const resolvedStatus: Array<MigrationRun[\"status\"]> = [\"done\", \"error\"];\n const unresolvedStatus: Array<MigrationRun[\"status\"]> = [\"init\", \"running\"];\n\n let lastRun = await this.repository.getLastRun();\n\n if (lastRun && unresolvedStatus.includes(lastRun.status)) {\n throw new MigrationInProgress(`Migration is already in progress (ID: ${lastRun.id})!`);\n }\n\n if (!lastRun || resolvedStatus.includes(lastRun.status)) {\n lastRun = {\n id: mdbid(),\n status: \"init\",\n startedOn: getCurrentISOTime(),\n finishedOn: \"\",\n migrations: [],\n context: this.context\n };\n\n await this.repository.saveRun(lastRun);\n }\n\n return lastRun;\n }\n\n private getOrCreateRunItem(run: MigrationRun, migration: DataMigration): MigrationRunItem {\n const existingItem = run.migrations.find(item => item.id === migration.getId());\n if (existingItem) {\n return {\n ...existingItem,\n status: \"running\"\n };\n }\n\n return {\n id: migration.getId(),\n status: \"running\"\n };\n }\n\n private setRunItem(run: MigrationRun, item: MigrationRunItem) {\n const index = run.migrations.findIndex(runItem => runItem.id === item.id);\n if (index < 0) {\n run.migrations.push(item);\n } else {\n run.migrations = [\n ...run.migrations.slice(0, index),\n item,\n ...run.migrations.slice(index + 1)\n ];\n }\n\n run.migrations = run.migrations.sort((a, b) => (a.id > b.id ? 1 : -1));\n }\n\n private async setRunItemAndSave(run: MigrationRun, item: MigrationRunItem) {\n this.setRunItem(run, item);\n await this.repository.saveRun(run);\n }\n}\n\nmakeInjectable(MigrationRunner, [\n inject(MigrationRepositorySymbol),\n inject(ExecutionTimeLimiterSymbol),\n inject(MigrationSymbol, { multi: true, optional: true }),\n inject(LoggerSymbol, { optional: true })\n]);\n"],"mappings":";;;;;;AAAA,IAAAA,OAAA,GAAAC,OAAA;AAEA,IAAAC,IAAA,GAAAD,OAAA;AACA,IAAAE,MAAA,GAAAF,OAAA;AACA,IAAAG,QAAA,GAAAH,OAAA;AAMA,IAAAI,iBAAA,GAAAJ,OAAA;AAaA,MAAMK,iBAAiB,GAAGA,CAAA,KAAM;EAC5B,OAAO,IAAIC,IAAI,CAAC,CAAC,CAACC,WAAW,CAAC,CAAC;AACnC,CAAC;AAED,MAAMC,kBAAkB,GAAIC,OAAyB,IAAK;EACtD,IAAI,CAACA,OAAO,CAACC,SAAS,IAAI,CAACD,OAAO,CAACE,UAAU,EAAE;IAC3C,OAAO,KAAK;EAChB;EAEA,OAAO,IAAIL,IAAI,CAACG,OAAO,CAACE,UAAU,CAAC,CAACC,OAAO,CAAC,CAAC,GAAG,IAAIN,IAAI,CAACG,OAAO,CAACC,SAAS,CAAC,CAACE,OAAO,CAAC,CAAC;AACzF,CAAC;AAED,MAAMC,kBAAkB,GAAIC,GAAkB,IAAK;EAC/C,MAAMC,GAAG,GAAI,kCAAiCD,GAAG,CAACE,KAAK,CAAC,CAAC,CAACC,OAAO,CAAC,SAAS,EAAE,GAAG,CAAE,EAAC;EAEnF,OAAOC,OAAO,CAACC,GAAG,CAACJ,GAAG,CAAC,KAAK,MAAM;AACtC,CAAC;AAED,MAAMK,oBAAoB,SAASC,KAAK,CAAC;AACzC,MAAMC,mBAAmB,SAASD,KAAK,CAAC;AAEjC,MAAME,eAAe,CAAC;EAKjBC,OAAO,GAAwB,CAAC,CAAC;EAEzCC,WAAWA,CACPC,UAA+B,EAC/BC,WAAiC,EACjCC,UAA2B,EAC3BC,MAA0B,EAC5B;IACE,IAAI,CAACH,UAAU,GAAGA,UAAU;IAC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E,CAAC;EAC1E;EAEA,MAAc0B,iBAAiBA,CAACuB,GAAiB,EAAEE,IAAsB,EAAE;IACvE,IAAI,CAAC1C,UAAU,CAACwC,GAAG,EAAEE,IAAI,CAAC;IAC1B,MAAM,IAAI,CAAC3E,UAAU,CAACgB,OAAO,CAACyD,GAAG,CAAC;EACtC;AACJ;AAACO,OAAA,CAAAnF,eAAA,GAAAA,eAAA;AAED,IAAAoF,mBAAc,EAACpF,eAAe,EAAE,CAC5B,IAAAqF,WAAM,EAACC,kCAAyB,CAAC,EACjC,IAAAD,WAAM,EAACE,mCAA0B,CAAC,EAClC,IAAAF,WAAM,EAACG,wBAAe,EAAE;EAAEC,KAAK,EAAE,IAAI;EAAEC,QAAQ,EAAE;AAAK,CAAC,CAAC,EACxD,IAAAL,WAAM,EAACM,qBAAY,EAAE;EAAED,QAAQ,EAAE;AAAK,CAAC,CAAC,CAC3C,CAAC"}
|
|
@@ -5,14 +5,9 @@ Object.defineProperty(exports, "__esModule", {
|
|
|
5
5
|
value: true
|
|
6
6
|
});
|
|
7
7
|
exports.CliMigrationRunReporter = void 0;
|
|
8
|
-
var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties"));
|
|
9
|
-
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
|
|
10
8
|
var _centerAlign = _interopRequireDefault(require("center-align"));
|
|
11
|
-
const _excluded = ["migrations"];
|
|
12
9
|
class CliMigrationRunReporter {
|
|
13
10
|
constructor(logReporter, context) {
|
|
14
|
-
(0, _defineProperty2.default)(this, "context", void 0);
|
|
15
|
-
(0, _defineProperty2.default)(this, "logReporter", void 0);
|
|
16
11
|
this.logReporter = logReporter;
|
|
17
12
|
this.context = context;
|
|
18
13
|
}
|
|
@@ -22,9 +17,9 @@ class CliMigrationRunReporter {
|
|
|
22
17
|
process.stdout.write("\n");
|
|
23
18
|
this.context.success(`Data migration Lambda %s executed successfully!`, functionName);
|
|
24
19
|
const {
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
20
|
+
migrations,
|
|
21
|
+
...run
|
|
22
|
+
} = data;
|
|
28
23
|
if (!migrations.length) {
|
|
29
24
|
this.context.info(`No applicable migrations were found!`);
|
|
30
25
|
return;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"names":["_centerAlign","_interopRequireDefault","require","
|
|
1
|
+
{"version":3,"names":["_centerAlign","_interopRequireDefault","require","CliMigrationRunReporter","constructor","logReporter","context","report","result","onSuccess","data","functionName","getFunctionName","split","pop","process","stdout","write","success","migrations","run","length","info","maxLength","Math","max","map","mig","status","id","startedOn","finishedOn","migration","description","center","makeEven","printLogStreamLinks","onError","error","message","str","exports"],"sources":["CliMigrationRunReporter.ts"],"sourcesContent":["import { MigrationRunnerResult, MigrationRunReporter } from \"~/cli\";\nimport center from \"center-align\";\nimport { CliContext } from \"@webiny/cli/types\";\nimport { LogReporter } from \"~/cli\";\n\nexport class CliMigrationRunReporter implements MigrationRunReporter {\n private context: CliContext;\n private logReporter: LogReporter;\n\n constructor(logReporter: LogReporter, context: CliContext) {\n this.logReporter = logReporter;\n this.context = context;\n }\n\n report(result: MigrationRunnerResult): Promise<void> {\n result.onSuccess(data => {\n const functionName = result.getFunctionName().split(\":\").pop();\n process.stdout.write(\"\\n\");\n this.context.success(`Data migration Lambda %s executed successfully!`, functionName);\n\n const { migrations, ...run } = data;\n if (!migrations.length) {\n this.context.info(`No applicable migrations were found!`);\n return;\n }\n\n const maxLength = Math.max(...migrations.map(mig => mig.status.length)) + 2;\n this.context.info(`Migration run: %s`, run.id);\n this.context.info(`Status: %s`, run.status);\n this.context.info(`Started on: %s`, run.startedOn);\n if (run.status === \"done\") {\n this.context.info(`Finished on: %s`, run.finishedOn);\n }\n for (const migration of migrations) {\n this.context.info(\n ...[\n `[%s] %s: ${migration.description}`,\n center(this.makeEven(migration.status), maxLength),\n migration.id\n ]\n );\n }\n\n this.logReporter.printLogStreamLinks();\n });\n\n result.onError(error => {\n this.context.error(error.message);\n });\n\n // Process the result!\n return result.process();\n }\n\n private makeEven(str: string) {\n if (str.length % 2 > 0) {\n return str + \" \";\n }\n return str;\n }\n}\n"],"mappings":";;;;;;;AACA,IAAAA,YAAA,GAAAC,sBAAA,CAAAC,OAAA;AAIO,MAAMC,uBAAuB,CAAiC;EAIjEC,WAAWA,CAACC,WAAwB,EAAEC,OAAmB,EAAE;IACvD,IAAI,CAACD,WAAW,GAAGA,WAAW;IAC9B,IAAI,CAACC,OAAO,GAAGA,OAAO;EAC1B;EAEAC,MAAMA,CAACC,MAA6B,EAAiB;IACjDA,MAAM,CAACC,SAAS,CAACC,IAAI,IAAI;MACrB,MAAMC,YAAY,GAAGH,MAAM,CAACI,eAAe,CAAC,CAAC,CAACC,KAAK,CAAC,GAAG,CAAC,CAACC,GAAG,CAAC,CAAC;MAC9DC,OAAO,CAACC,MAAM,CAACC,KAAK,CAAC,IAAI,CAAC;MAC1B,IAAI,CAACX,OAAO,CAACY,OAAO,CAAE,iDAAgD,EAAEP,YAAY,CAAC;MAErF,MAAM;QAAEQ,UAAU;QAAE,GAAGC;MAAI,CAAC,GAAGV,IAAI;MACnC,IAAI,CAACS,UAAU,CAACE,MAAM,EAAE;QACpB,IAAI,CAACf,OAAO,CAACgB,IAAI,CAAE,sCAAqC,CAAC;QACzD;MACJ;MAEA,MAAMC,SAAS,GAAGC,IAAI,CAACC,GAAG,CAAC,GAAGN,UAAU,CAACO,GAAG,CAACC,GAAG,IAAIA,GAAG,CAACC,MAAM,CAACP,MAAM,CAAC,CAAC,GAAG,CAAC;MAC3E,IAAI,CAACf,OAAO,CAACgB,IAAI,CAAE,mBAAkB,EAAEF,GAAG,CAACS,EAAE,CAAC;MAC9C,IAAI,CAACvB,OAAO,CAACgB,IAAI,CAAE,YAAW,EAAEF,GAAG,CAACQ,MAAM,CAAC;MAC3C,IAAI,CAACtB,OAAO,CAACgB,IAAI,CAAE,gBAAe,EAAEF,GAAG,CAACU,SAAS,CAAC;MAClD,IAAIV,GAAG,CAACQ,MAAM,KAAK,MAAM,EAAE;QACvB,IAAI,CAACtB,OAAO,CAACgB,IAAI,CAAE,iBAAgB,EAAEF,GAAG,CAACW,UAAU,CAAC;MACxD;MACA,KAAK,MAAMC,SAAS,IAAIb,UAAU,EAAE;QAChC,IAAI,CAACb,OAAO,CAACgB,IAAI,CACb,GAAG,CACE,YAAWU,SAAS,CAACC,WAAY,EAAC,EACnC,IAAAC,oBAAM,EAAC,IAAI,CAACC,QAAQ,CAACH,SAAS,CAACJ,MAAM,CAAC,EAAEL,SAAS,CAAC,EAClDS,SAAS,CAACH,EAAE,CAEpB,CAAC;MACL;MAEA,IAAI,CAACxB,WAAW,CAAC+B,mBAAmB,CAAC,CAAC;IAC1C,CAAC,CAAC;IAEF5B,MAAM,CAAC6B,OAAO,CAACC,KAAK,IAAI;MACpB,IAAI,CAAChC,OAAO,CAACgC,KAAK,CAACA,KAAK,CAACC,OAAO,CAAC;IACrC,CAAC,CAAC;;IAEF;IACA,OAAO/B,MAAM,CAACO,OAAO,CAAC,CAAC;EAC3B;EAEQoB,QAAQA,CAACK,GAAW,EAAE;IAC1B,IAAIA,GAAG,CAACnB,MAAM,GAAG,CAAC,GAAG,CAAC,EAAE;MACpB,OAAOmB,GAAG,GAAG,GAAG;IACpB;IACA,OAAOA,GAAG;EACd;AACJ;AAACC,OAAA,CAAAtC,uBAAA,GAAAA,uBAAA"}
|
|
@@ -5,12 +5,10 @@ Object.defineProperty(exports, "__esModule", {
|
|
|
5
5
|
value: true
|
|
6
6
|
});
|
|
7
7
|
exports.InteractiveCliStatusReporter = void 0;
|
|
8
|
-
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
|
|
9
8
|
var _readline = _interopRequireDefault(require("readline"));
|
|
10
9
|
class InteractiveCliStatusReporter {
|
|
10
|
+
firstCall = true;
|
|
11
11
|
constructor(logReporter) {
|
|
12
|
-
(0, _defineProperty2.default)(this, "logReporter", void 0);
|
|
13
|
-
(0, _defineProperty2.default)(this, "firstCall", true);
|
|
14
12
|
this.logReporter = logReporter;
|
|
15
13
|
console.log(`Using "InteractiveCliStatusReporter".`);
|
|
16
14
|
}
|
|
@@ -21,7 +19,7 @@ class InteractiveCliStatusReporter {
|
|
|
21
19
|
context
|
|
22
20
|
} = migrationStatus;
|
|
23
21
|
this.clearLine();
|
|
24
|
-
const currentLogStreamName = context
|
|
22
|
+
const currentLogStreamName = context?.logStreamName;
|
|
25
23
|
if (currentLogStreamName) {
|
|
26
24
|
this.logReporter.initializeStream(currentLogStreamName);
|
|
27
25
|
if (this.firstCall) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"names":["_readline","_interopRequireDefault","require","InteractiveCliStatusReporter","
|
|
1
|
+
{"version":3,"names":["_readline","_interopRequireDefault","require","InteractiveCliStatusReporter","firstCall","constructor","logReporter","console","log","report","migrationStatus","status","migrations","context","clearLine","currentLogStreamName","logStreamName","initializeStream","printLogStreamLinks","process","stdout","write","printLogs","currentMigration","find","mig","duration","getDuration","String","startedOn","id","includes","Promise","resolve","setTimeout","readline","cursorTo","since","ms","Date","getTime","seconds","Math","floor","minutes","undefined","exports"],"sources":["InteractiveCliStatusReporter.ts"],"sourcesContent":["import readline from \"readline\";\nimport { MigrationStatusReporter } from \"~/cli/MigrationStatusReporter\";\nimport { MigrationStatus } from \"~/types\";\nimport { LogReporter } from \"~/cli/LogReporter\";\n\nexport class InteractiveCliStatusReporter implements MigrationStatusReporter {\n private logReporter: LogReporter;\n private firstCall = true;\n\n constructor(logReporter: LogReporter) {\n this.logReporter = logReporter;\n console.log(`Using \"InteractiveCliStatusReporter\".`);\n }\n\n async report(migrationStatus: MigrationStatus) {\n const { status, migrations, context } = migrationStatus;\n this.clearLine();\n\n const currentLogStreamName = context?.logStreamName;\n if (currentLogStreamName) {\n this.logReporter.initializeStream(currentLogStreamName);\n if (this.firstCall) {\n this.logReporter.printLogStreamLinks();\n process.stdout.write(`\\n---------- MIGRATION LOGS START ----------\\n\\n`);\n }\n await this.logReporter.printLogs(currentLogStreamName);\n }\n\n if (status === \"running\") {\n const currentMigration = migrations.find(mig => mig.status === \"running\");\n if (currentMigration) {\n const duration = this.getDuration(String(currentMigration.startedOn));\n process.stdout.write(\n `Running data migration ${currentMigration.id} (${duration})...`\n );\n }\n }\n\n if (status === \"init\") {\n process.stdout.write(`Checking data migrations...`);\n }\n\n if ([\"done\", \"error\"].includes(status)) {\n this.clearLine();\n process.stdout.write(`Migration run finished, waiting for latest logs...`);\n\n // We want to give AWS some time for the latest log events to become available.\n await new Promise(resolve => {\n setTimeout(resolve, 8000);\n });\n\n if (currentLogStreamName) {\n this.clearLine();\n await this.logReporter.printLogs(currentLogStreamName);\n process.stdout.write(`\\n---------- MIGRATION LOGS END ----------\\n`);\n }\n }\n\n this.firstCall = false;\n }\n\n private clearLine() {\n readline.clearLine(process.stdout, 0);\n readline.cursorTo(process.stdout, 0);\n }\n\n private getDuration(since: string) {\n const ms = new Date().getTime() - new Date(since).getTime();\n let seconds = Math.floor(ms / 1000);\n let minutes = undefined;\n if (seconds > 60) {\n minutes = Math.floor(seconds / 60);\n seconds = Math.floor(seconds % 60);\n }\n\n return minutes ? `${minutes}m ${seconds}s` : `${seconds}s`;\n }\n}\n"],"mappings":";;;;;;;AAAA,IAAAA,SAAA,GAAAC,sBAAA,CAAAC,OAAA;AAKO,MAAMC,4BAA4B,CAAoC;EAEjEC,SAAS,GAAG,IAAI;EAExBC,WAAWA,CAACC,WAAwB,EAAE;IAClC,IAAI,CAACA,WAAW,GAAGA,WAAW;IAC9BC,OAAO,CAACC,GAAG,CAAE,uCAAsC,CAAC;EACxD;EAEA,MAAMC,MAAMA,CAACC,eAAgC,EAAE;IAC3C,MAAM;MAAEC,MAAM;MAAEC,UAAU;MAAEC;IAAQ,CAAC,GAAGH,eAAe;IACvD,IAAI,CAACI,SAAS,CAAC,CAAC;IAEhB,MAAMC,oBAAoB,GAAGF,OAAO,EAAEG,aAAa;IACnD,IA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E,8CAA6C,CAAC;MACxE;IACJ;IAEA,IAAI,CAACjB,SAAS,GAAG,KAAK;EAC1B;EAEQU,SAASA,CAAA,EAAG;IAChBqB,iBAAQ,CAACrB,SAAS,CAACK,OAAO,CAACC,MAAM,EAAE,CAAC,CAAC;IACrCe,iBAAQ,CAACC,QAAQ,CAACjB,OAAO,CAACC,MAAM,EAAE,CAAC,CAAC;EACxC;EAEQO,WAAWA,CAACU,KAAa,EAAE;IAC/B,MAAMC,EAAE,GAAG,IAAIC,IAAI,CAAC,CAAC,CAACC,OAAO,CAAC,CAAC,GAAG,IAAID,IAAI,CAACF,KAAK,CAAC,CAACG,OAAO,CAAC,CAAC;IAC3D,IAAIC,OAAO,GAAGC,IAAI,CAACC,KAAK,CAACL,EAAE,GAAG,IAAI,CAAC;IACnC,IAAIM,OAAO,GAAGC,SAAS;IACvB,IAAIJ,OAAO,GAAG,EAAE,EAAE;MACdG,OAAO,GAAGF,IAAI,CAACC,KAAK,CAACF,OAAO,GAAG,EAAE,CAAC;MAClCA,OAAO,GAAGC,IAAI,CAACC,KAAK,CAACF,OAAO,GAAG,EAAE,CAAC;IACtC;IAEA,OAAOG,OAAO,GAAI,GAAEA,OAAQ,KAAIH,OAAQ,GAAE,GAAI,GAAEA,OAAQ,GAAE;EAC9D;AACJ;AAACK,OAAA,CAAA3C,4BAAA,GAAAA,4BAAA"}
|
package/cli/LogReporter.js
CHANGED
|
@@ -1,17 +1,13 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
|
|
3
|
-
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
|
|
4
3
|
Object.defineProperty(exports, "__esModule", {
|
|
5
4
|
value: true
|
|
6
5
|
});
|
|
7
6
|
exports.LogReporter = void 0;
|
|
8
|
-
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
|
|
9
7
|
var _LogStream = require("./LogStream");
|
|
10
8
|
class LogReporter {
|
|
9
|
+
logStreams = new Set();
|
|
11
10
|
constructor(functionName) {
|
|
12
|
-
(0, _defineProperty2.default)(this, "logGroupName", void 0);
|
|
13
|
-
(0, _defineProperty2.default)(this, "logsCreatedSince", void 0);
|
|
14
|
-
(0, _defineProperty2.default)(this, "logStreams", new Set());
|
|
15
11
|
const baseName = functionName.split(":").pop();
|
|
16
12
|
this.logGroupName = `/aws/lambda/${baseName}`;
|
|
17
13
|
this.logsCreatedSince = Date.now();
|
package/cli/LogReporter.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"names":["_LogStream","require","LogReporter","
|
|
1
|
+
{"version":3,"names":["_LogStream","require","LogReporter","logStreams","Set","constructor","functionName","baseName","split","pop","logGroupName","logsCreatedSince","Date","now","printLogs","logStreamName","logStream","initializeStream","printLogsSince","printLogStreamLinks","size","Array","from","process","stdout","write","getLogStreamLink","name","LogStream","create","add","exports"],"sources":["LogReporter.ts"],"sourcesContent":["import { LogStream } from \"./LogStream\";\n\nexport class LogReporter {\n private readonly logGroupName: string;\n private readonly logsCreatedSince: number;\n private readonly logStreams = new Set<LogStream>();\n\n constructor(functionName: string) {\n const baseName = functionName.split(\":\").pop();\n this.logGroupName = `/aws/lambda/${baseName}`;\n this.logsCreatedSince = Date.now();\n }\n\n public async printLogs(logStreamName: string) {\n const logStream = this.initializeStream(logStreamName);\n await logStream.printLogsSince(this.logsCreatedSince);\n }\n\n public printLogStreamLinks() {\n if (this.logStreams.size === 0) {\n return;\n }\n\n const logStreams = Array.from(this.logStreams);\n\n if (this.logStreams.size === 1) {\n process.stdout.write(\n `\\nTo view detailed logs, visit the following AWS CloudWatch log stream:\\n`\n );\n process.stdout.write(logStreams[0].getLogStreamLink());\n } else {\n process.stdout.write(\n `\\nTo view detailed logs, visit the following AWS CloudWatch log streams:\\n`\n );\n\n for (const logStream of logStreams) {\n process.stdout.write(`- ${logStream.getLogStreamLink()}`);\n }\n }\n\n process.stdout.write(\"\\n\");\n }\n\n public initializeStream(name: string) {\n const logStream = LogStream.create(this.logG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CAACC,KAAK,CAAC,IAAI,CAAC;EAC9B;EAEOR,gBAAgBA,CAACU,IAAY,EAAE;IAClC,MAAMX,SAAS,GAAGY,oBAAS,CAACC,MAAM,CAAC,IAAI,CAACnB,YAAY,EAAEiB,IAAI,CAAC;IAC3D,IAAI,CAACxB,UAAU,CAAC2B,GAAG,CAACd,SAAS,CAAC;IAC9B,OAAOA,SAAS;EACpB;AACJ;AAACe,OAAA,CAAA7B,WAAA,GAAAA,WAAA"}
|
package/cli/LogStream.js
CHANGED
|
@@ -1,22 +1,16 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
|
|
3
|
-
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
|
|
4
3
|
Object.defineProperty(exports, "__esModule", {
|
|
5
4
|
value: true
|
|
6
5
|
});
|
|
7
6
|
exports.LogStream = void 0;
|
|
8
|
-
var
|
|
9
|
-
var _cloudwatchlogs = _interopRequireDefault(require("aws-sdk/clients/cloudwatchlogs"));
|
|
7
|
+
var _clientCloudwatch = require("@webiny/aws-sdk/client-cloudwatch");
|
|
10
8
|
const cache = new Map();
|
|
11
9
|
class LogStream {
|
|
12
10
|
constructor(logGroupName, logStreamName) {
|
|
13
|
-
(0, _defineProperty2.default)(this, "logGroupName", void 0);
|
|
14
|
-
(0, _defineProperty2.default)(this, "logStreamName", void 0);
|
|
15
|
-
(0, _defineProperty2.default)(this, "cloudWatchLogs", void 0);
|
|
16
|
-
(0, _defineProperty2.default)(this, "nextPage", void 0);
|
|
17
11
|
this.logGroupName = logGroupName;
|
|
18
12
|
this.logStreamName = logStreamName;
|
|
19
|
-
this.cloudWatchLogs = new
|
|
13
|
+
this.cloudWatchLogs = new _clientCloudwatch.CloudWatchLogs();
|
|
20
14
|
}
|
|
21
15
|
getLogStreamLink() {
|
|
22
16
|
const replacements = [[/\$/g, "$2524"], [/\//g, "$252F"], [/\[/g, "$255B"], [/]/g, "$255D"]];
|
|
@@ -38,7 +32,7 @@ class LogStream {
|
|
|
38
32
|
const {
|
|
39
33
|
events,
|
|
40
34
|
nextForwardToken
|
|
41
|
-
} = await this.cloudWatchLogs.getLogEvents(params)
|
|
35
|
+
} = await this.cloudWatchLogs.getLogEvents(params);
|
|
42
36
|
this.nextPage = nextForwardToken;
|
|
43
37
|
if (events) {
|
|
44
38
|
events.forEach(event => {
|
package/cli/LogStream.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"names":["
|
|
1
|
+
{"version":3,"names":["_clientCloudwatch","require","cache","Map","LogStream","constructor","logGroupName","logStreamName","cloudWatchLogs","CloudWatchLogs","getLogStreamLink","replacements","replacer","value","replacement","replace","process","env","AWS_REGION","reduce","join","printLogsSince","startTime","params","nextToken","nextPage","startFromHead","unmask","events","nextForwardToken","getLogEvents","forEach","event","stdout","write","String","message","err","console","log","create","cacheId","has","get","logStream","set","exports"],"sources":["LogStream.ts"],"sourcesContent":["import { CloudWatchLogs, GetLogEventsRequest } from \"@webiny/aws-sdk/client-cloudwatch\";\n\nconst cache = new Map<string, LogStream>();\n\nexport class LogStream {\n private readonly logGroupName: string;\n private readonly logStreamName: string;\n private readonly cloudWatchLogs: CloudWatchLogs;\n private nextPage: string | undefined;\n\n private constructor(logGroupName: string, logStreamName: string) {\n this.logGroupName = logGroupName;\n this.logStreamName = logStreamName;\n this.cloudWatchLogs = new CloudWatchLogs();\n }\n\n getLogStreamLink() {\n const replacements = [\n [/\\$/g, \"$2524\"],\n [/\\//g, \"$252F\"],\n [/\\[/g, \"$255B\"],\n [/]/g, \"$255D\"]\n ];\n\n const replacer = (value: string, replacement: (string | RegExp)[]) => {\n return value.replace(replacement[0], replacement[1] as string);\n };\n\n return [\n `https://${process.env.AWS_REGION}.console.aws.amazon.com/cloudwatch/home?region=${process.env.AWS_REGION}#logsV2:log-groups/log-group/`,\n replacements.reduce(replacer, this.logGroupName),\n \"/log-events/\",\n replacements.reduce(replacer, this.logStreamName)\n ].join(\"\");\n }\n\n async printLogsSince(startTime: number): Promise<void> {\n const params: GetLogEventsRequest = {\n logStreamName: this.logStreamName,\n logGroupName: this.logGroupName,\n nextToken: this.nextPage,\n startFromHead: true,\n startTime,\n unmask: true\n };\n\n try {\n const { events, nextForwardToken } = await this.cloudWatchLogs.getLogEvents(params);\n\n this.nextPage = nextForwardToken;\n\n if (events) {\n events.forEach(event => {\n process.stdout.write(String(event.message));\n });\n }\n } catch (err) {\n console.log(`Couldn't fetch logs: ${err.message}`);\n }\n }\n\n public static create(logGroupName: string, logStreamName: string) {\n const cacheId = `${logGroupName}:${logStreamName}`;\n\n if (cache.has(cacheId)) {\n return cache.get(cacheId) as LogStream;\n }\n\n const logStream = new LogStream(logGroupName, logStreamName);\n cache.set(cacheId, logStream);\n\n return logStream;\n }\n}\n"],"mappings":";;;;;;AAAA,IAAAA,iBAAA,GAAAC,OAAA;AAEA,MAAMC,KAAK,GAAG,IAAIC,GAAG,CAAoB,CAAC;AAEnC,MAAMC,SAAS,CAAC;EAMXC,WAAWA,CAACC,YAAoB,EAAEC,aAAqB,EAAE;IAC7D,IAAI,CAACD,YAAY,GAAGA,YAAY;IAChC,IAAI,CAACC,aAAa,GAAGA,aAAa;IAClC,IAAI,CAACC,cAAc,GAAG,IAAIC,gCAAc,CAAC,CAAC;EAC9C;EAEAC,gBAAgBA,CAAA,EAAG;IACf,MAAMC,YAAY,GAAG,CACjB,CAAC,KAAK,EAAE,OAAO,CAAC,EAChB,CAAC,KAAK,EAAE,OAAO,CAAC,EAChB,CAAC,KAAK,EAAE,OAAO,CAAC,EAChB,CAAC,IAAI,EAAE,OAAO,CAAC,CAClB;IAED,MAAMC,QAAQ,GAAGA,CAACC,KAAa,EAAEC,WAAgC,KAAK;MAClE,OAAOD,KAAK,CAACE,OAAO,CAACD,WAAW,CAAC,CAAC,CAAC,EAAEA,WAAW,CAAC,CAAC,CAAW,CAAC;IAClE,CAAC;IAED,OAAO,CACF,WAAUE,OAAO,CAACC,GAAG,CAACC,UAAW,kDAAiDF,OAAO,CAACC,GAA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C5DL,KAAK,CAAC2C,GAAG,CAACJ,OAAO,EAAEG,SAAS,CAAC;IAE7B,OAAOA,SAAS;EACpB;AACJ;AAACE,OAAA,CAAA1C,SAAA,GAAAA,SAAA"}
|
package/cli/MigrationRunner.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import LambdaClient from "aws-sdk/
|
|
1
|
+
import { LambdaClient } from "@webiny/aws-sdk/client-lambda";
|
|
2
2
|
import { MigrationStatusReporter } from "./MigrationStatusReporter";
|
|
3
3
|
import { MigrationInvocationErrorResponse, MigrationStatusResponse } from "../types";
|
|
4
4
|
interface MigrationRunnerConfig {
|
package/cli/MigrationRunner.js
CHANGED
|
@@ -1,20 +1,16 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
|
|
3
|
-
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
|
|
4
3
|
Object.defineProperty(exports, "__esModule", {
|
|
5
4
|
value: true
|
|
6
5
|
});
|
|
7
6
|
exports.MigrationRunnerResult = exports.MigrationRunner = void 0;
|
|
8
|
-
var
|
|
9
|
-
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
|
|
7
|
+
var _clientLambda = require("@webiny/aws-sdk/client-lambda");
|
|
10
8
|
var _utils = require("@webiny/utils");
|
|
11
9
|
var _VoidStatusReporter = require("./VoidStatusReporter");
|
|
12
10
|
class MigrationRunnerResult {
|
|
11
|
+
successBranch = [];
|
|
12
|
+
errorBranch = [];
|
|
13
13
|
constructor(functionName, result) {
|
|
14
|
-
(0, _defineProperty2.default)(this, "functionName", void 0);
|
|
15
|
-
(0, _defineProperty2.default)(this, "result", void 0);
|
|
16
|
-
(0, _defineProperty2.default)(this, "successBranch", []);
|
|
17
|
-
(0, _defineProperty2.default)(this, "errorBranch", []);
|
|
18
14
|
this.functionName = functionName;
|
|
19
15
|
this.result = result;
|
|
20
16
|
}
|
|
@@ -28,15 +24,20 @@ class MigrationRunnerResult {
|
|
|
28
24
|
this.errorBranch.push(cb);
|
|
29
25
|
}
|
|
30
26
|
async process() {
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
27
|
+
if (this.result.error) {
|
|
28
|
+
for (const handler of this.errorBranch) {
|
|
29
|
+
await handler(this.result.error);
|
|
30
|
+
}
|
|
31
|
+
return;
|
|
32
|
+
}
|
|
33
|
+
for (const handler of this.successBranch) {
|
|
34
|
+
await handler(this.result.data);
|
|
35
35
|
}
|
|
36
36
|
}
|
|
37
37
|
}
|
|
38
38
|
exports.MigrationRunnerResult = MigrationRunnerResult;
|
|
39
39
|
class MigrationRunner {
|
|
40
|
+
statusReporter = new _VoidStatusReporter.VoidStatusReporter();
|
|
40
41
|
static create(params) {
|
|
41
42
|
const runner = new MigrationRunner(params.lambdaClient, params.functionName);
|
|
42
43
|
if (params.statusReporter) {
|
|
@@ -45,9 +46,6 @@ class MigrationRunner {
|
|
|
45
46
|
return runner;
|
|
46
47
|
}
|
|
47
48
|
constructor(lambdaClient, functionName) {
|
|
48
|
-
(0, _defineProperty2.default)(this, "lambdaClient", void 0);
|
|
49
|
-
(0, _defineProperty2.default)(this, "functionName", void 0);
|
|
50
|
-
(0, _defineProperty2.default)(this, "statusReporter", new _VoidStatusReporter.VoidStatusReporter());
|
|
51
49
|
this.lambdaClient = lambdaClient;
|
|
52
50
|
this.functionName = functionName;
|
|
53
51
|
}
|
|
@@ -97,13 +95,14 @@ class MigrationRunner {
|
|
|
97
95
|
await this.statusReporter.report(data);
|
|
98
96
|
}
|
|
99
97
|
async invokeMigration(payload) {
|
|
100
|
-
const response = await this.lambdaClient.
|
|
98
|
+
const response = await this.lambdaClient.send(new _clientLambda.InvokeCommand({
|
|
101
99
|
FunctionName: this.functionName,
|
|
102
100
|
InvocationType: "Event",
|
|
103
|
-
Payload: JSON.stringify(
|
|
101
|
+
Payload: JSON.stringify({
|
|
102
|
+
...payload,
|
|
104
103
|
command: "execute"
|
|
105
|
-
})
|
|
106
|
-
})
|
|
104
|
+
})
|
|
105
|
+
}));
|
|
107
106
|
return response.StatusCode;
|
|
108
107
|
}
|
|
109
108
|
getResult(response) {
|
|
@@ -111,16 +110,18 @@ class MigrationRunner {
|
|
|
111
110
|
}
|
|
112
111
|
async getStatus(payload) {
|
|
113
112
|
const getStatus = () => {
|
|
114
|
-
return this.lambdaClient.
|
|
113
|
+
return this.lambdaClient.send(new _clientLambda.InvokeCommand({
|
|
115
114
|
FunctionName: this.functionName,
|
|
116
115
|
InvocationType: "RequestResponse",
|
|
117
|
-
Payload: JSON.stringify(
|
|
116
|
+
Payload: JSON.stringify({
|
|
117
|
+
...payload,
|
|
118
118
|
command: "status"
|
|
119
|
-
})
|
|
120
|
-
})
|
|
119
|
+
})
|
|
120
|
+
}));
|
|
121
121
|
};
|
|
122
122
|
const response = await (0, _utils.executeWithRetry)(getStatus);
|
|
123
|
-
|
|
123
|
+
const decoder = new TextDecoder("utf-8");
|
|
124
|
+
return JSON.parse(decoder.decode(response.Payload));
|
|
124
125
|
}
|
|
125
126
|
getMigrationStatusReportInterval() {
|
|
126
127
|
const envKey = "MIGRATION_STATUS_REPORT_INTERVAL";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"names":["_utils","require","_VoidStatusReporter","MigrationRunnerResult","constructor","functionName","result","_defineProperty2","default","getFunctionName","onSuccess","cb","successBranch","push","onError","errorBranch","process","branch","error","input","data","handler","exports","MigrationRunner","create","params","runner","lambdaClient","statusReporter","setStatusReporter","VoidStatusReporter","reporter","runMigration","payload","invokeMigration","response","Promise","resolve","setTimeout","getMigrationStatusReportInterval","getStatus","getResult","status","reportStatus","report","invoke","FunctionName","InvocationType","Payload","JSON","stringify","_objectSpread2","command","promise","StatusCode","executeWithRetry","parse","envKey","env","parseInt","String"],"sources":["MigrationRunner.ts"],"sourcesContent":["import LambdaClient from \"aws-sdk/clients/lambda\";\nimport { MigrationStatusReporter } from \"~/cli/MigrationStatusReporter\";\nimport {\n MigrationEventHandlerResponse,\n MigrationInvocationErrorResponse,\n MigrationStatus,\n MigrationStatusResponse\n} from \"~/types\";\nimport { executeWithRetry } from \"@webiny/utils\";\nimport { VoidStatusReporter } from \"./VoidStatusReporter\";\n\ninterface MigrationRunnerConfig {\n lambdaClient: LambdaClient;\n functionName: string;\n statusReporter?: MigrationStatusReporter;\n}\n\ninterface MigrationPayload {\n version: string;\n pattern?: string;\n}\n\ninterface SuccessResultHandler {\n (result: MigrationStatusResponse[\"data\"]): void | Promise<void>;\n}\n\ninterface ErrorResultHandler {\n (error: MigrationInvocationErrorResponse[\"error\"]): void | Promise<void>;\n}\n\nexport class MigrationRunnerResult {\n private readonly functionName: string;\n private readonly result: MigrationStatusResponse | MigrationInvocationErrorResponse;\n private readonly successBranch: SuccessResultHandler[] = [];\n private readonly errorBranch: ErrorResultHandler[] = [];\n\n constructor(\n functionName: string,\n result: MigrationStatusResponse | MigrationInvocationErrorResponse\n ) {\n this.functionName = functionName;\n this.result = result;\n }\n\n getFunctionName() {\n return this.functionName;\n }\n\n onSuccess(cb: SuccessResultHandler) {\n this.successBranch.push(cb);\n }\n\n onError(cb: ErrorResultHandler) {\n this.errorBranch.push(cb);\n }\n\n async process(): Promise<void> {\n const branch = this.result.error ? this.errorBranch : this.successBranch;\n const input = this.result.error ? this.result.error : this.result.data;\n\n for (const handler of branch) {\n await handler(input as any);\n }\n }\n}\n\nexport class MigrationRunner {\n private readonly lambdaClient: LambdaClient;\n private readonly functionName: string;\n private statusReporter: MigrationStatusReporter = new VoidStatusReporter();\n\n public static create(params: MigrationRunnerConfig) {\n const runner = new MigrationRunner(params.lambdaClient, params.functionName);\n if (params.statusReporter) {\n runner.setStatusReporter(params.statusReporter);\n }\n return runner;\n }\n\n private constructor(lambdaClient: LambdaClient, functionName: string) {\n this.lambdaClient = lambdaClient;\n this.functionName = functionName;\n }\n\n public setStatusReporter(reporter: MigrationStatusReporter) {\n this.statusReporter = reporter;\n }\n\n async runMigration(payload: MigrationPayload): Promise<MigrationRunnerResult> {\n // Execute migration function.\n await this.invokeMigration(payload);\n\n // Poll for status and re-execute when migration is in \"pending\" state.\n let response: MigrationEventHandlerResponse;\n\n while (true) {\n await new Promise(resolve =>\n setTimeout(resolve, this.getMigrationStatusReportInterval())\n );\n\n response = await this.getStatus(payload);\n\n if (!response) {\n continue;\n }\n\n const { data, error } = response;\n\n // If we received an error, it must be an unrecoverable error, and we don't retry.\n if (error) {\n return this.getResult(response);\n }\n\n switch (data.status) {\n case \"init\":\n await this.reportStatus(data);\n continue;\n case \"pending\":\n await this.invokeMigration(payload);\n break;\n case \"running\":\n await this.reportStatus(data);\n break;\n case \"done\":\n await this.reportStatus(data);\n return this.getResult(response);\n default:\n return this.getResult(response);\n }\n }\n }\n\n private async reportStatus(data: MigrationStatus) {\n await this.statusReporter.report(data);\n }\n\n private async invokeMigration(payload: MigrationPayload) {\n const response = await this.lambdaClient\n .invoke({\n FunctionName: this.functionName,\n InvocationType: \"Event\",\n Payload: JSON.stringify({ ...payload, command: \"execute\" })\n })\n .promise();\n\n return response.StatusCode;\n }\n\n private getResult(response: MigrationStatusResponse | MigrationInvocationErrorResponse) {\n return new MigrationRunnerResult(this.functionName, response);\n }\n\n private async getStatus(payload: Record<string, any>) {\n const getStatus = () => {\n return this.lambdaClient\n .invoke({\n FunctionName: this.functionName,\n InvocationType: \"RequestResponse\",\n Payload: JSON.stringify({ ...payload, command: \"status\" })\n })\n .promise();\n };\n\n const response = await executeWithRetry(getStatus);\n\n return JSON.parse(response.Payload as string) as MigrationEventHandlerResponse;\n }\n\n private getMigrationStatusReportInterval() {\n const envKey = \"MIGRATION_STATUS_REPORT_INTERVAL\";\n if (envKey in process.env) {\n return parseInt(String(process.env[envKey]));\n }\n return 2000;\n }\n}\n"],"mappings":";;;;;;;;;AAQA,IAAAA,MAAA,GAAAC,OAAA;AACA,IAAAC,mBAAA,GAAAD,OAAA;AAqBO,MAAME,qBAAqB,CAAC;EAM/BC,WAAWA,CACPC,YAAoB,EACpBC,MAAkE,EACpE;I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EAAG;IACvC,MAAMkB,MAAM,GAAG,kCAAkC;IACjD,IAAIA,MAAM,IAAIzC,OAAO,CAAC0C,GAAG,EAAE;MACvB,OAAOC,QAAQ,CAACC,MAAM,CAAC5C,OAAO,CAAC0C,GAAG,CAACD,MAAM,CAAC,CAAC,CAAC;IAChD;IACA,OAAO,IAAI;EACf;AACJ;AAACnC,OAAA,CAAAC,eAAA,GAAAA,eAAA"}
|
|
1
|
+
{"version":3,"names":["_clientLambda","require","_utils","_VoidStatusReporter","MigrationRunnerResult","successBranch","errorBranch","constructor","functionName","result","getFunctionName","onSuccess","cb","push","onError","process","error","handler","data","exports","MigrationRunner","statusReporter","VoidStatusReporter","create","params","runner","lambdaClient","setStatusReporter","reporter","runMigration","payload","invokeMigration","response","Promise","resolve","setTimeout","getMigrationStatusReportInterval","getStatus","getResult","status","reportStatus","report","send","InvokeCommand","FunctionName","InvocationType","Payload","JSON","stringify","command","StatusCode","executeWithRetry","decoder","TextDecoder","parse","decode","envKey","env","parseInt","String"],"sources":["MigrationRunner.ts"],"sourcesContent":["import { InvokeCommand, LambdaClient } from \"@webiny/aws-sdk/client-lambda\";\nimport { MigrationStatusReporter } from \"~/cli/MigrationStatusReporter\";\nimport {\n MigrationEventHandlerResponse,\n MigrationInvocationErrorResponse,\n MigrationStatus,\n MigrationStatusResponse\n} from \"~/types\";\nimport { executeWithRetry } from \"@webiny/utils\";\nimport { VoidStatusReporter } from \"./VoidStatusReporter\";\n\ninterface MigrationRunnerConfig {\n lambdaClient: LambdaClient;\n functionName: string;\n statusReporter?: MigrationStatusReporter;\n}\n\ninterface MigrationPayload {\n version: string;\n pattern?: string;\n}\n\ninterface SuccessResultHandler {\n (result: MigrationStatusResponse[\"data\"]): void | Promise<void>;\n}\n\ninterface ErrorResultHandler {\n (error: MigrationInvocationErrorResponse[\"error\"]): void | Promise<void>;\n}\n\nexport class MigrationRunnerResult {\n private readonly functionName: string;\n private readonly result: MigrationStatusResponse | MigrationInvocationErrorResponse;\n private readonly successBranch: SuccessResultHandler[] = [];\n private readonly errorBranch: ErrorResultHandler[] = [];\n\n constructor(\n functionName: string,\n result: MigrationStatusResponse | MigrationInvocationErrorResponse\n ) {\n this.functionName = functionName;\n this.result = result;\n }\n\n getFunctionName() {\n return this.functionName;\n }\n\n onSuccess(cb: SuccessResultHandler) {\n this.successBranch.push(cb);\n }\n\n onError(cb: ErrorResultHandler) {\n this.errorBranch.push(cb);\n }\n\n async process(): Promise<void> {\n if (this.result.error) {\n for (const handler of this.errorBranch) {\n await handler(this.result.error);\n }\n return;\n }\n\n for (const handler of this.successBranch) {\n await handler(this.result.data);\n }\n }\n}\n\nexport class MigrationRunner {\n private readonly lambdaClient: LambdaClient;\n private readonly functionName: string;\n private statusReporter: MigrationStatusReporter = new VoidStatusReporter();\n\n public static create(params: MigrationRunnerConfig) {\n const runner = new MigrationRunner(params.lambdaClient, params.functionName);\n if (params.statusReporter) {\n runner.setStatusReporter(params.statusReporter);\n }\n return runner;\n }\n\n private constructor(lambdaClient: LambdaClient, functionName: string) {\n this.lambdaClient = lambdaClient;\n this.functionName = functionName;\n }\n\n public setStatusReporter(reporter: MigrationStatusReporter) {\n this.statusReporter = reporter;\n }\n\n async runMigration(payload: MigrationPayload): Promise<MigrationRunnerResult> {\n // Execute migration function.\n await this.invokeMigration(payload);\n\n // Poll for status and re-execute when migration is in \"pending\" state.\n let response: MigrationEventHandlerResponse;\n\n while (true) {\n await new Promise(resolve =>\n setTimeout(resolve, this.getMigrationStatusReportInterval())\n );\n\n response = await this.getStatus(payload);\n\n if (!response) {\n continue;\n }\n\n const { data, error } = response;\n\n // If we received an error, it must be an unrecoverable error, and we don't retry.\n if (error) {\n return this.getResult(response);\n }\n\n switch (data.status) {\n case \"init\":\n await this.reportStatus(data);\n continue;\n case \"pending\":\n await this.invokeMigration(payload);\n break;\n case \"running\":\n await this.reportStatus(data);\n break;\n case \"done\":\n await this.reportStatus(data);\n return this.getResult(response);\n default:\n return this.getResult(response);\n }\n }\n }\n\n private async reportStatus(data: MigrationStatus) {\n await this.statusReporter.report(data);\n }\n\n private async invokeMigration(payload: MigrationPayload) {\n const response = await this.lambdaClient.send(\n new InvokeCommand({\n FunctionName: this.functionName,\n InvocationType: \"Event\",\n Payload: JSON.stringify({ ...payload, command: \"execute\" })\n })\n );\n\n return response.StatusCode;\n }\n\n private getResult(response: MigrationStatusResponse | MigrationInvocationErrorResponse) {\n return new MigrationRunnerResult(this.functionName, response);\n }\n\n private async getStatus(payload: Record<string, any>) {\n const getStatus = () => {\n return this.lambdaClient.send(\n new InvokeCommand({\n FunctionName: this.functionName,\n InvocationType: \"RequestResponse\",\n Payload: JSON.stringify({ ...payload, command: \"status\" })\n })\n );\n };\n\n const response = await executeWithRetry(getStatus);\n\n const decoder = new TextDecoder(\"utf-8\");\n return JSON.parse(decoder.decode(response.Payload)) as MigrationEventHandlerResponse;\n }\n\n private getMigrationStatusReportInterval() {\n const envKey = \"MIGRATION_STATUS_REPORT_INTERVAL\";\n if (envKey in process.env) {\n return parseInt(String(process.env[envKey]));\n }\n return 2000;\n }\n}\n"],"mappings":";;;;;;AAAA,IAAAA,aAAA,GAAAC,OAAA;AAQA,IAAAC,MAAA,GAAAD,OAAA;AACA,IAAAE,mBAAA,GAAAF,OAAA;AAqBO,MAAMG,qBAAqB,CAAC;EAGdC,aAAa,GAA2B,EAAE;EAC1CC,WAAW,GAAyB,EAAE;EAEvDC,WAAWA,CACPC,YAAoB,EACpBC,MAAkE,EACpE;IACE,IAAI,CAACD,YAAY,GAAGA,YAAY;IAChC,IAAI,CAACC,MAAM,GAAGA,MAAM;EACxB;EAEAC,eAAeA,CAAA,EAAG;IACd,OAAO,IAAI,CAACF,YAAY;EAC5B;EAEAG,SAASA,CAACC,EAAwB,EAAE;IAChC,IAAI,CAACP,aAAa,CAACQ,IAAI,CAACD,EAAE,CAAC;EAC/B;EAEAE,OAAOA,CAACF,EAAsB,EAAE;IAC5B,IAAI,CAACN,WAAW,CAACO,IAAI,CAACD,EAAE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ACI,YAAY,EAAEwB,QAAQ,CAAC;EACjE;EAEA,MAAcK,SAASA,CAACP,OAA4B,EAAE;IAClD,MAAMO,SAAS,GAAGA,CAAA,KAAM;MACpB,OAAO,IAAI,CAACX,YAAY,CAACgB,IAAI,CACzB,IAAIC,2BAAa,CAAC;QACdC,YAAY,EAAE,IAAI,CAACpC,YAAY;QAC/BqC,cAAc,EAAE,iBAAiB;QACjCC,OAAO,EAAEC,IAAI,CAACC,SAAS,CAAC;UAAE,GAAGlB,OAAO;UAAEmB,OAAO,EAAE;QAAS,CAAC;MAC7D,CAAC,CACL,CAAC;IACL,CAAC;IAED,MAAMjB,QAAQ,GAAG,MAAM,IAAAmB,uBAAgB,EAACd,SAAS,CAAC;IAElD,MAAMe,OAAO,GAAG,IAAIC,WAAW,CAAC,OAAO,CAAC;IACxC,OAAON,IAAI,CAACO,KAAK,CAACF,OAAO,CAACG,MAAM,CAACvB,QAAQ,CAACc,OAAO,CAAC,CAAC;EACvD;EAEQV,gCAAgCA,CAAA,EAAG;IACvC,MAAMoB,MAAM,GAAG,kCAAkC;IACjD,IAAIA,MAAM,IAAIzC,OAAO,CAAC0C,GAAG,EAAE;MACvB,OAAOC,QAAQ,CAACC,MAAM,CAAC5C,OAAO,CAAC0C,GAAG,CAACD,MAAM,CAAC,CAAC,CAAC;IAChD;IACA,OAAO,IAAI;EACf;AACJ;AAACrC,OAAA,CAAAC,eAAA,GAAAA,eAAA"}
|
|
@@ -1,15 +1,12 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
|
|
3
|
-
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
|
|
4
3
|
Object.defineProperty(exports, "__esModule", {
|
|
5
4
|
value: true
|
|
6
5
|
});
|
|
7
6
|
exports.NonInteractiveCliStatusReporter = void 0;
|
|
8
|
-
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
|
|
9
7
|
class NonInteractiveCliStatusReporter {
|
|
8
|
+
firstCall = true;
|
|
10
9
|
constructor(logReporter) {
|
|
11
|
-
(0, _defineProperty2.default)(this, "logReporter", void 0);
|
|
12
|
-
(0, _defineProperty2.default)(this, "firstCall", true);
|
|
13
10
|
this.logReporter = logReporter;
|
|
14
11
|
console.log(`Using "NonInteractiveCliStatusReporter".`);
|
|
15
12
|
}
|
|
@@ -18,7 +15,7 @@ class NonInteractiveCliStatusReporter {
|
|
|
18
15
|
status,
|
|
19
16
|
context
|
|
20
17
|
} = migrationStatus;
|
|
21
|
-
const currentLogStreamName = context
|
|
18
|
+
const currentLogStreamName = context?.logStreamName;
|
|
22
19
|
if (currentLogStreamName) {
|
|
23
20
|
this.logReporter.initializeStream(currentLogStreamName);
|
|
24
21
|
if (this.firstCall) {
|