Files
sencho/backend/src/__tests__/stack-op-lock-service.test.ts
T
Anso 5f1baa7522 fix: harden deploy/update concurrency and node-targeting safety (#1390)
* fix: harden deploy/update concurrency and node-targeting safety

Release stabilization for deploy/update operational safety.

Per-stack operation locking is now global. Background lifecycle paths
(scheduler auto stop/down/start/backup/update, webhook execute, Git source
auto-deploy, image auto-update, label bulk actions, fleet snapshot redeploy,
and mesh redeploy) acquire the per-node, per-stack lock through a new
StackOpLockService.runExclusive helper and skip rather than race a manual
deploy/update/rollback/backup on the same stack and node. Skips surface
honestly (a failed scheduled run, a recorded webhook failure, a per-stack
batch result, or a thrown error) instead of a silent no-op.

Update readiness and policy-bypass now run against the node captured when the
dialog opened, not the live active node, so switching nodes while a dialog is
open cannot retarget the update or the bypass retry.

Rollback readiness no longer presents a moving-tag or unpinned image as a ready
image revert. Restoring files does not revert a moving tag, so those stacks
read as partial, and the rollback success message states that the compose and
env files were restored.

* fix: lock blueprint reconcile against manual ops and correct rollback wording

Follow-up to the deploy/update safety hardening, closing two more gaps from a
verification pass.

BlueprintService.deployLocal and withdrawLocal called ComposeService directly,
so blueprint reconciliation could race a manual deploy/update/rollback/backup on
an owned stack. Both now run their compose lifecycle call through
StackOpLockService.runExclusive and skip (recorded as a failed reconcile,
retried on the next cycle) on conflict. The withdraw holds the lock across both
the compose down and the directory delete so neither races a manual operation.

The runtime rollback messages overstated recovery: a rollback restores the
compose and env files and recreates containers, but does not revert an image
behind a moving tag. The auto-rollback deploy-progress output, the recovery
panel and chip, the failure toasts, and the manual rollback route message now
state that the compose and env files were restored, with the matching OpenAPI
example and atomic-deployments doc updated.

* fix: acquire stack lock before blueprint deploy mutates compose and marker files

Local blueprint deploy wrote the compose and marker files and ran the policy
assert before acquiring the per-stack lock; the lock only wrapped the deploy
itself. A reconcile could therefore rewrite an owned stack's files while a
manual deploy/update/rollback/backup was running. The lock now wraps the whole
critical section (create, write compose, write marker, policy assert, deploy),
so on conflict nothing is written and the reconcile records a failed outcome.

Adds a test asserting a deploy under a held lock records failed, writes no
marker file, and leaves the manual lock untouched.

* fix: make remote blueprint apply atomic under the receiving node's stack lock

Remote blueprint deploy wrote the compose and marker files to the target node
via separate HTTP calls and only locked on the final deploy, so the file writes
could race a manual operation on that node. A node's operation lock is
process-local and cannot be held by the hub across HTTP calls, so the locked
create/write/deploy now runs on the receiving node.

The locked critical section is extracted into BlueprintService.applyLocalUnderLock
and exposed via POST /api/blueprints/apply-local. The hub posts the blueprint to
that endpoint in one call; the receiving node runs create + write compose+marker
+ deploy under its own per-stack lock. Older nodes without the route answer 404
and fall back to the legacy multi-call flow. The endpoint is gated by paid tier
and the same per-stack stack:edit and stack:deploy permissions as the
PUT-compose + deploy it bundles, validates the stack name, compose size, and
marker structure, and returns 409 on a lock conflict without writing anything.

Adds tests for the atomic single-call path, the 404 legacy fallback, the 409
lock-conflict mapping, the route validation and permission paths, and the
write-compose-then-marker-then-deploy ordering of the shared locked apply.

* fix(deps): bump undici to 7.28.0 to clear high-severity advisory

The frontend CI npm audit gate (--audit-level=high) failed on a transitive
undici 7.25.0 (a dev-only dependency via jsdom): TLS certificate validation
bypass (GHSA-vmh5-mc38-953g) and cross-user cache information disclosure
(GHSA-pr7r-676h-xcf6). Bumping undici within jsdom's existing ^7.25.0 range to
7.28.0 clears the high-severity advisory and unblocks the frontend job. Lockfile
only; no direct dependency or source change.
2026-06-18 13:38:19 -04:00

150 lines
5.5 KiB
TypeScript

/**
* Unit tests for StackOpLockService.
*
* The service is the in-memory mutex behind the 409 fast-fail for concurrent
* stack lifecycle operations. Each test resets the singleton via
* `resetForTests()` so state doesn't leak between cases.
*/
import { describe, it, expect, beforeEach } from 'vitest';
import { StackOpLockService, stackOpSkipMessage } from '../services/StackOpLockService';
beforeEach(() => {
StackOpLockService.resetForTests();
});
describe('StackOpLockService', () => {
it('returns a singleton instance', () => {
const a = StackOpLockService.getInstance();
const b = StackOpLockService.getInstance();
expect(a).toBe(b);
});
it('acquires a lock when the slot is empty', () => {
const svc = StackOpLockService.getInstance();
const result = svc.tryAcquire(1, 'web', 'deploy', 'admin');
expect(result.acquired).toBe(true);
expect(svc.size()).toBe(1);
});
it('returns acquired=false with the existing lock when already held', () => {
const svc = StackOpLockService.getInstance();
svc.tryAcquire(1, 'web', 'deploy', 'admin');
const result = svc.tryAcquire(1, 'web', 'restart', 'bob');
expect(result.acquired).toBe(false);
if (!result.acquired) {
expect(result.existing.action).toBe('deploy');
expect(result.existing.user).toBe('admin');
expect(typeof result.existing.startedAt).toBe('number');
}
});
it('different stacks on the same node lock independently', () => {
const svc = StackOpLockService.getInstance();
expect(svc.tryAcquire(1, 'web', 'deploy', 'admin').acquired).toBe(true);
expect(svc.tryAcquire(1, 'api', 'deploy', 'admin').acquired).toBe(true);
expect(svc.size()).toBe(2);
});
it('same stack name on different nodes locks independently', () => {
const svc = StackOpLockService.getInstance();
expect(svc.tryAcquire(1, 'web', 'deploy', 'admin').acquired).toBe(true);
expect(svc.tryAcquire(2, 'web', 'deploy', 'admin').acquired).toBe(true);
expect(svc.size()).toBe(2);
});
it('release frees the slot so the next caller acquires', () => {
const svc = StackOpLockService.getInstance();
svc.tryAcquire(1, 'web', 'deploy', 'admin');
svc.release(1, 'web');
expect(svc.size()).toBe(0);
expect(svc.tryAcquire(1, 'web', 'restart', 'bob').acquired).toBe(true);
});
it('release on an unheld key is a no-op', () => {
const svc = StackOpLockService.getInstance();
expect(() => svc.release(1, 'nope')).not.toThrow();
expect(svc.size()).toBe(0);
});
it('get returns the lock contents or undefined', () => {
const svc = StackOpLockService.getInstance();
expect(svc.get(1, 'web')).toBeUndefined();
svc.tryAcquire(1, 'web', 'update', 'eve');
const lock = svc.get(1, 'web');
expect(lock?.action).toBe('update');
expect(lock?.user).toBe('eve');
});
it('resetForTests clears all state and returns a fresh instance', () => {
const before = StackOpLockService.getInstance();
before.tryAcquire(1, 'web', 'deploy', 'admin');
StackOpLockService.resetForTests();
const after = StackOpLockService.getInstance();
expect(after).not.toBe(before);
expect(after.size()).toBe(0);
});
it('records the lock startedAt as a recent timestamp', () => {
const svc = StackOpLockService.getInstance();
const t0 = Date.now();
svc.tryAcquire(1, 'web', 'deploy', 'admin');
const lock = svc.get(1, 'web');
expect(lock).toBeDefined();
expect(lock!.startedAt).toBeGreaterThanOrEqual(t0);
expect(lock!.startedAt).toBeLessThanOrEqual(Date.now());
});
});
describe('StackOpLockService.runExclusive', () => {
it('runs fn and releases the lock when the slot is free', async () => {
const svc = StackOpLockService.getInstance();
const outcome = await svc.runExclusive(1, 'web', 'deploy', 'system', async () => 'done');
expect(outcome).toEqual({ ran: true, result: 'done' });
// Released after fn resolves, so a later op acquires.
expect(svc.size()).toBe(0);
});
it('holds the lock for the duration of fn, blocking a concurrent acquire', async () => {
const svc = StackOpLockService.getInstance();
let observed: ReturnType<typeof svc.tryAcquire> | null = null;
const outcome = await svc.runExclusive(1, 'web', 'update', 'system', async () => {
// A manual op attempting to acquire mid-operation must be rejected.
observed = svc.tryAcquire(1, 'web', 'deploy', 'admin');
return 42;
});
expect(outcome).toEqual({ ran: true, result: 42 });
expect(observed!.acquired).toBe(false);
});
it('skips (ran=false) and returns the holder when the lock is already held', async () => {
const svc = StackOpLockService.getInstance();
svc.tryAcquire(1, 'web', 'rollback', 'admin');
let called = false;
const outcome = await svc.runExclusive(1, 'web', 'deploy', 'system', async () => {
called = true;
return 'should not run';
});
expect(called).toBe(false);
expect(outcome.ran).toBe(false);
if (!outcome.ran) expect(outcome.existing.action).toBe('rollback');
});
it('releases the lock even when fn throws, then propagates', async () => {
const svc = StackOpLockService.getInstance();
await expect(
svc.runExclusive(1, 'web', 'deploy', 'system', async () => {
throw new Error('boom');
}),
).rejects.toThrow('boom');
expect(svc.size()).toBe(0);
});
});
describe('stackOpSkipMessage', () => {
it('names the stack and the conflicting action', () => {
expect(stackOpSkipMessage('web', 'update')).toBe(
'Skipped "web": another operation (update) is already in progress.',
);
});
});