rds-database-running-scheduler 0.4.4 → 0.5.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.
@@ -24206,13 +24206,42 @@ var import_web_api = __toESM(require_dist5());
24206
24206
  var import_aws_lambda_secret_fetcher = __toESM(require_lib3());
24207
24207
  var import_strict_env_resolver = __toESM(require_lib2());
24208
24208
 
24209
- // src/funcs/running-schedule-targets.ts
24209
+ // src/settings/consts.ts
24210
+ var DEFAULT_WAIT_INTERVAL_SECONDS = 60;
24211
+ var DEFAULT_MAX_WAIT_SECONDS = 1800;
24212
+ var MAX_WAIT_SECONDS_LIMIT = 6900;
24213
+
24214
+ // src/funcs/core/running-schedule-errors.ts
24215
+ var RdsDatabaseRunningSchedulerError = class _RdsDatabaseRunningSchedulerError extends Error {
24216
+ name = "RdsDatabaseRunningSchedulerError";
24217
+ constructor(message) {
24218
+ super(message);
24219
+ Object.setPrototypeOf(this, _RdsDatabaseRunningSchedulerError.prototype);
24220
+ }
24221
+ };
24222
+ var RdsDatabaseRunningSchedulerValidateError = class _RdsDatabaseRunningSchedulerValidateError extends RdsDatabaseRunningSchedulerError {
24223
+ name = "RdsDatabaseRunningSchedulerValidateError";
24224
+ constructor(message) {
24225
+ super(message);
24226
+ Object.setPrototypeOf(this, _RdsDatabaseRunningSchedulerValidateError.prototype);
24227
+ }
24228
+ };
24229
+ var RdsDatabaseRunningSchedulerTimeoutError = class _RdsDatabaseRunningSchedulerTimeoutError extends RdsDatabaseRunningSchedulerError {
24230
+ name = "RdsDatabaseRunningSchedulerTimeoutError";
24231
+ constructor(message) {
24232
+ super(message);
24233
+ Object.setPrototypeOf(this, _RdsDatabaseRunningSchedulerTimeoutError.prototype);
24234
+ }
24235
+ };
24236
+
24237
+ // src/funcs/core/running-schedule-targets.ts
24210
24238
  var parseRdsArn = (arn) => {
24211
24239
  const parts = arn.split(":");
24240
+ const type = parts[5] === "cluster" ? "cluster" : "db";
24212
24241
  return {
24213
24242
  targetResource: arn,
24214
24243
  identifier: parts[6] ?? "",
24215
- type: parts[5] === "cluster" ? "cluster" : "db",
24244
+ type,
24216
24245
  account: parts[4] ?? "",
24217
24246
  region: parts[3] ?? ""
24218
24247
  };
@@ -24245,11 +24274,7 @@ var filterClusterMemberDbs = (arns, dbClusterIdentifiers, clusterKeys) => {
24245
24274
  });
24246
24275
  };
24247
24276
 
