grada-run 0.0.2 → 0.33.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/.github/workflows/deploy-docs.yml +37 -0
- package/.github/workflows/e2e.yml +73 -0
- package/.github/workflows/iac-validation.yml +303 -0
- package/.github/workflows/publish.yml +68 -0
- package/.github/workflows/sync-bedrock-models.yml +57 -0
- package/.github/workflows/test.yml +43 -0
- package/.muserules +31 -0
- package/LICENSE +21 -0
- package/README.md +193 -3
- package/apps/docs/.astro/collections/docs.schema.json +644 -0
- package/apps/docs/.astro/content-assets.mjs +4 -0
- package/apps/docs/.astro/content-modules.mjs +4 -0
- package/apps/docs/.astro/content.d.ts +179 -0
- package/apps/docs/.astro/data-store.json +1 -0
- package/apps/docs/.astro/dev.json +14 -0
- package/apps/docs/.astro/settings.json +5 -0
- package/apps/docs/.astro/types.d.ts +2 -0
- package/apps/docs/astro.config.mjs +97 -0
- package/apps/docs/package.json +17 -0
- package/apps/docs/src/content/docs/adrs/0001-s3-native-state-locking.md +37 -0
- package/apps/docs/src/content/docs/adrs/0002-eject-mechanism-pure-iac.md +39 -0
- package/apps/docs/src/content/docs/adrs/0003-sync-ai-context-strategy.md +48 -0
- package/apps/docs/src/content/docs/adrs/0004-iac-driven-diagnostic-context.md +37 -0
- package/apps/docs/src/content/docs/adrs/0005-ecs-fargate-alb-runtime-target.md +38 -0
- package/apps/docs/src/content/docs/adrs/0006-github-oidc-no-stored-keys.md +37 -0
- package/apps/docs/src/content/docs/adrs/0007-framework-detection-with-fallback.md +37 -0
- package/apps/docs/src/content/docs/adrs/0008-secrets-names-in-git-values-in-aws.md +37 -0
- package/apps/docs/src/content/docs/adrs/0009-regenerate-with-backup-on-rerun.md +37 -0
- package/apps/docs/src/content/docs/adrs/0010-advisory-only-security-scans.md +37 -0
- package/apps/docs/src/content/docs/cli/add.md +85 -0
- package/apps/docs/src/content/docs/cli/apply.md +35 -0
- package/apps/docs/src/content/docs/cli/db.md +200 -0
- package/apps/docs/src/content/docs/cli/destroy.md +35 -0
- package/apps/docs/src/content/docs/cli/diagnose.md +37 -0
- package/apps/docs/src/content/docs/cli/doctor.md +28 -0
- package/apps/docs/src/content/docs/cli/domain.md +57 -0
- package/apps/docs/src/content/docs/cli/drift.md +40 -0
- package/apps/docs/src/content/docs/cli/eject.md +33 -0
- package/apps/docs/src/content/docs/cli/exec.md +49 -0
- package/apps/docs/src/content/docs/cli/gc.md +37 -0
- package/apps/docs/src/content/docs/cli/init.md +72 -0
- package/apps/docs/src/content/docs/cli/logs.md +39 -0
- package/apps/docs/src/content/docs/cli/rollback.md +51 -0
- package/apps/docs/src/content/docs/cli/secrets.md +73 -0
- package/apps/docs/src/content/docs/cli/sleep.md +53 -0
- package/apps/docs/src/content/docs/cli/status.md +34 -0
- package/apps/docs/src/content/docs/cli/sync-ai.md +27 -0
- package/apps/docs/src/content/docs/guides/architecture.md +87 -0
- package/apps/docs/src/content/docs/guides/aws-credentials.md +72 -0
- package/apps/docs/src/content/docs/guides/background-workers.md +45 -0
- package/apps/docs/src/content/docs/guides/cicd-pipeline.md +64 -0
- package/apps/docs/src/content/docs/guides/database-connections.md +64 -0
- package/apps/docs/src/content/docs/guides/docker-compose.md +37 -0
- package/apps/docs/src/content/docs/guides/dockerfiles.md +46 -0
- package/apps/docs/src/content/docs/guides/ephemeral-pr-previews.md +39 -0
- package/apps/docs/src/content/docs/guides/examples.md +50 -0
- package/apps/docs/src/content/docs/guides/frameworks.md +88 -0
- package/apps/docs/src/content/docs/guides/headless.md +87 -0
- package/apps/docs/src/content/docs/guides/quickstart.md +52 -0
- package/apps/docs/src/content/docs/guides/rerun-init.md +43 -0
- package/apps/docs/src/content/docs/guides/secrets-management.md +83 -0
- package/apps/docs/src/content/docs/guides/understanding-your-bill.md +63 -0
- package/apps/docs/src/content/docs/index.mdx +103 -0
- package/apps/docs/src/content/docs/migrations/astro-vercel-to-aws.md +55 -0
- package/apps/docs/src/content/docs/migrations/heroku-procfile-to-aws.md +41 -0
- package/apps/docs/src/content/docs/migrations/nextjs-vercel-to-aws.md +51 -0
- package/apps/docs/src/content/docs/migrations/sveltekit-vercel-to-aws.md +63 -0
- package/apps/docs/src/content/docs/roadmap.md +99 -0
- package/apps/docs/src/content/docs/testing-strategy.md +37 -0
- package/apps/docs/src/content.config.ts +7 -0
- package/apps/docs/src/custom.css +14 -0
- package/apps/docs/tsconfig.json +6 -0
- package/bin/cli.js +140 -0
- package/package.json +107 -7
- package/scripts/sync-bedrock-models.js +22 -0
- package/scripts/test-iac.js +261 -0
- package/specs/add-redis-sqs-bedrock.md +128 -0
- package/specs/add-storage-dynamodb.md +106 -0
- package/specs/bedrock-model-catalog.md +131 -0
- package/specs/ci-pipeline.md +17 -0
- package/specs/cost-transparency.md +115 -0
- package/specs/custom-domains-and-ses.md +153 -0
- package/specs/database-suite-expansion.md +151 -0
- package/specs/db-connect.md +69 -0
- package/specs/db-lifecycle-migrations.md +159 -0
- package/specs/dependency-aware-init.md +176 -0
- package/specs/deployment-safety.md +170 -0
- package/specs/diagnose.md +16 -0
- package/specs/docs-hub.md +16 -0
- package/specs/dx-polish.md +46 -0
- package/specs/e2e-testing.md +50 -0
- package/specs/exec.md +25 -0
- package/specs/finops-cron-drift.md +161 -0
- package/specs/gc.md +26 -0
- package/specs/integration-suite.md +16 -0
- package/specs/logs.md +32 -0
- package/specs/rollback-live-polling.md +40 -0
- package/specs/secrets-pull-audit.md +51 -0
- package/specs/serverless-lambda-target.md +133 -0
- package/specs/status.md +31 -0
- package/specs/telemetry-and-spawn-hardening.md +69 -0
- package/specs/telemetry-hardening.md +35 -0
- package/specs/test-suite-deduplication.md +42 -0
- package/src/commands/add.js +1111 -0
- package/src/commands/apply.js +214 -0
- package/src/commands/db/backup.js +229 -0
- package/src/commands/db/connect.js +304 -0
- package/src/commands/db/enable-vector.js +344 -0
- package/src/commands/db/import.js +604 -0
- package/src/commands/db/migrate.js +477 -0
- package/src/commands/db/restore.js +361 -0
- package/src/commands/db.js +87 -0
- package/src/commands/destroy.js +217 -0
- package/src/commands/diagnose.js +460 -0
- package/src/commands/doctor.js +109 -0
- package/src/commands/domain.js +685 -0
- package/src/commands/drift.js +243 -0
- package/src/commands/eject.js +130 -0
- package/src/commands/exec.js +222 -0
- package/src/commands/gc.js +250 -0
- package/src/commands/init.js +649 -0
- package/src/commands/logs.js +256 -0
- package/src/commands/rollback.js +323 -0
- package/src/commands/secrets.js +485 -0
- package/src/commands/sleep.js +347 -0
- package/src/commands/status.js +309 -0
- package/src/commands/sync-ai.js +115 -0
- package/src/commands/wake.js +337 -0
- package/src/core/parser.js +128 -0
- package/src/core/telemetry.js +244 -0
- package/src/data/bedrock-models.json +896 -0
- package/src/utils/addons.js +126 -0
- package/src/utils/ai-rules.js +59 -0
- package/src/utils/args.js +91 -0
- package/src/utils/aws.js +178 -0
- package/src/utils/backup.js +69 -0
- package/src/utils/bedrock-catalog.js +511 -0
- package/src/utils/capabilities.js +500 -0
- package/src/utils/command.js +78 -0
- package/src/utils/db-tunnel.js +164 -0
- package/src/utils/detector.js +298 -0
- package/src/utils/dockerCompose.js +65 -0
- package/src/utils/domains.js +73 -0
- package/src/utils/ecs-runner.js +289 -0
- package/src/utils/ecs.js +92 -0
- package/src/utils/frameworks.js +55 -0
- package/src/utils/generator.js +527 -0
- package/src/utils/hcl.js +426 -0
- package/src/utils/lambda-ecr.js +185 -0
- package/src/utils/prompts.js +278 -0
- package/src/utils/rds.js +131 -0
- package/src/utils/resolvers.js +174 -0
- package/src/utils/sleep-state.js +140 -0
- package/src/utils/sleep-targets.js +139 -0
- package/src/utils/system.js +42 -0
- package/src/utils/terraform.js +70 -0
- package/src/utils/visualizer.js +381 -0
- package/src/utils/warnings.js +49 -0
- package/templates/README.md +150 -0
- package/templates/docker/django.Dockerfile +40 -0
- package/templates/docker/go.Dockerfile +23 -0
- package/templates/docker/nestjs.Dockerfile +33 -0
- package/templates/docker/nextjs.Dockerfile +55 -0
- package/templates/docker/node.Dockerfile +24 -0
- package/templates/docker/nuxt.Dockerfile +47 -0
- package/templates/docker/python.Dockerfile +38 -0
- package/templates/docker/rails.Dockerfile +59 -0
- package/templates/docker/static.Dockerfile +32 -0
- package/templates/docker/svelte.Dockerfile +52 -0
- package/templates/github/deploy-lambda.yml +120 -0
- package/templates/github/deploy.yml +138 -0
- package/templates/github/drift.yml +112 -0
- package/templates/github/preview-lambda.yml +86 -0
- package/templates/github/preview.yml +69 -0
- package/templates/github/teardown.yml +43 -0
- package/templates/terraform/addons/bedrock.tf +34 -0
- package/templates/terraform/addons/cron-lambda.tf +78 -0
- package/templates/terraform/addons/cron.tf +101 -0
- package/templates/terraform/addons/dynamodb.tf +73 -0
- package/templates/terraform/addons/redis.tf +64 -0
- package/templates/terraform/addons/s3.tf +143 -0
- package/templates/terraform/addons/ses.tf +73 -0
- package/templates/terraform/addons/sqs.tf +67 -0
- package/templates/terraform/backend.tf +22 -0
- package/templates/terraform/cloudfront-lambda.tf +80 -0
- package/templates/terraform/cloudfront.tf +80 -0
- package/templates/terraform/database-aurora-postgresql.tf +92 -0
- package/templates/terraform/database-mysql.tf +72 -0
- package/templates/terraform/database.tf +71 -0
- package/templates/terraform/main-lambda.tf +229 -0
- package/templates/terraform/main.tf +296 -0
- package/templates/terraform/network.tf +95 -0
- package/templates/terraform/oidc.tf +64 -0
- package/templates/terraform/secrets.tf +31 -0
- package/templates/terraform/worker.tf +69 -0
- package/tests/__snapshots__/generator.test.js.snap +9633 -0
- package/tests/add.test.js +2018 -0
- package/tests/ai.test.js +91 -0
- package/tests/apply.test.js +446 -0
- package/tests/args.test.js +86 -0
- package/tests/aws.test.js +244 -0
- package/tests/capabilities.test.js +304 -0
- package/tests/cli.test.js +29 -0
- package/tests/command.test.js +99 -0
- package/tests/commands-import.test.js +74 -0
- package/tests/db.test.js +2673 -0
- package/tests/destroy.test.js +365 -0
- package/tests/detector.test.js +79 -0
- package/tests/diagnose.test.js +765 -0
- package/tests/doctor.test.js +195 -0
- package/tests/domain.test.js +882 -0
- package/tests/drift.test.js +228 -0
- package/tests/e2e/helpers.js +122 -0
- package/tests/e2e/tier0.e2e.test.js +142 -0
- package/tests/e2e/tier1.live.e2e.test.js +118 -0
- package/tests/ecs.test.js +130 -0
- package/tests/eject.test.js +65 -0
- package/tests/exec.test.js +366 -0
- package/tests/gc.test.js +466 -0
- package/tests/generator.test.js +794 -0
- package/tests/headless.test.js +491 -0
- package/tests/helpers/clack.js +103 -0
- package/tests/helpers/console.js +41 -0
- package/tests/helpers/telemetry.js +37 -0
- package/tests/helpers/tmpdir.js +36 -0
- package/tests/lambda-ecr.test.js +185 -0
- package/tests/logs.test.js +436 -0
- package/tests/parser.test.js +160 -0
- package/tests/rds.test.js +244 -0
- package/tests/resolvers.test.js +279 -0
- package/tests/rollback.test.js +670 -0
- package/tests/secrets.test.js +729 -0
- package/tests/sleep-wake.test.js +998 -0
- package/tests/status.test.js +356 -0
- package/tests/system.test.js +70 -0
- package/tests/telemetry.test.js +520 -0
- package/tests/terraform.test.js +84 -0
- package/tests/visualizer.test.js +480 -0
- package/vitest.config.js +10 -0
- package/vitest.e2e.tier0.config.js +8 -0
- package/vitest.e2e.tier1.config.js +8 -0
- package/index.js +0 -2
|
@@ -0,0 +1,998 @@
|
|
|
1
|
+
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
|
2
|
+
// NOTE: helper imports must stay above src imports: vi.mock factories run
|
|
3
|
+
// during module evaluation and need the factories initialized.
|
|
4
|
+
import { clackPromptsMockFactory } from './helpers/clack.js';
|
|
5
|
+
import { telemetryMockFactory } from './helpers/telemetry.js';
|
|
6
|
+
import { createTmpDirTracker } from './helpers/tmpdir.js';
|
|
7
|
+
import fs from 'fs';
|
|
8
|
+
import os from 'os';
|
|
9
|
+
import path from 'path';
|
|
10
|
+
import { stripVTControlCharacters } from 'node:util';
|
|
11
|
+
import { runSleep, parseSleepArgs } from '../src/commands/sleep.js';
|
|
12
|
+
import { runWake, parseWakeArgs } from '../src/commands/wake.js';
|
|
13
|
+
import {
|
|
14
|
+
resolveSleepTarget,
|
|
15
|
+
normalizeSleepEnv,
|
|
16
|
+
readSleepState,
|
|
17
|
+
writeSleepState,
|
|
18
|
+
removeSleepStateEntry,
|
|
19
|
+
ensureSleepGitignore,
|
|
20
|
+
computeAutoRestartAt,
|
|
21
|
+
formatUtcTimestamp,
|
|
22
|
+
RDS_AUTO_RESTART_MS,
|
|
23
|
+
} from '../src/utils/sleep-state.js';
|
|
24
|
+
import { estimateSleepSavings } from '../src/utils/visualizer.js';
|
|
25
|
+
import { trackEvent, flushTelemetry } from '../src/core/telemetry.js';
|
|
26
|
+
import { confirm } from '@clack/prompts';
|
|
27
|
+
import {
|
|
28
|
+
readCronScheduleName,
|
|
29
|
+
setSchedulerState,
|
|
30
|
+
setWorkerScalingSuspended,
|
|
31
|
+
} from '../src/utils/sleep-targets.js';
|
|
32
|
+
|
|
33
|
+
vi.mock('@clack/prompts', () => clackPromptsMockFactory());
|
|
34
|
+
|
|
35
|
+
vi.mock('../src/core/telemetry.js', (importOriginal) => telemetryMockFactory(importOriginal));
|
|
36
|
+
|
|
37
|
+
vi.mock('../src/utils/aws.js', () => ({
|
|
38
|
+
handleAuthErrorBranch: () => false,
|
|
39
|
+
resolveClient: (injected) => injected,
|
|
40
|
+
}));
|
|
41
|
+
|
|
42
|
+
const tmp = createTmpDirTracker();
|
|
43
|
+
let exitSpy;
|
|
44
|
+
let logSpy;
|
|
45
|
+
|
|
46
|
+
function makeTmp() {
|
|
47
|
+
return tmp.makeTmp('sleep-wake-test-');
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// Minimal ECS/RDS recorder: `ecs` maps service names to service objects,
|
|
51
|
+
// `db` is the findDbTarget result inputs ({ instance, cluster }).
|
|
52
|
+
function mockClients({ ecs = {}, db = null, onCommand = null } = {}) {
|
|
53
|
+
const seen = [];
|
|
54
|
+
const ecsClient = {
|
|
55
|
+
send: vi.fn(async (command) => {
|
|
56
|
+
seen.push(command.constructor.name);
|
|
57
|
+
if (onCommand) await onCommand(command);
|
|
58
|
+
const name = command.constructor.name;
|
|
59
|
+
if (name === 'DescribeServicesCommand') {
|
|
60
|
+
const services = (command.input.services || [])
|
|
61
|
+
.map((serviceName) => ecs[serviceName] || null)
|
|
62
|
+
.filter(Boolean);
|
|
63
|
+
return { services };
|
|
64
|
+
}
|
|
65
|
+
if (name === 'UpdateServiceCommand') {
|
|
66
|
+
const service = ecs[command.input.service];
|
|
67
|
+
if (service) service.desiredCount = command.input.desiredCount;
|
|
68
|
+
return {};
|
|
69
|
+
}
|
|
70
|
+
throw new Error(`unexpected ECS command: ${name}`);
|
|
71
|
+
}),
|
|
72
|
+
};
|
|
73
|
+
const rdsClient = {
|
|
74
|
+
send: vi.fn(async (command) => {
|
|
75
|
+
seen.push(command.constructor.name);
|
|
76
|
+
const name = command.constructor.name;
|
|
77
|
+
if (name === 'DescribeDBInstancesCommand') {
|
|
78
|
+
if (db?.instance) return { DBInstances: [db.instance] };
|
|
79
|
+
throw Object.assign(new Error('not found'), { name: 'DBInstanceNotFound' });
|
|
80
|
+
}
|
|
81
|
+
if (name === 'DescribeDBClustersCommand') {
|
|
82
|
+
if (db?.cluster) return { DBClusters: [db.cluster] };
|
|
83
|
+
throw Object.assign(new Error('not found'), { name: 'DBClusterNotFoundFault' });
|
|
84
|
+
}
|
|
85
|
+
if (name === 'StopDBInstanceCommand' && db?.instance) {
|
|
86
|
+
db.instance.Status = 'stopping';
|
|
87
|
+
return {};
|
|
88
|
+
}
|
|
89
|
+
if (name === 'StopDBClusterCommand' && db?.cluster) {
|
|
90
|
+
db.cluster.Status = 'stopping';
|
|
91
|
+
return {};
|
|
92
|
+
}
|
|
93
|
+
if (name === 'StartDBInstanceCommand' && db?.instance) {
|
|
94
|
+
db.instance.Status = 'starting';
|
|
95
|
+
return {};
|
|
96
|
+
}
|
|
97
|
+
if (name === 'StartDBClusterCommand' && db?.cluster) {
|
|
98
|
+
db.cluster.Status = 'starting';
|
|
99
|
+
return {};
|
|
100
|
+
}
|
|
101
|
+
return {};
|
|
102
|
+
}),
|
|
103
|
+
};
|
|
104
|
+
return { ecsClient, rdsClient, seen };
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function activeService(name, desiredCount) {
|
|
108
|
+
return { serviceName: name, status: 'ACTIVE', desiredCount, runningCount: desiredCount };
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
beforeEach(() => {
|
|
112
|
+
tmp.reset();
|
|
113
|
+
vi.clearAllMocks();
|
|
114
|
+
exitSpy = vi.spyOn(process, 'exit').mockImplementation(() => {});
|
|
115
|
+
logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
afterEach(() => {
|
|
119
|
+
exitSpy.mockRestore();
|
|
120
|
+
logSpy.mockRestore();
|
|
121
|
+
tmp.cleanup();
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
describe('parseSleepArgs / parseWakeArgs', () => {
|
|
125
|
+
it('parses the positional env and sleep flags', () => {
|
|
126
|
+
const options = parseSleepArgs(['sleep', 'staging', '--skip-db', '--region', 'eu-west-1', '--yes']);
|
|
127
|
+
expect(options).toMatchObject({ env: 'staging', skipDb: true, region: 'eu-west-1', yes: true });
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
it('parses wake flags including --no-wait and --workspace', () => {
|
|
131
|
+
const options = parseWakeArgs(['wake', '--no-wait', '--workspace', 'pr-42']);
|
|
132
|
+
expect(options).toMatchObject({ noWait: true, workspace: 'pr-42' });
|
|
133
|
+
expect(options.env).toBeUndefined();
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
it('collects extra positionals for the guard', () => {
|
|
137
|
+
expect(parseSleepArgs(['sleep', 'a', 'b']).unexpectedPositionals).toEqual(['b']);
|
|
138
|
+
});
|
|
139
|
+
});
|
|
140
|
+
|
|
141
|
+
describe('normalizeSleepEnv', () => {
|
|
142
|
+
it('maps default aliases and passes named envs through', () => {
|
|
143
|
+
expect(normalizeSleepEnv('default')).toBe('default');
|
|
144
|
+
expect(normalizeSleepEnv('prod')).toBe('default');
|
|
145
|
+
expect(normalizeSleepEnv('Production')).toBe('default');
|
|
146
|
+
expect(normalizeSleepEnv('staging')).toBe('staging');
|
|
147
|
+
expect(normalizeSleepEnv(' pr-42 ')).toBe('pr-42');
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
it('returns null for blank or non-string input', () => {
|
|
151
|
+
expect(normalizeSleepEnv('')).toBeNull();
|
|
152
|
+
expect(normalizeSleepEnv(' ')).toBeNull();
|
|
153
|
+
expect(normalizeSleepEnv(undefined)).toBeNull();
|
|
154
|
+
expect(normalizeSleepEnv(42)).toBeNull();
|
|
155
|
+
});
|
|
156
|
+
});
|
|
157
|
+
|
|
158
|
+
describe('resolveSleepTarget', () => {
|
|
159
|
+
it('resolves default names with no env', () => {
|
|
160
|
+
const dir = makeTmp();
|
|
161
|
+
const target = resolveSleepTarget({ projectName: 'myapp' }, dir);
|
|
162
|
+
expect(target).toMatchObject({
|
|
163
|
+
envKey: 'default',
|
|
164
|
+
envKind: 'default',
|
|
165
|
+
requiresConfirm: true,
|
|
166
|
+
appPrefix: 'myapp',
|
|
167
|
+
cluster: 'myapp-cluster',
|
|
168
|
+
appService: 'myapp-service',
|
|
169
|
+
workerService: 'myapp-worker-service',
|
|
170
|
+
dbIdentifier: 'myapp-db',
|
|
171
|
+
dbClusterIdentifier: 'myapp-db-cluster',
|
|
172
|
+
});
|
|
173
|
+
});
|
|
174
|
+
|
|
175
|
+
it('namespaces names for a positional env', () => {
|
|
176
|
+
const dir = makeTmp();
|
|
177
|
+
const target = resolveSleepTarget({ projectName: 'myapp', env: 'staging' }, dir);
|
|
178
|
+
expect(target).toMatchObject({
|
|
179
|
+
envKey: 'staging',
|
|
180
|
+
envKind: 'named',
|
|
181
|
+
requiresConfirm: false,
|
|
182
|
+
appPrefix: 'myapp-staging',
|
|
183
|
+
cluster: 'myapp-staging-cluster',
|
|
184
|
+
workerService: 'myapp-staging-worker-service',
|
|
185
|
+
dbIdentifier: 'myapp-staging-db',
|
|
186
|
+
});
|
|
187
|
+
});
|
|
188
|
+
|
|
189
|
+
it('prefers --workspace over the positional env', () => {
|
|
190
|
+
const dir = makeTmp();
|
|
191
|
+
const target = resolveSleepTarget({ projectName: 'myapp', env: 'staging', workspace: 'pr-42' }, dir);
|
|
192
|
+
expect(target.envKey).toBe('pr-42');
|
|
193
|
+
expect(target.appPrefix).toBe('myapp-pr-42');
|
|
194
|
+
});
|
|
195
|
+
|
|
196
|
+
it('lets explicit resource flags win', () => {
|
|
197
|
+
const dir = makeTmp();
|
|
198
|
+
const target = resolveSleepTarget({
|
|
199
|
+
projectName: 'myapp',
|
|
200
|
+
env: 'staging',
|
|
201
|
+
cluster: 'custom-cluster',
|
|
202
|
+
service: 'custom-service',
|
|
203
|
+
dbIdentifier: 'custom-db',
|
|
204
|
+
}, dir);
|
|
205
|
+
expect(target.cluster).toBe('custom-cluster');
|
|
206
|
+
expect(target.appService).toBe('custom-service');
|
|
207
|
+
expect(target.dbIdentifier).toBe('custom-db');
|
|
208
|
+
});
|
|
209
|
+
|
|
210
|
+
it('requires confirmation for prod aliases and auto-detected workspaces', () => {
|
|
211
|
+
const dir = makeTmp();
|
|
212
|
+
expect(resolveSleepTarget({ projectName: 'myapp', env: 'prod' }, dir).requiresConfirm).toBe(true);
|
|
213
|
+
fs.mkdirSync(path.join(dir, '.terraform'), { recursive: true });
|
|
214
|
+
fs.writeFileSync(path.join(dir, '.terraform', 'environment'), 'pr-42');
|
|
215
|
+
const auto = resolveSleepTarget({ projectName: 'myapp' }, dir);
|
|
216
|
+
expect(auto.envKey).toBe('pr-42');
|
|
217
|
+
expect(auto.requiresConfirm).toBe(true);
|
|
218
|
+
});
|
|
219
|
+
});
|
|
220
|
+
|
|
221
|
+
describe('sleep-state ledger', () => {
|
|
222
|
+
it('round-trips entries and removes by env', () => {
|
|
223
|
+
const dir = makeTmp();
|
|
224
|
+
expect(readSleepState(dir)).toEqual({});
|
|
225
|
+
writeSleepState(dir, { staging: { env: 'staging' } });
|
|
226
|
+
expect(readSleepState(dir)).toEqual({ staging: { env: 'staging' } });
|
|
227
|
+
expect(removeSleepStateEntry(dir, 'staging')).toBe(true);
|
|
228
|
+
expect(removeSleepStateEntry(dir, 'staging')).toBe(false);
|
|
229
|
+
expect(readSleepState(dir)).toEqual({});
|
|
230
|
+
});
|
|
231
|
+
|
|
232
|
+
it('reads corrupt files as empty', () => {
|
|
233
|
+
const dir = makeTmp();
|
|
234
|
+
fs.mkdirSync(path.join(dir, '.grada'), { recursive: true });
|
|
235
|
+
fs.writeFileSync(path.join(dir, '.grada', 'sleep-state.json'), '{nope');
|
|
236
|
+
expect(readSleepState(dir)).toEqual({});
|
|
237
|
+
});
|
|
238
|
+
|
|
239
|
+
it('falls back to the legacy ledger path', () => {
|
|
240
|
+
const dir = makeTmp();
|
|
241
|
+
fs.mkdirSync(path.join(dir, '.deploy-stack'), { recursive: true });
|
|
242
|
+
fs.writeFileSync(
|
|
243
|
+
path.join(dir, '.deploy-stack', 'sleep-state.json'),
|
|
244
|
+
JSON.stringify({ default: { env: 'default' } })
|
|
245
|
+
);
|
|
246
|
+
expect(readSleepState(dir)).toEqual({ default: { env: 'default' } });
|
|
247
|
+
});
|
|
248
|
+
|
|
249
|
+
it('prefers the new ledger path over legacy', () => {
|
|
250
|
+
const dir = makeTmp();
|
|
251
|
+
writeSleepState(dir, { staging: { env: 'staging' } });
|
|
252
|
+
fs.mkdirSync(path.join(dir, '.deploy-stack'), { recursive: true });
|
|
253
|
+
fs.writeFileSync(
|
|
254
|
+
path.join(dir, '.deploy-stack', 'sleep-state.json'),
|
|
255
|
+
JSON.stringify({ default: { env: 'default' } })
|
|
256
|
+
);
|
|
257
|
+
expect(readSleepState(dir)).toEqual({ staging: { env: 'staging' } });
|
|
258
|
+
});
|
|
259
|
+
|
|
260
|
+
it('gitignores the ledger exactly once', () => {
|
|
261
|
+
const dir = makeTmp();
|
|
262
|
+
expect(ensureSleepGitignore(dir)).toBe(true);
|
|
263
|
+
expect(fs.readFileSync(path.join(dir, '.gitignore'), 'utf8')).toContain('.grada/');
|
|
264
|
+
expect(ensureSleepGitignore(dir)).toBe(false);
|
|
265
|
+
});
|
|
266
|
+
|
|
267
|
+
it('leaves a legacy gitignore rule intact while adding the new one', () => {
|
|
268
|
+
const dir = makeTmp();
|
|
269
|
+
fs.writeFileSync(path.join(dir, '.gitignore'), '# Local deploy-stack runtime state (sleep/wake)\n.deploy-stack/\n');
|
|
270
|
+
expect(ensureSleepGitignore(dir)).toBe(true);
|
|
271
|
+
const content = fs.readFileSync(path.join(dir, '.gitignore'), 'utf8');
|
|
272
|
+
expect(content).toContain('.deploy-stack/');
|
|
273
|
+
expect(content).toContain('.grada/');
|
|
274
|
+
expect(ensureSleepGitignore(dir)).toBe(false);
|
|
275
|
+
});
|
|
276
|
+
|
|
277
|
+
it('computes the 7-day auto-restart timestamp in UTC', () => {
|
|
278
|
+
const nowMs = Date.UTC(2026, 0, 1, 12, 0, 0);
|
|
279
|
+
expect(computeAutoRestartAt(nowMs).getTime()).toBe(nowMs + RDS_AUTO_RESTART_MS);
|
|
280
|
+
expect(formatUtcTimestamp(computeAutoRestartAt(nowMs))).toBe('2026-01-08 12:00 UTC');
|
|
281
|
+
});
|
|
282
|
+
});
|
|
283
|
+
|
|
284
|
+
describe('estimateSleepSavings', () => {
|
|
285
|
+
it('pauses Fargate replicas plus RDS compute, never storage', () => {
|
|
286
|
+
const savings = estimateSleepSavings({ hasDb: true, appReplicas: 1, workerReplicas: 0 });
|
|
287
|
+
expect(savings.fargateMonthly).toBe('9.01');
|
|
288
|
+
expect(savings.dbComputeMonthly).toBe('11.68');
|
|
289
|
+
expect(savings.monthly).toBe('20.69');
|
|
290
|
+
expect(savings.hourly).toBe('0.028');
|
|
291
|
+
});
|
|
292
|
+
|
|
293
|
+
it('counts the worker and zeroes Aurora compute', () => {
|
|
294
|
+
const withWorker = estimateSleepSavings({ hasDb: true, appReplicas: 1, workerReplicas: 1 });
|
|
295
|
+
expect(withWorker.monthly).toBe('29.70');
|
|
296
|
+
const aurora = estimateSleepSavings({ hasDb: true, dbEngine: 'aurora-postgresql', appReplicas: 1 });
|
|
297
|
+
expect(aurora.dbComputeMonthly).toBe('0.00');
|
|
298
|
+
expect(aurora.monthly).toBe('9.01');
|
|
299
|
+
});
|
|
300
|
+
});
|
|
301
|
+
|
|
302
|
+
describe('runSleep', () => {
|
|
303
|
+
function sleepOptions(dir, overrides = {}) {
|
|
304
|
+
return {
|
|
305
|
+
cwd: dir,
|
|
306
|
+
projectName: 'myapp',
|
|
307
|
+
region: 'us-east-2',
|
|
308
|
+
env: 'staging',
|
|
309
|
+
nowMs: Date.UTC(2026, 0, 1, 12, 0, 0),
|
|
310
|
+
...overrides,
|
|
311
|
+
};
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
it('scales services to zero, stops the instance, and persists state', async () => {
|
|
315
|
+
const dir = makeTmp();
|
|
316
|
+
const { ecsClient, rdsClient, seen } = mockClients({
|
|
317
|
+
ecs: {
|
|
318
|
+
'myapp-staging-service': activeService('myapp-staging-service', 1),
|
|
319
|
+
'myapp-staging-worker-service': activeService('myapp-staging-worker-service', 2),
|
|
320
|
+
},
|
|
321
|
+
db: { instance: { Engine: 'postgres', Status: 'available', DBName: 'db' } },
|
|
322
|
+
});
|
|
323
|
+
const result = await runSleep(sleepOptions(dir, { ecsClient, rdsClient }));
|
|
324
|
+
expect(result.ok).toBe(true);
|
|
325
|
+
expect(result.ecsScaled).toBe(2);
|
|
326
|
+
expect(result.dbStopped).toBe(true);
|
|
327
|
+
expect(seen).toContain('UpdateServiceCommand');
|
|
328
|
+
expect(seen).toContain('StopDBInstanceCommand');
|
|
329
|
+
expect(exitSpy).not.toHaveBeenCalled();
|
|
330
|
+
|
|
331
|
+
const state = readSleepState(dir);
|
|
332
|
+
expect(state.staging).toMatchObject({
|
|
333
|
+
env: 'staging',
|
|
334
|
+
services: { app: 1, worker: 2 },
|
|
335
|
+
dbKind: 'instance',
|
|
336
|
+
});
|
|
337
|
+
expect(state.staging.autoRestartAt).toBe('2026-01-08T12:00:00.000Z');
|
|
338
|
+
expect(fs.readFileSync(path.join(dir, '.gitignore'), 'utf8')).toContain('.grada/');
|
|
339
|
+
|
|
340
|
+
const output = logSpy.mock.calls.map((call) => String(call[0])).join('\n');
|
|
341
|
+
expect(output).toContain('2026-01-08 12:00 UTC');
|
|
342
|
+
expect(output).toContain('Estimated Savings While Asleep');
|
|
343
|
+
expect(output).toContain('npx grada-run wake staging');
|
|
344
|
+
expect(trackEvent).toHaveBeenCalledWith('sleep_run', expect.objectContaining({
|
|
345
|
+
env_kind: 'named', ecs_scaled: 2, db_stopped: true, db_kind: 'instance', success: true,
|
|
346
|
+
}));
|
|
347
|
+
});
|
|
348
|
+
|
|
349
|
+
it('stops Aurora clusters with StopDBClusterCommand', async () => {
|
|
350
|
+
const dir = makeTmp();
|
|
351
|
+
const { ecsClient, rdsClient, seen } = mockClients({
|
|
352
|
+
ecs: { 'myapp-staging-service': activeService('myapp-staging-service', 1) },
|
|
353
|
+
db: { cluster: { Engine: 'aurora-postgresql', Status: 'available' } },
|
|
354
|
+
});
|
|
355
|
+
const result = await runSleep(sleepOptions(dir, { ecsClient, rdsClient }));
|
|
356
|
+
expect(result.ok).toBe(true);
|
|
357
|
+
expect(result.dbKind).toBe('cluster');
|
|
358
|
+
expect(seen).toContain('StopDBClusterCommand');
|
|
359
|
+
expect(seen).not.toContain('StopDBInstanceCommand');
|
|
360
|
+
});
|
|
361
|
+
|
|
362
|
+
it('is idempotent when services are already asleep and the db is stopped', async () => {
|
|
363
|
+
const dir = makeTmp();
|
|
364
|
+
const { ecsClient, rdsClient, seen } = mockClients({
|
|
365
|
+
ecs: { 'myapp-staging-service': activeService('myapp-staging-service', 0) },
|
|
366
|
+
db: { instance: { Engine: 'postgres', Status: 'stopped' } },
|
|
367
|
+
});
|
|
368
|
+
const result = await runSleep(sleepOptions(dir, { ecsClient, rdsClient }));
|
|
369
|
+
expect(result.ok).toBe(true);
|
|
370
|
+
expect(result.ecsScaled).toBe(0);
|
|
371
|
+
expect(result.dbStopped).toBe(false);
|
|
372
|
+
expect(seen).not.toContain('UpdateServiceCommand');
|
|
373
|
+
expect(seen).not.toContain('StopDBInstanceCommand');
|
|
374
|
+
// No ledger history: defaults restore to 1/0 (no worker service live).
|
|
375
|
+
expect(readSleepState(dir).staging.services).toEqual({ app: 1, worker: 0 });
|
|
376
|
+
});
|
|
377
|
+
|
|
378
|
+
it('preserves the original replica counts on a repeat sleep', async () => {
|
|
379
|
+
const dir = makeTmp();
|
|
380
|
+
const ecs = { 'myapp-staging-service': activeService('myapp-staging-service', 3) };
|
|
381
|
+
const first = mockClients({ ecs, db: { instance: { Engine: 'postgres', Status: 'available' } } });
|
|
382
|
+
await runSleep(sleepOptions(dir, { ecsClient: first.ecsClient, rdsClient: first.rdsClient }));
|
|
383
|
+
expect(readSleepState(dir).staging.services.app).toBe(3);
|
|
384
|
+
const second = mockClients({ ecs, db: { instance: { Engine: 'postgres', Status: 'stopping' } } });
|
|
385
|
+
await runSleep(sleepOptions(dir, { ecsClient: second.ecsClient, rdsClient: second.rdsClient }));
|
|
386
|
+
expect(readSleepState(dir).staging.services.app).toBe(3);
|
|
387
|
+
});
|
|
388
|
+
|
|
389
|
+
it('honors --skip-db and skips transitional databases', async () => {
|
|
390
|
+
const dir = makeTmp();
|
|
391
|
+
const skipped = mockClients({
|
|
392
|
+
ecs: { 'myapp-staging-service': activeService('myapp-staging-service', 1) },
|
|
393
|
+
db: { instance: { Engine: 'postgres', Status: 'available' } },
|
|
394
|
+
});
|
|
395
|
+
await runSleep(sleepOptions(dir, { ecsClient: skipped.ecsClient, rdsClient: skipped.rdsClient, skipDb: true }));
|
|
396
|
+
expect(skipped.seen).not.toContain('DescribeDBInstancesCommand');
|
|
397
|
+
|
|
398
|
+
const transitional = mockClients({
|
|
399
|
+
ecs: { 'myapp-staging-service': activeService('myapp-staging-service', 1) },
|
|
400
|
+
db: { instance: { Engine: 'postgres', Status: 'starting' } },
|
|
401
|
+
});
|
|
402
|
+
const result = await runSleep(sleepOptions(dir, { ecsClient: transitional.ecsClient, rdsClient: transitional.rdsClient }));
|
|
403
|
+
expect(result.ok).toBe(true);
|
|
404
|
+
expect(result.dbStopped).toBe(false);
|
|
405
|
+
expect(transitional.seen).not.toContain('StopDBInstanceCommand');
|
|
406
|
+
});
|
|
407
|
+
|
|
408
|
+
it('fails when nothing exists to sleep', async () => {
|
|
409
|
+
const dir = makeTmp();
|
|
410
|
+
const { ecsClient, rdsClient } = mockClients({});
|
|
411
|
+
const result = await runSleep(sleepOptions(dir, { ecsClient, rdsClient }));
|
|
412
|
+
expect(result.ok).toBe(false);
|
|
413
|
+
expect(result.reason).toBe('nothing-to-sleep');
|
|
414
|
+
expect(exitSpy).toHaveBeenCalledWith(1);
|
|
415
|
+
});
|
|
416
|
+
|
|
417
|
+
it('guards the default environment: headless requires --yes', async () => {
|
|
418
|
+
const dir = makeTmp();
|
|
419
|
+
const { ecsClient, rdsClient } = mockClients({
|
|
420
|
+
ecs: { 'myapp-service': activeService('myapp-service', 1) },
|
|
421
|
+
});
|
|
422
|
+
const denied = await runSleep({ cwd: dir, projectName: 'myapp', region: 'us-east-2', isHeadless: true, ecsClient, rdsClient });
|
|
423
|
+
expect(denied.ok).toBe(false);
|
|
424
|
+
expect(denied.reason).toBe('confirmation-required');
|
|
425
|
+
expect(exitSpy).toHaveBeenCalledWith(1);
|
|
426
|
+
expect(ecsClient.send).not.toHaveBeenCalled();
|
|
427
|
+
|
|
428
|
+
vi.mocked(confirm).mockResolvedValueOnce(false);
|
|
429
|
+
const declined = await runSleep({ cwd: dir, projectName: 'myapp', region: 'us-east-2', isHeadless: false, ecsClient, rdsClient });
|
|
430
|
+
expect(declined).toMatchObject({ ok: false, reason: 'cancelled' });
|
|
431
|
+
|
|
432
|
+
vi.mocked(confirm).mockResolvedValueOnce(true);
|
|
433
|
+
const accepted = await runSleep({ cwd: dir, projectName: 'myapp', region: 'us-east-2', isHeadless: false, ecsClient, rdsClient });
|
|
434
|
+
expect(accepted.ok).toBe(true);
|
|
435
|
+
expect(vi.mocked(confirm)).toHaveBeenCalledWith(expect.objectContaining({ initialValue: false }));
|
|
436
|
+
});
|
|
437
|
+
});
|
|
438
|
+
|
|
439
|
+
describe('runWake', () => {
|
|
440
|
+
function wakeOptions(dir, overrides = {}) {
|
|
441
|
+
return {
|
|
442
|
+
cwd: dir,
|
|
443
|
+
projectName: 'myapp',
|
|
444
|
+
region: 'us-east-2',
|
|
445
|
+
env: 'staging',
|
|
446
|
+
pollIntervalMs: 1,
|
|
447
|
+
timeoutMs: 1000,
|
|
448
|
+
...overrides,
|
|
449
|
+
};
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
it('starts the database first, then restores ledger counts', async () => {
|
|
453
|
+
const dir = makeTmp();
|
|
454
|
+
writeSleepState(dir, {
|
|
455
|
+
staging: {
|
|
456
|
+
env: 'staging',
|
|
457
|
+
sleptAt: new Date().toISOString(),
|
|
458
|
+
autoRestartAt: new Date(Date.now() + 3600_000).toISOString(),
|
|
459
|
+
services: { app: 2, worker: 1 },
|
|
460
|
+
dbId: 'myapp-staging-db',
|
|
461
|
+
dbKind: 'instance',
|
|
462
|
+
},
|
|
463
|
+
});
|
|
464
|
+
const db = { instance: { Engine: 'postgres', Status: 'stopped' } };
|
|
465
|
+
const order = [];
|
|
466
|
+
const { ecsClient, rdsClient } = mockClients({
|
|
467
|
+
ecs: {
|
|
468
|
+
'myapp-staging-service': { ...activeService('myapp-staging-service', 0), runningCount: 2 },
|
|
469
|
+
'myapp-staging-worker-service': { ...activeService('myapp-staging-worker-service', 0), runningCount: 1 },
|
|
470
|
+
},
|
|
471
|
+
db,
|
|
472
|
+
onCommand: async (command) => {
|
|
473
|
+
if (command.constructor.name === 'StartDBInstanceCommand') order.push('start-db');
|
|
474
|
+
if (command.constructor.name === 'UpdateServiceCommand') order.push('restore-ecs');
|
|
475
|
+
},
|
|
476
|
+
});
|
|
477
|
+
// RDS reports available as soon as the start lands.
|
|
478
|
+
rdsClient.send.mockImplementation(async (command) => {
|
|
479
|
+
const name = command.constructor.name;
|
|
480
|
+
if (name === 'DescribeDBInstancesCommand') {
|
|
481
|
+
if (db.instance.Status === 'starting') db.instance.Status = 'available';
|
|
482
|
+
return { DBInstances: [db.instance] };
|
|
483
|
+
}
|
|
484
|
+
if (name === 'StartDBInstanceCommand') {
|
|
485
|
+
order.push('start-db');
|
|
486
|
+
db.instance.Status = 'starting';
|
|
487
|
+
return {};
|
|
488
|
+
}
|
|
489
|
+
if (name === 'DescribeDBClustersCommand') throw Object.assign(new Error('x'), { name: 'DBClusterNotFoundFault' });
|
|
490
|
+
throw new Error(`unexpected RDS command: ${name}`);
|
|
491
|
+
});
|
|
492
|
+
const updates = [];
|
|
493
|
+
ecsClient.send.mockImplementation(async (command) => {
|
|
494
|
+
const name = command.constructor.name;
|
|
495
|
+
if (name === 'DescribeServicesCommand') {
|
|
496
|
+
return { services: (command.input.services || []).map((serviceName) => ({
|
|
497
|
+
serviceName, status: 'ACTIVE', desiredCount: 0, runningCount: serviceName.endsWith('worker-service') ? 1 : 2,
|
|
498
|
+
})) };
|
|
499
|
+
}
|
|
500
|
+
if (name === 'UpdateServiceCommand') {
|
|
501
|
+
order.push('restore-ecs');
|
|
502
|
+
updates.push({ service: command.input.service, desiredCount: command.input.desiredCount });
|
|
503
|
+
return {};
|
|
504
|
+
}
|
|
505
|
+
throw new Error(`unexpected ECS command: ${name}`);
|
|
506
|
+
});
|
|
507
|
+
|
|
508
|
+
const result = await runWake(wakeOptions(dir, { ecsClient, rdsClient }));
|
|
509
|
+
expect(result.ok).toBe(true);
|
|
510
|
+
expect(result.dbStarted).toBe(true);
|
|
511
|
+
expect(result.ecsRestored).toBe(2);
|
|
512
|
+
expect(result.waited).toBe(true);
|
|
513
|
+
expect(order[0]).toBe('start-db');
|
|
514
|
+
expect(updates).toContainEqual({ service: 'myapp-staging-service', desiredCount: 2 });
|
|
515
|
+
expect(updates).toContainEqual({ service: 'myapp-staging-worker-service', desiredCount: 1 });
|
|
516
|
+
expect(readSleepState(dir)).toEqual({});
|
|
517
|
+
expect(trackEvent).toHaveBeenCalledWith('wake_run', expect.objectContaining({
|
|
518
|
+
env_kind: 'named', ecs_restored: 2, db_started: true, waited: true, success: true,
|
|
519
|
+
}));
|
|
520
|
+
});
|
|
521
|
+
|
|
522
|
+
it('defaults to 1/1 without ledger state and skips waiting with --no-wait', async () => {
|
|
523
|
+
const dir = makeTmp();
|
|
524
|
+
const updates = [];
|
|
525
|
+
const ecsClient = {
|
|
526
|
+
send: vi.fn(async (command) => {
|
|
527
|
+
if (command.constructor.name === 'DescribeServicesCommand') {
|
|
528
|
+
return { services: (command.input.services || []).map((serviceName) => ({ serviceName, status: 'ACTIVE', desiredCount: 0, runningCount: 0 })) };
|
|
529
|
+
}
|
|
530
|
+
updates.push({ service: command.input.service, desiredCount: command.input.desiredCount });
|
|
531
|
+
return {};
|
|
532
|
+
}),
|
|
533
|
+
};
|
|
534
|
+
const rdsClient = {
|
|
535
|
+
send: vi.fn(async (command) => {
|
|
536
|
+
if (command.constructor.name === 'DescribeDBInstancesCommand') {
|
|
537
|
+
return { DBInstances: [{ Engine: 'postgres', Status: 'available' }] };
|
|
538
|
+
}
|
|
539
|
+
throw new Error(`unexpected RDS command: ${command.constructor.name}`);
|
|
540
|
+
}),
|
|
541
|
+
};
|
|
542
|
+
const result = await runWake(wakeOptions(dir, { ecsClient, rdsClient, noWait: true }));
|
|
543
|
+
expect(result.ok).toBe(true);
|
|
544
|
+
expect(result.waited).toBe(false);
|
|
545
|
+
expect(result.dbStarted).toBe(false);
|
|
546
|
+
expect(updates).toContainEqual({ service: 'myapp-staging-service', desiredCount: 1 });
|
|
547
|
+
expect(updates).toContainEqual({ service: 'myapp-staging-worker-service', desiredCount: 1 });
|
|
548
|
+
// No polling: two discovery Describes (app + worker), then UpdateService only.
|
|
549
|
+
expect(ecsClient.send.mock.calls.filter(([command]) => command.constructor.name === 'DescribeServicesCommand')).toHaveLength(2);
|
|
550
|
+
});
|
|
551
|
+
|
|
552
|
+
it('fails on RDS wake timeout and keeps the ledger for retry', async () => {
|
|
553
|
+
const dir = makeTmp();
|
|
554
|
+
writeSleepState(dir, { staging: { env: 'staging', services: { app: 1, worker: 0 } } });
|
|
555
|
+
const ecsClient = { send: vi.fn(async () => ({ services: [] })) };
|
|
556
|
+
const rdsClient = {
|
|
557
|
+
send: vi.fn(async (command) => {
|
|
558
|
+
if (command.constructor.name === 'DescribeDBInstancesCommand') {
|
|
559
|
+
return { DBInstances: [{ Engine: 'postgres', Status: 'starting' }] };
|
|
560
|
+
}
|
|
561
|
+
if (command.constructor.name === 'StartDBInstanceCommand') return {};
|
|
562
|
+
throw new Error(`unexpected: ${command.constructor.name}`);
|
|
563
|
+
}),
|
|
564
|
+
};
|
|
565
|
+
// First call: stopped → start; subsequent polls: starting forever.
|
|
566
|
+
let calls = 0;
|
|
567
|
+
const inner = rdsClient.send.getMockImplementation();
|
|
568
|
+
rdsClient.send.mockImplementation(async (command) => {
|
|
569
|
+
if (command.constructor.name === 'DescribeDBInstancesCommand' && calls++ === 0) {
|
|
570
|
+
return { DBInstances: [{ Engine: 'postgres', Status: 'stopped' }] };
|
|
571
|
+
}
|
|
572
|
+
return inner(command);
|
|
573
|
+
});
|
|
574
|
+
const result = await runWake(wakeOptions(dir, {
|
|
575
|
+
ecsClient,
|
|
576
|
+
rdsClient,
|
|
577
|
+
timeoutMs: 0,
|
|
578
|
+
sleepFn: async () => {},
|
|
579
|
+
nowFn: (() => { let now = 1000; return () => now++; })(),
|
|
580
|
+
}));
|
|
581
|
+
expect(result.ok).toBe(false);
|
|
582
|
+
expect(result.reason).toBe('rds-wake-timeout');
|
|
583
|
+
expect(readSleepState(dir).staging).toBeTruthy();
|
|
584
|
+
});
|
|
585
|
+
|
|
586
|
+
it('warns when the 7-day window elapsed', async () => {
|
|
587
|
+
const dir = makeTmp();
|
|
588
|
+
writeSleepState(dir, {
|
|
589
|
+
staging: {
|
|
590
|
+
env: 'staging',
|
|
591
|
+
autoRestartAt: new Date(Date.now() - 1000).toISOString(),
|
|
592
|
+
services: { app: 1, worker: 0 },
|
|
593
|
+
},
|
|
594
|
+
});
|
|
595
|
+
const ecsClient = {
|
|
596
|
+
send: vi.fn(async (command) => {
|
|
597
|
+
if (command.constructor.name === 'DescribeServicesCommand') {
|
|
598
|
+
return { services: [{ serviceName: command.input.services[0], status: 'ACTIVE', desiredCount: 0, runningCount: 1 }] };
|
|
599
|
+
}
|
|
600
|
+
return {};
|
|
601
|
+
}),
|
|
602
|
+
};
|
|
603
|
+
const rdsClient = {
|
|
604
|
+
send: vi.fn(async (command) => {
|
|
605
|
+
if (command.constructor.name === 'DescribeDBInstancesCommand') {
|
|
606
|
+
return { DBInstances: [{ Engine: 'postgres', Status: 'available' }] };
|
|
607
|
+
}
|
|
608
|
+
throw Object.assign(new Error('x'), { name: 'DBClusterNotFoundFault' });
|
|
609
|
+
}),
|
|
610
|
+
};
|
|
611
|
+
await runWake(wakeOptions(dir, { ecsClient, rdsClient, noWait: true }));
|
|
612
|
+
const output = logSpy.mock.calls.map((call) => String(call[0])).join('\n');
|
|
613
|
+
expect(output).toContain('7-day sleep window has elapsed');
|
|
614
|
+
});
|
|
615
|
+
});
|
|
616
|
+
|
|
617
|
+
describe('sleep-targets: cron schedule discovery', () => {
|
|
618
|
+
it('resolves the schedule name from cron.tf with the app prefix', () => {
|
|
619
|
+
const dir = makeTmp();
|
|
620
|
+
fs.mkdirSync(path.join(dir, 'terraform'), { recursive: true });
|
|
621
|
+
fs.writeFileSync(
|
|
622
|
+
path.join(dir, 'terraform', 'cron.tf'),
|
|
623
|
+
'resource "aws_scheduler_schedule" "cron" {\n name = "${local.app_name}-cron-nightly-cleanup"\n}\n'
|
|
624
|
+
);
|
|
625
|
+
expect(readCronScheduleName(dir, 'myapp-staging')).toBe('myapp-staging-cron-nightly-cleanup');
|
|
626
|
+
});
|
|
627
|
+
|
|
628
|
+
it('returns null when cron.tf is missing or hand-edited', () => {
|
|
629
|
+
expect(readCronScheduleName(makeTmp(), 'myapp')).toBeNull();
|
|
630
|
+
const dir = makeTmp();
|
|
631
|
+
fs.mkdirSync(path.join(dir, 'terraform'), { recursive: true });
|
|
632
|
+
fs.writeFileSync(path.join(dir, 'terraform', 'cron.tf'), '# nothing scheduled here\n');
|
|
633
|
+
expect(readCronScheduleName(dir, 'myapp')).toBeNull();
|
|
634
|
+
});
|
|
635
|
+
});
|
|
636
|
+
|
|
637
|
+
describe('sleep-targets: scheduler state', () => {
|
|
638
|
+
const scheduleDoc = {
|
|
639
|
+
Name: 'myapp-staging-cron-nightly',
|
|
640
|
+
Arn: 'arn:aws:scheduler:us-east-2:123456789012:schedule/default/myapp-staging-cron-nightly',
|
|
641
|
+
CreationDate: '2026-01-01T00:00:00Z',
|
|
642
|
+
LastModificationDate: '2026-01-02T00:00:00Z',
|
|
643
|
+
State: 'ENABLED',
|
|
644
|
+
ScheduleExpression: 'rate(1 hour)',
|
|
645
|
+
ScheduleExpressionTimezone: 'UTC',
|
|
646
|
+
FlexibleTimeWindow: { Mode: 'OFF' },
|
|
647
|
+
Target: { Arn: 'arn:aws:ecs:cluster', RoleArn: 'arn:aws:iam:role' },
|
|
648
|
+
};
|
|
649
|
+
|
|
650
|
+
it('passes the fetched document back with only State flipped', () => {
|
|
651
|
+
const seen = [];
|
|
652
|
+
const run = vi.fn((cmd, args) => {
|
|
653
|
+
seen.push(args);
|
|
654
|
+
if (args[1] === 'get-schedule') return { status: 0, stdout: JSON.stringify(scheduleDoc), stderr: '' };
|
|
655
|
+
return { status: 0, stdout: '{}', stderr: '' };
|
|
656
|
+
});
|
|
657
|
+
expect(setSchedulerState({ name: scheduleDoc.Name, enabled: false, region: 'us-east-2', run })).toEqual({ ok: true });
|
|
658
|
+
const updateArgs = seen.find((args) => args[1] === 'update-schedule');
|
|
659
|
+
const payload = JSON.parse(updateArgs[updateArgs.indexOf('--cli-input-json') + 1]);
|
|
660
|
+
expect(payload).toMatchObject({
|
|
661
|
+
Name: scheduleDoc.Name,
|
|
662
|
+
State: 'DISABLED',
|
|
663
|
+
ScheduleExpression: 'rate(1 hour)',
|
|
664
|
+
ScheduleExpressionTimezone: 'UTC',
|
|
665
|
+
FlexibleTimeWindow: { Mode: 'OFF' },
|
|
666
|
+
Target: scheduleDoc.Target,
|
|
667
|
+
});
|
|
668
|
+
expect(payload).not.toHaveProperty('Arn');
|
|
669
|
+
expect(payload).not.toHaveProperty('CreationDate');
|
|
670
|
+
expect(payload).not.toHaveProperty('LastModificationDate');
|
|
671
|
+
});
|
|
672
|
+
|
|
673
|
+
it('skips the update when already in the desired state', () => {
|
|
674
|
+
const run = vi.fn(() => ({
|
|
675
|
+
status: 0, stdout: JSON.stringify({ ...scheduleDoc, State: 'DISABLED' }), stderr: '',
|
|
676
|
+
}));
|
|
677
|
+
expect(setSchedulerState({ name: scheduleDoc.Name, enabled: false, region: 'us-east-2', run }))
|
|
678
|
+
.toEqual({ ok: true, skipped: 'already' });
|
|
679
|
+
expect(run).toHaveBeenCalledTimes(1);
|
|
680
|
+
});
|
|
681
|
+
|
|
682
|
+
it('reports undeployed schedules and a missing CLI', () => {
|
|
683
|
+
const notFound = () => ({ status: 254, stdout: '', stderr: 'An error occurred (ResourceNotFoundException) when calling GetSchedule' });
|
|
684
|
+
expect(setSchedulerState({ name: 'x', enabled: false, region: 'us-east-2', run: notFound }).reason).toBe('not-deployed');
|
|
685
|
+
const noCli = () => ({ error: { code: 'ENOENT' } });
|
|
686
|
+
expect(setSchedulerState({ name: 'x', enabled: false, region: 'us-east-2', run: noCli }).reason).toBe('cli-missing');
|
|
687
|
+
});
|
|
688
|
+
});
|
|
689
|
+
|
|
690
|
+
describe('sleep-targets: worker scaling suspend/resume', () => {
|
|
691
|
+
it('suspends all three scaling dimensions when registered', () => {
|
|
692
|
+
const seen = [];
|
|
693
|
+
const run = vi.fn((cmd, args) => {
|
|
694
|
+
seen.push(args);
|
|
695
|
+
if (args[1] === 'describe-scalable-targets') {
|
|
696
|
+
return { status: 0, stdout: JSON.stringify({ ScalableTargets: [{ SuspendedState: {} }] }), stderr: '' };
|
|
697
|
+
}
|
|
698
|
+
return { status: 0, stdout: '{}', stderr: '' };
|
|
699
|
+
});
|
|
700
|
+
const result = setWorkerScalingSuspended({
|
|
701
|
+
cluster: 'myapp-staging-cluster', service: 'myapp-staging-worker-service', suspended: true, region: 'us-east-2', run,
|
|
702
|
+
});
|
|
703
|
+
expect(result).toEqual({ ok: true });
|
|
704
|
+
const register = seen.find((args) => args[1] === 'register-scalable-target');
|
|
705
|
+
expect(register).toContain('service/myapp-staging-cluster/myapp-staging-worker-service');
|
|
706
|
+
const flag = register[register.indexOf('--suspended-state') + 1];
|
|
707
|
+
expect(flag).toContain('DynamicScalingInSuspended=true');
|
|
708
|
+
expect(flag).toContain('DynamicScalingOutSuspended=true');
|
|
709
|
+
expect(flag).toContain('ScheduledScalingSuspended=true');
|
|
710
|
+
});
|
|
711
|
+
|
|
712
|
+
it('skips unregistered targets and already-matching state', () => {
|
|
713
|
+
const empty = vi.fn(() => ({ status: 0, stdout: JSON.stringify({ ScalableTargets: [] }), stderr: '' }));
|
|
714
|
+
expect(setWorkerScalingSuspended({ cluster: 'c', service: 's', suspended: true, region: 'us-east-2', run: empty }).reason)
|
|
715
|
+
.toBe('not-registered');
|
|
716
|
+
expect(empty).toHaveBeenCalledTimes(1);
|
|
717
|
+
const already = vi.fn(() => ({
|
|
718
|
+
status: 0,
|
|
719
|
+
stdout: JSON.stringify({ ScalableTargets: [{ SuspendedState: { DynamicScalingInSuspended: true, DynamicScalingOutSuspended: true, ScheduledScalingSuspended: true } }] }),
|
|
720
|
+
stderr: '',
|
|
721
|
+
}));
|
|
722
|
+
expect(setWorkerScalingSuspended({ cluster: 'c', service: 's', suspended: true, region: 'us-east-2', run: already }))
|
|
723
|
+
.toEqual({ ok: true, skipped: 'already' });
|
|
724
|
+
expect(already).toHaveBeenCalledTimes(1);
|
|
725
|
+
});
|
|
726
|
+
});
|
|
727
|
+
|
|
728
|
+
describe('runSleep: cron pause, scaling suspend, and cache note', () => {
|
|
729
|
+
function baseOptions(dir, overrides = {}) {
|
|
730
|
+
return {
|
|
731
|
+
cwd: dir,
|
|
732
|
+
projectName: 'myapp',
|
|
733
|
+
region: 'us-east-2',
|
|
734
|
+
env: 'staging',
|
|
735
|
+
nowMs: Date.UTC(2026, 0, 1, 12, 0, 0),
|
|
736
|
+
...overrides,
|
|
737
|
+
};
|
|
738
|
+
}
|
|
739
|
+
|
|
740
|
+
function writeCronTf(dir, slug = 'nightly') {
|
|
741
|
+
fs.mkdirSync(path.join(dir, 'terraform'), { recursive: true });
|
|
742
|
+
fs.writeFileSync(
|
|
743
|
+
path.join(dir, 'terraform', 'cron.tf'),
|
|
744
|
+
`resource "aws_scheduler_schedule" "cron" {\n name = "\${local.app_name}-cron-${slug}"\n}\n`
|
|
745
|
+
);
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
it('pauses the cron schedule and suspends worker scaling', async () => {
|
|
749
|
+
const dir = makeTmp();
|
|
750
|
+
writeCronTf(dir);
|
|
751
|
+
fs.writeFileSync(path.join(dir, 'terraform', 'sqs.tf'), '# queue\n');
|
|
752
|
+
fs.writeFileSync(path.join(dir, 'terraform', 'worker.tf'), '# worker\n');
|
|
753
|
+
const { ecsClient, rdsClient } = mockClients({
|
|
754
|
+
ecs: {
|
|
755
|
+
'myapp-staging-service': activeService('myapp-staging-service', 1),
|
|
756
|
+
'myapp-staging-worker-service': activeService('myapp-staging-worker-service', 1),
|
|
757
|
+
},
|
|
758
|
+
});
|
|
759
|
+
const seen = [];
|
|
760
|
+
const spawnSyncImpl = vi.fn((cmd, args) => {
|
|
761
|
+
seen.push(args);
|
|
762
|
+
if (args[1] === 'get-schedule') {
|
|
763
|
+
return {
|
|
764
|
+
status: 0,
|
|
765
|
+
stdout: JSON.stringify({
|
|
766
|
+
State: 'ENABLED',
|
|
767
|
+
ScheduleExpression: 'rate(1 hour)',
|
|
768
|
+
ScheduleExpressionTimezone: 'UTC',
|
|
769
|
+
FlexibleTimeWindow: { Mode: 'OFF' },
|
|
770
|
+
Target: { Arn: 'a', RoleArn: 'r' },
|
|
771
|
+
}),
|
|
772
|
+
stderr: '',
|
|
773
|
+
};
|
|
774
|
+
}
|
|
775
|
+
if (args[1] === 'describe-scalable-targets') {
|
|
776
|
+
return { status: 0, stdout: JSON.stringify({ ScalableTargets: [{ SuspendedState: {} }] }), stderr: '' };
|
|
777
|
+
}
|
|
778
|
+
return { status: 0, stdout: '{}', stderr: '' };
|
|
779
|
+
});
|
|
780
|
+
const result = await runSleep(baseOptions(dir, { ecsClient, rdsClient, skipDb: true, spawnSyncImpl }));
|
|
781
|
+
expect(result.ok).toBe(true);
|
|
782
|
+
expect(result.cronPaused).toBe(true);
|
|
783
|
+
expect(result.scalingSuspended).toBe(true);
|
|
784
|
+
const getArgs = seen.find((args) => args[1] === 'get-schedule');
|
|
785
|
+
expect(getArgs).toContain('myapp-staging-cron-nightly');
|
|
786
|
+
expect(getArgs).toContain('us-east-2');
|
|
787
|
+
const updateArgs = seen.find((args) => args[1] === 'update-schedule');
|
|
788
|
+
expect(JSON.parse(updateArgs[updateArgs.indexOf('--cli-input-json') + 1])).toMatchObject({ State: 'DISABLED' });
|
|
789
|
+
const registerArgs = seen.find((args) => args[1] === 'register-scalable-target');
|
|
790
|
+
expect(registerArgs[registerArgs.indexOf('--suspended-state') + 1]).toContain('DynamicScalingOutSuspended=true');
|
|
791
|
+
const output = stripVTControlCharacters(logSpy.mock.calls.map((call) => String(call[0])).join('\n'));
|
|
792
|
+
expect(output).toContain('myapp-staging-cron-nightly paused');
|
|
793
|
+
expect(output).toContain('worker auto-scaling suspended');
|
|
794
|
+
expect(trackEvent).toHaveBeenCalledWith('sleep_run', expect.objectContaining({
|
|
795
|
+
cron_paused: true, scaling_suspended: true, success: true,
|
|
796
|
+
}));
|
|
797
|
+
});
|
|
798
|
+
|
|
799
|
+
it('skips gracefully when the schedule is undeployed and scaling is unregistered', async () => {
|
|
800
|
+
const dir = makeTmp();
|
|
801
|
+
writeCronTf(dir);
|
|
802
|
+
fs.writeFileSync(path.join(dir, 'terraform', 'sqs.tf'), '# queue\n');
|
|
803
|
+
fs.writeFileSync(path.join(dir, 'terraform', 'worker.tf'), '# worker\n');
|
|
804
|
+
const { ecsClient, rdsClient } = mockClients({
|
|
805
|
+
ecs: { 'myapp-staging-service': activeService('myapp-staging-service', 1) },
|
|
806
|
+
});
|
|
807
|
+
const spawnSyncImpl = vi.fn((cmd, args) => {
|
|
808
|
+
if (args[1] === 'get-schedule') return { status: 254, stdout: '', stderr: 'ResourceNotFoundException' };
|
|
809
|
+
if (args[1] === 'describe-scalable-targets') return { status: 0, stdout: JSON.stringify({ ScalableTargets: [] }), stderr: '' };
|
|
810
|
+
return { status: 0, stdout: '{}', stderr: '' };
|
|
811
|
+
});
|
|
812
|
+
const result = await runSleep(baseOptions(dir, { ecsClient, rdsClient, skipDb: true, spawnSyncImpl }));
|
|
813
|
+
expect(result.ok).toBe(true);
|
|
814
|
+
expect(result.cronPaused).toBe(false);
|
|
815
|
+
expect(result.scalingSuspended).toBe(false);
|
|
816
|
+
const output = logSpy.mock.calls.map((call) => String(call[0])).join('\n');
|
|
817
|
+
expect(output).toContain('not deployed yet, skipped');
|
|
818
|
+
expect(output).toContain('not registered, skipped');
|
|
819
|
+
});
|
|
820
|
+
|
|
821
|
+
it('notes unpausable Valkey billing when redis.tf exists', async () => {
|
|
822
|
+
const dir = makeTmp();
|
|
823
|
+
fs.mkdirSync(path.join(dir, 'terraform'), { recursive: true });
|
|
824
|
+
fs.writeFileSync(path.join(dir, 'terraform', 'redis.tf'), '# valkey\n');
|
|
825
|
+
const { ecsClient, rdsClient } = mockClients({
|
|
826
|
+
ecs: { 'myapp-staging-service': activeService('myapp-staging-service', 1) },
|
|
827
|
+
});
|
|
828
|
+
const result = await runSleep(baseOptions(dir, { ecsClient, rdsClient, skipDb: true }));
|
|
829
|
+
expect(result.ok).toBe(true);
|
|
830
|
+
const output = logSpy.mock.calls.map((call) => String(call[0])).join('\n');
|
|
831
|
+
expect(output).toContain('Valkey keeps billing (~$9.49/mo)');
|
|
832
|
+
});
|
|
833
|
+
|
|
834
|
+
it('stays silent about cron, scaling, and cache when unconfigured', async () => {
|
|
835
|
+
const dir = makeTmp();
|
|
836
|
+
const { ecsClient, rdsClient } = mockClients({
|
|
837
|
+
ecs: { 'myapp-staging-service': activeService('myapp-staging-service', 1) },
|
|
838
|
+
});
|
|
839
|
+
const spawnSyncImpl = vi.fn(() => ({ status: 0, stdout: '{}', stderr: '' }));
|
|
840
|
+
const result = await runSleep(baseOptions(dir, { ecsClient, rdsClient, skipDb: true, spawnSyncImpl }));
|
|
841
|
+
expect(result.ok).toBe(true);
|
|
842
|
+
expect(spawnSyncImpl).not.toHaveBeenCalled();
|
|
843
|
+
const output = logSpy.mock.calls.map((call) => String(call[0])).join('\n');
|
|
844
|
+
expect(output).not.toContain('cron:');
|
|
845
|
+
expect(output).not.toContain('scaling:');
|
|
846
|
+
expect(output).not.toContain('cache:');
|
|
847
|
+
});
|
|
848
|
+
});
|
|
849
|
+
|
|
850
|
+
describe('runWake: cron resume and scaling resume', () => {
|
|
851
|
+
it('resumes the cron schedule and worker scaling', async () => {
|
|
852
|
+
const dir = makeTmp();
|
|
853
|
+
fs.mkdirSync(path.join(dir, 'terraform'), { recursive: true });
|
|
854
|
+
fs.writeFileSync(
|
|
855
|
+
path.join(dir, 'terraform', 'cron.tf'),
|
|
856
|
+
'resource "aws_scheduler_schedule" "cron" {\n name = "${local.app_name}-cron-nightly"\n}\n'
|
|
857
|
+
);
|
|
858
|
+
fs.writeFileSync(path.join(dir, 'terraform', 'sqs.tf'), '# queue\n');
|
|
859
|
+
fs.writeFileSync(path.join(dir, 'terraform', 'worker.tf'), '# worker\n');
|
|
860
|
+
writeSleepState(dir, {
|
|
861
|
+
staging: {
|
|
862
|
+
env: 'staging',
|
|
863
|
+
sleptAt: new Date().toISOString(),
|
|
864
|
+
autoRestartAt: new Date(Date.now() + 3600_000).toISOString(),
|
|
865
|
+
services: { app: 1, worker: 1 },
|
|
866
|
+
},
|
|
867
|
+
});
|
|
868
|
+
const { ecsClient, rdsClient } = mockClients({
|
|
869
|
+
ecs: {
|
|
870
|
+
'myapp-staging-service': activeService('myapp-staging-service', 0),
|
|
871
|
+
'myapp-staging-worker-service': activeService('myapp-staging-worker-service', 0),
|
|
872
|
+
},
|
|
873
|
+
});
|
|
874
|
+
const seen = [];
|
|
875
|
+
const spawnSyncImpl = vi.fn((cmd, args) => {
|
|
876
|
+
seen.push(args);
|
|
877
|
+
if (args[1] === 'get-schedule') {
|
|
878
|
+
return {
|
|
879
|
+
status: 0,
|
|
880
|
+
stdout: JSON.stringify({
|
|
881
|
+
State: 'DISABLED',
|
|
882
|
+
ScheduleExpression: 'rate(1 hour)',
|
|
883
|
+
ScheduleExpressionTimezone: 'UTC',
|
|
884
|
+
FlexibleTimeWindow: { Mode: 'OFF' },
|
|
885
|
+
Target: { Arn: 'a', RoleArn: 'r' },
|
|
886
|
+
}),
|
|
887
|
+
stderr: '',
|
|
888
|
+
};
|
|
889
|
+
}
|
|
890
|
+
if (args[1] === 'describe-scalable-targets') {
|
|
891
|
+
return {
|
|
892
|
+
status: 0,
|
|
893
|
+
stdout: JSON.stringify({ ScalableTargets: [{ SuspendedState: { DynamicScalingInSuspended: true, DynamicScalingOutSuspended: true, ScheduledScalingSuspended: true } }] }),
|
|
894
|
+
stderr: '',
|
|
895
|
+
};
|
|
896
|
+
}
|
|
897
|
+
return { status: 0, stdout: '{}', stderr: '' };
|
|
898
|
+
});
|
|
899
|
+
const result = await runWake({
|
|
900
|
+
cwd: dir, projectName: 'myapp', region: 'us-east-2', env: 'staging',
|
|
901
|
+
noWait: true, pollIntervalMs: 1, timeoutMs: 1000,
|
|
902
|
+
ecsClient, rdsClient, skipDb: true, spawnSyncImpl,
|
|
903
|
+
});
|
|
904
|
+
expect(result.ok).toBe(true);
|
|
905
|
+
expect(result.cronResumed).toBe(true);
|
|
906
|
+
expect(result.scalingResumed).toBe(true);
|
|
907
|
+
const updateArgs = seen.find((args) => args[1] === 'update-schedule');
|
|
908
|
+
expect(JSON.parse(updateArgs[updateArgs.indexOf('--cli-input-json') + 1])).toMatchObject({ State: 'ENABLED' });
|
|
909
|
+
const registerArgs = seen.find((args) => args[1] === 'register-scalable-target');
|
|
910
|
+
expect(registerArgs[registerArgs.indexOf('--suspended-state') + 1]).toContain('DynamicScalingOutSuspended=false');
|
|
911
|
+
const output = stripVTControlCharacters(logSpy.mock.calls.map((call) => String(call[0])).join('\n'));
|
|
912
|
+
expect(output).toContain('myapp-staging-cron-nightly resumed');
|
|
913
|
+
expect(output).toContain('worker auto-scaling resumed');
|
|
914
|
+
expect(trackEvent).toHaveBeenCalledWith('wake_run', expect.objectContaining({
|
|
915
|
+
cron_resumed: true, scaling_resumed: true, success: true,
|
|
916
|
+
}));
|
|
917
|
+
});
|
|
918
|
+
});
|
|
919
|
+
|
|
920
|
+
describe('runSleep on --target lambda projects', () => {
|
|
921
|
+
function lambdaDir() {
|
|
922
|
+
const dir = makeTmp();
|
|
923
|
+
fs.mkdirSync(path.join(dir, 'terraform'), { recursive: true });
|
|
924
|
+
fs.writeFileSync(
|
|
925
|
+
path.join(dir, 'terraform', 'main.tf'),
|
|
926
|
+
'locals {\n app_name = "myapp${local.env_suffix}"\n}\nresource "aws_lambda_function" "app" {}\n'
|
|
927
|
+
);
|
|
928
|
+
return dir;
|
|
929
|
+
}
|
|
930
|
+
|
|
931
|
+
it('stops the database without touching ECS and ledgers zero replicas', async () => {
|
|
932
|
+
const dir = lambdaDir();
|
|
933
|
+
const { ecsClient, rdsClient, seen } = mockClients({
|
|
934
|
+
ecs: { 'myapp-staging-service': activeService('myapp-staging-service', 1) },
|
|
935
|
+
db: { instance: { Engine: 'postgres', Status: 'available', DBName: 'db' } },
|
|
936
|
+
});
|
|
937
|
+
const result = await runSleep({
|
|
938
|
+
cwd: dir, projectName: 'myapp', region: 'us-east-2', env: 'staging',
|
|
939
|
+
nowMs: Date.UTC(2026, 0, 1, 12, 0, 0), ecsClient, rdsClient,
|
|
940
|
+
});
|
|
941
|
+
expect(result.ok).toBe(true);
|
|
942
|
+
expect(result.ecsScaled).toBe(0);
|
|
943
|
+
expect(result.dbStopped).toBe(true);
|
|
944
|
+
expect(seen).not.toContain('DescribeServicesCommand');
|
|
945
|
+
expect(seen).not.toContain('UpdateServiceCommand');
|
|
946
|
+
expect(seen).toContain('StopDBInstanceCommand');
|
|
947
|
+
expect(readSleepState(dir).staging).toMatchObject({ services: { app: 0, worker: 0 } });
|
|
948
|
+
});
|
|
949
|
+
|
|
950
|
+
it('reports nothing to sleep when no database exists', async () => {
|
|
951
|
+
const dir = lambdaDir();
|
|
952
|
+
const { ecsClient, rdsClient } = mockClients({});
|
|
953
|
+
const result = await runSleep({
|
|
954
|
+
cwd: dir, projectName: 'myapp', region: 'us-east-2', env: 'staging', ecsClient, rdsClient,
|
|
955
|
+
});
|
|
956
|
+
expect(result).toMatchObject({ ok: false, reason: 'nothing-to-sleep' });
|
|
957
|
+
});
|
|
958
|
+
});
|
|
959
|
+
|
|
960
|
+
describe('runWake on --target lambda projects', () => {
|
|
961
|
+
function lambdaDir() {
|
|
962
|
+
const dir = makeTmp();
|
|
963
|
+
fs.mkdirSync(path.join(dir, 'terraform'), { recursive: true });
|
|
964
|
+
fs.writeFileSync(
|
|
965
|
+
path.join(dir, 'terraform', 'main.tf'),
|
|
966
|
+
'locals {\n app_name = "myapp${local.env_suffix}"\n}\nresource "aws_lambda_function" "app" {}\n'
|
|
967
|
+
);
|
|
968
|
+
return dir;
|
|
969
|
+
}
|
|
970
|
+
|
|
971
|
+
it('starts the database without restoring ECS services', async () => {
|
|
972
|
+
const dir = lambdaDir();
|
|
973
|
+
writeSleepState(dir, {
|
|
974
|
+
staging: {
|
|
975
|
+
env: 'staging',
|
|
976
|
+
sleptAt: new Date(Date.UTC(2026, 0, 1)).toISOString(),
|
|
977
|
+
autoRestartAt: new Date(Date.UTC(2026, 0, 8)).toISOString(),
|
|
978
|
+
services: { app: 0, worker: 0 },
|
|
979
|
+
dbId: 'myapp-staging-db',
|
|
980
|
+
dbKind: 'instance',
|
|
981
|
+
},
|
|
982
|
+
});
|
|
983
|
+
const { ecsClient, rdsClient, seen } = mockClients({
|
|
984
|
+
ecs: { 'myapp-staging-service': activeService('myapp-staging-service', 0) },
|
|
985
|
+
db: { instance: { Engine: 'postgres', Status: 'stopped', DBName: 'db' } },
|
|
986
|
+
});
|
|
987
|
+
const result = await runWake({
|
|
988
|
+
cwd: dir, projectName: 'myapp', region: 'us-east-2', env: 'staging',
|
|
989
|
+
noWait: true, ecsClient, rdsClient,
|
|
990
|
+
});
|
|
991
|
+
expect(result.ok).toBe(true);
|
|
992
|
+
expect(result.dbStarted).toBe(true);
|
|
993
|
+
expect(result.ecsRestored).toBe(0);
|
|
994
|
+
expect(seen).not.toContain('UpdateServiceCommand');
|
|
995
|
+
expect(seen).toContain('StartDBInstanceCommand');
|
|
996
|
+
expect(readSleepState(dir).staging).toBeUndefined();
|
|
997
|
+
});
|
|
998
|
+
});
|