Skip to content

armgit / TREK

Public Imported from GitHub
0

The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.

fix(server): trace a cron tick lost to another process as skipped

Mauricea72497b3c49f
diff --git a/server/CLAUDE.md b/server/CLAUDE.md
index f13e9cca7..f518a0374 100644
--- a/server/CLAUDE.md
+++ b/server/CLAUDE.md
@@ -47,7 +47,7 @@ Nest owns everything. Every domain is a DI module under `src/nest/<domain>/` (`c
- **`src/bootstrap.ts` — `buildApp()`** is the single builder for production and the test harness. Everything on the raw Express instance (global middleware, uploads, discovery metadata, statics, the named `jsonParser`/`urlencodedParser` wrappers) is registered **before `app.init()`**, because Nest throws `NotFoundException` on unmatched routes and nothing after init is reachable. The wrappers exempt `/mcp` so the MCP SDK reads the raw stream — **never `@Body()` a `/mcp` route**. Don't add routes to that pre-init shell; it bypasses every global guard, interceptor and filter.
- **Realtime**: `/ws` is a Nest gateway in `src/nest/realtime/`. Inject `RealtimeService`; `src/websocket.ts` is a re-export stub for old call sites. Trip mutations forward `X-Socket-Id` so the originating client doesn't echo its own change.
- **MCP**: `src/nest-mcp/` is the decorator/registry layer (`@McpController`/`@Tool`/`@Resource`/`@Prompt`; see its `README.md`); tools live in `<domain>.mcp.ts` files beside each module; the HTTP transport is `src/nest/mcp-transport/`; `src/mcp/` holds process-wide state only (scopes, session manager, boot policy). Every tool invocation writes an audit row through the registry's `onInvoke` seam. MCP tools are adapters over the same services and permission checks as REST — a change on one side lands on the other in the same change.
-- **Scheduling**: `src/nest/scheduling/` (`CronRegistrarService`) is the one way to schedule a cron. Jobs are `*.job.ts` providers in their owning domain. The registrar refuses to schedule under `NODE_ENV=test` (an integration test pins it). **Never use a `@Cron` decorator** — it bypasses that gate. Every tick first takes the job's row in `scheduler_leases` (`SchedulerLeasesRepository.acquire`, one conditional UPDATE), renews it while it runs and keeps it for a short settle window afterwards, so two processes on one database never run the same tick; a job needs nothing of its own for this. Claims on individual rows (the reminder jobs' `claimReminder`) stay where they are: the lease decides who runs a tick, the claim what a tick may send.
+- **Scheduling**: `src/nest/scheduling/` (`CronRegistrarService`) is the one way to schedule a cron. Jobs are `*.job.ts` providers in their owning domain. The registrar refuses to schedule under `NODE_ENV=test` (an integration test pins it). **Never use a `@Cron` decorator** — it bypasses that gate. Every tick first takes the job's row in `scheduler_leases` (`SchedulerLeasesRepository.acquire` in one `UnitOfWork` transaction, where a conditional UPDATE decides the race), renews it while it runs and keeps it for a short settle window afterwards, so two processes on one database never run the same tick; a job needs nothing of its own for this. Claims on individual rows (the reminder jobs' `claimReminder`) stay where they are: the lease decides who runs a tick, the claim what a tick may send.
- **Plugins** (`src/nest/plugins/`): the child-process runtime (`supervisor/`, `runtime/plugin-host-entry.ts`, `protocol/envelope.ts`) is **intentionally not Nest** — it is the security boundary. `host/rpc-host.ts` registers an RPC method at spawn only if the plugin holds the unlocking permission (registration = authorization). Install-time gates live in `install/`; the manifest's `trek` version range fails closed, and `TREK_PLUGINS_IGNORE_TREK_RANGE` downgrades that to a warning. The protocol tables in `protocol/envelope.ts` (+ `src/plugin-event-sink.ts`) are **generated** into `plugin-sdk/` and `shared/` — run `gen:plugin-facts` after touching them and commit the output. `runtime/egress-policy.ts` is a hand-kept mirror guarded by a parity test in `plugin-sdk/`; change both sides together.
- **Storage**: `src/nest/storage/` is the upload driver abstraction (local / S3 / mirror behind one interface, with an admin surface and a usage job). Domain services never touch the filesystem or the S3 SDK directly. Where the data lives (`data/`, `uploads/`, backups, logs, key files, the DB file) is resolved in one place, `src/app-config/data-paths.ts`; Nest classes inject `DataPathsService`, and nothing anchors a data path on its own `__dirname` or on `process.cwd()`.
- **DB** (`src/db/`): `better-sqlite3`, WAL, FK on. `database.ts` only holds the connection and applies pragmas. It does not build a schema, and importing it opens nothing (the first reader does). The connection's lifecycle belongs to the `DatabaseLifecycle` provider (`nest/database/database-lifecycle.service.ts`): `buildApp()` opens it through `open()` (which binds the ORM to later swaps and runs the schema bootstrap below), the shutdown closes it through `close()`, and a restore or the demo reset swaps the file only through the database backup port, `DATABASE_BACKUP` (`nest/database/database-backup.interface.ts`; the SQLite implementation is `nest/backup/sqlite-database-backup.ts`: `VACUUM INTO` snapshot, close, atomic file swap, `reopen()`). The port works on `DatabaseLifecycle.file`, the one resolved path (`TREK_DB_FILE` or `data/travel.db`), and a snapshot that fails fails the backup rather than archiving the live file. `MaintenanceRepository` is provided only by `MaintenanceModule`'s factory and injected everywhere else; no consumer constructs it. A provider that has to follow every reopen (the demo reset job saves the first demo baseline after a restore's re-bootstrap seeded the example trips) registers with `DatabaseLifecycle.onReopened()`, which runs after the reopen's schema bootstrap; a listener contains its own failures, since one that throws fails the reopen. MikroORM's migrations (`db/migrations/`) are the only schema source, **including for tests**: the hand-kept `schema.ts`/`migrations.ts`/`seeds.ts` builders and the parity test that guarded them are gone. Seeding is the MikroORM seeders in `db/seeders/`, applied by `db/orm.ts` from `buildApp()` before anything reads. An install the retired positional runner migrated (a `schema_version` row, no `mikro_orm_migrations` rows) is baselined by `db/legacy-baseline.ts`: the migrations whose `Legacy migration step N` docstring is ≤ its version are recorded as executed (never replayed) in the same transaction as the migrator run, while the baseline migration itself still runs first, as the legacy runner's `createTables()` did on every boot; anything it cannot map refuses the boot. Before a boot applies pending migrations to a file database that holds anything, `db/pre-migrate-snapshot.ts` writes a `VACUUM INTO` copy next to it (`pre-migrate-<schema>-<time>.db`, `<schema>` being `legacy-<schema_version>` or the last recorded migration's timestamp; the newest `TREK_DB_PRE_MIGRATE_SNAPSHOT_KEEP` stay) and the newer-database refusal names the matching copy; a copy that cannot be written refuses the boot unless `TREK_DB_PRE_MIGRATE_SNAPSHOT=false`. It is off under `NODE_ENV=test` unless a suite sets that variable to true, and a restore's re-bootstrap skips it (the archive is the copy). After the migrator, `db/email-case-index.ts` creates the case-insensitive unique index on `users.email` that its migration had to defer on an install holding two accounts whose emails differ only in case (flag `email_case_index_pending`). `db/orm-driver.ts` binds the ORM to that same connection instead of opening a second one — with `:memory:` under test, a second connection is a second, empty database. Kysely statements (`this.kysely<...>()`) type against `DB` from `db/kysely/db.ts`, narrowed with `Pick<DB, 'trips' | 'days'>`; those files are generated from the migrated schema by `scripts/generate-db-types.ts`, so a migration that adds or changes a column is followed by `npm run gen:db-types`, never by a hand-written table interface. Every read and write goes through a repository in `db/repositories/` (each extends the shared `TrekRepository` base in `db/repositories/_shared/`, which validates the request context before delegating to MikroORM) and, for multi-statement writes, `UnitOfWork.transactional(...)` (`nest/database/unit-of-work.ts`, provided by the global `OrmModule`) — there is no `DatabaseService`/`DatabaseModule` to inject any more. Entrypoints outside an HTTP request — an MCP tool call, a plugin RPC dispatch, a WebSocket message, a cron job, boot-time seeding, a backup restore — open one explicitly with `withRequestContext()` (`nest/database/request-context.ts`), since only the pathless `mikroOrmRequestContext` middleware `buildApp()` mounts (with `@mikro-orm/nestjs`'s own `registerRequestContext` turned off in `app.module.ts`, UPLOADS-P16) forks an `EntityManager` per HTTP request. `NODE_ENV=test` ⇒ isolated `:memory:` DB per vitest worker, opened from a snapshot `tests/global-setup.ts` migrates once per run; `TREK_DB_FILE` ⇒ explicit file DB (Playwright harness).
@@ -95,7 +95,7 @@ SQLite is the engine today and Postgres is the planned second one. Code under `s
- **`src/nest/common/`**: the global exception filter (error envelope), the Zod validation pipe, the idempotency interceptor (`X-Idempotency-Key` replay), and `validate-route-guards.ts` (boot-time ratchet refusing any public route not on its allow-list).
- **Auth is default-deny**: the global auth guard and the MFA policy guard run as `APP_GUARD`s, followed by the managed-install guard (`managed.guard.ts`), which refuses the routes a centrally administered install withholds from its own admin — it runs last so strangers still get a 401, never a route-revealing 403. Routes opt out with `@Public()`/`@OptionalAuth()`. The global guard stands down for routes declaring their own guard chain, so `@UseGuards(JwtAuthGuard, TripAccessGuard)` + `@RequirePermission` stacks work. Session is a cookie (`trek_session`); `@CurrentUser()` reads the user. **Never gate a multipart upload with a guard** — guards run before the parser and the client sees ECONNRESET instead of your 403; check in the handler.
- **Logging**: `src/nest/audit/audit-log.logger.ts` (`logInfo`/`logWarn`/`logError`/`logDebug`) prints each line to the console and queues it for `data/logs/trek.log`, which `log-file.ts` appends in batches off the event loop and rotates at 10 MB over five files; `index.ts` flushes what is queued on exit. Never write the log file synchronously from a request path.
-- **Request correlation** (`src/nest/common/request-correlation.ts`): every HTTP request runs under an id (a well-formed incoming `X-Request-Id`, else a fresh UUID) that the response carries in `X-Request-Id`, and every log line written inside it is tagged `[http <id>]`. The exception filter leaves a 5xx on `res.locals` so the access log writes the request line and the stack as one entry. The other entry points (MCP tool/resource/prompt calls via the registry's `around` seam, WebSocket messages in `TrekWsAdapter`, plugin RPC dispatches in the supervisor, cron ticks in `CronRegistrarService`) each run under their own id through `traceEntry()` (`nest/audit/entry-trace.logger.ts`), which logs one line per call: debug on success, warn or error with the reason on failure. A new entry point goes through `traceEntry()` too.
+- **Request correlation** (`src/nest/common/request-correlation.ts`): every HTTP request runs under an id (a well-formed incoming `X-Request-Id`, else a fresh UUID) that the response carries in `X-Request-Id`, and every log line written inside it is tagged `[http <id>]`. The exception filter leaves a 5xx on `res.locals` so the access log writes the request line and the stack as one entry. The other entry points (MCP tool/resource/prompt calls via the registry's `around` seam, WebSocket messages in `TrekWsAdapter`, plugin RPC dispatches in the supervisor, cron ticks in `CronRegistrarService`) each run under their own id through `traceEntry()` (`nest/audit/entry-trace.logger.ts`), which logs one line per call: debug on success, debug as `skipped` when the call declines its work on purpose (a cron tick whose lease another process holds), warn or error with the reason on failure. A new entry point goes through `traceEntry()` too.
- **Process safety nets** (`src/index.ts`, `src/shutdown.ts`): `unhandledRejection` and `uncaughtException` are logged to trek.log and end in the same orderly shutdown as SIGTERM, with exit code 1; a second fatal error during it exits at once. A shutdown first marks `ReadinessService` (`nest/health/`) as draining, so `/api/health/ready` answers 503 for the whole drain. The HTTP server keeps idle keep-alive connections for `HTTP_KEEP_ALIVE_TIMEOUT_MS` (65 s, above the usual proxy idle timeout) with the headers timeout one second above it (`applyProxyTimeouts` in `bootstrap.ts`).
- **Process-local state sits behind injectable ports**, each with an in-memory implementation that keeps today's behaviour: `RateLimitStore` (`nest/common/rate-limit.store.ts`, provided by `RateLimitModule`), `PendingCodeStore` (`nest/oauth/oauth.pending-codes.ts`), `OidcFlowStore` (`nest/oidc/oidc-flow.store.ts`), `PermissionsCacheStore` (`nest/permissions/permissions-cache.ts`) and `RoomRegistry` (`nest/realtime/ws-state.ts`). The owning module provides the implementation, and a hand-built consumer falls back to the same in-memory one, so a store shared between processes replaces a provider rather than the consumers. New process-local state follows the same shape; TREK still runs as one process.
- **`src/middleware/globalMiddleware.ts`** is the only Express middleware left (helmet/CSP, CORS, HSTS, forced-HTTPS, logging, cookies).
diff --git a/server/src/db/repositories/SchedulerLeases.repository.ts b/server/src/db/repositories/SchedulerLeases.repository.ts
index 818e2ad83..1919eede7 100644
--- a/server/src/db/repositories/SchedulerLeases.repository.ts
+++ b/server/src/db/repositories/SchedulerLeases.repository.ts
@@ -12,7 +12,8 @@ export class SchedulerLeasesRepository extends TrekRepository<SchedulerLeases> {
* free at `now`. The decision is one conditional UPDATE, so of two
* processes asking at the same moment exactly one gets a changed row; the
* insert before it only makes sure there is a row to race on. True when
- * `owner` holds the lease afterwards.
+ * `owner` holds the lease afterwards. Two statements, so the caller runs it
+ * inside `UnitOfWork.transactional` (CronRegistrarService does).
*/
async acquire(name: string, owner: string, now: number, until: number): Promise<boolean> {
await this.upsert(
diff --git a/server/src/nest/audit/entry-trace.logger.ts b/server/src/nest/audit/entry-trace.logger.ts
index 26f275b17..355d8d61f 100644
--- a/server/src/nest/audit/entry-trace.logger.ts
+++ b/server/src/nest/audit/entry-trace.logger.ts
@@ -15,6 +15,13 @@ export interface TraceOptions<T = unknown> {
* failure, null when it is not. A failure found this way is logged at warn.
*/
refusal?: (result: Awaited<T>) => string | null;
+ /**
+ * For entry points that may decline to do their work on purpose (a cron tick
+ * whose lease another process holds): the reason when `result` says the call
+ * did nothing, null when it ran. A skip is logged at debug, as `skipped`
+ * rather than `ok`, so the line says which process actually did the work.
+ */
+ skipped?: (result: Awaited<T>) => string | null;
}
function messageOf(error: unknown): string {
@@ -36,8 +43,8 @@ function isThenable(value: unknown): value is PromiseLike<unknown> {
/**
* Run one call of a non-HTTP entry point (an MCP tool, a WebSocket message, a
* plugin RPC, a cron tick) under its own correlation id, and log one line for
- * it: at debug when it succeeds, mirroring the HTTP access log, and at warn
- * (or error) with the reason when it fails. Every line the call writes in
+ * it: at debug when it succeeds or skips its work on purpose, mirroring the
+ * HTTP access log, and at warn (or error) with the reason when it fails. Every line the call writes in
* between carries the same id.
*
* The call's own result comes back untouched, a plain value as a plain value
@@ -57,8 +64,13 @@ export function traceEntry<T>(
const succeeded = (value: Awaited<T>): void => {
const refused = options.refusal?.(value) ?? null;
- if (refused === null) logDebug(`${kind} ${label} ok ${elapsed()}`);
- else logWarn(`${kind} ${label} refused ${elapsed()}: ${refused}`);
+ if (refused !== null) {
+ logWarn(`${kind} ${label} refused ${elapsed()}: ${refused}`);
+ return;
+ }
+ const skipped = options.skipped?.(value) ?? null;
+ if (skipped !== null) logDebug(`${kind} ${label} skipped ${elapsed()}: ${skipped}`);
+ else logDebug(`${kind} ${label} ok ${elapsed()}`);
};
const failed = (error: unknown): void => {
const line = options.failureMessage?.(error) ?? `${kind} ${label} failed ${elapsed()}: ${messageOf(error)}`;
diff --git a/server/src/nest/scheduling/cron-registrar.service.ts b/server/src/nest/scheduling/cron-registrar.service.ts
index 43e5a670a..050b305ab 100644
--- a/server/src/nest/scheduling/cron-registrar.service.ts
+++ b/server/src/nest/scheduling/cron-registrar.service.ts
@@ -7,7 +7,8 @@ import { MikroORM } from '@mikro-orm/core';
import { readEnv } from '../../app-config';
import { RuntimeEnvService } from '../app-config/runtime-env.service';
import { withRequestContext } from '../database/request-context';
-import { logDebug, logError } from '../audit/audit-log.logger';
+import { UnitOfWork } from '../database/unit-of-work';
+import { logError } from '../audit/audit-log.logger';
import { traceEntry, wasTraced } from '../audit/entry-trace.logger';
import { SchedulerLeases } from '../../db/entities/SchedulerLeases.entity';
@@ -115,9 +116,10 @@ export class CronRegistrarService implements OnApplicationShutdown {
}
// Each tick is its own unit of work: one correlation id for every line
// the job writes, and one line for the tick itself.
- return traceEntry('cron', name, () => withRequestContext(orm, () => this.runLeased(orm, name, onTick)), {
+ await traceEntry('cron', name, () => withRequestContext(orm, () => this.runLeased(orm, name, onTick)), {
failureLevel: 'error',
failureMessage: failed,
+ skipped: (outcome) => (outcome === 'skipped' ? 'lease held by another process' : null),
});
};
// waitForCompletion: a tick still running when the next one is due is not
@@ -150,13 +152,25 @@ export class CronRegistrarService implements OnApplicationShutdown {
* and held for LEASE_SETTLE_MS afterwards, so a peer whose timer fires late
* for the same tick does not run it again. A process that dies holding it
* frees the job after LEASE_TTL_MS.
+ *
+ * Says whether the tick ran here, so the trace line names the process that
+ * did the work instead of reporting `ok` from both.
*/
- private async runLeased(orm: Pick<MikroORM, 'em'>, name: string, onTick: () => void | Promise<void>): Promise<void> {
+ private async runLeased(
+ orm: Pick<MikroORM, 'em'>,
+ name: string,
+ onTick: () => void | Promise<void>,
+ ): Promise<'ran' | 'skipped'> {
const leases = orm.em.getRepository(SchedulerLeases);
- if (!(await leases.acquire(name, LEASE_OWNER, Date.now(), Date.now() + LEASE_TTL_MS))) {
- logDebug(`Cron job "${name}" skipped: another process holds this tick`);
- return;
- }
+ // acquire() is two statements (make sure the row exists, then the
+ // conditional UPDATE that decides the race), so it runs as one unit of
+ // work like every other multi-statement write. A UnitOfWork over the ORM
+ // this tick already has, rather than an injected one: the partial e2e
+ // graphs build this service without the global OrmModule.
+ const acquired = await new UnitOfWork(orm.em).transactional(() =>
+ leases.acquire(name, LEASE_OWNER, Date.now(), Date.now() + LEASE_TTL_MS),
+ );
+ if (!acquired) return 'skipped';
const leaseFailed = (err: unknown) =>
logError(`Cron job "${name}": lease update failed: ${err instanceof Error ? err.message : String(err)}`);
const heartbeat = setInterval(() => {
@@ -170,6 +184,7 @@ export class CronRegistrarService implements OnApplicationShutdown {
// Never let the bookkeeping replace the tick's own error.
await leases.extend(name, LEASE_OWNER, Date.now() + LEASE_SETTLE_MS).catch(leaseFailed);
}
+ return 'ran';
}
/**
diff --git a/server/tests/unit/nest/cron-registrar.service.test.ts b/server/tests/unit/nest/cron-registrar.service.test.ts
index a5f6515aa..cc4e583fd 100644
--- a/server/tests/unit/nest/cron-registrar.service.test.ts
+++ b/server/tests/unit/nest/cron-registrar.service.test.ts
@@ -43,9 +43,10 @@ vi.mock('cron', () => ({
}));
const logErrorMock = vi.hoisted(() => vi.fn());
+const logDebugMock = vi.hoisted(() => vi.fn());
vi.mock('../../../src/nest/audit/audit-log.logger', () => ({
logInfo: vi.fn(),
- logDebug: vi.fn(),
+ logDebug: logDebugMock,
logError: logErrorMock,
logWarn: vi.fn(),
}));
@@ -62,6 +63,7 @@ import type { RuntimeEnvService } from '../../../src/nest/app-config/runtime-env
import { createSnapshotTestDb } from '../../helpers/db-mock';
import { createTestOrm, type TestOrm } from '../../helpers/test-orm';
import { Users } from '../../../src/db/entities/Users.entity';
+import { SchedulerLeasesRepository } from '../../../src/db/repositories/SchedulerLeases.repository';
import { currentCorrelation, type Correlation } from '../../../src/nest/common/request-correlation';
function makeRegistrar(isTest: boolean) {
@@ -317,6 +319,52 @@ describe('CronRegistrarService', () => {
expect(holder(name)!.owner).toBe('other-host:1:peer');
});
+ it('CRONREG-021: a tick lost to another process is traced as skipped, and a tick run here as ok', async () => {
+ const name = 'lease-trace-line';
+ testDb
+ .prepare('INSERT INTO scheduler_leases (name, owner, expires_at) VALUES (?, ?, ?)')
+ .run(name, 'other-host:1:peer', Date.now() + 60_000);
+ const registrar = new CronRegistrarService(new SchedulerRegistry(), { isTest: () => false } as RuntimeEnvService, t.orm);
+ registrar.register(name, '* * * * *', () => undefined);
+ logDebugMock.mockClear();
+ await h.jobs[0].onTick();
+ await vi.waitFor(() => expect(logDebugMock).toHaveBeenCalled());
+ const lines = () => logDebugMock.mock.calls.map((call) => String(call[0])).filter((line) => line.startsWith(`cron ${name} `));
+ expect(lines()).toHaveLength(1);
+ expect(lines()[0]).toMatch(new RegExp(`^cron ${name} skipped \\d+ms: lease held by another process$`));
+
+ testDb.prepare('UPDATE scheduler_leases SET expires_at = 1 WHERE name = ?').run(name);
+ logDebugMock.mockClear();
+ await h.jobs[0].onTick();
+ await vi.waitFor(() => expect(lines()).toHaveLength(1));
+ expect(lines()[0]).toMatch(new RegExp(`^cron ${name} ok \\d+ms$`));
+ });
+
+ it('CRONREG-022: the lease is taken inside one transaction', async () => {
+ const name = 'lease-in-a-transaction';
+ const original = SchedulerLeasesRepository.prototype.acquire;
+ const inTransaction: boolean[] = [];
+ const spy = vi
+ .spyOn(SchedulerLeasesRepository.prototype, 'acquire')
+ .mockImplementation(function (this: SchedulerLeasesRepository, ...args: Parameters<typeof original>) {
+ inTransaction.push(t.orm.em.getContext().isInTransaction());
+ return original.apply(this, args);
+ });
+ try {
+ const registrar = new CronRegistrarService(new SchedulerRegistry(), { isTest: () => false } as RuntimeEnvService, t.orm);
+ let ran = false;
+ registrar.register(name, '* * * * *', () => {
+ ran = true;
+ });
+ await h.jobs[0].onTick();
+ expect(inTransaction).toEqual([true]);
+ expect(ran).toBe(true);
+ expect(holder(name)!.owner).toBe(LEASE_OWNER);
+ } finally {
+ spy.mockRestore();
+ }
+ });
+
it('CRONREG-018: a lapsed lease is taken over, and held for the settle window after the tick', async () => {
const name = 'lease-lapsed';
testDb
diff --git a/server/tests/unit/nest/entry-trace.logger.test.ts b/server/tests/unit/nest/entry-trace.logger.test.ts
index 370eb1e7e..fba12a0d9 100644
--- a/server/tests/unit/nest/entry-trace.logger.test.ts
+++ b/server/tests/unit/nest/entry-trace.logger.test.ts
@@ -1,7 +1,7 @@
/**
* traceEntry (nest/audit/entry-trace.logger.ts): one correlation id and one
* log line per call of a non-HTTP entry point, without changing what the call
- * returns or when it runs. TRACE-001 through TRACE-008.
+ * returns or when it runs. TRACE-001 through TRACE-009.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest';
@@ -102,4 +102,14 @@ describe('traceEntry', () => {
const ids = [1, 2].map(() => traceEntry('ws', 'leave', () => currentCorrelation()?.id));
expect(ids[0]).not.toBe(ids[1]);
});
+
+ it('TRACE-009: a call that skips its work on purpose is logged at debug as skipped, not ok', async () => {
+ const skipped = (outcome: string) => (outcome === 'skipped' ? 'lease held by another process' : null);
+ await traceEntry('cron', 'auto-backup', () => Promise.resolve('skipped'), { skipped });
+ await traceEntry('cron', 'auto-backup', () => Promise.resolve('ran'), { skipped });
+ await vi.waitFor(() => expect(log.logDebug).toHaveBeenCalledTimes(2));
+ expect(log.logDebug.mock.calls[0][0]).toMatch(/^cron auto-backup skipped \d+ms: lease held by another process$/);
+ expect(log.logDebug.mock.calls[1][0]).toMatch(/^cron auto-backup ok \d+ms$/);
+ expect(log.logWarn).not.toHaveBeenCalled();
+ });
});