24248
- // src/funcs/running-schedule.lambda.ts
24249
- var STATE_LIST = [
24250
- { name: "AVAILABLE", emoji: "\u{1F929}", state: "available" },
24251
- { name: "STOPPED", emoji: "\u{1F634}", state: "stopped" }
24252
- ];
24277
+ // src/funcs/core/running-schedule-wait.ts
24253
24278
  var TRANSITIONING_STATES = [
24254
24279
  "starting",
24255
24280
  "configuring-enhanced-monitoring",
@@ -24257,6 +24282,82 @@ var TRANSITIONING_STATES = [
24257
24282
  "modifying",
24258
24283
  "stopping"
24259
24284
  ];
24285
+ var TRANSITIONING_STATE_SET = new Set(TRANSITIONING_STATES);
24286
+ var isTransitioningState = (current) => TRANSITIONING_STATE_SET.has(current);
24287
+ var decideResourceAction = (mode, current) => {
24288
+ if (current === "not-found") {
24289
+ return "not-found";
24290
+ }
24291
+ if (mode === "Start" && current === "available") {
24292
+ return "done";
24293
+ }
24294
+ if (mode === "Stop" && current === "stopped") {
24295
+ return "done";
24296
+ }
24297
+ if (mode === "Start" && current === "stopped") {
24298
+ return "start";
24299
+ }
24300
+ if (mode === "Stop" && current === "available") {
24301
+ return "stop";
24302
+ }
24303
+ if (isTransitioningState(current)) {
24304
+ return "wait";
24305
+ }
24306
+ return "unexpected";
24307
+ };
24308
+ var hasWaitBudget = (elapsedWaitSeconds, intervalSeconds, maxWaitSeconds) => elapsedWaitSeconds + intervalSeconds <= maxWaitSeconds;
24309
+ var nextWaitStep = (mode, current, elapsedWaitSeconds, intervalSeconds, maxWaitSeconds) => {
24310
+ const action = decideResourceAction(mode, current);
24311
+ if (action === "not-found") {
24312
+ return { kind: "finish", status: "skipped" };
24313
+ }
24314
+ if (action === "done" && (current === "available" || current === "stopped")) {
24315
+ return { kind: "finish", status: current };
24316
+ }
24317
+ if (action === "unexpected" || action === "done") {
24318
+ return { kind: "fail", current };
24319
+ }
24320
+ if (!hasWaitBudget(elapsedWaitSeconds, intervalSeconds, maxWaitSeconds)) {
24321
+ return { kind: "timed-out" };
24322
+ }
24323
+ if (action === "start") {
24324
+ return { kind: "pause", command: "start" };
24325
+ }
24326
+ if (action === "stop") {
24327
+ return { kind: "pause", command: "stop" };
24328
+ }
24329
+ return { kind: "pause", command: "none" };
24330
+ };
24331
+ var shouldContinueWaitLoop = (signal) => signal === "open";
24332
+ var resolveResourceWait = (intervalSeconds, maxSeconds) => {
24333
+ if (!Number.isInteger(intervalSeconds) || intervalSeconds <= 0) {
24334
+ throw new RdsDatabaseRunningSchedulerValidateError(
24335
+ "resourceWait.intervalSeconds must be a positive integer"
24336
+ );
24337
+ }
24338
+ if (!Number.isInteger(maxSeconds) || maxSeconds <= 0) {
24339
+ throw new RdsDatabaseRunningSchedulerValidateError(
24340
+ "resourceWait.maxSeconds must be a positive integer"
24341
+ );
24342
+ }
24343
+ if (maxSeconds < intervalSeconds) {
24344
+ throw new RdsDatabaseRunningSchedulerValidateError(
24345
+ "resourceWait.maxSeconds must be greater than or equal to resourceWait.intervalSeconds"
24346
+ );
24347
+ }
24348
+ if (maxSeconds > MAX_WAIT_SECONDS_LIMIT) {
24349
+ throw new RdsDatabaseRunningSchedulerValidateError(
24350
+ `resourceWait.maxSeconds must be less than or equal to ${MAX_WAIT_SECONDS_LIMIT}`
24351
+ );
24352
+ }
24353
+ return { intervalSeconds, maxSeconds };
24354
+ };
24355
+
24356
+ // src/funcs/running-schedule.lambda.ts
24357
+ var STATE_LIST = [
24358
+ { name: "AVAILABLE", emoji: "\u{1F929}", state: "available" },
24359
+ { name: "STOPPED", emoji: "\u{1F634}", state: "stopped" }
24360
+ ];
24260
24361
  var rdsClientCache = /* @__PURE__ */ new Map();
24261
24362
  var getRdsClient = (region) => {
24262
24363
  if (!region) {
@@ -24293,91 +24394,113 @@ var getStateDisplay = (current) => {
24293
24394
  const found = STATE_LIST.find((s) => s.state === current);
24294
24395
  return found ? { emoji: found.emoji, name: found.name } : void 0;
24295
24396
  };
24296
- var processing = async (context, targetResource, mode) => {
24397
+ var readErrorName = (err) => {
24398
+ if (typeof err !== "object" || err === null) {
24399
+ return "";
24400
+ }
24401
+ if (!("name" in err)) {
24402
+ return "";
24403
+ }
24404
+ if (typeof err.name !== "string") {
24405
+ return "";
24406
+ }
24407
+ return err.name;
24408
+ };
24409
+ var processing = async (context, targetResource, mode, waitSettings) => {
24297
24410
  const target = await context.step("get-identifier", async () => parseRdsArn(targetResource));
24298
24411
  const rds = getRdsClient(target.region);
24412
+ const { intervalSeconds, maxSeconds } = waitSettings;
24299
24413
  let iteration = 0;
24300
- for (; ; ) {
24414
+ let elapsedWaitSeconds = 0;
24415
+ let signal = "open";
24416
+ let outcome;
24417
+ let failureMessage;
24418
+ const toResult = (status) => ({
24419
+ resource: targetResource,
24420
+ status,
24421
+ account: target.account,
24422
+ region: target.region,
24423
+ identifier: target.identifier,
24424
+ type: target.type
24425
+ });
24426
+ do {
24301
24427
  const stepName = `describe-${target.type}-${target.identifier}-${iteration}`;
24302
24428
  const statusResult = await context.step(stepName, async () => {
24303
24429
  if (target.type === "db") {
24304
24430
  const res = await rds.send(new import_client_rds.DescribeDBInstancesCommand({ DBInstanceIdentifier: target.identifier }));
24305
- const current2 = res.DBInstances?.[0]?.DBInstanceStatus;
24306
- if (current2 == null) {
24431
+ const current = res.DBInstances?.[0]?.DBInstanceStatus;
24432
+ if (current == null) {
24307
24433
  throw new Error(`DB instance not found: ${target.identifier}`);
24308
24434
  }
24309
- return { current: current2, type: target.type, identifier: target.identifier };
24435
+ return { current, type: target.type, identifier: target.identifier };
24310
24436
  }
24311
24437
  try {
24312
24438
  const res = await rds.send(new import_client_rds.DescribeDBClustersCommand({ DBClusterIdentifier: target.identifier }));
24313
- const current2 = res.DBClusters?.[0]?.Status;
24314
- if (current2 == null) {
24439
+ const current = res.DBClusters?.[0]?.Status;
24440
+ if (current == null) {
24315
24441
  return { current: "not-found", type: target.type, identifier: target.identifier };
24316
24442
  }
24317
- return { current: current2, type: target.type, identifier: target.identifier };
24443
+ return { current, type: target.type, identifier: target.identifier };
24318
24444
  } catch (err) {
24319
- const code = err && typeof err === "object" && "name" in err ? err.name : "";
24445
+ const code = readErrorName(err);
24320
24446
  if (code === "DBClusterNotFoundFault" || code === "DbClusterNotFoundException") {
24321
24447
  return { current: "not-found", type: target.type, identifier: target.identifier };
24322
24448
  }
24323
24449
  throw err;
24324
24450
  }
24325
24451
  });
24326
- iteration += 1;
24327
- if (statusResult.current === "not-found") {
24328
- return { resource: targetResource, status: "skipped", account: target.account, region: target.region, identifier: target.identifier, type: target.type };
24329
- }
24330
- const current = statusResult.current;
24331
- const isDb = target.type === "db";
24332
- const isCluster = target.type === "cluster";
24333
- const needStart = mode === "Start" && current === "stopped";
24334
- const needStop = mode === "Stop" && current === "available";
24335
- const alreadyDone = mode === "Start" && current === "available" || mode === "Stop" && current === "stopped";
24336
- const isTransitioning = TRANSITIONING_STATES.includes(current);
24337
- if (needStart && isDb) {
24452
+ const step = nextWaitStep(
24453
+ mode,
24454
+ statusResult.current,
24455
+ elapsedWaitSeconds,
24456
+ intervalSeconds,
24457
+ maxSeconds
24458
+ );
24459
+ if (step.kind === "finish") {
24460
+ signal = "settled";
24461
+ outcome = toResult(step.status);
24462
+ }
24463
+ if (step.kind === "timed-out") {
24464
+ signal = "settled";
24465
+ outcome = toResult("timed-out");
24466
+ }
24467
+ if (step.kind === "fail") {
24468
+ signal = "failed";
24469
+ failureMessage = `db instance or cluster status fail: type=${target.type} identifier=${target.identifier} current=${step.current}`;
24470
+ }
24471
+ if (step.kind === "pause" && step.command === "start" && target.type === "db") {
24338
24472
  await context.step(`start-db-${target.identifier}`, async () => {
24339
24473
  await rds.send(new import_client_rds.StartDBInstanceCommand({ DBInstanceIdentifier: target.identifier }));
24340
24474
  });
24341
- await context.wait({ seconds: 60 });
24342
- continue;
24343
24475
  }
24344
- if (needStart && isCluster) {
24476
+ if (step.kind === "pause" && step.command === "start" && target.type === "cluster") {
24345
24477
  await context.step(`start-cluster-${target.identifier}`, async () => {
24346
24478
  await rds.send(new import_client_rds.StartDBClusterCommand({ DBClusterIdentifier: target.identifier }));
24347
24479
  });
24348
- await context.wait({ seconds: 60 });
24349
- continue;
24350
24480
  }
24351
- if (needStop && isDb) {
24481
+ if (step.kind === "pause" && step.command === "stop" && target.type === "db") {
24352
24482
  await context.step(`stop-db-${target.identifier}`, async () => {
24353
24483
  await rds.send(new import_client_rds.StopDBInstanceCommand({ DBInstanceIdentifier: target.identifier }));
24354
24484
  });
24355
- await context.wait({ seconds: 60 });
24356
- continue;
24357
24485
  }
24358
- if (needStop && isCluster) {
24486
+ if (step.kind === "pause" && step.command === "stop" && target.type === "cluster") {
24359
24487
  await context.step(`stop-cluster-${target.identifier}`, async () => {
24360
24488
  await rds.send(new import_client_rds.StopDBClusterCommand({ DBClusterIdentifier: target.identifier }));
24361
24489
  });
24362
- await context.wait({ seconds: 60 });
24363
- continue;
24364
- }
24365
- if (alreadyDone) {
24366
- return {
24367
- resource: targetResource,
24368
- status: current,
24369
- account: target.account,
24370
- region: target.region,
24371
- identifier: target.identifier,
24372
- type: target.type
24373
- };
24374
24490
  }
24375
- if (isTransitioning) {
24376
- await context.wait({ seconds: 60 });
24377
- continue;
24491
+ if (step.kind === "pause") {
24492
+ await context.wait({ seconds: intervalSeconds });
24493
+ elapsedWaitSeconds += intervalSeconds;
24378
24494
  }
24379
- throw new Error(`db instance or cluster status fail: type=${target.type} identifier=${target.identifier} current=${current}`);
24495
+ iteration += 1;
24496
+ } while (shouldContinueWaitLoop(signal));
24497
+ if (failureMessage !== void 0) {
24498
+ throw new Error(failureMessage);
24499
+ }
24500
+ if (outcome === void 0) {
24501
+ throw new Error(`wait loop ended without a result: type=${target.type} identifier=${target.identifier}`);
24380
24502
  }
24503
+ return outcome;
24381
24504
  };
24382
24505
  var handler = withDurableExecution(
24383
24506
  async (event, context) => {
@@ -24385,6 +24508,15 @@ var handler = withDurableExecution(
24385
24508
  if (!params?.TagKey || !params?.TagValues || !params?.Mode) {
24386
24509
  throw new Error("Invalid event: Params.TagKey, Params.TagValues, Params.Mode are required.");
24387
24510
  }
24511
+ const resourceWait = resolveResourceWait(
24512
+ import_strict_env_resolver.StrictEnvResolver.resolve("WAIT_INTERVAL_SECONDS", import_strict_env_resolver.StrictEnvType.Number, { default: DEFAULT_WAIT_INTERVAL_SECONDS }),
24513
+ import_strict_env_resolver.StrictEnvResolver.resolve("MAX_WAIT_SECONDS", import_strict_env_resolver.StrictEnvType.Number, { default: DEFAULT_MAX_WAIT_SECONDS })
24514
+ );
24515
+ const notifySlackOnWaitTimeout = import_strict_env_resolver.StrictEnvResolver.resolve(
24516
+ "NOTIFY_SLACK_ON_WAIT_TIMEOUT",
24517
+ import_strict_env_resolver.StrictEnvType.Boolean,
24518
+ { default: false }
24519
+ );
24388
24520
  const slackSecretName = import_strict_env_resolver.StrictEnvResolver.resolve("SLACK_SECRET_NAME", import_strict_env_resolver.StrictEnvType.String, { default: "" });
24389
24521
  let slackClient;
24390
24522
  let slackChannel;
@@ -24427,10 +24559,39 @@ var handler = withDurableExecution(
24427
24559
  targetResources,
24428
24560
  async (ctx, targetResource, index) => {
24429
24561
  return ctx.runInChildContext(`resource-${index}`, async (childCtx) => {
24430
- const result = await processing(childCtx, targetResource, params.Mode);
24562
+ const result = await processing(childCtx, targetResource, params.Mode, resourceWait);
24431
24563
  if (result.status === "skipped") {
24432
24564
  return result;
24433
24565
  }
24566
+ if (result.status === "timed-out") {
24567
+ if (slackClient && slackChannel && notifySlackOnWaitTimeout) {
24568
+ const client2 = slackClient;
24569
+ const channel2 = slackChannel;
24570
+ await childCtx.step("post-slack-timeout-message", async () => {
24571
+ return client2.chat.postMessage({
24572
+ channel: channel2,
24573
+ thread_ts: slackParentMessageTs,
24574
+ attachments: [
24575
+ {
24576
+ color: "#e01e5a",
24577
+ pretext: `The RDS ${result.type} ${result.identifier} did not reach the target state within the wait limit.`,
24578
+ fields: [
24579
+ { title: "Account", value: result.account, short: true },
24580
+ { title: "Region", value: result.region, short: true },
24581
+ { title: "Type", value: result.type, short: true },
24582
+ { title: "Identifier", value: result.identifier, short: true },
24583
+ { title: "Status", value: "TIMED_OUT", short: true },
24584
+ { title: "Max wait (seconds)", value: String(resourceWait.maxSeconds), short: true }
24585
+ ]
24586
+ }
24587
+ ]
24588
+ });
24589
+ });
24590
+ }
24591
+ throw new RdsDatabaseRunningSchedulerTimeoutError(
24592
+ `wait timed out: type=${result.type} identifier=${result.identifier} maxWaitSeconds=${resourceWait.maxSeconds}`
24593
+ );
24594
+ }
24434
24595
  if (!slackClient || !slackChannel) {
24435
24596
  return result;
24436
24597
  }