diff --git a/.gitignore b/.gitignore index 1da14112..e37c9e47 100755 --- a/.gitignore +++ b/.gitignore @@ -24,3 +24,5 @@ coverage/ # Written by functions:serve into the project directory, as V1 did. logs/ +!/src/logs/ +!/src/commands/launch/logs/ diff --git a/.talismanrc b/.talismanrc index 6d1a44ce..c9fd18d3 100644 --- a/.talismanrc +++ b/.talismanrc @@ -1,14 +1,18 @@ fileignoreconfig: +- filename: test/integration/logs-get.test.ts + checksum: 7822d714f476fa4ee588f1b602a7c9e69b8843cc60c09b4ae14cbe4eb2b4ad3b +- filename: src/commands/launch/logs/get.test.ts + checksum: 5ee3d8ba6b014b3a9ac558a750a9a58782bb679d32d30b621e41f977dcc98a0a - filename: src/core/failure.test.ts checksum: 242d43885d1e3ef46edf1e347899a90549ebf95ec6827426746852f7a6dfc418 - filename: test/integration/retired-commands.test.ts - checksum: 4f1a3d7b6b6684986f720a44dcd4d4c014a64dd15c41d41d0266afb0ebe828c0 + checksum: c38d6e8dae6bd4d2034ff48bff488e89cc00d950a7417c6df890168ac743ae37 - filename: test/integration/manage-base-path.test.ts checksum: 79eb9ad420ea47d5bee8045d812c45b010bbeeafcaf5f85d11653140b0cd0db1 - filename: src/transport/rest-client.ts - checksum: 755aabbc8ee7a2440d4b696e0c502b612c6a60c50fea38db6537d46849521b41 + checksum: 3e44b756be0647422309cb14137bc18f5707cd42de6dd638abd2e0b625fda894 - filename: src/transport/rest-client.test.ts - checksum: 02981226eef6131634d0903fc04fa73a5fb8cac82213f00f49d5f66950d75f8e + checksum: 8f08eb868bb8d608a0d31800c103f7b257f8f414d0fdc6b06ef4ab62acfffd85 - filename: src/transport/cma-client.ts checksum: 87b8399a9b84ea60fe322802c2e5270772858ba85ac33c436941fe7cf40afc38 - filename: src/transport/auth-strategy.test.ts @@ -18,7 +22,7 @@ fileignoreconfig: - filename: src/projects/projects.api.ts checksum: 59818dd541577d99c12c50c0c6ef4846ef2db614ab6183cb6dd7b71710931eb1 - filename: src/core/service-context.test.ts - checksum: 7bc4f6ca3ec8a960f84fb4c07453a287bb2bb0ccc7e06c5805a7f56df160024a + checksum: 495972ae75e7ef1b62632c8d099fc589b023976a17d77caaebb049d974edd1bc - filename: src/core/rules.test.ts checksum: addfdcffa45491accbc861f28cc2f17528a7e9d77d4c852b302a75cd68d7bdee - filename: src/core/inputs.test.ts @@ -87,7 +91,7 @@ fileignoreconfig: - "'SECRET=hunter2'" - "formFieldKey" - filename: test/integration/projects-create.test.ts - checksum: e37d9a0fdce75f942836f621a2e281cb9b448cd583673ebcacb075de3faaf187 + checksum: 4826ca20f0c7fe1f23b82598ceed0a374199e2bb8b604b676efcf720244ff961 - filename: test/fixtures/README.md checksum: d801c84c8b7d7f38f967573e9a3a70da4405b7cbcbf10d2a6e5be3d65fb3daa1 allowed_patterns: @@ -224,12 +228,12 @@ fileignoreconfig: allowed_patterns: - "FlagKey" - filename: src/resources.test.ts - checksum: 742d9faaa855390c853963388bb2479355fe69f0ee05b5a8965de091621d711d + checksum: 05a4c54c69bfff1042fa0df038c46881830e3d7014777c87919c5c0739974f45 allowed_patterns: - "a project name passed on argv to the project resolver" - "expect\\(Object.keys\\(DEPENDENCIES\\)\\).toEqual\\(\\['project', 'env'\\]\\)" - filename: AGENTS.md - checksum: 89b7e72236e7218326eb3c9c3176c5ab36d58e79a9bf845f422fe28d98c144a1 + checksum: aafd85677e293bf72dd5764875b202ac3a5531aa083c1c452adaa55021af8c95 allowed_patterns: - "Do not add an exemption to a guard to make a new file pass" - "passes its own error wording to `client.request\\(req, MESSAGES\\)`" @@ -253,7 +257,7 @@ fileignoreconfig: - filename: src/git/local-repository.ts checksum: b9091ed135dfebdf590a5412bbfba2b2f96d4a177cf944a20909b93405268e9f - filename: test/guards/layering.test.ts - checksum: fea55eeb036ea4acb1cc4d177ae9cbfc1a06bbc5a1ea65b2f5c82717cd0251a9 + checksum: fa3a7ee934a03ff88618d02722273ea913b0fc1728d177e86a71d9e69236aa71 - filename: src/commands/launch/projects/create.test.ts checksum: 9c40b4b6ed4f7d678ecb921a71f5af7284cd685c1337f47144456ae43a38b1ad - filename: src/commands/launch/projects/delete.test.ts @@ -325,7 +329,7 @@ fileignoreconfig: - filename: src/commands/launch/env/update.test.ts checksum: 2da219594e7bdd589adc0eff9ff035252a75aaa51dfa20514b18fd3266d7b752 - filename: README.md - checksum: 9c87e9e46dbc9606b4946bb6d84ce36352d8f6d733280f5f48e0a65bd6cf6ded + checksum: 8f1e4d97fa7e97a4c6a3bdb6bbf3d0f4d3735c3dfc23579a4d0a7c6d725bc8e4 allowed_patterns: - "password-protection" - "-p, --password" @@ -431,7 +435,7 @@ fileignoreconfig: - filename: test/integration/deployments-create.test.ts checksum: fd367019e10b47121898440e4b3a54fb2041d6302bee2dea28a97ad58eb88ee9 - filename: src/deployments/deployment.watcher.test.ts - checksum: c2cdab908cba7d4e162d06f59a471f918c959eb9c220ebc3666f0c6299f141b2 + checksum: 0a9dab3e2436531279078bb5c0b3ef8524cebf7824b0602b7685ae0b4ef47923 - filename: src/deployments/deployment.create.ts checksum: ca64f3b29a68c4a2755a88a141e2cd9dbd6fa851a2776876d78c40f3168492e3 - filename: src/commands/launch/deployments/create.test.ts diff --git a/AGENTS.md b/AGENTS.md index 3bf2587a..682770c3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -133,7 +133,8 @@ src/ core/ the command framework: LaunchCommand, the resolver engine, errors, exit codes, the core flag catalog (coreFlags), region derivation, the .cs-launch.json store, and the output primitives - transport/ RestApiClient, the retry policy, auth strategies, proxy detection, + transport/ RestApiClient, EventStreamClient (SSE, event-stream.ts), the one request-header + builder both share, the retry policy, auth strategies, proxy detection, and LaunchApiError / LaunchNetworkError - no CLI wording lives here projects/ one resource: repository, value object, domain service, presenter, error wording, prompt adapter, and the flags it contributes @@ -162,6 +163,9 @@ src/ git/ the internal git-namespace / repository / branch lookups organizations/ the --org flag, its organization picker, and the lookup behind it, which reads the Contentstack Management API rather than Launch + logs/ logs:get: the server-log window parser and repository, the live log API over SSE, and + the LiveLogFollower that reconnects it; the build-log follow is deployments'. It + reaches deployments only cache/ the CDN cache purge behind launch:cache:purge: CacheApi, the --path / --prefix / --tags / --hosts inputs and their normalisation, the criterion prompt and the success lines site/ the URL choice for an environment's live site (`siteUrlOf`, shared with the deployment follower), @@ -491,7 +495,7 @@ promoting these to `src/core/catalog.ts` now. | 0 | none - oclif exits 0 implicitly | the command did what it was asked to do | | 1 | `EXIT_RUNTIME` | a runtime failure - `LaunchApiError`, `LaunchNetworkError`, `UnauthenticatedError`, anything oclif handles | | 2 | `EXIT_USAGE` | a usage error - `UsageError`, `MissingInputError`, a failing cross-flag rule | -| 3 | `EXIT_CANCELLED` | the user declined a confirmation or chose nothing at a picker (`CancelledError`) | +| 3 | `EXIT_CANCELLED` | the user declined a confirmation, chose nothing at a picker (`CancelledError`) or pressed Ctrl-C while the CLI was following a deployment's logs or a live log stream (`logs:get`) | `launch:functions:serve` is deliberately a plain oclif `Command` rather than a `LaunchCommand`, because it talks to no API and needs no auth gate, and it is **outside** @@ -718,6 +722,30 @@ returning, so the last lines of a build are never lost. The logs are auxiliary: failed read prints nothing, is retried from the same cursor on the next poll, and never changes the outcome - the status poll alone decides that. +**The terminal poll drains the logs.** A poll that sees a terminal status does not read the logs once: it keeps +reading from the advancing `tail.since()` until `tail.fresh` returns nothing new, at most `MAX_PAGES` reads, so a +build that wrote more than one page after the last in-flight poll is never cut short. An in-flight poll still makes +exactly one read. A read that fails mid-drain prints nothing, ends the drain and never changes the +outcome. `stop` (an `AbortSignal` on `DeploymentWatchDeps`, `DeploymentFollower.watch(scope, stop)`) ends the wait +with `stop.reason` wherever it is noticed: before a poll, after one, during the drain, and at the sleep - a signal +already aborted when the loop would sleep ends it at once rather than sleeping the full delay, and the default +`sleep` takes the signal as its second argument and clears its timer on abort, so no timer outlives an interrupt. +`onInterrupt(listener)` in `src/core/interruptible-ux.ts` is the one way to hear Ctrl-C around such a wait; like +`cancelOnInterrupt` it detaches in a microtask after the signal, so it is still attached while `signal-exit` looks. + +**The live stream is not the watcher.** `logs:get --type live` reads server-sent events, so it sits beside the +polling loop: `EventStreamClient` (`src/transport/event-stream.ts`) is a `node:http`/`node:https` GET (nock can +intercept it; it goes through `proxyRouteFor`) sending `Accept: text/event-stream` - without it the logs service cuts the +request after 14 s. It has an idle timeout (`EVENT_STREAM_IDLE_TIMEOUT_MS`, 30 s) that any received bytes, heartbeats +included, reset, instead of the 60 s request timeout. A 2xx is open; anything else is parsed with `parseErrorEnvelope` +and never retried, except that one 401 gets one `auth.refresh()` and one more request. `LiveLogFollower` +(`src/logs/live-log.follower.ts`) treats a clean end of stream and a retryable `LaunchNetworkError` as a drop and +reconnects after `RetryPolicy.delayFor(n)`; `DEPLOYMENT_MAX_POLL_ERRORS` consecutive drops end it with a +`LaunchNetworkError`, and a connection that delivered any frame starts the count again. `event: session-ended` is the +server's own 5-minute cap: it exits 0 and is never followed by a reconnect. Ctrl-C aborts the same `AbortSignal` the +sleep and the socket listen to, exit 3. The header builder, `buildRequestHeaders` in `rest-client.ts`, is the only place +`X-CS-CLI`, `x-cs-api-version`, the auth headers and the org/project scope headers are assembled. + **Writing a test for it: the fake clock must advance.** `now()` and `sleep()` are injected and both are required, not optional with defaults. A fake `now: () => 0` with a `sleep` that does nothing makes the deadline unreachable and the suite **hangs** rather than failing - the same failure mode diff --git a/README.md b/README.md index d9537aac..bb845f8b 100644 --- a/README.md +++ b/README.md @@ -60,6 +60,7 @@ with exit code 2 and name their V2 replacements. `launch:functions:serve` is liv * [`csdx launch:functions`](#csdx-launchfunctions) * [`csdx launch:functions:serve`](#csdx-launchfunctionsserve) * [`csdx launch:logs`](#csdx-launchlogs) +* [`csdx launch:logs:get`](#csdx-launchlogsget) * [`csdx launch:open`](#csdx-launchopen) * [`csdx launch:projects:create`](#csdx-launchprojectscreate) * [`csdx launch:projects:delete`](#csdx-launchprojectsdelete) @@ -549,6 +550,39 @@ DESCRIPTION _See code: [src/commands/launch/logs/index.ts](https://github.com/contentstack/launch-cli/blob/v2.0.0-beta.0/src/commands/launch/logs/index.ts)_ +## `csdx launch:logs:get` + +Read the build or server logs of a deployment of a Launch environment + +``` +USAGE + $ csdx launch:logs:get [-c ] [-d ] [--org ] [--project ] [--env ] [--deployment + ] [--since ] [--until ] [--type ] + +FLAGS + -c, --config= Path to the local '.cs-launch.json' file + -d, --data-dir= Current working directory + --deployment= Deployment UID + --env= Environment name or UID + --org= Organization UID + --project= Project name or UID + --since= Server logs only: start of the window, relative (45s, 30m, 12hr, 2d) or an ISO 8601 + timestamp with an offset. Defaults to one hour before --until + --type= Kind of logs to read (deployment | server | live). Defaults to deployment + --until= Server logs only: end of the window, relative (45s, 30m, 12hr, 2d) or an ISO 8601 timestamp + with an offset. Defaults to now + +DESCRIPTION + Read the build or server logs of a deployment of a Launch environment + +EXAMPLES + $ csdx launch:logs:get --org --project --env + + $ csdx launch:logs:get --org --project --env --deployment --type server --since 2h +``` + +_See code: [src/commands/launch/logs/get.ts](https://github.com/contentstack/launch-cli/blob/v2.0.0-beta.0/src/commands/launch/logs/get.ts)_ + ## `csdx launch:open` Removed in v2 - open the site with launch:site:open diff --git a/package.json b/package.json index 9402a24b..196d6b27 100644 --- a/package.json +++ b/package.json @@ -82,6 +82,9 @@ "launch:site": { "description": "Open the live site of a Launch environment" }, + "launch:logs": { + "description": "Read Launch deployment, server and live logs" + }, "launch:variables": { "description": "List, set and remove the environment variables of a Launch environment" }, @@ -172,6 +175,7 @@ "launch:functions": "LNCH-FN", "launch:functions:serve": "LNCH-FN-SRV", "launch:logs": "LNCH-LGS", + "launch:logs:get": "LNCH-LGS-GET", "launch:open": "LNCH-OPN", "launch:projects:create": "LNCH-PRJ-CRT", "launch:projects:delete": "LNCH-PRJ-DEL", diff --git a/src/commands/launch/logs/get.test.ts b/src/commands/launch/logs/get.test.ts new file mode 100644 index 00000000..bc100625 --- /dev/null +++ b/src/commands/launch/logs/get.test.ts @@ -0,0 +1,421 @@ +import { Errors } from '@oclif/core'; + +import { EXIT_CANCELLED } from '../../../core/constants'; +import { UsageError } from '../../../core/errors'; +import * as interruptible from '../../../core/interruptible-ux'; +import type { UxLike } from '../../../core/prompt'; +import { catalog } from '../../../resources'; +import { DeploymentUnsuccessfulError } from '../../../deployments/deployment.errors'; +import { DeploymentFollower } from '../../../deployments/deployment.follower'; +import { LiveLogFollower } from '../../../logs/live-log.follower'; +import type { DeploymentOutcome } from '../../../deployments/deployment.watcher'; +import { LaunchApiError } from '../../../transport/errors'; +import LogsGet from './get'; + +const NOW = Date.parse('2026-10-28T12:00:00.000Z'); + +interface Options { + resolved?: Record; + latest?: unknown; + get?: () => Promise; + serverLogs?: unknown[]; + outputIsTTY?: boolean; +} + +function commandUnderTest(options: Options = {}) { + const lines: string[] = []; + const ux: UxLike = { + print: (message: string) => { + lines.push(message); + }, + inquire: async () => undefined as never, + }; + const latestCalls: unknown[] = []; + const getCalls: unknown[] = []; + const windowCalls: unknown[] = []; + const command = Object.create(LogsGet.prototype) as LogsGet; + + Object.assign(command, { + ux, + resolved: { org: 'org1', project: 'proj1', env: 'env1', 'log-type': 'deployment', ...options.resolved }, + services: { + ux, + isTTY: false, + outputIsTTY: options.outputIsTTY ?? false, + api: { + deployments: { + latest: async (params: unknown) => { + latestCalls.push(params); + return 'latest' in options ? options.latest : { uid: 'dLatest' }; + }, + get: async (params: unknown) => { + getCalls.push(params); + return options.get === undefined ? { uid: 'd1', status: 'LIVE' } : options.get(); + }, + }, + serverLogs: { + window: async (params: unknown) => { + windowCalls.push(params); + return options.serverLogs ?? []; + }, + }, + }, + }, + }); + + return { command, lines, latestCalls, getCalls, windowCalls }; +} + +function outcome(kind: DeploymentOutcome['kind'], status: string, deployment: object = {}): DeploymentOutcome { + return { kind, status, deployment }; +} + +describe('LogsGet', () => { + beforeEach(() => { + jest.spyOn(Date, 'now').mockReturnValue(NOW); + }); + + it('exposes the log type as --type and never as --log-type', () => { + expect(Object.keys(LogsGet.flags).sort()).toEqual(['deployment', 'env', 'org', 'project', 'since', 'type', 'until']); + expect(LogsGet.flags.type).toBe(catalog['log-type']); + }); + + it('declares the window rules and the log type input the rules read', () => { + expect(LogsGet.rules).toHaveLength(2); + expect(Object.keys(LogsGet.inputs)).toContain('log-type'); + }); + + it('T94: follows the live stream of the latest deployment without verifying it again or watching the build', async () => { + const release = jest.fn(); + jest.spyOn(interruptible, 'onInterrupt').mockReturnValue(release); + const follow = jest.spyOn(LiveLogFollower.prototype, 'follow').mockResolvedValue(undefined); + const watch = jest.spyOn(DeploymentFollower.prototype, 'watch'); + const { command, latestCalls, getCalls, windowCalls } = commandUnderTest({ resolved: { 'log-type': 'live' } }); + + await command.run(); + + expect(follow).toHaveBeenCalledTimes(1); + expect(follow.mock.calls[0][0]).toEqual({ org: 'org1', project: 'proj1', environment: 'env1', deployment: 'dLatest' }); + expect(follow.mock.calls[0][1]).toBeInstanceOf(AbortSignal); + expect(follow.mock.calls[0][1].aborted).toBe(false); + expect(latestCalls).toEqual([{ org: 'org1', project: 'proj1', environment: 'env1' }]); + expect(getCalls).toEqual([]); + expect(windowCalls).toEqual([]); + expect(watch).not.toHaveBeenCalled(); + expect(release).toHaveBeenCalledTimes(1); + }); + + it('verifies a given deployment before following its live stream', async () => { + jest.spyOn(LiveLogFollower.prototype, 'follow').mockResolvedValue(undefined); + const { command, latestCalls, getCalls } = commandUnderTest({ resolved: { 'log-type': 'live', deployment: 'd9' } }); + + await command.run(); + + expect(getCalls).toEqual([{ org: 'org1', project: 'proj1', environment: 'env1', deployment: 'd9' }]); + expect(latestCalls).toEqual([]); + }); + + it('T92: stops a live stream on Ctrl-C with the yellow line and exit 3, then releases the listener', async () => { + const release = jest.fn(); + let interrupt: () => void = () => undefined; + jest.spyOn(interruptible, 'onInterrupt').mockImplementation((listener) => { + interrupt = listener; + return release; + }); + jest.spyOn(LiveLogFollower.prototype, 'follow').mockImplementation( + (_scope, stop) => + new Promise((_resolve, reject) => { + stop.addEventListener('abort', () => reject(stop.reason), { once: true }); + interrupt(); + }), + ); + const { command, lines } = commandUnderTest({ resolved: { 'log-type': 'live' }, outputIsTTY: true }); + + const running = command.run(); + + await expect(running).rejects.toMatchObject({ oclif: { exit: EXIT_CANCELLED } }); + expect(lines).toEqual(['\u001b[33mStopped following the logs.\u001b[39m']); + expect(release).toHaveBeenCalledTimes(1); + }); + + it('lets a failure of the live stream through and still releases the listener', async () => { + const release = jest.fn(); + jest.spyOn(interruptible, 'onInterrupt').mockReturnValue(release); + const failure = new LaunchApiError(404, [{ code: 'launch.DEPLOYMENT.NOT_FOUND', message: 'gone' }]); + jest.spyOn(LiveLogFollower.prototype, 'follow').mockRejectedValue(failure); + const { command, lines } = commandUnderTest({ resolved: { 'log-type': 'live' } }); + + await expect(command.run()).rejects.toBe(failure); + expect(lines).toEqual([]); + expect(release).toHaveBeenCalledTimes(1); + }); + + it('refuses a missing latest deployment with exit 2 for both types', async () => { + for (const type of ['deployment', 'server']) { + const { command, windowCalls } = commandUnderTest({ resolved: { 'log-type': type }, latest: undefined }); + + await expect(command.run()).rejects.toThrow('No deployments found in this environment.'); + expect(windowCalls).toEqual([]); + } + }); + + it('verifies a given deployment with a get and never asks for the latest', async () => { + const { command, latestCalls, getCalls, windowCalls } = commandUnderTest({ + resolved: { 'log-type': 'server', deployment: 'd9' }, + }); + + await command.run(); + + expect(getCalls).toEqual([{ org: 'org1', project: 'proj1', environment: 'env1', deployment: 'd9' }]); + expect(latestCalls).toEqual([]); + expect(windowCalls).toEqual([ + { + org: 'org1', + project: 'proj1', + environment: 'env1', + deployment: 'd9', + startTime: NOW - 3_600_000, + endTime: NOW, + }, + ]); + }); + + it('reads the server logs of the latest deployment when none is given', async () => { + const { command, latestCalls, getCalls, windowCalls } = commandUnderTest({ resolved: { 'log-type': 'server' } }); + + await command.run(); + + expect(latestCalls).toEqual([{ org: 'org1', project: 'proj1', environment: 'env1' }]); + expect(getCalls).toEqual([]); + expect(windowCalls).toEqual([expect.objectContaining({ deployment: 'dLatest' })]); + }); + + it('turns a not-found verification into the generic exit-2 wording and reads no logs', async () => { + const missing = new LaunchApiError(404, [{ code: 'launch.DEPLOYMENT.NOT_FOUND', message: 'raw' }]); + const { command, windowCalls } = commandUnderTest({ + resolved: { 'log-type': 'server', deployment: 'd9' }, + get: async () => Promise.reject(missing), + }); + + const running = command.run(); + + await expect(running).rejects.toThrow(UsageError); + await expect(running).rejects.toThrow('No deployment with UID "d9" found in this environment.'); + expect(windowCalls).toEqual([]); + }); + + it('propagates a failed verification untouched', async () => { + const failure = new LaunchApiError(500, [{ code: 'launch.UNKNOWN', message: 'boom' }]); + const { command } = commandUnderTest({ resolved: { deployment: 'd9' }, get: async () => Promise.reject(failure) }); + + await expect(command.run()).rejects.toBe(failure); + }); + + it('prints the server lines and stays quiet about the cap at 4999 lines', async () => { + const serverLogs = Array.from({ length: 4999 }, (_, index) => ({ + timestamp: '2026-10-28T11:30:00.000Z', + message: `line ${index}`, + })); + const { command, lines } = commandUnderTest({ resolved: { 'log-type': 'server' }, serverLogs }); + + await command.run(); + + expect(lines).toHaveLength(4999); + expect(lines[0]).toBe('2026-10-28 11:30:00.000: line 0'); + expect(lines.join('\n')).not.toContain('Showing the newest'); + }); + + it('prints the cap notice last at exactly 5000 lines and not at 5001', async () => { + const entries = (count: number) => + Array.from({ length: count }, (_, index) => ({ timestamp: '2026-10-28T11:30:00.000Z', message: `line ${index}` })); + const capped = commandUnderTest({ resolved: { 'log-type': 'server' }, serverLogs: entries(5000) }); + const over = commandUnderTest({ resolved: { 'log-type': 'server' }, serverLogs: entries(5001) }); + + await capped.command.run(); + await over.command.run(); + + expect(capped.lines).toHaveLength(5001); + expect(capped.lines.at(-1)).toBe( + 'Showing the newest 5000 server log lines in this window. Narrow --since/--until to see earlier ones.', + ); + expect(over.lines).toHaveLength(5001); + expect(over.lines.join('\n')).not.toContain('Showing the newest'); + }); + + it('prints the empty server notice for the resolved window, yellow on a terminal', async () => { + const { command, lines } = commandUnderTest({ resolved: { 'log-type': 'server' }, outputIsTTY: true }); + + await command.run(); + + expect(lines).toEqual([ + '\u001b[33mNo server logs found between 2026-10-28T11:00:00.000Z and 2026-10-28T12:00:00.000Z.\u001b[39m', + ]); + }); + + it('prints the 24 hour notice before the lines and sends the window as the user gave it', async () => { + const serverLogs = [{ timestamp: '2026-10-27T11:00:00.000Z', message: 'old' }]; + const { command, lines, windowCalls } = commandUnderTest({ + resolved: { 'log-type': 'server', since: '2d' }, + serverLogs, + }); + + await command.run(); + + expect(lines).toEqual([ + 'Server logs are kept for 24 hours; showing from 2026-10-27T12:00:00.000Z.', + '2026-10-27 11:00:00.000: old', + ]); + expect(windowCalls).toEqual([expect.objectContaining({ startTime: NOW - 172_800_000, endTime: NOW })]); + }); + + it('prints no notice for a window of exactly 24 hours', async () => { + const { command, lines } = commandUnderTest({ + resolved: { 'log-type': 'server', since: '24h' }, + serverLogs: [{ message: 'x' }], + }); + + await command.run(); + + expect(lines).toEqual(['x']); + }); + + it('rejects a bad window before any read', async () => { + const { command, windowCalls } = commandUnderTest({ resolved: { 'log-type': 'server', since: 'yesterday' } }); + + await expect(command.run()).rejects.toThrow(UsageError); + expect(windowCalls).toEqual([]); + }); + + it('propagates a failed server read', async () => { + const failure = new LaunchApiError(500, [{ code: 'launch.UNKNOWN', message: 'boom' }]); + const { command } = commandUnderTest({ resolved: { 'log-type': 'server' } }); + Object.assign((command as unknown as { services: { api: { serverLogs: object } } }).services.api.serverLogs, { + window: async () => Promise.reject(failure), + }); + + await expect(command.run()).rejects.toBe(failure); + }); + + it('follows the latest deployment, prints the status line after the lines and releases the listener', async () => { + const release = jest.fn(); + jest.spyOn(interruptible, 'onInterrupt').mockReturnValue(release); + const seen: { scope?: unknown; stop?: AbortSignal } = {}; + jest.spyOn(DeploymentFollower.prototype, 'watch').mockImplementation(async function (this: DeploymentFollower, scope, stop) { + seen.scope = scope; + seen.stop = stop; + (this as unknown as { services: { ux: UxLike } }).services.ux.print('a build line'); + return outcome('success', 'LIVE', { deploymentNumber: 4 }); + }); + const { command, lines } = commandUnderTest(); + + await command.run(); + + expect(seen.scope).toEqual({ org: 'org1', project: 'proj1', environment: 'env1', deployment: 'dLatest' }); + expect(seen.stop?.aborted).toBe(false); + expect(lines).toEqual(['a build line', 'Deployment #4 is LIVE.']); + expect(release).toHaveBeenCalledTimes(1); + }); + + it('prints the empty notice before the status line when the follower printed nothing', async () => { + jest.spyOn(DeploymentFollower.prototype, 'watch').mockResolvedValue(outcome('failure', 'FAILED', {})); + const { command, lines } = commandUnderTest({ resolved: { deployment: 'd1' }, outputIsTTY: true }); + + await command.run(); + + expect(lines).toEqual([ + '\u001b[33mNo deployment logs found for deployment d1.\u001b[39m', + 'Deployment is FAILED.', + ]); + }); + + it('counts the unavailable notice as output so it never claims there were no logs', async () => { + jest.spyOn(DeploymentFollower.prototype, 'watch').mockImplementation(async function (this: DeploymentFollower) { + (this as unknown as { services: { ux: UxLike } }).services.ux.print(' ! Could not read the deployment logs (x).'); + return outcome('success', 'LIVE', { deploymentNumber: 1 }); + }); + const { command, lines } = commandUnderTest(); + + await command.run(); + + expect(lines).toEqual([' ! Could not read the deployment logs (x).', 'Deployment #1 is LIVE.']); + }); + + it('exits 1 with the timed-out message and prints no status line when the wait ran out', async () => { + jest.spyOn(DeploymentFollower.prototype, 'watch').mockResolvedValue(outcome('timed-out', 'DEPLOYING', {})); + const { command, lines } = commandUnderTest({ resolved: { deployment: 'd1' } }); + + const running = command.run(); + + await expect(running).rejects.toThrow(DeploymentUnsuccessfulError); + await expect(running).rejects.toThrow( + 'Stopped waiting after 20 minutes; the deployment was still DEPLOYING. ' + + 'Run csdx launch:logs:get --org org1 --project proj1 --env env1 --deployment d1 again to keep following it.', + ); + expect(lines).toEqual([]); + }); + + it('stops on Ctrl-C with the yellow line and exit 3, then releases the listener', async () => { + const release = jest.fn(); + let interrupt: () => void = () => undefined; + jest.spyOn(interruptible, 'onInterrupt').mockImplementation((listener) => { + interrupt = listener; + return release; + }); + jest.spyOn(DeploymentFollower.prototype, 'watch').mockImplementation( + (_scope, stop) => + new Promise((_resolve, reject) => { + stop?.addEventListener('abort', () => reject(stop.reason), { once: true }); + interrupt(); + }), + ); + const { command, lines } = commandUnderTest({ outputIsTTY: true }); + + const running = command.run(); + + await expect(running).rejects.toBeInstanceOf(Errors.ExitError); + await expect(running).rejects.toMatchObject({ oclif: { exit: EXIT_CANCELLED } }); + expect(lines).toEqual(['\u001b[33mStopped following the logs.\u001b[39m']); + expect(release).toHaveBeenCalledTimes(1); + }); + + it('rethrows a failure that is not the interrupt and still releases the listener', async () => { + const release = jest.fn(); + jest.spyOn(interruptible, 'onInterrupt').mockReturnValue(release); + const failure = new LaunchApiError(500, [{ code: 'launch.UNKNOWN', message: 'boom' }]); + jest.spyOn(DeploymentFollower.prototype, 'watch').mockRejectedValue(failure); + const { command, lines } = commandUnderTest(); + + await expect(command.run()).rejects.toBe(failure); + expect(lines).toEqual([]); + expect(release).toHaveBeenCalledTimes(1); + }); + + it('does not take the interrupt path for a failure when the signal was aborted with another reason', async () => { + const release = jest.fn(); + let interrupt: () => void = () => undefined; + jest.spyOn(interruptible, 'onInterrupt').mockImplementation((listener) => { + interrupt = listener; + return release; + }); + const failure = new LaunchApiError(500, [{ code: 'launch.UNKNOWN', message: 'boom' }]); + jest.spyOn(DeploymentFollower.prototype, 'watch').mockImplementation(async () => { + interrupt(); + throw failure; + }); + const { command, lines } = commandUnderTest(); + + await expect(command.run()).rejects.toBe(failure); + expect(lines).toEqual([]); + }); + + it('registers no interrupt listener and reads no deployment logs for --type server', async () => { + const listener = jest.spyOn(interruptible, 'onInterrupt'); + const watch = jest.spyOn(DeploymentFollower.prototype, 'watch'); + const { command } = commandUnderTest({ resolved: { 'log-type': 'server' } }); + + await command.run(); + + expect(listener).not.toHaveBeenCalled(); + expect(watch).not.toHaveBeenCalled(); + }); +}); diff --git a/src/commands/launch/logs/get.ts b/src/commands/launch/logs/get.ts new file mode 100644 index 00000000..da0d7d25 --- /dev/null +++ b/src/commands/launch/logs/get.ts @@ -0,0 +1,185 @@ +import type { Interfaces } from '@oclif/core'; + +import { EXIT_CANCELLED } from '../../../core/constants'; +import { UsageError } from '../../../core/errors'; +import { flagsFor, inputs } from '../../../core/inputs'; +import { onInterrupt } from '../../../core/interruptible-ux'; +import { LaunchCommand } from '../../../core/launch-command'; +import type { UxLike } from '../../../core/prompt'; +import type { ServiceContext } from '../../../core/service-context'; +import { DeploymentUnsuccessfulError, DeploymentWaitInterruptedError } from '../../../deployments/deployment.errors'; +import { DeploymentFollower } from '../../../deployments/deployment.follower'; +import { fetchDeployment } from '../../../deployments/deployment.resolver'; +import { defaultWatchTiming } from '../../../deployments/deployment.watcher'; +import { LOG_TYPE_FLAG, windowOnlyWithServer } from '../../../logs/logs.inputs'; +import { + deploymentStatusLine, + logsWaitTimedOutMessage, + noDeploymentLogsLine, + noServerLogsLine, + serverLogLine, + serverLogsCapLine, + serverLogsRetentionLine, + stoppedFollowingLine, +} from '../../../logs/logs.presenter'; +import { LiveLogFollower } from '../../../logs/live-log.follower'; +import { parseLogWindow, type LogWindow } from '../../../logs/log-window'; +import { SERVER_LOGS_PAGE_CAP } from '../../../logs/types'; + +const getInputs = inputs({ + org: { required: true }, + project: { required: true }, + env: { required: true }, + deployment: {}, + 'log-type': {}, + since: {}, + until: {}, +}); + +const { 'log-type': logTypeFlag, ...otherFlags } = flagsFor(getInputs); + +interface LogScope { + org: string; + project: string; + environment: string; + deployment: string; +} + +export default class LogsGet extends LaunchCommand { + static description = 'Read the build or server logs of a deployment of a Launch environment'; + + static examples = [ + '$ csdx launch:logs:get --org --project --env ', + '$ csdx launch:logs:get --org --project --env ' + + '--deployment --type server --since 2h', + ]; + + static inputs = getInputs; + + static flags = { ...otherFlags, [LOG_TYPE_FLAG]: logTypeFlag }; + + static rules = [windowOnlyWithServer('since'), windowOnlyWithServer('until')]; + + protected async parse< + F extends Record, + B extends Record, + A extends Record, + >(options?: Interfaces.Input, argv?: string[]): Promise> { + const parsed = await super.parse(options, argv); + + if (LOG_TYPE_FLAG in parsed.flags) { + Object.assign(parsed.flags, { 'log-type': parsed.flags[LOG_TYPE_FLAG] }); + } + + return parsed; + } + + async run(): Promise { + const type = this.resolved['log-type']; + const { org, project, env: environment } = this.resolved; + + if (type === 'server') { + const window = parseLogWindow({ since: this.resolved.since, until: this.resolved.until }, () => Date.now()); + + await this.printServerLogs(await this.verifiedDeployment({ org, project, environment }), window); + return; + } + + const scope = await this.verifiedDeployment({ org, project, environment }); + + await this.untilInterrupted((stop) => + type === 'live' ? this.followLiveLogs(scope, stop) : this.followDeploymentLogs(scope, stop), + ); + } + + private async verifiedDeployment(environmentScope: Omit): Promise { + const { deployments } = this.services.api; + const requested = this.resolved.deployment; + + if (requested !== undefined) { + await fetchDeployment(deployments, { ...environmentScope, deployment: requested }); + + return { ...environmentScope, deployment: requested }; + } + + const latest = await deployments.latest(environmentScope); + + if (latest === undefined) { + throw new UsageError('No deployments found in this environment.'); + } + + return { ...environmentScope, deployment: latest.uid }; + } + + private async printServerLogs(scope: LogScope, window: LogWindow): Promise { + const outputIsTTY = this.services.outputIsTTY === true; + const { startTime, endTime, clampedFrom } = window; + const logs = await this.services.api.serverLogs.window({ ...scope, startTime, endTime }); + + if (clampedFrom !== undefined) { + this.ux.print(serverLogsRetentionLine(clampedFrom, outputIsTTY)); + } + + if (logs.length === 0) { + this.ux.print(noServerLogsLine(startTime, endTime, outputIsTTY)); + return; + } + + for (const log of logs) { + this.ux.print(serverLogLine(log, outputIsTTY, process.stdout.columns)); + } + + if (logs.length === SERVER_LOGS_PAGE_CAP) { + this.ux.print(serverLogsCapLine(outputIsTTY)); + } + } + + private async untilInterrupted(follow: (stop: AbortSignal) => Promise): Promise { + const stop = new AbortController(); + const release = onInterrupt(() => stop.abort(new DeploymentWaitInterruptedError('Stopped following the logs.'))); + + try { + await follow(stop.signal); + } catch (error) { + if (stop.signal.aborted && error === stop.signal.reason) { + this.ux.print(stoppedFollowingLine(this.services.outputIsTTY === true)); + this.exit(EXIT_CANCELLED); + } + + throw error; + } finally { + release(); + } + } + + private followLiveLogs(scope: LogScope, stop: AbortSignal): Promise { + return new LiveLogFollower(this.services, defaultWatchTiming(), { columns: process.stdout.columns }).follow( + scope, + stop, + ); + } + + private async followDeploymentLogs(scope: LogScope, stop: AbortSignal): Promise { + const outputIsTTY = this.services.outputIsTTY === true; + let printed = 0; + const counting: UxLike = { + ...this.ux, + print: (message) => { + printed += 1; + this.ux.print(message); + }, + }; + const services: ServiceContext = { ...this.services, ux: counting }; + const outcome = await new DeploymentFollower(services, defaultWatchTiming()).watch(scope, stop); + + if (outcome.kind === 'timed-out') { + throw new DeploymentUnsuccessfulError(logsWaitTimedOutMessage(outcome.status, scope, scope.deployment)); + } + + if (printed === 0) { + this.ux.print(noDeploymentLogsLine(scope.deployment, outputIsTTY)); + } + + this.ux.print(deploymentStatusLine(outcome.deployment, outcome.status)); + } +} diff --git a/src/core/interruptible-ux.test.ts b/src/core/interruptible-ux.test.ts index 1100a17d..c1341bf4 100644 --- a/src/core/interruptible-ux.test.ts +++ b/src/core/interruptible-ux.test.ts @@ -1,7 +1,7 @@ import { EventEmitter } from 'node:events'; import { CancelledError } from './errors'; -import { cancelOnInterrupt, holdEventLoop } from './interruptible-ux'; +import { cancelOnInterrupt, holdEventLoop, onInterrupt } from './interruptible-ux'; import type { UxLike } from './prompt'; function pendingUx(): { ux: UxLike; payloads: unknown[]; printed: string[]; settle: (outcome: { value?: unknown; error?: Error }) => void } { @@ -169,3 +169,73 @@ describe('holdEventLoop', () => { expect(activeTimers()).toBe(before); }); }); + +describe('onInterrupt', () => { + it('runs the listener on Ctrl-C once and stops listening when released', async () => { + const signals = new EventEmitter(); + const calls: string[] = []; + + const release = onInterrupt(() => calls.push('interrupted'), signals); + const attached = signals.listenerCount('SIGINT'); + signals.emit('SIGINT'); + await new Promise((done) => setImmediate(done)); + signals.emit('SIGINT'); + + expect(attached).toBe(1); + expect(calls).toEqual(['interrupted']); + expect(signals.listenerCount('SIGINT')).toBe(0); + release(); + }); + + it('removes the listener on Release before any signal, and a second Release is harmless', () => { + const signals = new EventEmitter(); + const calls: string[] = []; + + const release = onInterrupt(() => calls.push('interrupted'), signals); + release(); + release(); + signals.emit('SIGINT'); + + expect(signals.listenerCount('SIGINT')).toBe(0); + expect(calls).toEqual([]); + }); + + it('is still listening while a later SIGINT listener runs, so signal-exit does not re-raise it and exit 130', async () => { + const signals = new EventEmitter(); + const counted: number[] = []; + + onInterrupt(() => undefined, signals); + signals.on('SIGINT', () => counted.push(signals.listenerCount('SIGINT'))); + signals.emit('SIGINT'); + await new Promise((done) => setImmediate(done)); + + expect(counted).toEqual([2]); + expect(signals.listenerCount('SIGINT')).toBe(1); + }); + + it('does not remove a listener that Release already removed when the signal then arrives in the same tick', async () => { + const signals = new EventEmitter(); + const other = jest.fn(); + signals.on('SIGINT', other); + + const release = onInterrupt(() => undefined, signals); + signals.emit('SIGINT'); + release(); + release(); + await new Promise((done) => setImmediate(done)); + + expect(signals.listenerCount('SIGINT')).toBe(1); + expect(other).toHaveBeenCalledTimes(1); + }); + + it('listens on the process itself by default and restores the listener count on Release', () => { + const before = process.listenerCount('SIGINT'); + + const release = onInterrupt(() => undefined); + const during = process.listenerCount('SIGINT'); + release(); + + expect(during).toBe(before + 1); + expect(process.listenerCount('SIGINT')).toBe(before); + }); +}); diff --git a/src/core/interruptible-ux.ts b/src/core/interruptible-ux.ts index 1ae8c888..bd50bc0b 100644 --- a/src/core/interruptible-ux.ts +++ b/src/core/interruptible-ux.ts @@ -16,6 +16,24 @@ export function holdEventLoop(): Release { return () => clearInterval(timer); } +export function onInterrupt(listener: () => void, signals: InterruptSource = process): Release { + let attached = true; + const release = (): void => { + if (attached) { + attached = false; + signals.removeListener('SIGINT', handle); + } + }; + const handle = (): void => { + queueMicrotask(release); + listener(); + }; + + signals.on('SIGINT', handle); + + return release; +} + export interface InterruptOptions { signals?: InterruptSource; hold?: () => Release; diff --git a/src/core/service-context.test.ts b/src/core/service-context.test.ts index e0517159..6289f3e7 100644 --- a/src/core/service-context.test.ts +++ b/src/core/service-context.test.ts @@ -1,6 +1,7 @@ import { randomUUID } from 'node:crypto'; import { HttpClient, authHandler, configHandler } from '@contentstack/cli-utilities'; +import nock from 'nock'; import { SessionExpiredError, UnauthenticatedError } from './errors'; import type { UxLike } from './prompt'; @@ -187,3 +188,30 @@ describe('buildServiceContext request wiring', () => { expirySpy.mockRestore(); }); }); + +describe('buildServiceContext live logs wiring', () => { + afterEach(() => { + nock.cleanAll(); + }); + + it('T84: opens the live route under the logs base path with the session token and the analytics info', async () => { + const token = randomUUID(); + const configSpy = basicSession(token); + const route = nock('https://launch-api.test', { + reqheaders: { accept: 'text/event-stream', authtoken: token, 'x-cs-cli': 'cli/2.0.0', 'x-organization-uid': 'org1' }, + }) + .get('/logs/projects/p1/environments/e1/deployments/d1/logs/live') + .reply(200, 'data: hello\n\n', { 'content-type': 'text/event-stream' }); + const frames: unknown[] = []; + + await context().api.liveLogs.open( + { org: 'org1', project: 'p1', environment: 'e1', deployment: 'd1' }, + { onFrame: (frame) => frames.push(frame) }, + new AbortController().signal, + ); + + expect(route.isDone()).toBe(true); + expect(frames).toEqual([{ event: undefined, data: 'hello' }]); + configSpy.mockRestore(); + }); +}); diff --git a/src/core/service-context.ts b/src/core/service-context.ts index e89f1807..b9e9b027 100644 --- a/src/core/service-context.ts +++ b/src/core/service-context.ts @@ -3,6 +3,7 @@ import { buildApi } from '../resources'; import { RestApiClient } from '../transport/rest-client'; import { selectAuthStrategy } from '../transport/auth-strategy'; import { createCmaSession } from '../transport/cma-client'; +import { EventStreamClient } from '../transport/event-stream'; import { getLogsApiBaseUrl, getManageApiBaseUrl, resolveLaunchAppUrl } from './region'; import { openInBrowser } from './browser'; import type { UxLike } from './prompt'; @@ -37,6 +38,11 @@ export function buildServiceContext(options: ServiceContextOptions): ServiceCont clientFor(getManageApiBaseUrl(options.launchHubUrl)), cma, clientFor(getLogsApiBaseUrl(options.launchHubUrl)), + new EventStreamClient({ + baseUrl: getLogsApiBaseUrl(options.launchHubUrl), + analyticsInfo: options.analyticsInfo, + auth, + }), ), ux: options.ux, isTTY: options.isTTY, diff --git a/src/deployments/deployment.presenter.ts b/src/deployments/deployment.presenter.ts index 83683976..1171e358 100644 --- a/src/deployments/deployment.presenter.ts +++ b/src/deployments/deployment.presenter.ts @@ -96,7 +96,7 @@ export function wrapLogMessage(message: string, width: number): string[] { return rows; } -function clockOf(time: number): string { +export function clockOf(time: number): string { const at = new Date(time); const pad = (value: number) => String(value).padStart(2, '0'); diff --git a/src/deployments/deployment.watcher.test.ts b/src/deployments/deployment.watcher.test.ts index 73d4534f..81a08aca 100644 --- a/src/deployments/deployment.watcher.test.ts +++ b/src/deployments/deployment.watcher.test.ts @@ -1,6 +1,7 @@ import { randomBytes } from 'node:crypto'; import type { UxLike } from '../core/prompt'; +import { MAX_PAGES } from '../core/constants'; import { DEPLOYMENT_LOGS_FROM } from './deployment.log-tail'; import { DEPLOYMENT_MAX_BACKOFF_STEPS, @@ -480,6 +481,7 @@ describe('deployment log streaming', () => { { message: 'three', timestamp: '2026-09-25T10:00:00.123Z' }, { message: 'four', timestamp: '2026-09-25T10:00:00.500Z' }, ], + [], ], ); @@ -762,7 +764,7 @@ describe('deployment wait loop stopped from outside', () => { await expect(watchDeployment(aborting)).rejects.toBe(reason); expect(slept).toEqual([]); - expect(events).toEqual(['poll DEPLOYING', `start ${DEPLOYMENT_LOADER_MESSAGE}`, 'stop']); + expect(events).toEqual(['poll DEPLOYING', 'stop']); expect(jest.getTimerCount()).toBe(0); } finally { jest.useRealTimers(); @@ -809,6 +811,243 @@ describe('deployment wait loop stopped from outside', () => { }); }); +function logAt(second: number, message: string): DeploymentLog { + return { message, timestamp: new Date(Date.UTC(2026, 8, 25, 10, 0, second)).toISOString() }; +} + +describe('deployment log drain on the terminal poll', () => { + it('keeps reading from the advancing cursor until nothing new arrives, printing each line once in order and never sleeping', async () => { + const { deps, lines, since } = streamingHarness( + ['LIVE'], + [[logAt(1, 'one')], [logAt(2, 'two')], [logAt(3, 'three')], []], + ); + const slept: number[] = []; + + const outcome = await watchDeployment({ ...deps, sleep: async (ms) => void slept.push(ms) }); + + expect(outcome.kind).toBe('success'); + expect(lines).toEqual([ + '2026-09-25 10:00:01.000: one', + '2026-09-25 10:00:02.000: two', + '2026-09-25 10:00:03.000: three', + ]); + expect(since).toEqual([ + DEPLOYMENT_LOGS_FROM, + '2026-09-25T10:00:00.999Z', + '2026-09-25T10:00:01.999Z', + '2026-09-25T10:00:02.999Z', + ]); + expect(slept).toEqual([]); + }); + + it('reads exactly MAX_PAGES pages when every page brings something new', async () => { + let reads = 0; + const { deps, lines } = streamingHarness(['LIVE'], [[]]); + const logs = async (): Promise => { + reads += 1; + return [logAt(reads, `line ${reads}`)]; + }; + + await watchDeployment({ ...deps, logs }); + + expect(reads).toBe(MAX_PAGES); + expect(lines).toHaveLength(MAX_PAGES); + }); + + it('makes exactly one logs read per in-flight poll and drains only on the terminal one', async () => { + const { deps, since } = streamingHarness( + ['QUEUED', 'DEPLOYING', 'LIVE'], + [[logAt(1, 'a')], [logAt(2, 'b')], [logAt(3, 'c')], [logAt(4, 'd')], []], + ); + + await watchDeployment(deps); + + expect(since).toEqual([ + DEPLOYMENT_LOGS_FROM, + '2026-09-25T10:00:00.999Z', + '2026-09-25T10:00:01.999Z', + '2026-09-25T10:00:02.999Z', + '2026-09-25T10:00:03.999Z', + ]); + }); + + it('stops draining on a page that repeats only what was printed, and prints nothing twice', async () => { + const { deps, lines, since } = streamingHarness(['LIVE'], [[logAt(1, 'one')], [logAt(1, 'one')], [logAt(9, 'never')]]); + + await watchDeployment(deps); + + expect(lines).toEqual(['2026-09-25 10:00:01.000: one']); + expect(since).toHaveLength(2); + }); + + it('stops draining silently at a read that fails mid-drain and leaves the outcome alone', async () => { + const { deps, lines } = streamingHarness(['LIVE'], [[logAt(1, 'one')], new Error('Bad gateway'), [logAt(2, 'two')]]); + let reads = 0; + const logs = (after: string): Promise => { + reads += 1; + return deps.logs(after); + }; + + const outcome = await watchDeployment({ ...deps, logs }); + + expect(outcome).toEqual(expect.objectContaining({ kind: 'success', status: 'LIVE' })); + expect(lines).toEqual([ + '2026-09-25 10:00:01.000: one', + ]); + expect(reads).toBe(2); + }); + + it('prints nothing for log reads that keep failing across polls', async () => { + const { deps, lines } = streamingHarness(['DEPLOYING', 'LIVE'], [new Error('down'), new Error('down')]); + + const outcome = await watchDeployment(deps); + + expect(outcome).toEqual(expect.objectContaining({ kind: 'success', status: 'LIVE' })); + expect(lines).toEqual([]); + }); + + it('stops the drain when stopped mid-read, rejecting with the reason, reading no further and stopping the loader last', async () => { + const controller = new AbortController(); + const reason = new Error('interrupted'); + const { deps, lines, events } = streamingHarness(['LIVE'], [[]]); + let reads = 0; + const logs = async (): Promise => { + reads += 1; + + if (reads === 2) { + controller.abort(reason); + } + + return [logAt(reads, `line ${reads}`)]; + }; + + await expect(watchDeployment({ ...deps, logs, stop: controller.signal })).rejects.toBe(reason); + + expect(reads).toBe(2); + expect(lines).toEqual(['2026-09-25 10:00:01.000: line 1']); + expect(events.at(-1)).toBe('stop'); + }); +}); + +describe('deployment wait loop already stopped when it would sleep', () => { + function stoppedAtSleep(statuses: string[]) { + const controller = new AbortController(); + const slept: number[] = []; + const { deps: base } = harness(statuses); + const deps = { + ...base, + stop: controller.signal, + sleep: async (ms: number) => void slept.push(ms), + }; + + return { deps, controller, slept }; + } + + it('ends with the stop reason without sleeping when the signal was aborted while the poll was pending', async () => { + const { deps, controller, slept } = stoppedAtSleep(['DEPLOYING', 'LIVE']); + const reason = new Error('interrupted during the poll'); + const poll = deps.poll; + + await expect( + watchDeployment({ + ...deps, + poll: async () => { + const deployment = await poll(); + controller.abort(reason); + return deployment; + }, + }), + ).rejects.toBe(reason); + + expect(slept).toEqual([]); + }); + + it('ends with the stop reason without sleeping when the signal was aborted during the logs read of an in-flight poll', async () => { + const { deps, controller, slept } = stoppedAtSleep(['DEPLOYING', 'LIVE']); + const reason = new Error('interrupted during the logs read'); + + await expect( + watchDeployment({ + ...deps, + logs: async () => { + controller.abort(reason); + return []; + }, + }), + ).rejects.toBe(reason); + + expect(slept).toEqual([]); + }); + + it('does not sleep when the signal was aborted just as the loader started', async () => { + const { deps, controller, slept } = stoppedAtSleep(['DEPLOYING', 'LIVE']); + const reason = new Error('interrupted at the loader'); + + await expect( + watchDeployment({ + ...deps, + loader: { start: () => controller.abort(reason), stop: () => undefined }, + }), + ).rejects.toBe(reason); + + expect(slept).toEqual([]); + }); + + it('does not sleep between failing polls when the signal was aborted by the time the retry would wait', async () => { + const { deps, controller, slept } = stoppedAtSleep(['DEPLOYING']); + const reason = new Error('interrupted during the failing poll'); + + await expect( + watchDeployment({ + ...deps, + poll: async () => { + controller.abort(reason); + throw new Error('502'); + }, + }), + ).rejects.toBe(reason); + + expect(slept).toEqual([]); + }); + + it('leaves no timer and no abort listener behind when stopped during the real sleep', async () => { + jest.useRealTimers(); + const controller = new AbortController(); + const reason = new Error('interrupted in the real sleep'); + const timers = (): number => process.getActiveResourcesInfo().filter((resource) => resource === 'Timeout').length; + const before = timers(); + const { deps } = harness(['DEPLOYING']); + + const waiting = watchDeployment({ + ...deps, + sleep: defaultWatchTiming().sleep, + stop: controller.signal, + pollDelayMs: 600_000, + timeoutMs: 24 * 60 * 60 * 1000, + }).catch((error: unknown) => error); + await new Promise((resolve) => setImmediate(resolve)); + const during = timers(); + controller.abort(reason); + const settled = await waiting; + + expect(during).toBe(before + 1); + expect(settled).toBe(reason); + expect(timers()).toBe(before); + }); + + it('rejects an already aborted signal at once from the default sleep without arming a timer', async () => { + const controller = new AbortController(); + const reason = new Error('already aborted'); + controller.abort(reason); + const timers = (): number => process.getActiveResourcesInfo().filter((resource) => resource === 'Timeout').length; + const before = timers(); + + await expect(defaultWatchTiming().sleep(600_000, controller.signal)).rejects.toBe(reason); + + expect(timers()).toBe(before); + }); +}); + describe('deployment wait loop with an until condition', () => { const isLive = (deployment: Deployment): boolean => deployment.status === 'LIVE'; diff --git a/src/deployments/deployment.watcher.ts b/src/deployments/deployment.watcher.ts index 79fd798b..bd108238 100644 --- a/src/deployments/deployment.watcher.ts +++ b/src/deployments/deployment.watcher.ts @@ -1,3 +1,4 @@ +import { MAX_PAGES } from '../core/constants'; import type { Loader } from '../core/loader'; import type { UxLike } from '../core/prompt'; import { RetryPolicy } from '../transport/retry-policy'; @@ -13,7 +14,7 @@ export const DEPLOYMENT_MAX_POLL_ERRORS = 3; export const DEPLOYMENT_LOADER_MESSAGE = 'Loading deployment logs...'; export interface WatchTiming { - sleep(ms: number): Promise; + sleep(ms: number, stop?: AbortSignal): Promise; now(): number; pollDelayMs: number; maxBackoffSteps: number; @@ -38,9 +39,29 @@ export interface DeploymentOutcome { deployment: Deployment; } +function abortableSleep(ms: number, stop?: AbortSignal): Promise { + return new Promise((resolve, reject) => { + if (stop?.aborted) { + reject(stop.reason); + return; + } + + const abandon = (): void => { + clearTimeout(timer); + reject(stop?.reason); + }; + const timer = setTimeout(() => { + stop?.removeEventListener('abort', abandon); + resolve(); + }, ms); + + stop?.addEventListener('abort', abandon, { once: true }); + }); +} + export function defaultWatchTiming(): WatchTiming { return { - sleep: (ms: number) => new Promise((done) => setTimeout(done, ms)), + sleep: abortableSleep, now: () => Date.now(), pollDelayMs: DEPLOYMENT_POLL_DELAY_MS, maxBackoffSteps: DEPLOYMENT_MAX_BACKOFF_STEPS, @@ -72,15 +93,13 @@ function sleepUnlessStopped(deps: DeploymentWatchDeps, ms: number): Promise((resolve, reject) => { const abandon = (): void => reject(stop.reason); stop.addEventListener('abort', abandon, { once: true }); - deps.sleep(ms).then( + deps.sleep(ms, stop).then( () => { stop.removeEventListener('abort', abandon); resolve(); @@ -139,8 +158,18 @@ async function waitFor(deps: DeploymentWatchDeps): Promise { const kind = deps.until === undefined ? classifyStatus(deployment.status) : untilKind(deps.until, deployment); const terminal = kind === 'success' || kind === 'failure'; - for (const log of await freshLogs(deps, tail)) { - deps.ux.print(deploymentLogLine(log, deps.outputIsTTY, process.stdout.columns)); + for (let page = 0; page < (terminal ? MAX_PAGES : 1); page += 1) { + const logs = await freshLogs(deps, tail); + + deps.stop?.throwIfAborted(); + + for (const log of logs) { + deps.ux.print(deploymentLogLine(log, deps.outputIsTTY, process.stdout.columns)); + } + + if (logs.length === 0) { + break; + } } if (terminal) { diff --git a/src/logs/live-log.follower.test.ts b/src/logs/live-log.follower.test.ts new file mode 100644 index 00000000..93dede22 --- /dev/null +++ b/src/logs/live-log.follower.test.ts @@ -0,0 +1,478 @@ +import { randomBytes } from 'node:crypto'; + +import { cliux } from '@contentstack/cli-utilities'; + +import type { Loader } from '../core/loader'; +import type { UxLike } from '../core/prompt'; +import type { ServiceContext } from '../core/service-context'; +import { LaunchApiError, LaunchNetworkError } from '../transport/errors'; +import type { StreamFrame } from '../transport/event-stream'; +import { RetryPolicy } from '../transport/retry-policy'; +import type { LiveLogHandlers } from './live-logs.api'; +import { LIVE_LOADER_MESSAGE, LiveLogFollower } from './live-log.follower'; + +const SCOPE = { + org: randomBytes(9).toString('hex'), + project: randomBytes(12).toString('hex'), + environment: randomBytes(12).toString('hex'), + deployment: randomBytes(12).toString('hex'), +}; + +const SESSION: StreamFrame = { event: 'session', data: '{"expiresAt":"2026-10-28T14:05:09.000Z"}' }; +const ENDED: StreamFrame = { event: 'session-ended', data: '{"reason":"timeout"}' }; +const HEARTBEAT: StreamFrame = { event: undefined, data: '' }; +const YELLOW = (text: string): string => `\u001b[33m${text}\u001b[39m`; + +function log(message: string, timestamp = '2026-10-28T10:00:00.000Z'): StreamFrame { + return { event: undefined, data: JSON.stringify({ timestamp, message, source: 'edge-function' }) }; +} + +type Attempt = (handlers: LiveLogHandlers, signal: AbortSignal) => Promise; + +function delivering(frames: StreamFrame[], after: () => Promise = async () => undefined): Attempt { + return async (handlers) => { + frames.forEach((frame) => handlers.onFrame(frame)); + await after(); + }; +} + +function failing(error: unknown, frames: StreamFrame[] = []): Attempt { + return delivering(frames, async () => { + throw error; + }); +} + +const dropped = (): LaunchNetworkError => new LaunchNetworkError('socket closed', undefined, true); + +function untilAborted(): Attempt { + return (_handlers, signal) => + new Promise((_resolve, reject) => { + if (signal.aborted) { + reject(signal.reason); + return; + } + + signal.addEventListener('abort', () => reject(signal.reason), { once: true }); + }); +} + +function harness(attempts: Attempt[], options: { outputIsTTY?: boolean; columns?: number } = {}) { + const lines: string[] = []; + const events: string[] = []; + const delays: number[] = []; + const signals: AbortSignal[] = []; + let opened = 0; + const ux: UxLike = { + print: (message: string) => { + lines.push(message); + events.push('print'); + }, + inquire: async () => undefined as never, + }; + const loader: Loader = { + start: (message) => events.push(`start:${message}`), + stop: () => events.push('stop'), + }; + const services = { + ux, + outputIsTTY: options.outputIsTTY === true, + api: { + liveLogs: { + open: async (_scope: unknown, handlers: LiveLogHandlers, signal: AbortSignal) => { + signals.push(signal); + const attempt = attempts[opened]; + opened += 1; + await attempt(handlers, signal); + }, + }, + }, + } as unknown as ServiceContext; + const stop = new AbortController(); + const sleep = jest.fn(async (ms: number, signal?: AbortSignal) => { + delays.push(ms); + + if (signal?.aborted) { + throw signal.reason; + } + }); + const follower = new LiveLogFollower(services, { sleep }, { + loader, + columns: options.columns, + retry: new RetryPolicy({ retryDelayMs: 700 }), + }); + + return { + lines, + events, + delays, + signals, + stop, + sleep, + opens: () => opened, + follow: () => follower.follow(SCOPE, stop.signal), + }; +} + +describe('LiveLogFollower', () => { + it('T87: prints each log frame through the deployment log line, ignoring the source and keeping the colour on a terminal', async () => { + const run = harness([delivering([log('\u001b[31mboom\u001b[0m'), ENDED])], { outputIsTTY: true }); + + await run.follow(); + + expect(run.lines[0]).toBe('\u001b[2m10:00:00\u001b[22m \u001b[31mboom\u001b[0m'); + expect(run.lines[0]).not.toContain('edge-function'); + }); + + it('T87: prints the plain stamped line without escape codes on a pipe', async () => { + const run = harness([delivering([log('\u001b[31mboom\u001b[0m'), ENDED])]); + + await run.follow(); + + expect(run.lines).toEqual(['2026-10-28 10:00:00.000: boom', 'The live session ended (server limit). Run the command again to keep following.']); + }); + + it('T87: wraps a long line to the terminal width it was given', async () => { + const run = harness([delivering([log('alpha bravo charlie delta echo foxtrot golf hotel'), ENDED])], { + outputIsTTY: true, + columns: 50, + }); + + await run.follow(); + + expect(run.lines[0]).toBe( + '\u001b[2m10:00:00\u001b[22m alpha bravo charlie delta echo foxtrot\n golf hotel', + ); + }); + + it.each([ + ['a heartbeat', HEARTBEAT], + ['a frame that is not JSON', { event: undefined, data: 'hello' }], + ['a half-written JSON frame', { event: undefined, data: '{"message":' }], + ['a JSON number', { event: undefined, data: '42' }], + ['JSON null', { event: undefined, data: 'null' }], + ['a JSON string', { event: undefined, data: '""' }], + ['an event this CLI does not know', { event: 'something-new', data: '{"message":"x"}' }], + ])('T75: skips %s and prints only the one real log line', async (_name, skipped) => { + const run = harness([delivering([skipped, log('real'), skipped, ENDED])]); + + await run.follow(); + + expect(run.lines).toEqual([ + '2026-10-28 10:00:00.000: real', + 'The live session ended (server limit). Run the command again to keep following.', + ]); + }); + + it('T85: stops the spinner before every print, restarts it after, and ends stopped on a terminal', async () => { + const run = harness([delivering([SESSION, log('one'), log('two'), ENDED])], { outputIsTTY: true }); + + await run.follow(); + + const start = `start:${LIVE_LOADER_MESSAGE}`; + expect(LIVE_LOADER_MESSAGE).toBe('Waiting for live server logs...'); + expect(run.events).toEqual([ + start, + 'stop', 'print', start, + 'stop', 'print', start, + 'stop', 'print', start, + 'stop', 'print', + 'stop', + ]); + }); + + it('T85: stops the spinner when the stream fails for good', async () => { + const run = harness([failing(new LaunchApiError(404, [{ code: 'launch.DEPLOYMENT.NOT_FOUND' }]))]); + + await expect(run.follow()).rejects.toBeInstanceOf(LaunchApiError); + + expect(run.events[run.events.length - 1]).toBe('stop'); + }); + + it('T85: starts no spinner and prints no escape code on a pipe by default', async () => { + const spinner = jest.spyOn(cliux, 'loaderV2').mockReturnValue(undefined as never); + const printed: string[] = []; + const services = { + ux: { print: (message: string) => printed.push(message), inquire: async () => undefined as never }, + outputIsTTY: false, + api: { liveLogs: { open: async (_s: unknown, handlers: LiveLogHandlers) => handlers.onFrame(ENDED) } }, + } as unknown as ServiceContext; + + await new LiveLogFollower(services, { sleep: async () => undefined }).follow(SCOPE, new AbortController().signal); + + expect(spinner).not.toHaveBeenCalled(); + expect(printed.join('')).not.toContain('\u001b'); + }); + + it('T85: draws the real spinner on a terminal by default and stops it', async () => { + const handle = { id: 'spinner' }; + const spinner = jest.spyOn(cliux, 'loaderV2').mockReturnValue(handle as never); + const services = { + ux: { print: () => undefined, inquire: async () => undefined as never }, + outputIsTTY: true, + api: { liveLogs: { open: async (_s: unknown, handlers: LiveLogHandlers) => handlers.onFrame(ENDED) } }, + } as unknown as ServiceContext; + + await new LiveLogFollower(services, { sleep: async () => undefined }).follow(SCOPE, new AbortController().signal); + + expect(spinner).toHaveBeenNthCalledWith(1, LIVE_LOADER_MESSAGE); + expect(spinner).toHaveBeenLastCalledWith('done', handle); + }); + + it('T86: prints the session end once, dimmed, on a terminal', async () => { + const run = harness([delivering([SESSION, ENDED])], { outputIsTTY: true }); + + await run.follow(); + + expect(run.lines[0]).toBe('\u001b[2mLive session ends at 14:05:09; press Ctrl-C to stop.\u001b[22m'); + }); + + it('T86: prints no session line on a pipe', async () => { + const run = harness([delivering([SESSION, ENDED])]); + + await run.follow(); + + expect(run.lines.some((line) => line.includes('Live session ends'))).toBe(false); + }); + + it('T86: does not repeat the session line after a reconnect', async () => { + const run = harness([delivering([SESSION], async () => undefined), delivering([SESSION, ENDED])], { outputIsTTY: true }); + + await run.follow(); + + expect(run.lines.filter((line) => line.includes('Live session ends'))).toHaveLength(1); + }); + + it.each([ + ['no expiry', '{}'], + ['an expiry that is not a date', '{"expiresAt":"soon"}'], + ['an expiry of the wrong type', '{"expiresAt":true}'], + ['a body that is not JSON', 'oops'], + ['a body that is not an object', '7'], + ])('T86: prints no session line for %s', async (_name, data) => { + const run = harness([delivering([{ event: 'session', data }, ENDED])], { outputIsTTY: true }); + + await run.follow(); + + expect(run.lines.some((line) => line.includes('Live session ends'))).toBe(false); + }); + + it('T86: shows the line from a later session frame when the first one had no usable expiry', async () => { + const run = harness([delivering([{ event: 'session', data: '{}' }, SESSION, ENDED])], { outputIsTTY: true }); + + await run.follow(); + + expect(run.lines.filter((line) => line.includes('Live session ends at 14:05:09'))).toHaveLength(1); + }); + + it('T86: reads a numeric expiry as epoch milliseconds', async () => { + const endsAt = Date.parse('2026-10-28T14:05:09.000Z'); + const run = harness([delivering([{ event: 'session', data: JSON.stringify({ expiresAt: endsAt }) }, ENDED])], { + outputIsTTY: true, + }); + + await run.follow(); + + expect(run.lines[0]).toContain('Live session ends at 14:05:09;'); + }); + + it('T88: prints the server-limit line, opens once, never sleeps and resolves', async () => { + const run = harness([delivering([log('one'), ENDED])]); + + await expect(run.follow()).resolves.toBeUndefined(); + + expect(run.lines[run.lines.length - 1]).toBe( + 'The live session ended (server limit). Run the command again to keep following.', + ); + expect(run.opens()).toBe(1); + expect(run.sleep).not.toHaveBeenCalled(); + }); + + it('T88: prints the yellow notice after the end line when the session carried no log line', async () => { + const run = harness([delivering([SESSION, HEARTBEAT, ENDED])], { outputIsTTY: true }); + + await run.follow(); + + expect(run.lines.slice(-2)).toEqual([ + 'The live session ended (server limit). Run the command again to keep following.', + YELLOW('No live server logs arrived during this session.'), + ]); + }); + + it('T88: ends the session even when the socket then fails, without a reconnect', async () => { + const run = harness([failing(dropped(), [ENDED])]); + + await run.follow(); + + expect(run.opens()).toBe(1); + expect(run.sleep).not.toHaveBeenCalled(); + }); + + it('T89: reconnects after a clean end of stream and after a dropped socket with the policy delays', async () => { + const run = harness([delivering([]), failing(dropped()), delivering([log('back'), ENDED])]); + + await run.follow(); + + expect(run.opens()).toBe(3); + expect(run.delays).toEqual([700, 1400]); + expect(run.lines[0]).toBe('2026-10-28 10:00:00.000: back'); + }); + + it('T90: gives up after three consecutive failures with three opens and two sleeps', async () => { + const last = dropped(); + const run = harness([failing(dropped()), failing(dropped()), failing(last)]); + + const error = await run.follow().catch((caught: unknown) => caught); + + expect(error).toBeInstanceOf(LaunchNetworkError); + expect((error as LaunchNetworkError).message).toBe( + 'Lost the connection to the live server logs after 3 attempts. Check your network connection and run the command again.', + ); + expect((error as LaunchNetworkError).cause).toBe(last); + expect((error as LaunchNetworkError).retryable).toBe(false); + expect(run.opens()).toBe(3); + expect(run.delays).toEqual([700, 1400]); + }); + + it('T90: counts a clean end of stream with nothing delivered as a failure too', async () => { + const run = harness([delivering([]), delivering([]), delivering([])]); + + const error = await run.follow().catch((caught: unknown) => caught); + + expect((error as LaunchNetworkError).cause).toBeUndefined(); + expect(run.opens()).toBe(3); + }); + + it('T90: starts counting again after a connection that delivered frames', async () => { + const run = harness([ + failing(dropped()), + failing(dropped(), [log('a')]), + failing(dropped()), + failing(dropped(), [HEARTBEAT]), + failing(dropped()), + delivering([ENDED]), + ]); + + await run.follow(); + + expect(run.opens()).toBe(6); + expect(run.delays).toEqual([700, 700, 1400, 700, 1400]); + }); + + it.each([ + ['a refusal from the API', new LaunchApiError(404, [{ code: 'launch.DEPLOYMENT.NOT_FOUND' }])], + ['a network failure that is not worth retrying', new LaunchNetworkError('proxy unreachable', undefined, false)], + ['an error nobody classified', new Error('boom')], + ])('T90: lets %s through at once without a retry', async (_name, error) => { + const run = harness([failing(error)]); + + await expect(run.follow()).rejects.toBe(error); + + expect(run.opens()).toBe(1); + expect(run.sleep).not.toHaveBeenCalled(); + }); + + it('T91: prints nothing of its own when the stream is lost, leaving the error to the command', async () => { + const run = harness([failing(dropped()), failing(dropped()), failing(dropped())], { outputIsTTY: true }); + + await run.follow().catch(() => undefined); + + expect(run.lines).toEqual([]); + }); + + it('T92: rejects with the interruption reason when the stream is aborted, handing the signal to the open', async () => { + const run = harness([untilAborted()]); + const reason = new Error('Stopped following the logs.'); + + const outcome = run.follow().catch((caught: unknown) => caught); + await Promise.resolve(); + run.stop.abort(reason); + + expect(await outcome).toBe(reason); + expect(run.signals).toHaveLength(1); + expect(run.signals[0]).not.toBe(run.stop.signal); + expect(run.signals[0].aborted).toBe(true); + expect(run.signals[0].reason).toBe(reason); + expect(run.events[run.events.length - 1]).toBe('stop'); + }); + + it('T93: an abort during the reconnect backoff cancels the sleep and opens nothing more', async () => { + const reason = new Error('Stopped following the logs.'); + const run = harness([failing(dropped()), delivering([ENDED])]); + run.sleep.mockImplementation( + (ms: number, signal?: AbortSignal) => + new Promise((_resolve, reject) => { + run.delays.push(ms); + signal?.addEventListener('abort', () => reject(signal.reason), { once: true }); + setImmediate(() => run.stop.abort(reason)); + }), + ); + + const error = await run.follow().catch((caught: unknown) => caught); + + expect(error).toBe(reason); + expect(run.opens()).toBe(1); + expect(run.delays).toEqual([700]); + expect(run.events[run.events.length - 1]).toBe('stop'); + }); + + it('T88: aborts the connection at the end line and ignores every frame after it', async () => { + const attempt: Attempt = async (handlers, signal) => { + handlers.onFrame(log('before')); + handlers.onFrame(ENDED); + handlers.onFrame(log('after')); + handlers.onFrame(HEARTBEAT); + handlers.onFrame(ENDED); + handlers.onFrame(SESSION); + await untilAborted()(handlers, signal); + }; + const run = harness([attempt, delivering([log('reconnected')])], { outputIsTTY: true }); + + await run.follow(); + + expect(run.opens()).toBe(1); + expect(run.signals[0].aborted).toBe(true); + expect(run.stop.signal.aborted).toBe(false); + expect(run.lines).toHaveLength(2); + expect(run.lines[1]).toContain('The live session ended (server limit).'); + expect(run.delays).toEqual([]); + expect(run.events[run.events.length - 1]).toBe('stop'); + }); + + it('T88: prints the end line once when the connection ends in a failure after the end frame', async () => { + const attempt: Attempt = async (handlers) => { + handlers.onFrame(ENDED); + throw dropped(); + }; + const run = harness([attempt]); + + await run.follow(); + + expect(run.opens()).toBe(1); + expect(run.lines.filter((line) => line.startsWith('The live session ended'))).toHaveLength(1); + expect(run.delays).toEqual([]); + }); + + it('T88: removes its listener from the stop signal after every connection', async () => { + const run = harness([failing(dropped()), delivering([ENDED])]); + const added = jest.spyOn(run.stop.signal, 'addEventListener'); + const removed = jest.spyOn(run.stop.signal, 'removeEventListener'); + + await run.follow().catch(() => undefined); + + const listeners = added.mock.calls.filter(([type]) => type === 'abort').map(([, listener]) => listener); + expect(listeners.length).toBeGreaterThanOrEqual(2); + listeners.forEach((listener) => expect(removed).toHaveBeenCalledWith('abort', listener)); + }); + + it('T92: a stop that was already aborted reaches the connection signal at once', async () => { + const reason = new Error('Stopped following the logs.'); + const run = harness([untilAborted()]); + run.stop.abort(reason); + + const error = await run.follow().catch((caught: unknown) => caught); + + expect(error).toBe(reason); + expect(run.signals[0].aborted).toBe(true); + expect(run.signals[0].reason).toBe(reason); + }); +}); diff --git a/src/logs/live-log.follower.ts b/src/logs/live-log.follower.ts new file mode 100644 index 00000000..30eea87b --- /dev/null +++ b/src/logs/live-log.follower.ts @@ -0,0 +1,176 @@ +import type { Loader } from '../core/loader'; +import { silentLoader, terminalLoader } from '../core/loader'; +import type { ServiceContext } from '../core/service-context'; +import { isRecord } from '../core/values'; +import type { DeploymentScope } from '../deployments/deployment.follower'; +import { DEPLOYMENT_MAX_POLL_ERRORS, type WatchTiming } from '../deployments/deployment.watcher'; +import { LaunchNetworkError } from '../transport/errors'; +import type { StreamFrame } from '../transport/event-stream'; +import { RetryPolicy } from '../transport/retry-policy'; +import { + liveSessionEndedLine, + liveSessionLine, + liveStreamLostMessage, + noLiveLinesLine, + serverLogLine, +} from './logs.presenter'; +import type { ServerLog } from './types'; + +export const LIVE_LOADER_MESSAGE = 'Waiting for live server logs...'; + +export interface LiveFollowerOptions { + loader?: Loader; + columns?: number; + retry?: RetryPolicy; +} + +function parsed(data: string): unknown { + try { + return JSON.parse(data); + } catch { + return undefined; + } +} + +function isTransient(error: unknown): boolean { + return error instanceof LaunchNetworkError && error.retryable; +} + +export class LiveLogFollower { + private readonly outputIsTTY: boolean; + private readonly loader: Loader; + private readonly retry: RetryPolicy; + private printed = 0; + private sessionShown = false; + private ended = false; + private connection = new AbortController(); + + constructor( + private readonly services: ServiceContext, + private readonly timing: Pick, + private readonly options: LiveFollowerOptions = {}, + ) { + this.outputIsTTY = services.outputIsTTY === true; + this.loader = options.loader ?? (this.outputIsTTY ? terminalLoader() : silentLoader); + this.retry = options.retry ?? new RetryPolicy(); + } + + async follow(scope: DeploymentScope, stop: AbortSignal): Promise { + try { + await this.reconnecting(scope, stop); + } finally { + this.loader.stop(); + } + } + + private async reconnecting(scope: DeploymentScope, stop: AbortSignal): Promise { + let failures = 0; + + for (;;) { + let delivered = false; + let lastFailure: unknown; + + this.loader.start(LIVE_LOADER_MESSAGE); + + const connection = new AbortController(); + const relay = (): void => connection.abort(stop.reason); + + this.connection = connection; + stop.addEventListener('abort', relay, { once: true }); + + if (stop.aborted) { + relay(); + } + + try { + await this.services.api.liveLogs.open( + scope, + { + onFrame: (frame) => { + delivered = true; + this.onFrame(frame); + }, + }, + connection.signal, + ); + } catch (error) { + if (!this.ended && !isTransient(error)) { + throw error; + } + + lastFailure = error; + } finally { + stop.removeEventListener('abort', relay); + } + + if (this.ended) { + return; + } + + failures = delivered ? 1 : failures + 1; + + if (failures >= DEPLOYMENT_MAX_POLL_ERRORS) { + throw new LaunchNetworkError(liveStreamLostMessage(failures), lastFailure); + } + + await this.timing.sleep(this.retry.delayFor(failures), stop); + } + } + + private onFrame(frame: StreamFrame): void { + if (this.ended) { + return; + } + + if (frame.event === 'session') { + this.announceSession(frame.data); + return; + } + + if (frame.event === 'session-ended') { + this.finish(); + return; + } + + if (frame.event !== undefined) { + return; + } + + const entry = parsed(frame.data); + + if (isRecord(entry)) { + this.printed += 1; + this.emit(serverLogLine(entry as ServerLog, this.outputIsTTY, this.options.columns)); + } + } + + private announceSession(data: string): void { + const session = parsed(data); + const expiresAt = isRecord(session) ? session.expiresAt : undefined; + const endsAt = typeof expiresAt === 'string' || typeof expiresAt === 'number' ? new Date(expiresAt).getTime() : NaN; + + if (!this.outputIsTTY || this.sessionShown || Number.isNaN(endsAt)) { + return; + } + + this.sessionShown = true; + this.emit(liveSessionLine(endsAt, this.outputIsTTY)); + } + + private finish(): void { + this.ended = true; + this.connection.abort(); + this.loader.stop(); + this.services.ux.print(liveSessionEndedLine()); + + if (this.printed === 0) { + this.services.ux.print(noLiveLinesLine(this.outputIsTTY)); + } + } + + private emit(line: string): void { + this.loader.stop(); + this.services.ux.print(line); + this.loader.start(LIVE_LOADER_MESSAGE); + } +} diff --git a/src/logs/live-logs.api.test.ts b/src/logs/live-logs.api.test.ts new file mode 100644 index 00000000..98eb8852 --- /dev/null +++ b/src/logs/live-logs.api.test.ts @@ -0,0 +1,61 @@ +import { randomBytes } from 'node:crypto'; + +import type { EventStreamClient, EventStreamRequest, StreamFrame } from '../transport/event-stream'; +import { LOGS_ERROR_MESSAGES } from './logs.errors'; +import { LiveLogsApi } from './live-logs.api'; + +const SCOPE = { + org: randomBytes(9).toString('hex'), + project: randomBytes(12).toString('hex'), + environment: randomBytes(12).toString('hex'), + deployment: randomBytes(12).toString('hex'), +}; + +function fakeStreamClient(outcome: () => Promise = async () => undefined) { + const calls: { + req: EventStreamRequest; + onFrame: (frame: StreamFrame) => void; + signal?: AbortSignal; + messages?: unknown; + }[] = []; + const client = { + open: async (req: EventStreamRequest, onFrame: (frame: StreamFrame) => void, signal?: AbortSignal, messages?: unknown) => { + calls.push({ req, onFrame, signal, messages }); + await outcome(); + }, + } as unknown as EventStreamClient; + + return { client, calls }; +} + +describe('LiveLogsApi', () => { + it('T84: opens the live route under the deployment path, scoped by org and project, with the signal and the logs wording', async () => { + const { client, calls } = fakeStreamClient(); + const stop = new AbortController(); + const frames: StreamFrame[] = []; + + await new LiveLogsApi(client).open(SCOPE, { onFrame: (frame) => frames.push(frame) }, stop.signal); + + expect(calls).toHaveLength(1); + expect(calls[0].req).toEqual({ + path: `/projects/${SCOPE.project}/environments/${SCOPE.environment}/deployments/${SCOPE.deployment}/logs/live`, + orgUid: SCOPE.org, + projectUid: SCOPE.project, + }); + expect(calls[0].signal).toBe(stop.signal); + expect(calls[0].messages).toBe(LOGS_ERROR_MESSAGES); + calls[0].onFrame({ event: undefined, data: 'x' }); + expect(frames).toEqual([{ event: undefined, data: 'x' }]); + }); + + it('T84: lets the failure of the stream through', async () => { + const failure = new Error('stream failed'); + const { client } = fakeStreamClient(async () => { + throw failure; + }); + + await expect(new LiveLogsApi(client).open(SCOPE, { onFrame: () => undefined }, new AbortController().signal)).rejects.toBe( + failure, + ); + }); +}); diff --git a/src/logs/live-logs.api.ts b/src/logs/live-logs.api.ts new file mode 100644 index 00000000..88bc5c13 --- /dev/null +++ b/src/logs/live-logs.api.ts @@ -0,0 +1,20 @@ +import { DeploymentsApi, type GetDeploymentParams } from '../deployments/deployments.api'; +import type { EventStreamClient, StreamFrame } from '../transport/event-stream'; +import { LOGS_ERROR_MESSAGES } from './logs.errors'; + +export interface LiveLogHandlers { + onFrame(frame: StreamFrame): void; +} + +export class LiveLogsApi { + constructor(private readonly client: EventStreamClient) {} + + open(scope: GetDeploymentParams, handlers: LiveLogHandlers, signal: AbortSignal): Promise { + return this.client.open( + { path: `${DeploymentsApi.pathOf(scope)}/logs/live`, orgUid: scope.org, projectUid: scope.project }, + handlers.onFrame, + signal, + LOGS_ERROR_MESSAGES, + ); + } +} diff --git a/src/logs/log-window.test.ts b/src/logs/log-window.test.ts new file mode 100644 index 00000000..bb4b5291 --- /dev/null +++ b/src/logs/log-window.test.ts @@ -0,0 +1,209 @@ +import { UsageError } from '../core/errors'; +import { parseLogWindow } from './log-window'; + +const NOW = Date.UTC(2025, 5, 15, 12, 0, 0); +const HOUR = 3_600_000; +const DAY = 86_400_000; +const MIXED = '--since and --until must both be relative (like 12hr) or both absolute (ISO 8601) timestamps.'; +const clock = () => NOW; + +function failureOf(window: { since?: string | null; until?: string | null }): UsageError { + try { + parseLogWindow(window, clock); + } catch (error) { + return error as UsageError; + } + + throw new Error('parseLogWindow did not throw'); +} + +describe('parseLogWindow', () => { + it.each([ + ['45s', 45_000], + ['30m', 30 * 60_000], + ['30min', 30 * 60_000], + ['2h', 2 * HOUR], + ['12hr', 12 * HOUR], + ['2d', 2 * DAY], + ['12HR', 12 * HOUR], + ['30MIN', 30 * 60_000], + [' 5m ', 5 * 60_000], + ])('reads a relative since of %s from the one clock reading and ends the window at now', (since, offset) => { + const window = parseLogWindow({ since }, clock); + + expect(window.startTime).toBe(NOW - offset); + expect(window.endTime).toBe(NOW); + }); + + it('reads an absolute timestamp literally whatever the local time zone, across a daylight saving change', () => { + const original = process.env.TZ; + process.env.TZ = 'America/New_York'; + + try { + const march = () => Date.UTC(2025, 2, 9, 18, 0); + const offset = parseLogWindow( + { since: '2025-03-09T01:30:00-05:00', until: '2025-03-09T12:00:00-04:00' }, + march, + ); + const zulu = parseLogWindow({ since: '2025-03-09T06:30:00Z', until: '2025-03-09T16:00:00Z' }, march); + const india = parseLogWindow({ since: '2025-03-09T12:00:00+05:30', until: '2025-03-09T21:30:00+05:30' }, march); + + expect(offset).toEqual({ startTime: Date.UTC(2025, 2, 9, 6, 30), endTime: Date.UTC(2025, 2, 9, 16, 0) }); + expect(zulu).toEqual(offset); + expect(india).toEqual({ startTime: Date.UTC(2025, 2, 9, 6, 30), endTime: Date.UTC(2025, 2, 9, 16, 0) }); + } finally { + if (original === undefined) { + delete process.env.TZ; + } else { + process.env.TZ = original; + } + } + }); + + it('accepts optional seconds and fractional seconds in an absolute timestamp', () => { + const minutes = parseLogWindow({ since: '2025-06-15T10:00Z', until: '2025-06-15T11:00:00.250Z' }, clock); + + expect(minutes).toEqual({ startTime: Date.UTC(2025, 5, 15, 10, 0), endTime: Date.UTC(2025, 5, 15, 11, 0, 0, 250) }); + }); + + it.each([ + ['2025-06-15'], + ['2025-06-15T10:00:00'], + ['2025-06-15 10:00:00Z'], + ['2025-06-15T10:00:00+0530'], + ['2025-02-31T10:00:00Z'], + ['2025-13-01T10:00:00Z'], + ['2025-06-15T24:00:00Z'], + ['2025-06-15T10:60:00Z'], + ['2025-06-15T10:00:60Z'], + ['2025-06-15T10:00:00+24:00'], + ['2025-06-15T10:00:00+05:60'], + ])('refuses the timestamp %s naming the flag and both formats', (since) => { + const failure = failureOf({ since }); + + expect(failure).toBeInstanceOf(UsageError); + expect(failure.exitCode).toBe(2); + expect(failure.message).toBe( + `--since must be a relative time like 12hr (units s, m, h, d) or an ISO 8601 timestamp with an offset like 2025-01-15T10:00:00Z; "${since}" is not.`, + ); + }); + + it.each([ + [{ since: '2025-06-15T10:00:00Z', until: '12h' }], + [{ since: '12h', until: '2025-06-15T10:00:00Z' }], + ])('refuses a pair that mixes relative and absolute with the exact message for %j', (window) => { + const failure = failureOf(window); + + expect(failure).toBeInstanceOf(UsageError); + expect(failure.exitCode).toBe(2); + expect(failure.message).toBe(MIXED); + }); + + it.each([['yesterday'], ['12'], ['-5m'], ['5w'], ['1.5h'], ['30 m'], ['0h'], ['00m'], ['h'], ['5 '.repeat(2)]])( + 'refuses the relative value %p naming --since', + (since) => { + const failure = failureOf({ since }); + + expect(failure.exitCode).toBe(2); + expect(failure.message).toContain('--since must be a relative time like 12hr'); + expect(failure.message).toContain('ISO 8601'); + expect(failure.message).toContain(`"${since}" is not.`); + }, + ); + + it('names --until when it is the bad one, even beside a valid since', () => { + const failure = failureOf({ since: '1h', until: 'yesterday' }); + + expect(failure.message).toContain('--until must be a relative time like 12hr'); + expect(failure.message).toContain('"yesterday" is not.'); + }); + + it('refuses an amount too large to be a time', () => { + const failure = failureOf({ since: `${'9'.repeat(20)}d` }); + + expect(failure.message).toContain('--since must be a relative time like 12hr'); + }); + + it('accepts since equal to until and refuses since one millisecond after it', () => { + const same = parseLogWindow({ since: '2025-06-15T10:00:00.000Z', until: '2025-06-15T10:00:00.000Z' }, clock); + const failure = failureOf({ since: '2025-06-15T10:00:00.001Z', until: '2025-06-15T10:00:00.000Z' }); + + expect(same.startTime).toBe(same.endTime); + expect(failure).toBeInstanceOf(UsageError); + expect(failure.exitCode).toBe(2); + expect(failure.message).toBe('--since must not be later than --until.'); + }); + + it('refuses a relative since that lies after a relative until', () => { + expect(failureOf({ since: '1h', until: '2h' }).message).toBe('--since must not be later than --until.'); + expect(parseLogWindow({ since: '2h', until: '1h' }, clock)).toEqual({ startTime: NOW - 2 * HOUR, endTime: NOW - HOUR }); + }); + + it('defaults to the hour ending now', () => { + expect(parseLogWindow({}, clock)).toEqual({ startTime: NOW - HOUR, endTime: NOW }); + }); + + it('takes the default hour from the supplied until and the default until from now, never as a mixed pair', () => { + const onlyUntil = parseLogWindow({ until: '30m' }, clock); + const onlyAbsoluteUntil = parseLogWindow({ until: '2025-06-15T10:00:00Z' }, clock); + const onlyAbsoluteSince = parseLogWindow({ since: '2025-06-15T10:00:00Z' }, clock); + const onlyRelativeSince = parseLogWindow({ since: '3h' }, clock); + + expect(onlyUntil).toEqual({ startTime: NOW - 30 * 60_000 - HOUR, endTime: NOW - 30 * 60_000 }); + expect(onlyAbsoluteUntil).toEqual({ + startTime: Date.UTC(2025, 5, 15, 9, 0), + endTime: Date.UTC(2025, 5, 15, 10, 0), + }); + expect(onlyAbsoluteSince).toEqual({ startTime: Date.UTC(2025, 5, 15, 10, 0), endTime: NOW }); + expect(onlyRelativeSince).toEqual({ startTime: NOW - 3 * HOUR, endTime: NOW }); + }); + + it.each([[undefined], [null], [''], [' ']])('treats %p for either flag as absent', (blank) => { + expect(parseLogWindow({ since: blank, until: blank }, clock)).toEqual({ startTime: NOW - HOUR, endTime: NOW }); + expect(parseLogWindow({ since: '2h', until: blank }, clock)).toEqual({ startTime: NOW - 2 * HOUR, endTime: NOW }); + expect(parseLogWindow({ since: blank, until: '2025-06-15T10:00:00Z' }, clock)).toEqual({ + startTime: Date.UTC(2025, 5, 15, 9, 0), + endTime: Date.UTC(2025, 5, 15, 10, 0), + }); + }); + + it('reads the clock exactly once even when it advances on every call', () => { + let calls = 0; + const advancing = () => { + calls += 1; + + return NOW + calls * 1000; + }; + + const window = parseLogWindow({ since: '2h', until: '1h' }, advancing); + + expect(calls).toBe(1); + expect(window).toEqual({ startTime: NOW + 1000 - 2 * HOUR, endTime: NOW + 1000 - HOUR }); + }); + + it('reads the clock once for the default window too', () => { + let calls = 0; + + parseLogWindow({}, () => { + calls += 1; + + return NOW; + }); + + expect(calls).toBe(1); + }); + + it('reports no clamp at exactly 24 hours and a clamp from now minus 24 hours one millisecond past it', () => { + const atLimit = parseLogWindow({ since: '24h' }, clock); + const absoluteAtLimit = parseLogWindow({ since: new Date(NOW - DAY).toISOString(), until: '2025-06-15T11:00:00Z' }, clock); + const pastLimit = parseLogWindow({ since: new Date(NOW - DAY - 1).toISOString(), until: '2025-06-15T11:00:00Z' }, clock); + const twoDays = parseLogWindow({ since: '2d' }, clock); + + expect(atLimit).toEqual({ startTime: NOW - DAY, endTime: NOW }); + expect('clampedFrom' in atLimit).toBe(false); + expect('clampedFrom' in absoluteAtLimit).toBe(false); + expect(pastLimit.startTime).toBe(NOW - DAY - 1); + expect(pastLimit.clampedFrom).toBe(NOW - DAY); + expect(twoDays).toEqual({ startTime: NOW - 2 * DAY, endTime: NOW, clampedFrom: NOW - DAY }); + }); +}); diff --git a/src/logs/log-window.ts b/src/logs/log-window.ts new file mode 100644 index 00000000..680d2778 --- /dev/null +++ b/src/logs/log-window.ts @@ -0,0 +1,132 @@ +import { UsageError } from '../core/errors'; +import { isAbsent } from '../core/values'; + +export const DEFAULT_LOG_WINDOW_MS = 3_600_000; + +export const SERVER_LOG_RETENTION_MS = 86_400_000; + +const MAX_DATE_MS = 8.64e15; + +const MS_BY_UNIT: Record = { + s: 1000, + m: 60_000, + min: 60_000, + h: 3_600_000, + hr: 3_600_000, + d: 86_400_000, +}; + +const RELATIVE = /^(\d+)(s|min|m|hr|h|d)$/i; + +const ABSOLUTE = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::(\d{2})(?:\.\d+)?)?(?:Z|[+-](\d{2}):(\d{2}))$/; + +const MIXED_PAIR = '--since and --until must both be relative (like 12hr) or both absolute (ISO 8601) timestamps.'; + +export interface LogWindowInput { + since?: string | null; + until?: string | null; +} + +export interface LogWindow { + startTime: number; + endTime: number; + clampedFrom?: number; +} + +type Kind = 'relative' | 'absolute'; + +interface Reading { + kind: Kind; + value: number; +} + +function badValue(flag: string, value: string): UsageError { + return new UsageError( + `--${flag} must be a relative time like 12hr (units s, m, h, d) or an ISO 8601 timestamp ` + + `with an offset like 2025-01-15T10:00:00Z; "${value}" is not.`, + ); +} + +function isPresent(value: string | null | undefined): value is string { + return !isAbsent(value); +} + +function daysIn(year: number, month: number): number { + return new Date(Date.UTC(year, month, 0)).getUTCDate(); +} + +function absoluteMs(text: string): number | undefined { + const match = ABSOLUTE.exec(text); + + if (match === null) { + return undefined; + } + + const [year, month, day, hour, minute] = match.slice(1, 6).map(Number); + const second = match[6] === undefined ? 0 : Number(match[6]); + const offsetHour = match[7] === undefined ? 0 : Number(match[7]); + const offsetMinute = match[8] === undefined ? 0 : Number(match[8]); + const valid = + month >= 1 && + month <= 12 && + day >= 1 && + day <= daysIn(year, month) && + hour <= 23 && + minute <= 59 && + second <= 59 && + offsetHour <= 23 && + offsetMinute <= 59; + + return valid ? Date.parse(text) : undefined; +} + +function relativeOffset(text: string): number | undefined { + const match = RELATIVE.exec(text); + + if (match === null) { + return undefined; + } + + const amount = Number(match[1]); + const offset = amount * MS_BY_UNIT[match[2].toLowerCase()]; + + return amount > 0 && Number.isSafeInteger(offset) ? offset : undefined; +} + +function read(flag: string, raw: string, now: number): Reading { + const text = raw.trim(); + const absolute = absoluteMs(text); + + if (absolute !== undefined) { + return { kind: 'absolute', value: absolute }; + } + + const offset = relativeOffset(text); + + if (offset === undefined || Math.abs(now - offset) > MAX_DATE_MS) { + throw badValue(flag, raw); + } + + return { kind: 'relative', value: now - offset }; +} + +export function parseLogWindow({ since, until }: LogWindowInput, now: () => number): LogWindow { + const current = now(); + const start = isPresent(since) ? read('since', since, current) : undefined; + const end = isPresent(until) ? read('until', until, current) : undefined; + + if (start !== undefined && end !== undefined && start.kind !== end.kind) { + throw new UsageError(MIXED_PAIR); + } + + const endTime = end?.value ?? current; + const startTime = start?.value ?? endTime - DEFAULT_LOG_WINDOW_MS; + + if (startTime > endTime) { + throw new UsageError('--since must not be later than --until.'); + } + + const oldest = current - SERVER_LOG_RETENTION_MS; + + return { startTime, endTime, ...(startTime < oldest && { clampedFrom: oldest }) }; +} diff --git a/src/logs/logs.errors.test.ts b/src/logs/logs.errors.test.ts new file mode 100644 index 00000000..7df5638c --- /dev/null +++ b/src/logs/logs.errors.test.ts @@ -0,0 +1,37 @@ +import { DEPLOYMENT_ERROR_MESSAGES } from '../deployments/deployment.errors'; +import { LaunchApiError } from '../transport/errors'; +import { LOGS_ERROR_MESSAGES } from './logs.errors'; + +describe('logs error wording', () => { + it.each([ + ['launch.SERVERLOGS.NOT_INTEGER', 'The Launch API could not read the time window of the server logs.'], + [ + 'launch.LOGS.QUERY_TIMEOUT', + 'The server logs query took too long. Narrow the window with --since and --until and try again.', + ], + [ + 'launch.LOGS.REQUEST_TIMEOUT', + 'The Launch API took too long to answer. Try again, or narrow the window with --since and --until.', + ], + ['launch.DEPLOYMENT.PROJECT_MISMATCH', 'That deployment does not belong to this project.'], + ['launch.DEPLOYMENT.ENVIRONMENT_MISMATCH', 'That deployment does not belong to this environment.'], + ['launch.PROJECT.NOT_FOUND', 'No project found with that UID.'], + ['launch.DEPLOYMENT.NOT_FOUND', 'No deployment found with that UID.'], + ])('rewords %s and never shows the raw message', (code, wording) => { + const error = new LaunchApiError(400, [{ code, message: 'raw server text' }], LOGS_ERROR_MESSAGES); + + expect(error.message).toBe(wording); + }); + + it('carries every deployment entry without copying one of its own', () => { + for (const [code, wording] of Object.entries(DEPLOYMENT_ERROR_MESSAGES)) { + expect(LOGS_ERROR_MESSAGES[code]).toBe(wording); + } + }); + + it('falls back to the API text for a code it does not reword', () => { + const error = new LaunchApiError(400, [{ code: 'launch.LOGS.SOMETHING_NEW', message: 'raw server text' }], LOGS_ERROR_MESSAGES); + + expect(error.message).toBe('raw server text'); + }); +}); diff --git a/src/logs/logs.errors.ts b/src/logs/logs.errors.ts new file mode 100644 index 00000000..cb94369f --- /dev/null +++ b/src/logs/logs.errors.ts @@ -0,0 +1,14 @@ +import type { ErrorMessages } from '../transport/errors'; +import { DEPLOYMENT_ERROR_MESSAGES } from '../deployments/deployment.errors'; + +export const LOGS_ERROR_MESSAGES: ErrorMessages = { + ...DEPLOYMENT_ERROR_MESSAGES, + 'launch.SERVERLOGS.NOT_INTEGER': 'The Launch API could not read the time window of the server logs.', + 'launch.LOGS.QUERY_TIMEOUT': + 'The server logs query took too long. Narrow the window with --since and --until and try again.', + 'launch.LOGS.REQUEST_TIMEOUT': + 'The Launch API took too long to answer. Try again, or narrow the window with --since and --until.', + 'launch.DEPLOYMENT.PROJECT_MISMATCH': 'That deployment does not belong to this project.', + 'launch.DEPLOYMENT.ENVIRONMENT_MISMATCH': 'That deployment does not belong to this environment.', + 'launch.PROJECT.NOT_FOUND': 'No project found with that UID.', +}; diff --git a/src/logs/logs.inputs.test.ts b/src/logs/logs.inputs.test.ts new file mode 100644 index 00000000..2f592960 --- /dev/null +++ b/src/logs/logs.inputs.test.ts @@ -0,0 +1,158 @@ +import { Parser } from '@oclif/core'; + +import { InputDependencyError, UsageError } from '../core/errors'; +import { inputs } from '../core/inputs'; +import { resolveInputs, resolveInputsTraced } from '../core/resolve'; +import { projectTypeChoiceOf } from '../projects/project.inputs'; +import type { ApiSurface } from '../resources'; +import { catalog, resolution } from '../resources'; +import { logTypeOf, logsFlags, logsResolution, windowOnlyWithServer } from './logs.inputs'; + +const logInputs = inputs({ 'log-type': {}, since: {}, until: {} }); +const rules = [windowOnlyWithServer('since'), windowOnlyWithServer('until')]; +const prompts: unknown[] = []; +const services = { + api: {} as ApiSurface, + ux: { + print: () => undefined, + inquire: async (question: unknown) => { + prompts.push(question); + + return undefined as never; + }, + }, + isTTY: true, +}; + +function resolve(parsed: Record) { + return resolveInputsTraced(logInputs, { parsed, projectConfig: {}, services, rules }); +} + +async function failureOf(parsed: Record): Promise { + return resolve(parsed).then( + () => { + throw new Error('resolution did not fail'); + }, + (error: UsageError) => error, + ); +} + +beforeEach(() => { + prompts.length = 0; +}); + +describe('logs inputs', () => { + it('shares the log type, since and until through the catalog without touching the project type flag', () => { + expect(Object.keys(logsFlags).sort()).toEqual(Object.keys(logsResolution).sort()); + expect(Object.keys(logsFlags)).toHaveLength(3); + expect(catalog['log-type']).toBe(logsFlags['log-type']); + expect(catalog.since).toBe(logsFlags.since); + expect(catalog.until).toBe(logsFlags.until); + expect(resolution['log-type']).toBe(logsResolution['log-type']); + expect(catalog.type.description).toContain('GitHub | FileUpload'); + expect(logsFlags['log-type'].description).toContain('deployment | server | live'); + expect(logsFlags['log-type'].required).toBeFalsy(); + expect(logsFlags.since.required).toBeFalsy(); + expect(logsFlags.until.required).toBeFalsy(); + }); + + it.each([ + [' Server ', 'server'], + ['LIVE', 'live'], + ['deployment', 'deployment'], + ['Deployment', 'deployment'], + ])('normalises the log type %p to the canonical %p', async (typed, canonical) => { + const { resolved, sources } = await resolve({ 'log-type': typed }); + + expect(resolved['log-type']).toBe(canonical); + expect(sources['log-type']).toBe('flag'); + expect(logTypeOf(typed)).toBe(canonical); + }); + + it('defaults the log type to deployment and records that it was a default', async () => { + const { resolved, sources } = await resolve({}); + + expect(resolved['log-type']).toBe('deployment'); + expect(sources['log-type']).toBe('default'); + }); + + it.each([[''], [' '], [null], [undefined]])('reads %p as an absent log type and defaults it', async (blank) => { + const { resolved } = await resolve({ 'log-type': blank }); + + expect(resolved['log-type']).toBe('deployment'); + }); + + it('refuses an unknown log type with the exact usage message naming --type', async () => { + const failure = await failureOf({ 'log-type': 'build' }); + + expect(failure).toBeInstanceOf(UsageError); + expect(failure.exitCode).toBe(2); + expect(failure.message).toBe('--type must be one of deployment, server, live; "build" is not.'); + expect(() => logTypeOf('build')).toThrow('--type must be one of deployment, server, live; "build" is not.'); + }); + + it('never prompts for the log type, on a terminal or off it, and never asks the project type question', async () => { + await resolve({}); + await resolveInputs(logInputs, { parsed: {}, projectConfig: {}, services: { ...services, isTTY: false }, rules }); + + expect(prompts).toEqual([]); + expect(logsResolution['log-type']).not.toHaveProperty('prompt'); + expect(logsResolution['log-type']).not.toHaveProperty('configPath'); + }); + + it('leaves the project type spec rejecting server and prompting, so projects:create is unchanged', async () => { + const projectType = resolution.type; + + await expect(projectType.normalize('server')).rejects.toThrow( + '--type must be one of GitHub, FileUpload; "server" is not.', + ); + expect(() => projectTypeChoiceOf('server')).toThrow(UsageError); + expect(projectType).toHaveProperty('prompt'); + expect(resolution['log-type']).not.toBe(projectType); + expect(resolution['log-type'].normalize).not.toBe(projectType.normalize); + }); + + it('refuses --since with the default deployment type, closing the default-gate hole', async () => { + const failure = await failureOf({ since: '2h' }); + + expect(failure).toBeInstanceOf(UsageError); + expect(failure.exitCode).toBe(2); + expect(failure.message).toBe('--since is only supported when --type is one of server; --type is deployment.'); + }); + + it('refuses --since with an explicit deployment type and --until with live', async () => { + const since = await failureOf({ 'log-type': 'deployment', since: '2h' }); + const until = await failureOf({ 'log-type': 'LIVE', until: '30m' }); + const untilDefault = await failureOf({ until: '30m' }); + + expect(since.message).toBe('--since is only supported when --type is one of server; --type is deployment.'); + expect(until.message).toBe('--until is only supported when --type is one of server; --type is live.'); + expect(untilDefault.message).toBe('--until is only supported when --type is one of server; --type is deployment.'); + }); + + it('accepts since and until with the server type, and a blank one with any type', async () => { + const server = await resolve({ 'log-type': 'Server', since: ' 2h ', until: '1h' }); + const blank = await resolve({ since: ' ', until: '' }); + const nulls = await resolve({ 'log-type': 'live', since: null, until: undefined }); + + expect(server.resolved).toEqual({ 'log-type': 'server', since: '2h', until: '1h' }); + expect(blank.resolved).toEqual({ 'log-type': 'deployment', since: undefined, until: undefined }); + expect(nulls.resolved['log-type']).toBe('live'); + }); + + it('refuses a window flag when the log type is not an input of the command, rather than skipping the check', async () => { + const bare = inputs({ since: {} }); + const run = resolveInputs(bare, { parsed: { since: '1h' }, projectConfig: {}, services, rules }); + + await expect(run).rejects.toBeInstanceOf(InputDependencyError); + await expect(run).rejects.toThrow('--since cannot be checked without --type'); + }); + + it('parses --since and --until as plain strings', async () => { + const parsed = await Parser.parse(['--since', '12hr', '--until=2025-06-15T10:00:00Z'], { + flags: { since: catalog.since, until: catalog.until }, + }); + + expect(parsed.flags).toEqual({ since: '12hr', until: '2025-06-15T10:00:00Z' }); + }); +}); diff --git a/src/logs/logs.inputs.ts b/src/logs/logs.inputs.ts new file mode 100644 index 00000000..09d244c1 --- /dev/null +++ b/src/logs/logs.inputs.ts @@ -0,0 +1,62 @@ +import { Flags } from '@contentstack/cli-utilities'; + +import { InputDependencyError } from '../core/errors'; +import type { ResolutionSpec } from '../core/resolution'; +import type { Rule } from '../core/rules'; +import { requireValueOf } from '../core/rules'; +import { isAbsent, oneOf } from '../core/values'; + +export const LOG_TYPES = ['deployment', 'server', 'live'] as const; + +export type LogType = (typeof LOG_TYPES)[number]; + +export const DEFAULT_LOG_TYPE: LogType = 'deployment'; + +export const LOG_TYPE_FLAG = 'type'; + +export const WINDOW_LOG_TYPES: readonly LogType[] = ['server']; + +const WINDOW_FORMATS = 'relative (45s, 30m, 12hr, 2d) or an ISO 8601 timestamp with an offset'; + +export const logsFlags = { + 'log-type': Flags.string({ + description: `Kind of logs to read (${LOG_TYPES.join(' | ')}). Defaults to ${DEFAULT_LOG_TYPE}`, + }), + since: Flags.string({ + description: `Server logs only: start of the window, ${WINDOW_FORMATS}. Defaults to one hour before --until`, + }), + until: Flags.string({ + description: `Server logs only: end of the window, ${WINDOW_FORMATS}. Defaults to now`, + }), +}; + +export function logTypeOf(value: string): LogType { + return oneOf(LOG_TYPE_FLAG, value, LOG_TYPES); +} + +export const logsResolution = { + 'log-type': { + default: DEFAULT_LOG_TYPE, + normalize: async (value) => logTypeOf(value), + } satisfies ResolutionSpec, + since: { normalize: async (value) => value.trim() } satisfies ResolutionSpec, + until: { normalize: async (value) => value.trim() } satisfies ResolutionSpec, +}; + +export function windowOnlyWithServer(flag: 'since' | 'until'): Rule { + return (resolved) => { + if (isAbsent(resolved[flag])) { + return; + } + + const type = resolved['log-type']; + + if (typeof type !== 'string') { + throw new InputDependencyError( + `--${flag} cannot be checked without --${LOG_TYPE_FLAG}: declare log-type in the command inputs.`, + ); + } + + requireValueOf(flag, LOG_TYPE_FLAG, WINDOW_LOG_TYPES, type); + }; +} diff --git a/src/logs/logs.presenter.test.ts b/src/logs/logs.presenter.test.ts new file mode 100644 index 00000000..892c686a --- /dev/null +++ b/src/logs/logs.presenter.test.ts @@ -0,0 +1,139 @@ +import { + deploymentStatusLine, + liveSessionEndedLine, + liveSessionLine, + liveStreamLostMessage, + noLiveLinesLine, + logsWaitTimedOutMessage, + noDeploymentLogsLine, + noServerLogsLine, + serverLogLine, + serverLogsCapLine, + serverLogsRetentionLine, + stoppedFollowingLine, +} from './logs.presenter'; + +const YELLOW_OPEN = '\u001b[33m'; +const YELLOW_CLOSE = '\u001b[39m'; + +function yellow(text: string): string { + return `${YELLOW_OPEN}${text}${YELLOW_CLOSE}`; +} + +describe('logs presenter', () => { + it('words the empty deployment result in yellow on a terminal and plain on a pipe', () => { + expect(noDeploymentLogsLine('d1', true)).toBe(yellow('No deployment logs found for deployment d1.')); + expect(noDeploymentLogsLine('d1', false)).toBe('No deployment logs found for deployment d1.'); + }); + + it('names the resolved window in ISO UTC for the empty server result', () => { + const start = Date.parse('2026-10-28T09:00:00.000Z'); + const end = Date.parse('2026-10-28T10:00:00.500Z'); + + expect(noServerLogsLine(start, end, false)).toBe( + 'No server logs found between 2026-10-28T09:00:00.000Z and 2026-10-28T10:00:00.500Z.', + ); + expect(noServerLogsLine(start, end, true)).toBe( + yellow('No server logs found between 2026-10-28T09:00:00.000Z and 2026-10-28T10:00:00.500Z.'), + ); + }); + + it('words the 5000-line notice exactly', () => { + expect(serverLogsCapLine(false)).toBe( + 'Showing the newest 5000 server log lines in this window. Narrow --since/--until to see earlier ones.', + ); + expect(serverLogsCapLine(true)).toBe(yellow(serverLogsCapLine(false))); + }); + + it('words the 24 hour notice from the clamped start', () => { + const from = Date.parse('2026-10-27T10:00:00.000Z'); + + expect(serverLogsRetentionLine(from, false)).toBe( + 'Server logs are kept for 24 hours; showing from 2026-10-27T10:00:00.000Z.', + ); + expect(serverLogsRetentionLine(from, true)).toBe(yellow(serverLogsRetentionLine(from, false))); + }); + + it('words the interrupt line in yellow on a terminal and plain on a pipe', () => { + expect(stoppedFollowingLine(true)).toBe(yellow('Stopped following the logs.')); + expect(stoppedFollowingLine(false)).toBe('Stopped following the logs.'); + }); + + it.each([ + [{ deploymentNumber: 7 }, 'LIVE', 'Deployment #7 is LIVE.'], + [{ deploymentNumber: 0 }, 'FAILED', 'Deployment #0 is FAILED.'], + [{}, 'LIVE', 'Deployment is LIVE.'], + [{ deploymentNumber: null as unknown as number }, 'CANCELLED', 'Deployment is CANCELLED.'], + [{ deploymentNumber: 3 }, 'UNKNOWN', 'Deployment #3 is UNKNOWN.'], + ])('words the status line for %j and %s', (deployment, status, line) => { + expect(deploymentStatusLine(deployment, status)).toBe(line); + }); + + it('words the timed-out message with the full scope and the status', () => { + expect( + logsWaitTimedOutMessage('DEPLOYING', { org: 'o1', project: 'p1', environment: 'e1' }, 'd1'), + ).toBe( + 'Stopped waiting after 20 minutes; the deployment was still DEPLOYING. ' + + 'Run csdx launch:logs:get --org o1 --project p1 --env e1 --deployment d1 again to keep following it.', + ); + }); + + it('renders a server entry like a deployment log line', () => { + expect(serverLogLine({ timestamp: '2026-10-28T10:00:00.250Z', message: 'hello', source: 'edge' }, false)).toBe( + '2026-10-28 10:00:00.250: hello', + ); + }); + + it('renders an epoch millisecond timestamp through the same format', () => { + expect(serverLogLine({ timestamp: Date.parse('2026-10-28T10:00:00.250Z'), message: 'hello' }, false)).toBe( + '2026-10-28 10:00:00.250: hello', + ); + }); + + it('drops the colour of a server message on a pipe and keeps it on a terminal', () => { + const message = '\u001b[31mboom\u001b[0m'; + + expect(serverLogLine({ timestamp: '2026-10-28T10:00:00.000Z', message }, false)).toBe( + '2026-10-28 10:00:00.000: boom', + ); + expect(serverLogLine({ timestamp: '2026-10-28T10:00:00.000Z', message }, true, 200)).toContain(message); + }); + + it.each([ + [{}, ''], + [{ message: 'only a message' }, 'only a message'], + [{ timestamp: '2026-10-28T10:00:00.000Z' }, '2026-10-28 10:00:00.000:'], + [{ timestamp: Number.NaN, message: 'nan' }, 'nan'], + [{ timestamp: Number.POSITIVE_INFINITY, message: 'inf' }, 'inf'], + [{ timestamp: 9e15, message: 'beyond the date range' }, 'beyond the date range'], + [{ timestamp: 'not a time', message: 'bad' }, 'bad'], + [{ timestamp: null as unknown as string, message: null as unknown as string }, ''], + [{ message: 42 as unknown as string }, ''], + [null as unknown as object, ''], + ['text' as unknown as object, ''], + ])('prints a fallback for the server entry %j', (log, line) => { + expect(serverLogLine(log, false)).toBe(line); + }); + + it('T86: words the live session end in the local clock, dimmed on a terminal', () => { + const endsAt = new Date(2026, 9, 28, 14, 5, 9).getTime(); + + expect(liveSessionLine(endsAt, false)).toBe('Live session ends at 14:05:09; press Ctrl-C to stop.'); + expect(liveSessionLine(endsAt, true)).toBe('\u001b[2mLive session ends at 14:05:09; press Ctrl-C to stop.\u001b[22m'); + }); + + it('T88: words the server-limit end of a live session exactly', () => { + expect(liveSessionEndedLine()).toBe('The live session ended (server limit). Run the command again to keep following.'); + }); + + it('words the live session that printed nothing in yellow on a terminal and plain on a pipe', () => { + expect(noLiveLinesLine(false)).toBe('No live server logs arrived during this session.'); + expect(noLiveLinesLine(true)).toBe(yellow('No live server logs arrived during this session.')); + }); + + it('T90: words the lost live stream with the number of attempts', () => { + expect(liveStreamLostMessage(3)).toBe( + 'Lost the connection to the live server logs after 3 attempts. Check your network connection and run the command again.', + ); + }); +}); diff --git a/src/logs/logs.presenter.ts b/src/logs/logs.presenter.ts new file mode 100644 index 00000000..b1890160 --- /dev/null +++ b/src/logs/logs.presenter.ts @@ -0,0 +1,96 @@ +import { DEPLOYMENT_WAIT_TIMEOUT_MS } from '../deployments/deployment.watcher'; +import { clockOf, deploymentLogLine } from '../deployments/deployment.presenter'; +import type { Deployment } from '../deployments/types'; +import { styled } from '../core/style'; +import { isRecord } from '../core/values'; +import { SERVER_LOGS_PAGE_CAP, type ServerLog } from './types'; + +const MS_PER_MINUTE = 60_000; + +interface DeploymentScopeLabels { + org: string; + project: string; + environment: string; +} + +function deploymentLogsHint(scope: DeploymentScopeLabels, deploymentUid: string): string { + const flags = `--org ${scope.org} --project ${scope.project} --env ${scope.environment}`; + + return `csdx launch:logs:get ${flags} --deployment ${deploymentUid}`; +} + +function isoOf(time: number): string { + return new Date(time).toISOString(); +} + +function timestampOf(value: ServerLog['timestamp']): string | undefined { + if (typeof value === 'number') { + return Number.isFinite(value) && Math.abs(value) <= 8.64e15 ? isoOf(value) : undefined; + } + + return typeof value === 'string' ? value : undefined; +} + +export function serverLogLine(log: ServerLog, outputIsTTY: boolean, columns?: number): string { + const entry: ServerLog = isRecord(log) ? log : {}; + const message = typeof entry.message === 'string' ? entry.message : undefined; + + return deploymentLogLine({ message, timestamp: timestampOf(entry.timestamp) }, outputIsTTY, columns); +} + +export function noDeploymentLogsLine(deployment: string, outputIsTTY: boolean): string { + return styled(`No deployment logs found for deployment ${deployment}.`, 'yellow', outputIsTTY); +} + +export function noServerLogsLine(startTime: number, endTime: number, outputIsTTY: boolean): string { + return styled(`No server logs found between ${isoOf(startTime)} and ${isoOf(endTime)}.`, 'yellow', outputIsTTY); +} + +export function serverLogsCapLine(outputIsTTY: boolean): string { + return styled( + `Showing the newest ${SERVER_LOGS_PAGE_CAP} server log lines in this window. ` + + 'Narrow --since/--until to see earlier ones.', + 'yellow', + outputIsTTY, + ); +} + +export function serverLogsRetentionLine(clampedFrom: number, outputIsTTY: boolean): string { + return styled(`Server logs are kept for 24 hours; showing from ${isoOf(clampedFrom)}.`, 'yellow', outputIsTTY); +} + +export function stoppedFollowingLine(outputIsTTY: boolean): string { + return styled('Stopped following the logs.', 'yellow', outputIsTTY); +} + +export function liveSessionLine(endsAt: number, outputIsTTY: boolean): string { + return styled(`Live session ends at ${clockOf(endsAt)}; press Ctrl-C to stop.`, 'dim', outputIsTTY); +} + +export function liveSessionEndedLine(): string { + return 'The live session ended (server limit). Run the command again to keep following.'; +} + +export function noLiveLinesLine(outputIsTTY: boolean): string { + return styled('No live server logs arrived during this session.', 'yellow', outputIsTTY); +} + +export function liveStreamLostMessage(attempts: number): string { + return ( + `Lost the connection to the live server logs after ${attempts} attempts. ` + + 'Check your network connection and run the command again.' + ); +} + +export function deploymentStatusLine(deployment: Deployment, status: string): string { + const number = typeof deployment.deploymentNumber === 'number' ? ` #${deployment.deploymentNumber}` : ''; + + return `Deployment${number} is ${status}.`; +} + +export function logsWaitTimedOutMessage(status: string, scope: DeploymentScopeLabels, deployment: string): string { + return ( + `Stopped waiting after ${DEPLOYMENT_WAIT_TIMEOUT_MS / MS_PER_MINUTE} minutes; ` + + `the deployment was still ${status}. Run ${deploymentLogsHint(scope, deployment)} again to keep following it.` + ); +} diff --git a/src/logs/server-logs.api.test.ts b/src/logs/server-logs.api.test.ts new file mode 100644 index 00000000..8af58e24 --- /dev/null +++ b/src/logs/server-logs.api.test.ts @@ -0,0 +1,76 @@ +import { randomBytes } from 'node:crypto'; + +import { LaunchApiError } from '../transport/errors'; +import type { RestApiClient, RestRequest } from '../transport/rest-client'; +import { LOGS_ERROR_MESSAGES } from './logs.errors'; +import { ServerLogsApi } from './server-logs.api'; + +const ORG = randomBytes(9).toString('hex'); +const PROJECT = randomBytes(12).toString('hex'); +const ENVIRONMENT = randomBytes(12).toString('hex'); +const DEPLOYMENT = randomBytes(12).toString('hex'); + +const WINDOW = { org: ORG, project: PROJECT, environment: ENVIRONMENT, deployment: DEPLOYMENT, startTime: 1_000, endTime: 2_000 }; + +function fakeRestClient(result: unknown) { + const requests: RestRequest[] = []; + const messages: unknown[] = []; + const client = { + request: async (req: RestRequest, errorMessages: unknown) => { + requests.push(req); + messages.push(errorMessages); + return result; + }, + } as unknown as RestApiClient; + + return { client, requests, messages }; +} + +describe('ServerLogsApi', () => { + it('reads the window as a scoped GET on the deployment path and returns the entries in order', async () => { + const entries = [ + { timestamp: '2026-10-28T10:00:00.000Z', message: 'first', source: 'edge' }, + { timestamp: '2026-10-28T10:00:01.000Z', message: 'second', source: 'edge' }, + ]; + const { client, requests, messages } = fakeRestClient({ serverLogs: entries }); + + const result = await new ServerLogsApi(client).window(WINDOW); + + expect(result).toEqual(entries); + expect(requests).toEqual([ + { + method: 'GET', + path: `/projects/${PROJECT}/environments/${ENVIRONMENT}/deployments/${DEPLOYMENT}/logs/server-logs`, + orgUid: ORG, + projectUid: PROJECT, + query: { startTime: 1_000, endTime: 2_000 }, + }, + ]); + expect(messages[0]).toBe(LOGS_ERROR_MESSAGES); + }); + + it('returns an empty page as an empty list', async () => { + const { client } = fakeRestClient({ serverLogs: [] }); + + await expect(new ServerLogsApi(client).window(WINDOW)).resolves.toEqual([]); + }); + + it.each([[{}], [{ serverLogs: null }], [{ serverLogs: {} }], [null], ['text']])( + 'raises a malformed-response error when the body %j has no serverLogs array', + async (body) => { + const { client } = fakeRestClient(body); + + const reading = new ServerLogsApi(client).window(WINDOW); + + await expect(reading).rejects.toThrow(LaunchApiError); + await expect(reading).rejects.toThrow('The Launch API returned a server log page without a serverLogs array.'); + }, + ); + + it('propagates a failed request with its own error', async () => { + const failure = new LaunchApiError(502, [{ code: 'launch.UPSTREAM', message: 'Bad gateway' }]); + const client = { request: async () => Promise.reject(failure) } as unknown as RestApiClient; + + await expect(new ServerLogsApi(client).window(WINDOW)).rejects.toBe(failure); + }); +}); diff --git a/src/logs/server-logs.api.ts b/src/logs/server-logs.api.ts new file mode 100644 index 00000000..e0ea909e --- /dev/null +++ b/src/logs/server-logs.api.ts @@ -0,0 +1,33 @@ +import { DeploymentsApi, type GetDeploymentParams } from '../deployments/deployments.api'; +import { assertArray } from '../transport/envelope'; +import type { RestApiClient } from '../transport/rest-client'; +import { LOGS_ERROR_MESSAGES } from './logs.errors'; +import type { ServerLog, ServerLogsResponse } from './types'; + +export * from './types'; + +export interface ServerLogsWindowParams extends GetDeploymentParams { + startTime: number; + endTime: number; +} + +export class ServerLogsApi { + constructor(private readonly client: RestApiClient) {} + + async window(params: ServerLogsWindowParams): Promise { + const response = await this.client.request( + { + method: 'GET', + path: `${DeploymentsApi.pathOf(params)}/logs/server-logs`, + orgUid: params.org, + projectUid: params.project, + query: { startTime: params.startTime, endTime: params.endTime }, + }, + LOGS_ERROR_MESSAGES, + ); + + assertArray(response, 'serverLogs', 'server log page'); + + return response.serverLogs; + } +} diff --git a/src/logs/types.ts b/src/logs/types.ts new file mode 100644 index 00000000..aaf9d153 --- /dev/null +++ b/src/logs/types.ts @@ -0,0 +1,11 @@ +export const SERVER_LOGS_PAGE_CAP = 5000; + +export interface ServerLog { + timestamp?: string | number; + message?: string; + source?: string; +} + +export interface ServerLogsResponse { + serverLogs: ServerLog[]; +} diff --git a/src/projects/projects.api.test.ts b/src/projects/projects.api.test.ts index 17c5f02b..6863faec 100644 --- a/src/projects/projects.api.test.ts +++ b/src/projects/projects.api.test.ts @@ -299,7 +299,7 @@ describe('ProjectsApi', () => { it('buildApi exposes the projects resource', () => { const { client } = fakeRestClient({}); - expect(buildApi(client, UNUSED_CMA, {} as never).projects).toBeInstanceOf(ProjectsApi); + expect(buildApi(client, UNUSED_CMA, {} as never, {} as never).projects).toBeInstanceOf(ProjectsApi); }); }); diff --git a/src/resources.test.ts b/src/resources.test.ts index 89c2056a..68f9de40 100644 --- a/src/resources.test.ts +++ b/src/resources.test.ts @@ -2,6 +2,8 @@ import type { ApiSurface } from './resources'; import { DEPENDENCIES, buildApi, catalog, resolutionTable } from './resources'; import { DeploymentsApi } from './deployments/deployments.api'; import { DeploymentLogsApi } from './deployments/deployment-logs.api'; +import { LiveLogsApi } from './logs/live-logs.api'; +import { ServerLogsApi } from './logs/server-logs.api'; import { EnvironmentsApi } from './environments/environments.api'; import { UploadsApi } from './uploads/uploads.api'; import { CacheApi } from './cache/cache.api'; @@ -12,7 +14,9 @@ import * as prompt from './projects/project.prompt'; import * as organizationPrompt from './organizations/organization.prompt'; import { OrganizationsApi } from './organizations/organizations.api'; import { ProjectResolver } from './projects/project.resolver'; +import { LOGS_ERROR_MESSAGES } from './logs/logs.errors'; import type { CmaSession } from './transport/cma-client'; +import type { EventStreamClient } from './transport/event-stream'; import type { RestApiClient, RestRequest } from './transport/rest-client'; const UNUSED_CMA: CmaSession = { @@ -187,7 +191,7 @@ describe('resolution', () => { describe('the api surface', () => { it('assembles one repository per resource from the single client', () => { const client = {} as never; - const api = buildApi(client, UNUSED_CMA, {} as never); + const api = buildApi(client, UNUSED_CMA, {} as never, {} as never); expect(Object.keys(api).sort()).toEqual([ 'cache', @@ -195,13 +199,17 @@ describe('the api surface', () => { 'deployments', 'environments', 'git', + 'liveLogs', 'organizations', 'projects', + 'serverLogs', 'stacks', 'uploads', 'variables', ]); expect(api.deploymentLogs).toBeInstanceOf(DeploymentLogsApi); + expect(api.serverLogs).toBeInstanceOf(ServerLogsApi); + expect(api.liveLogs).toBeInstanceOf(LiveLogsApi); expect(api.organizations).toBeInstanceOf(OrganizationsApi); expect(api.projects).toBeInstanceOf(ProjectsApi); expect(api.environments).toBeInstanceOf(EnvironmentsApi); @@ -211,7 +219,7 @@ describe('the api surface', () => { expect(api.cache).toBeInstanceOf(CacheApi); }); - it('sends deployment log reads through the logs client and nothing else through it', async () => { + it('sends deployment and server log reads through the logs client and nothing else through it', async () => { const sent = { manage: [] as RestRequest[], logs: [] as RestRequest[] }; const recording = (into: RestRequest[], body: unknown) => ({ @@ -223,17 +231,39 @@ describe('the api surface', () => { const api = buildApi( recording(sent.manage, { deployment: { uid: 'd1', status: 'LIVE' } }), UNUSED_CMA, - recording(sent.logs, { deploymentLogs: [] }), + recording(sent.logs, { deploymentLogs: [], serverLogs: [] }), + {} as never, ); const scope = { org: 'o1', project: 'p1', environment: 'e1', deployment: 'd1' }; await api.deploymentLogs.after({ ...scope, timestamp: '2026-09-25T10:00:00.000Z' }); + await api.serverLogs.window({ ...scope, startTime: 1, endTime: 2 }); await api.deployments.get(scope); - expect(sent.logs.map((req) => req.path)).toEqual(['/projects/p1/environments/e1/deployments/d1/logs/deployment-logs']); + expect(sent.logs.map((req) => req.path)).toEqual([ + '/projects/p1/environments/e1/deployments/d1/logs/deployment-logs', + '/projects/p1/environments/e1/deployments/d1/logs/server-logs', + ]); expect(sent.manage.map((req) => req.path)).toEqual(['/projects/p1/environments/e1/deployments/d1']); }); + it('T84: opens the live route through the stream client and not through either rest client', async () => { + const opened: unknown[] = []; + const sent: RestRequest[] = []; + const rest = { request: async (req: RestRequest) => void sent.push(req) } as unknown as RestApiClient; + const stream = { + open: async (req: unknown, _onFrame: unknown, _signal: unknown, messages: unknown) => void opened.push([req, messages]), + } as unknown as EventStreamClient; + const scope = { org: 'o1', project: 'p1', environment: 'e1', deployment: 'd1' }; + + await buildApi(rest, UNUSED_CMA, rest, stream).liveLogs.open(scope, { onFrame: () => undefined }, new AbortController().signal); + + expect(opened).toEqual([ + [{ path: '/projects/p1/environments/e1/deployments/d1/logs/live', orgUid: 'o1', projectUid: 'p1' }, LOGS_ERROR_MESSAGES], + ]); + expect(sent).toEqual([]); + }); + it('hands the organizations repository the CMA session it was given', async () => { const fetched: unknown[] = []; const cma: CmaSession = { @@ -251,7 +281,7 @@ describe('the api surface', () => { scopedOrganizationUid: () => 'org7', }; - const available = await buildApi({} as never, cma, {} as never).organizations.available(); + const available = await buildApi({} as never, cma, {} as never, {} as never).organizations.available(); expect(fetched).toEqual(['org7']); expect(available).toEqual({ organizations: [{ uid: 'org7', name: 'Scoped Org' }], scoped: true }); diff --git a/src/resources.ts b/src/resources.ts index b9f30b2f..51ce079c 100644 --- a/src/resources.ts +++ b/src/resources.ts @@ -10,6 +10,9 @@ import { import { variableFlags, variableResolution } from './variables/variable.inputs'; import { cacheFlags, cacheResolution } from './cache/cache.inputs'; import { DEPLOYMENT_DEPENDENCIES, deploymentFlags, deploymentResolution } from './deployments/deployment.inputs'; +import { logsFlags, logsResolution } from './logs/logs.inputs'; +import { LiveLogsApi } from './logs/live-logs.api'; +import { ServerLogsApi } from './logs/server-logs.api'; import { ProjectsApi } from './projects/projects.api'; import { EnvironmentsApi } from './environments/environments.api'; import { DeploymentsApi } from './deployments/deployments.api'; @@ -21,6 +24,7 @@ import { StacksApi } from './stacks/stacks.api'; import { VariablesApi } from './variables/variables.api'; import { CacheApi } from './cache/cache.api'; import type { CmaSession } from './transport/cma-client'; +import type { EventStreamClient } from './transport/event-stream'; import type { RestApiClient } from './transport/rest-client'; export const catalog = { @@ -31,12 +35,14 @@ export const catalog = { ...variableFlags, ...cacheFlags, ...deploymentFlags, + ...logsFlags, }; export type Catalog = typeof catalog; export type FlagKey = keyof Catalog; export const resolution = { + ...logsResolution, ...projectResolution, ...organizationResolution, ...coreResolution, @@ -66,6 +72,8 @@ export interface ApiSurface { environments: EnvironmentsApi; deployments: DeploymentsApi; deploymentLogs: DeploymentLogsApi; + serverLogs: ServerLogsApi; + liveLogs: LiveLogsApi; git: GitApi; uploads: UploadsApi; stacks: StacksApi; @@ -73,13 +81,20 @@ export interface ApiSurface { cache: CacheApi; } -export function buildApi(client: RestApiClient, cma: CmaSession, logsClient: RestApiClient): ApiSurface { +export function buildApi( + client: RestApiClient, + cma: CmaSession, + logsClient: RestApiClient, + logsStream: EventStreamClient, +): ApiSurface { return { organizations: new OrganizationsApi(cma), projects: new ProjectsApi(client), environments: new EnvironmentsApi(client), deployments: new DeploymentsApi(client), deploymentLogs: new DeploymentLogsApi(logsClient), + serverLogs: new ServerLogsApi(logsClient), + liveLogs: new LiveLogsApi(logsStream), git: new GitApi(client), uploads: new UploadsApi(client), stacks: new StacksApi(cma), diff --git a/src/transport/event-stream.test.ts b/src/transport/event-stream.test.ts new file mode 100644 index 00000000..e75acfb4 --- /dev/null +++ b/src/transport/event-stream.test.ts @@ -0,0 +1,110 @@ +import { FrameParser, type StreamFrame } from './event-stream'; + +const encoder = new TextEncoder(); + +function parseAll(chunks: (string | Uint8Array)[]): StreamFrame[] { + const parser = new FrameParser(); + + return chunks.flatMap((chunk) => parser.push(typeof chunk === 'string' ? encoder.encode(chunk) : chunk)); +} + +describe('FrameParser', () => { + it('T70: dispatches a named frame and an unnamed frame at each blank line', () => { + const frames = parseAll(['event: session\ndata: {"expiresAt":"x"}\n\ndata: {"message":"hi"}\n\n']); + + expect(frames).toEqual([ + { event: 'session', data: '{"expiresAt":"x"}' }, + { event: undefined, data: '{"message":"hi"}' }, + ]); + }); + + it('T70: holds a frame back until its blank line arrives', () => { + const parser = new FrameParser(); + + expect(parser.push(encoder.encode('data: one\n'))).toEqual([]); + expect(parser.push(encoder.encode('\n'))).toEqual([{ event: undefined, data: 'one' }]); + }); + + it('T71: parses byte by byte exactly as it parses the whole body', () => { + const body = encoder.encode('event: session\r\ndata: {"a":1}\r\n\r\ndata: héllo \u{1F600}\n\n'); + const whole = parseAll([body]); + + const bytewise = parseAll([...body].map((byte) => Uint8Array.of(byte))); + + expect(bytewise).toEqual(whole); + expect(whole[1].data).toBe('héllo \u{1F600}'); + }); + + it('T71: parses a multi-byte character split between two chunks', () => { + const body = encoder.encode('data: é\u{1F600}\n\n'); + const middle = body.indexOf(0xf0) + 2; + + const frames = parseAll([body.subarray(0, middle), body.subarray(middle)]); + + expect(frames).toEqual([{ event: undefined, data: 'é\u{1F600}' }]); + }); + + it.each([ + ['CRLF', '\r\n'], + ['lone CR', '\r'], + ['LF', '\n'], + ])('T72: reads %s line endings', (_name, eol) => { + const frames = parseAll([`event: session${eol}data: one${eol}${eol}data: two${eol}${eol}`]); + + expect(frames).toEqual([ + { event: 'session', data: 'one' }, + { event: undefined, data: 'two' }, + ]); + }); + + it('T72: treats a CRLF split across two chunks as one line ending', () => { + const frames = parseAll(['data: one\r', '\n\r', '\ndata: two\n\n']); + + expect(frames).toEqual([ + { event: undefined, data: 'one' }, + { event: undefined, data: 'two' }, + ]); + }); + + it('T73: skips comment lines, accepts data without a space and strips exactly one leading space', () => { + const frames = parseAll([': keep-alive\ndata:tight\n\ndata: two spaces\n\n']); + + expect(frames).toEqual([ + { event: undefined, data: 'tight' }, + { event: undefined, data: ' two spaces' }, + ]); + }); + + it('T73: joins several data lines with a newline and reads a bare field as an empty value', () => { + const frames = parseAll(['data: a\ndata: b\ndata\n\n']); + + expect(frames).toEqual([{ event: undefined, data: 'a\nb\n' }]); + }); + + it('T73: ignores the id and retry fields', () => { + const frames = parseAll(['id: 7\nretry: 100\ndata: x\n\n']); + + expect(frames).toEqual([{ event: undefined, data: 'x' }]); + }); + + it('T74: emits nothing for an event line without data and does not leak its name into the next frame', () => { + const frames = parseAll(['event: session\n\ndata: later\n\n']); + + expect(frames).toEqual([{ event: undefined, data: 'later' }]); + }); + + it('T74: discards an unterminated tail', () => { + const frames = parseAll(['data: whole\n\ndata: cut off']); + + expect(frames).toEqual([{ event: undefined, data: 'whole' }]); + }); + + it('T75: dispatches a heartbeat as a frame with empty data', () => { + const frames = parseAll(['data: \n\ndata\n\n']); + + expect(frames).toEqual([ + { event: undefined, data: '' }, + { event: undefined, data: '' }, + ]); + }); +}); diff --git a/src/transport/event-stream.ts b/src/transport/event-stream.ts new file mode 100644 index 00000000..76fd95a2 --- /dev/null +++ b/src/transport/event-stream.ts @@ -0,0 +1,249 @@ +import { request as httpRequest } from 'node:http'; +import type { IncomingMessage } from 'node:http'; +import { request as httpsRequest } from 'node:https'; +import { URL } from 'node:url'; + +import type { AuthStrategy } from './auth-strategy'; +import type { ErrorMessages } from './errors'; +import { LaunchNetworkError, PROXY_ERROR_CODES, diagnoseTransportError, parseErrorEnvelope } from './errors'; +import { proxyFailureMessage, proxyRouteFor } from './proxy'; +import { buildRequestHeaders, type RequestScope } from './rest-client'; + +export const EVENT_STREAM_IDLE_TIMEOUT_MS = 30_000; + +const MAX_REFUSAL_BODY_BYTES = 64 * 1024; +const FIRST_UNREACHABLE_STATUS = 300; +const FIRST_OPEN_STATUS = 200; + +export interface StreamFrame { + event: string | undefined; + data: string; +} + +const LINE_ENDING = /\r\n|\r|\n/; + +export class FrameParser { + private readonly decoder = new TextDecoder('utf-8'); + private tail = ''; + private skipLineFeed = false; + private event: string | undefined; + private data: string[] = []; + + push(chunk: Uint8Array): StreamFrame[] { + let text = this.decoder.decode(chunk, { stream: true }); + + if (text === '') { + return []; + } + + if (this.skipLineFeed && text.startsWith('\n')) { + text = text.slice(1); + } + + this.skipLineFeed = text.endsWith('\r'); + + const lines = (this.tail + text).split(LINE_ENDING); + this.tail = lines.pop() as string; + + return lines.flatMap((line) => this.read(line)); + } + + private read(line: string): StreamFrame[] { + if (line === '') { + return this.dispatch(); + } + + if (line.startsWith(':')) { + return []; + } + + const colon = line.indexOf(':'); + const field = colon === -1 ? line : line.slice(0, colon); + const raw = colon === -1 ? '' : line.slice(colon + 1); + const value = raw.startsWith(' ') ? raw.slice(1) : raw; + + if (field === 'event') { + this.event = value; + } + + if (field === 'data') { + this.data.push(value); + } + + return []; + } + + private dispatch(): StreamFrame[] { + const frame = { event: this.event, data: this.data.join('\n') }; + const hadData = this.data.length > 0; + + this.event = undefined; + this.data = []; + + return hadData ? [frame] : []; + } +} + +export interface EventStreamClientOptions { + baseUrl: string; + analyticsInfo: string; + auth: AuthStrategy; + idleTimeoutMs?: number; +} + +export interface EventStreamRequest extends RequestScope { + path: string; +} + +interface Refusal { + status: number; + body: unknown; +} + +function jsonOrUndefined(text: string): unknown { + try { + return JSON.parse(text); + } catch { + return undefined; + } +} + +function interrupted(): LaunchNetworkError { + return new LaunchNetworkError( + 'The connection to the Launch API was closed before the stream finished.', + undefined, + true, + ); +} + +export class EventStreamClient { + constructor(private readonly options: EventStreamClientOptions) {} + + async open( + req: EventStreamRequest, + onFrame: (frame: StreamFrame) => void, + signal?: AbortSignal, + errorMessages: ErrorMessages = {}, + ): Promise { + let refreshed = false; + + for (;;) { + const headers = { ...(await buildRequestHeaders(this.options, req)), Accept: 'text/event-stream' }; + const refusal = await this.connect(req.path, headers, onFrame, signal); + + if (refusal === undefined) { + return; + } + + if (refusal.status === 401 && !refreshed && this.options.auth.refresh) { + refreshed = true; + await this.options.auth.refresh(); + continue; + } + + throw parseErrorEnvelope(refusal.status, refusal.body, errorMessages); + } + } + + private connect( + path: string, + headers: Record, + onFrame: (frame: StreamFrame) => void, + signal?: AbortSignal, + ): Promise { + const url = new URL(`${this.options.baseUrl}${path}`); + const send = url.protocol === 'http:' ? httpRequest : httpsRequest; + const proxy = proxyRouteFor(url.href); + const idleMs = this.options.idleTimeoutMs ?? EVENT_STREAM_IDLE_TIMEOUT_MS; + + const watched = signal ?? new AbortController().signal; + + return new Promise((resolve, reject) => { + if (watched.aborted) { + reject(watched.reason); + return; + } + + let settled = false; + let timer: NodeJS.Timeout | undefined; + + const settle = (outcome: () => void): void => { + if (!settled) { + settled = true; + clearTimeout(timer); + watched.removeEventListener('abort', onAbort); + outcome(); + } + }; + const fail = (error: unknown): void => + settle(() => { + request.destroy(); + reject(error); + }); + const onAbort = (): void => fail(watched.reason); + const rearm = (): void => { + clearTimeout(timer); + timer = setTimeout( + () => + fail( + new LaunchNetworkError( + `The connection to the Launch API went quiet: nothing was received for ${idleMs / 1000} seconds.`, + undefined, + true, + ), + ), + idleMs, + ); + }; + const read = (response: IncomingMessage): void => { + const status = Number(response.statusCode); + const open = status >= FIRST_OPEN_STATUS && status < FIRST_UNREACHABLE_STATUS; + const parser = new FrameParser(); + const body: Buffer[] = []; + let bodyBytes = 0; + + rearm(); + response.on('data', (chunk: Buffer) => { + rearm(); + + if (!open) { + bodyBytes += chunk.length; + + if (bodyBytes <= MAX_REFUSAL_BODY_BYTES) { + body.push(chunk); + } + + return; + } + + try { + parser.push(chunk).forEach(onFrame); + } catch (error) { + fail(error); + } + }); + response.on('end', () => + settle(() => + resolve(open ? undefined : { status, body: jsonOrUndefined(Buffer.concat(body).toString('utf8')) }), + ), + ); + response.on('error', (error) => fail(diagnoseTransportError(error))); + response.on('close', () => fail(interrupted())); + }; + + const request = send(url, { method: 'GET', headers, agent: proxy?.agent ?? false }, read); + + request.on('error', (error: NodeJS.ErrnoException) => { + if (proxy !== undefined && PROXY_ERROR_CODES.includes(error.code as string)) { + fail(new LaunchNetworkError(proxyFailureMessage(proxy.address), error)); + return; + } + + fail(diagnoseTransportError(error)); + }); + watched.addEventListener('abort', onAbort, { once: true }); + rearm(); + request.end(); + }); + } +} diff --git a/src/transport/rest-client.test.ts b/src/transport/rest-client.test.ts index 0a06cac6..b6bbdafa 100644 --- a/src/transport/rest-client.test.ts +++ b/src/transport/rest-client.test.ts @@ -5,7 +5,7 @@ import { HttpClient, configHandler } from '@contentstack/cli-utilities'; import { API_VERSION } from '../core/constants'; import { LaunchApiError, LaunchNetworkError } from './errors'; import type { HttpClientLike } from './rest-client'; -import { RestApiClient } from './rest-client'; +import { RestApiClient, buildRequestHeaders } from './rest-client'; import { DEFAULT_REQUEST_TIMEOUT_MS } from './retry-policy'; const QUOTA_CODE = 'launch.ORGANIZATION.REVALIDATE_RATE_LIMIT_EXCEEDED'; @@ -812,3 +812,36 @@ describe('RestApiClient', () => { createSpy.mockRestore(); }); }); + +describe('buildRequestHeaders', () => { + const identity = { analyticsInfo: 'cli/2.0.0', auth: { headers: async () => ({ authtoken: 'tok' }) } }; + + it('returns the CLI marker, the api version, the auth headers and both scope headers', async () => { + const headers = await buildRequestHeaders(identity, { orgUid: 'org1', projectUid: 'proj1' }); + + expect(headers).toEqual({ + 'X-CS-CLI': 'cli/2.0.0', + 'x-cs-api-version': API_VERSION, + authtoken: 'tok', + 'x-organization-uid': 'org1', + 'x-project-uid': 'proj1', + }); + }); + + it('leaves the scope headers out when no scope is given', async () => { + const headers = await buildRequestHeaders(identity, {}); + + expect(headers).not.toHaveProperty('x-organization-uid'); + expect(headers).not.toHaveProperty('x-project-uid'); + expect(Object.keys(headers)).toHaveLength(3); + }); + + it.each([ + ['orgUid', 'x-organization-uid'], + ['projectUid', 'x-project-uid'], + ])('refuses a blank %s rather than sending an unscoped request', async (field, header) => { + await expect(buildRequestHeaders(identity, { [field]: ' ' })).rejects.toThrow( + `${header} was given a blank value; an unscoped Launch API request is never correct.`, + ); + }); +}); diff --git a/src/transport/rest-client.ts b/src/transport/rest-client.ts index 54b47861..c1829595 100644 --- a/src/transport/rest-client.ts +++ b/src/transport/rest-client.ts @@ -68,6 +68,32 @@ function scopeHeader(headers: Record, name: string, value: strin headers[name] = value; } +export interface RequestIdentity { + analyticsInfo: string; + auth: AuthStrategy; +} + +export interface RequestScope { + orgUid?: string; + projectUid?: string; +} + +export async function buildRequestHeaders( + identity: RequestIdentity, + scope: RequestScope, +): Promise> { + const headers: Record = { + 'X-CS-CLI': identity.analyticsInfo, + 'x-cs-api-version': API_VERSION, + ...(await identity.auth.headers()), + }; + + scopeHeader(headers, 'x-organization-uid', scope.orgUid); + scopeHeader(headers, 'x-project-uid', scope.projectUid); + + return headers; +} + const EXPIRED_TOKEN_MESSAGE = 'access token is invalid or expired'; const GIT_PROVIDER_CODE_PREFIX = 'launch.GIT_PROVIDER.'; @@ -144,14 +170,7 @@ export class RestApiClient { const create = this.options.createHttpClient ?? createUtilityHttpClient; const client = create(); - const headers: Record = { - 'X-CS-CLI': this.options.analyticsInfo, - 'x-cs-api-version': API_VERSION, - ...(await this.options.auth.headers()), - }; - - scopeHeader(headers, 'x-organization-uid', req.orgUid); - scopeHeader(headers, 'x-project-uid', req.projectUid); + const headers = await buildRequestHeaders(this.options, req); client .baseUrl(this.options.baseUrl) diff --git a/test/guards/layering.test.ts b/test/guards/layering.test.ts index f27742bf..e4f9912a 100644 --- a/test/guards/layering.test.ts +++ b/test/guards/layering.test.ts @@ -20,6 +20,7 @@ const RESOURCE_EDGES: Record = { stacks: [], variables: ['environments', 'stacks'], cache: [], + logs: ['deployments'], site: ['deployments', 'environments'], }; @@ -154,6 +155,23 @@ describe('layering between resources', () => { expect([...new Set(reachedByCommands)].sort()).toEqual(['deployments', 'environments', 'variables']); }); + it('records the one edge the logs resource and its command really use, and no others', () => { + expect(RESOURCE_EDGES.logs).toEqual(['deployments']); + + expect([...new Set(sourceFilesIn('logs').flatMap((path) => crossResourceEdges(path)))].sort()).toEqual([ + 'deployments', + ]); + + const commandFiles = filesUnder('commands/launch/logs', true).filter((path) => !path.endsWith('.test.ts')); + const reachedByCommands = commandFiles.flatMap((path) => + importedPaths(path) + .map((specifier) => resourceOf(specifier, directoryOf(path))) + .filter((target): target is string => target !== undefined && target !== 'logs'), + ); + + expect([...new Set(reachedByCommands)].sort()).toEqual(['deployments']); + }); + it('reports a disallowed edge rather than passing vacuously', () => { const owner = 'git'; diff --git a/test/integration/event-stream.test.ts b/test/integration/event-stream.test.ts new file mode 100644 index 00000000..89509937 --- /dev/null +++ b/test/integration/event-stream.test.ts @@ -0,0 +1,497 @@ +import { randomBytes, randomUUID } from 'node:crypto'; +import { getEventListeners } from 'node:events'; +import type { IncomingHttpHeaders, IncomingMessage, ServerResponse } from 'node:http'; +import { createServer, type Server } from 'node:http'; +import type { AddressInfo, Socket } from 'node:net'; +import { connect } from 'node:net'; + +import { API_VERSION } from '../../src/core/constants'; +import { SessionExpiredError } from '../../src/core/errors'; +import type { StreamFrame } from '../../src/transport/event-stream'; +import { EVENT_STREAM_IDLE_TIMEOUT_MS, EventStreamClient } from '../../src/transport/event-stream'; +import { LaunchApiError, LaunchNetworkError } from '../../src/transport/errors'; +import type { AuthStrategy } from '../../src/transport/auth-strategy'; +import { trackTimers } from '../support/timers'; + +const PROXY_VARIABLES = ['HTTPS_PROXY', 'HTTP_PROXY', 'https_proxy', 'http_proxy', 'NO_PROXY', 'no_proxy']; +const ANALYTICS_INFO = '@contentstack/cli-launch/2.0.0 linux-x64 node-v22.0.0'; +const PATH = '/projects/p1/environments/e1/deployments/d1/logs/live'; +const SCOPE = { path: PATH, orgUid: 'org1', projectUid: 'proj1' }; + +interface Seen { + url: string; + headers: IncomingHttpHeaders; +} + +interface Harness { + baseUrl: string; + seen: Seen[]; + sockets: Set; + closed: () => number; + stop: () => Promise; +} + +async function serve(handler: (req: IncomingMessage, res: ServerResponse, index: number) => void): Promise { + const seen: Seen[] = []; + const sockets = new Set(); + let closedSockets = 0; + const server: Server = createServer((req, res) => { + seen.push({ url: req.url ?? '', headers: req.headers }); + handler(req, res, seen.length - 1); + }); + + server.on('connection', (socket) => { + sockets.add(socket); + socket.on('close', () => { + sockets.delete(socket); + closedSockets += 1; + }); + }); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + + return { + baseUrl: `http://127.0.0.1:${(server.address() as AddressInfo).port}/logs`, + seen, + sockets, + closed: () => closedSockets, + stop: () => { + server.closeAllConnections(); + return new Promise((resolve) => server.close(() => resolve())); + }, + }; +} + +function stream(res: ServerResponse, status = 200): void { + res.writeHead(status, { 'content-type': 'text/event-stream' }); + res.flushHeaders(); +} + +function clientFor(baseUrl: string, auth?: Partial, idleTimeoutMs?: number): EventStreamClient { + return new EventStreamClient({ + baseUrl, + analyticsInfo: ANALYTICS_INFO, + auth: { headers: async () => ({ authtoken: 'tok' }), ...auth }, + idleTimeoutMs, + }); +} + +async function collect(client: EventStreamClient, signal?: AbortSignal): Promise { + const frames: StreamFrame[] = []; + + await client.open(SCOPE, (frame) => frames.push(frame), signal); + + return frames; +} + +async function eventually(check: () => boolean): Promise { + for (let waited = 0; !check() && waited < 2000; waited += 10) { + await new Promise((resolve) => setTimeout(resolve, 10)); + } +} + +describe('integration: the server-sent events client on a real socket', () => { + let harness: Harness; + let saved: Record; + + beforeEach(() => { + saved = {}; + for (const name of PROXY_VARIABLES) { + saved[name] = process.env[name]; + delete process.env[name]; + } + }); + + afterEach(async () => { + await harness?.stop(); + for (const name of PROXY_VARIABLES) { + if (saved[name] === undefined) { + delete process.env[name]; + } else { + process.env[name] = saved[name]; + } + } + }); + + it('T76: requests the route under the base path with the event-stream accept header and every shared header', async () => { + harness = await serve((_req, res) => { + stream(res); + res.end('event: session\ndata: {"a":1}\n\ndata: {"b":2}\n\n'); + }); + + const frames = await collect(clientFor(harness.baseUrl)); + + expect(frames).toEqual([ + { event: 'session', data: '{"a":1}' }, + { event: undefined, data: '{"b":2}' }, + ]); + expect(harness.seen).toHaveLength(1); + expect(harness.seen[0].url).toBe(`/logs${PATH}`); + expect(harness.seen[0].headers).toMatchObject({ + accept: 'text/event-stream', + 'x-cs-cli': ANALYTICS_INFO, + 'x-cs-api-version': API_VERSION, + authtoken: 'tok', + 'x-organization-uid': 'org1', + 'x-project-uid': 'proj1', + }); + }); + + it('T78: is not cut by an idle limit while heartbeats keep arriving for three times that long', async () => { + harness = await serve((_req, res) => { + stream(res); + const beat = setInterval(() => res.write('data: \n\n'), 50); + setTimeout(() => { + clearInterval(beat); + res.end(); + }, 600); + }); + + const frames = await collect(clientFor(harness.baseUrl, undefined, 200)); + + expect(frames.length).toBeGreaterThanOrEqual(8); + expect(frames.every((frame) => frame.data === '')).toBe(true); + }); + + it('T79: fails a stream that goes silent with a retryable network error and closes the socket', async () => { + const timers = trackTimers(100); + harness = await serve((_req, res) => { + stream(res); + res.write('data: first\n\n'); + }); + const frames: StreamFrame[] = []; + + const error = await clientFor(harness.baseUrl, undefined, 100) + .open(SCOPE, (frame) => frames.push(frame)) + .catch((caught: unknown) => caught); + + await eventually(() => harness.closed() === 1); + expect(error).toBeInstanceOf(LaunchNetworkError); + expect((error as LaunchNetworkError).retryable).toBe(true); + expect((error as LaunchNetworkError).message).toBe( + 'The connection to the Launch API went quiet: nothing was received for 0.1 seconds.', + ); + expect(frames).toEqual([{ event: undefined, data: 'first' }]); + expect(harness.closed()).toBe(1); + expect(timers.created()).toBeGreaterThan(0); + expect(timers.pending()).toBe(0); + }); + + it('T79: also times out a server that accepts the request and never answers', async () => { + harness = await serve(() => undefined); + + const error = await clientFor(harness.baseUrl, undefined, 80) + .open(SCOPE, () => undefined) + .catch((caught: unknown) => caught); + + expect(error).toBeInstanceOf(LaunchNetworkError); + expect((error as LaunchNetworkError).retryable).toBe(true); + }); + + it('T79: reports a connection the server drops mid-stream as a retryable error', async () => { + harness = await serve((_req, res) => { + stream(res); + res.write('data: first\n\n'); + setTimeout(() => res.socket?.destroy(), 20); + }); + + const error = await clientFor(harness.baseUrl).open(SCOPE, () => undefined).catch((caught: unknown) => caught); + + expect(error).toBeInstanceOf(LaunchNetworkError); + expect((error as LaunchNetworkError).retryable).toBe(true); + }); + + it('T79: reports a refused connection as a retryable error', async () => { + harness = await serve(() => undefined); + const { baseUrl } = harness; + await harness.stop(); + + const error = await clientFor(baseUrl).open(SCOPE, () => undefined).catch((caught: unknown) => caught); + + expect(error).toBeInstanceOf(LaunchNetworkError); + expect((error as LaunchNetworkError).retryable).toBe(true); + }); + + it('T79: rejects with the error a frame handler throws and closes the socket', async () => { + harness = await serve((_req, res) => { + stream(res); + res.write('data: one\n\n'); + }); + const boom = new Error('handler failed'); + + const error = await clientFor(harness.baseUrl) + .open(SCOPE, () => { + throw boom; + }) + .catch((caught: unknown) => caught); + + await eventually(() => harness.closed() === 1); + expect(error).toBe(boom); + expect(harness.closed()).toBe(1); + }); + + it.each([ + [404, 'launch.DEPLOYMENT.NOT_FOUND'], + [300, 'launch.UNKNOWN'], + ])('T80: answers an open with status %i as a parsed error after exactly one request', async (status, code) => { + harness = await serve((_req, res) => { + res.writeHead(status, { 'content-type': 'application/json' }); + res.end( + status === 404 + ? JSON.stringify({ errors: [{ code: 'launch.DEPLOYMENT.NOT_FOUND', message: 'gone' }] }) + : 'not json', + ); + }); + + const error = await collect(clientFor(harness.baseUrl)).catch((caught: unknown) => caught); + + expect(error).toBeInstanceOf(LaunchApiError); + expect((error as LaunchApiError).status).toBe(status); + expect((error as LaunchApiError).code).toBe(code); + expect(harness.seen).toHaveLength(1); + }); + + it('T80: words a refusal from the messages it was given', async () => { + harness = await serve((_req, res) => { + res.writeHead(404, { 'content-type': 'application/json' }); + res.end(JSON.stringify({ errors: [{ code: 'launch.X', message: 'raw' }] })); + }); + + const error = await clientFor(harness.baseUrl) + .open(SCOPE, () => undefined, undefined, { 'launch.X': 'CLI words' }) + .catch((caught: unknown) => caught); + + expect((error as LaunchApiError).message).toBe('CLI words'); + }); + + it('T80: treats 299 as an open stream and 200 as one too', async () => { + harness = await serve((_req, res, index) => { + stream(res, index === 0 ? 299 : 200); + res.end(`data: from-${index}\n\n`); + }); + const client = clientFor(harness.baseUrl); + + const first = await collect(client); + const second = await collect(client); + + expect(first).toEqual([{ event: undefined, data: 'from-0' }]); + expect(second).toEqual([{ event: undefined, data: 'from-1' }]); + }); + + it('T80: reads no more than the cap of a refusal body, so an oversized one falls back to the status wording', async () => { + harness = await serve((_req, res) => { + res.writeHead(502); + res.end(JSON.stringify({ errors: [{ code: 'launch.BIG', message: 'x'.repeat(100_000) }] })); + }); + + const error = await collect(clientFor(harness.baseUrl)).catch((caught: unknown) => caught); + + expect((error as LaunchApiError).status).toBe(502); + expect((error as LaunchApiError).code).toBe('launch.UNKNOWN'); + }); + + it('T81: refreshes once on a 401 and retries with the new token', async () => { + const stale = randomUUID(); + const fresh = randomUUID(); + let token = stale; + const refresh = jest.fn(async () => { + token = fresh; + }); + harness = await serve((_req, res, index) => { + if (index === 0) { + res.writeHead(401).end(); + return; + } + stream(res); + res.end('data: ok\n\n'); + }); + + const frames = await collect(clientFor(harness.baseUrl, { headers: async () => ({ authtoken: token }), refresh })); + + expect(frames).toEqual([{ event: undefined, data: 'ok' }]); + expect(refresh).toHaveBeenCalledTimes(1); + expect(harness.seen.map((request) => request.headers.authtoken)).toEqual([stale, fresh]); + }); + + it('T81: parses the error after exactly two requests when the 401 repeats', async () => { + const refresh = jest.fn(async () => undefined); + harness = await serve((_req, res) => { + res.writeHead(401, { 'content-type': 'application/json' }); + res.end(JSON.stringify({ errors: [{ code: 'launch.AUTH.EXPIRED', message: 'expired' }] })); + }); + + const error = await collect(clientFor(harness.baseUrl, { refresh })).catch((caught: unknown) => caught); + + expect(error).toBeInstanceOf(LaunchApiError); + expect((error as LaunchApiError).status).toBe(401); + expect((error as LaunchApiError).code).toBe('launch.AUTH.EXPIRED'); + expect(harness.seen).toHaveLength(2); + expect(refresh).toHaveBeenCalledTimes(1); + }); + + it.each([400, 403, 404])('T81: never refreshes the session for a %i', async (status) => { + const refresh = jest.fn(async () => undefined); + harness = await serve((_req, res) => { + res.writeHead(status).end(); + }); + + const error = await collect(clientFor(harness.baseUrl, { refresh })).catch((caught: unknown) => caught); + + expect((error as LaunchApiError).status).toBe(status); + expect(refresh).not.toHaveBeenCalled(); + expect(harness.seen).toHaveLength(1); + }); + + it('T81: parses a 401 at once when the session cannot be refreshed', async () => { + harness = await serve((_req, res) => { + res.writeHead(401).end(); + }); + + const error = await collect(clientFor(harness.baseUrl, { refresh: undefined })).catch((caught: unknown) => caught); + + expect((error as LaunchApiError).status).toBe(401); + expect(harness.seen).toHaveLength(1); + }); + + it('T81: lets the failure of a refresh through and sends nothing more', async () => { + harness = await serve((_req, res) => { + res.writeHead(401).end(); + }); + + const error = await collect( + clientFor(harness.baseUrl, { + refresh: async () => { + throw new SessionExpiredError(); + }, + }), + ).catch((caught: unknown) => caught); + + expect(error).toBeInstanceOf(SessionExpiredError); + expect(harness.seen).toHaveLength(1); + }); + + it('T81: lets the failure of the auth headers through and opens no connection', async () => { + harness = await serve(() => undefined); + const broken = new Error('no credentials'); + + const error = await collect( + clientFor(harness.baseUrl, { + headers: async () => { + throw broken; + }, + }), + ).catch((caught: unknown) => caught); + + expect(error).toBe(broken); + expect(harness.seen).toEqual([]); + }); + + it('T82: tunnels the stream through the proxy with a CONNECT to the target', async () => { + const connects: string[] = []; + const proxy = createServer(); + proxy.on('connect', (req, client) => { + connects.push(req.url as string); + const [host, port] = (req.url as string).split(':'); + const upstream = connect(Number(port), host, () => { + client.write('HTTP/1.1 200 Connection Established\r\n\r\n'); + upstream.pipe(client); + client.pipe(upstream); + }); + }); + await new Promise((resolve) => proxy.listen(0, '127.0.0.1', resolve)); + harness = await serve((_req, res) => { + stream(res); + res.end('data: via-proxy\n\n'); + }); + process.env.HTTPS_PROXY = `http://127.0.0.1:${(proxy.address() as AddressInfo).port}`; + + try { + const frames = await collect(clientFor(harness.baseUrl)); + + expect(frames).toEqual([{ event: undefined, data: 'via-proxy' }]); + expect(connects).toEqual([new URL(harness.baseUrl).host]); + } finally { + proxy.closeAllConnections(); + await new Promise((resolve) => proxy.close(() => resolve())); + } + }); + + it('T82: names the proxy and never its credentials when the proxy cannot be reached, without a retry hint', async () => { + const user = `u${randomBytes(4).toString('hex')}`; + const phrase = randomBytes(12).toString('hex'); + const closed = createServer(); + await new Promise((resolve) => closed.listen(0, '127.0.0.1', resolve)); + const port = (closed.address() as AddressInfo).port; + await new Promise((resolve) => closed.close(() => resolve())); + process.env.HTTPS_PROXY = `http://${user}:${phrase}@127.0.0.1:${port}`; + harness = await serve(() => undefined); + + const error = await collect(clientFor(harness.baseUrl)).catch((caught: unknown) => caught); + + expect(error).toBeInstanceOf(LaunchNetworkError); + expect((error as LaunchNetworkError).message).toBe( + `Proxy error: Unable to connect to proxy server at http://127.0.0.1:${port}. Please verify your proxy configuration.`, + ); + expect((error as LaunchNetworkError).message).not.toContain(phrase); + expect((error as LaunchNetworkError).message).not.toContain(user); + expect((error as LaunchNetworkError).retryable).toBe(false); + }); + + it('T83: aborting mid-stream rejects with the reason, destroys the socket and leaves no listener or timer', async () => { + const timers = trackTimers(EVENT_STREAM_IDLE_TIMEOUT_MS); + const stop = new AbortController(); + const reason = new Error('interrupted'); + harness = await serve((_req, res) => { + stream(res); + res.write('data: first\n\n'); + }); + + const outcome = collect(clientFor(harness.baseUrl), stop.signal).catch((caught: unknown) => caught); + await eventually(() => harness.seen.length === 1); + setTimeout(() => stop.abort(reason), 30); + const error = await outcome; + + await eventually(() => harness.closed() === 1); + expect(error).toBe(reason); + expect(harness.closed()).toBe(1); + expect(getEventListeners(stop.signal, 'abort')).toHaveLength(0); + expect(timers.created()).toBeGreaterThan(0); + expect(timers.pending()).toBe(0); + }); + + it('T83: aborting before the server answers destroys the request', async () => { + const stop = new AbortController(); + harness = await serve(() => undefined); + + const outcome = collect(clientFor(harness.baseUrl), stop.signal).catch((caught: unknown) => caught); + await eventually(() => harness.seen.length === 1); + stop.abort(new Error('early')); + + expect(((await outcome) as Error).message).toBe('early'); + await eventually(() => harness.closed() === 1); + expect(harness.closed()).toBe(1); + }); + + it('T83: an already aborted signal rejects at once and sends no request', async () => { + const stop = new AbortController(); + const reason = new Error('before start'); + stop.abort(reason); + harness = await serve(() => undefined); + + const error = await collect(clientFor(harness.baseUrl), stop.signal).catch((caught: unknown) => caught); + + expect(error).toBe(reason); + expect(harness.seen).toEqual([]); + }); + + it('T83: a stream that ends normally removes its abort listener', async () => { + const stop = new AbortController(); + harness = await serve((_req, res) => { + stream(res); + res.end('data: x\n\n'); + }); + + await collect(clientFor(harness.baseUrl), stop.signal); + + expect(getEventListeners(stop.signal, 'abort')).toHaveLength(0); + }); +}); diff --git a/test/integration/logs-get.test.ts b/test/integration/logs-get.test.ts new file mode 100644 index 00000000..f99f6934 --- /dev/null +++ b/test/integration/logs-get.test.ts @@ -0,0 +1,1189 @@ +import { tmpdir } from 'node:os'; +import { Readable } from 'node:stream'; + +import { authHandler, cliux, configHandler } from '@contentstack/cli-utilities'; +import type { Interfaces } from '@oclif/core'; +import { runCommand } from '@oclif/test'; +import nock from 'nock'; + +import * as watcher from '../../src/deployments/deployment.watcher'; +import { EVENT_STREAM_IDLE_TIMEOUT_MS } from '../../src/transport/event-stream'; +import listFixture from '../fixtures/deployments-list.json'; +import notFoundFixture from '../fixtures/deployment-not-found.json'; +import { answerPrompts, stdinReportingTTY, stdoutReportingTTY } from '../support/terminal'; +import { loadCliConfig, routeConsoleLogToStdout } from '../support/oclif'; +import { projectOwnership } from '../support/project-ownership'; +import { trackTimers } from '../support/timers'; + +const realWatchTiming = watcher.defaultWatchTiming; + +const LAUNCH_HUB_URL = 'https://launch-api.integration.test'; +const ORG_UID = 'blt4d9e2a7c1f6b3085'; +const PROJECT_UID = 'a1b2c3d4e5f60718293a4b5c'; +const ENV_UID = 'e1f2a3b4c5d6e7f8091a2b3c'; +const DEPLOYMENT_UID = 'd1e2f3a4b5c6d7e8f9012345'; +const DATA_DIR = tmpdir(); +const NOW = Date.parse('2026-10-28T12:00:00.000Z'); +const ESCAPE = '\u001b'; + +const CONFIG: Record = { + authorisationType: 'BASIC', + authtoken: 'test-authtoken', + email: 'cli-user@example.test', + region: { + name: 'integration', + cma: 'https://cma.integration.test', + cda: 'https://cda.integration.test', + uiHost: 'https://app.integration.test', + launchHubUrl: LAUNCH_HUB_URL, + }, +}; + +const DEPLOYMENTS = `/manage/projects/${PROJECT_UID}/environments/${ENV_UID}/deployments`; +const DEPLOYMENT_PATH = `${DEPLOYMENTS}/${DEPLOYMENT_UID}`; +const BUILD_LOGS = `/logs/projects/${PROJECT_UID}/environments/${ENV_UID}/deployments/${DEPLOYMENT_UID}/logs/deployment-logs`; +const LIVE_LOGS = `/logs/projects/${PROJECT_UID}/environments/${ENV_UID}/deployments/${DEPLOYMENT_UID}/logs/live`; +const SERVER_LOGS = `/logs/projects/${PROJECT_UID}/environments/${ENV_UID}/deployments/${DEPLOYMENT_UID}/logs/server-logs`; + +const LINE_ONE = { message: 'Installing dependencies...', timestamp: '2026-10-28T10:00:00.000Z', stage: 'INSTALL' }; +const LINE_TWO = { message: 'Build complete', timestamp: '2026-10-28T10:00:05.000Z', stage: 'BUILD' }; +const LINE_THREE = { message: 'Deploying', timestamp: '2026-10-28T10:00:09.000Z', stage: 'DEPLOY' }; + +let config: Interfaces.Config; +let onWire: string[]; + +function recordWire(): void { + onWire = []; + nock.emitter.on('no match', (request: { method?: string; path?: string }) => { + onWire.push(`${request.method ?? 'UNKNOWN'} ${request.path ?? ''}`); + }); +} + +function hub(): nock.Scope { + return nock(LAUNCH_HUB_URL) + .matchHeader('x-organization-uid', ORG_UID) + .matchHeader('x-project-uid', PROJECT_UID) + .matchHeader('x-cs-api-version', '1.0'); +} + +function ownedProject(): nock.Scope { + return projectOwnership(LAUNCH_HUB_URL, ORG_UID, PROJECT_UID); +} + +function getArgs(...extra: string[]): string[] { + return [ + 'launch:logs:get', + '--org', + ORG_UID, + '--project', + PROJECT_UID, + '--env', + ENV_UID, + ...extra, + '--data-dir', + DATA_DIR, + ]; +} + +function deploymentGet(status: string, extra: Record = {}): nock.Scope { + return hub() + .get(DEPLOYMENT_PATH) + .reply(200, { deployment: { uid: DEPLOYMENT_UID, deploymentNumber: 4, status, ...extra } }); +} + +function buildLogs(lines: unknown[]): nock.Scope { + return hub().get(BUILD_LOGS).query(true).reply(200, { deploymentLogs: lines }); +} + +function serverLogs(window: { startTime: number; endTime: number }, entries: unknown[]): nock.Scope { + return hub() + .get(SERVER_LOGS) + .query({ startTime: String(window.startTime), endTime: String(window.endTime) }) + .reply(200, { serverLogs: entries }); +} + +const SESSION_FRAME = 'event: session\ndata: {"expiresAt":"2026-10-28T12:05:00.000Z"}\n\n'; +const SESSION_ENDED_FRAME = 'event: session-ended\ndata: {"reason":"timeout"}\n\n'; +const SESSION_ENDED_LINE = 'The live session ended (server limit). Run the command again to keep following.'; + +function logFrame(message: string, timestamp = '2026-10-28T12:00:01.000Z'): string { + return `data: ${JSON.stringify({ timestamp, message, source: 'edge-function' })}\n\n`; +} + +function liveRoute(): nock.Interceptor { + return hub().matchHeader('accept', 'text/event-stream').matchHeader('authtoken', 'test-authtoken').get(LIVE_LOGS); +} + +function liveStream(body: string): nock.Scope { + return liveRoute().reply(200, body, { 'content-type': 'text/event-stream' }); +} + +function outputLines(stdout: string): string[] { + return stdout.split('\n').filter((line) => line !== ''); +} + +function timeouts(): number { + return process.getActiveResourcesInfo().filter((name) => name === 'Timeout').length; +} + +describe('integration: launch:logs:get on the wire', () => { + beforeAll(async () => { + config = await loadCliConfig(); + nock.disableNetConnect(); + }); + + beforeEach(() => { + process.exitCode = 0; + recordWire(); + routeConsoleLogToStdout(); + jest.spyOn(configHandler, 'get').mockImplementation((key: string) => CONFIG[key]); + jest.spyOn(authHandler, 'compareOAuthExpiry').mockResolvedValue(undefined); + jest.spyOn(watcher, 'defaultWatchTiming').mockImplementation(() => ({ + ...realWatchTiming(), + sleep: async () => undefined, + })); + }); + + afterEach(() => { + process.exitCode = 0; + nock.emitter.removeAllListeners('no match'); + nock.cleanAll(); + }); + + afterAll(() => { + nock.enableNetConnect(); + nock.restore(); + }); + + it('T40: prints the build lines then the status line of a finished LIVE deployment on a pipe, exit 0', async () => { + ownedProject(); + const verify = deploymentGet('LIVE'); + const poll = deploymentGet('LIVE'); + const first = buildLogs([LINE_ONE, LINE_TWO]); + const drain = buildLogs([]); + + const { error, stdout } = await runCommand(getArgs('--deployment', DEPLOYMENT_UID), config); + + expect(error).toBeUndefined(); + expect(outputLines(stdout)).toEqual([ + '2026-10-28 10:00:00.000: Installing dependencies...', + '2026-10-28 10:00:05.000: Build complete', + 'Deployment #4 is LIVE.', + ]); + expect(stdout).not.toContain(ESCAPE); + expect([verify, poll, first, drain].every((scope) => scope.isDone())).toBe(true); + expect(nock.pendingMocks()).toEqual([]); + expect(onWire).toEqual([]); + }); + + it('T41: follows the latest deployment when --deployment is absent, with limit=1 and no prompt', async () => { + ownedProject(); + const answered = answerPrompts({}); + const restoreStdin = stdinReportingTTY(true); + const latest = hub() + .get(DEPLOYMENTS) + .query({ limit: '1', skip: '0' }) + .reply(200, { ...listFixture, deployments: [{ uid: DEPLOYMENT_UID, deploymentNumber: 4, status: 'LIVE' }] }); + const other = hub().get(DEPLOYMENTS).query({ limit: '100', skip: '0' }).reply(200, listFixture); + deploymentGet('LIVE'); + buildLogs([LINE_ONE]); + buildLogs([]); + + try { + const { error, stdout } = await runCommand(getArgs(), config); + + expect(error).toBeUndefined(); + expect(latest.isDone()).toBe(true); + expect(other.isDone()).toBe(false); + expect(outputLines(stdout)).toEqual(['2026-10-28 10:00:00.000: Installing dependencies...', 'Deployment #4 is LIVE.']); + expect(answered.messages).toEqual([]); + expect(cliux.inquire).not.toHaveBeenCalled(); + expect(onWire).toEqual([]); + } finally { + restoreStdin(); + } + }); + + it('T41: exits 2 when the environment has no deployment, for either type, and reads no logs', async () => { + for (const type of ['deployment', 'server']) { + ownedProject(); + hub().get(DEPLOYMENTS).query({ limit: '1', skip: '0' }).reply(200, { ...listFixture, deployments: [] }); + const logs = hub().get(BUILD_LOGS).query(true).reply(200, { deploymentLogs: [] }); + + const { error } = await runCommand(getArgs('--type', type), config); + + expect(error?.oclif?.exit).toBe(2); + expect(error?.message).toBe('No deployments found in this environment.'); + expect(logs.isDone()).toBe(false); + nock.cleanAll(); + } + + expect(onWire).toEqual([]); + }); + + it.each(['FAILED', 'CANCELLED'])('T42: prints the lines and the status line of a %s deployment, exit 0, no failure hint', async (status) => { + ownedProject(); + deploymentGet(status); + deploymentGet(status); + buildLogs([LINE_ONE]); + buildLogs([]); + + const { error, stdout, stderr } = await runCommand(getArgs('--deployment', DEPLOYMENT_UID), config); + + expect(error).toBeUndefined(); + expect(outputLines(stdout)).toEqual(['2026-10-28 10:00:00.000: Installing dependencies...', `Deployment #4 is ${status}.`]); + expect(stdout).not.toContain('did not succeed'); + expect(stdout).not.toContain('csdx launch:'); + expect(stderr).toBe(''); + expect(onWire).toEqual([]); + }); + + it('T43: prints each line of an in-flight deployment once, in order, with no escape codes on a pipe', async () => { + ownedProject(); + deploymentGet('QUEUED'); + deploymentGet('QUEUED'); + buildLogs([]); + deploymentGet('DEPLOYING'); + buildLogs([LINE_ONE, LINE_TWO]); + deploymentGet('LIVE'); + buildLogs([LINE_THREE]); + buildLogs([]); + + const { error, stdout } = await runCommand(getArgs('--deployment', DEPLOYMENT_UID), config); + + expect(error).toBeUndefined(); + expect(outputLines(stdout)).toEqual([ + '2026-10-28 10:00:00.000: Installing dependencies...', + '2026-10-28 10:00:05.000: Build complete', + '2026-10-28 10:00:09.000: Deploying', + 'Deployment #4 is LIVE.', + ]); + expect(stdout).not.toContain(ESCAPE); + expect(nock.pendingMocks()).toEqual([]); + expect(onWire).toEqual([]); + }); + + it('T44: prints the yellow no-logs line then the status line on a terminal', async () => { + const restoreStdout = stdoutReportingTTY(true); + + try { + ownedProject(); + deploymentGet('LIVE'); + deploymentGet('LIVE'); + buildLogs([]); + + const { error, stdout } = await runCommand(getArgs('--deployment', DEPLOYMENT_UID), config, { stripAnsi: false }); + + expect(error).toBeUndefined(); + expect(outputLines(stdout)).toEqual([ + `${ESCAPE}[33mNo deployment logs found for deployment ${DEPLOYMENT_UID}.${ESCAPE}[39m`, + 'Deployment #4 is LIVE.', + ]); + } finally { + restoreStdout(); + } + }); + + it('T44: prints the no-logs line plain on a pipe', async () => { + ownedProject(); + deploymentGet('LIVE'); + deploymentGet('LIVE'); + buildLogs([]); + + const { error, stdout } = await runCommand(getArgs('--deployment', DEPLOYMENT_UID), config); + + expect(error).toBeUndefined(); + expect(outputLines(stdout)).toEqual([ + `No deployment logs found for deployment ${DEPLOYMENT_UID}.`, + 'Deployment #4 is LIVE.', + ]); + }); + + it.each([ + [{ deploymentNumber: 7 }, 'Deployment #7 is LIVE.'], + [{ deploymentNumber: 0 }, 'Deployment #0 is LIVE.'], + [{ deploymentNumber: null }, 'Deployment is LIVE.'], + [{ deploymentNumber: undefined }, 'Deployment is LIVE.'], + ])('T45: words the status line for %j', async (extra, line) => { + ownedProject(); + deploymentGet('LIVE', extra); + deploymentGet('LIVE', extra); + buildLogs([LINE_ONE]); + buildLogs([]); + + const { error, stdout } = await runCommand(getArgs('--deployment', DEPLOYMENT_UID), config); + + expect(error).toBeUndefined(); + expect(outputLines(stdout).at(-1)).toBe(line); + }); + + it('T46: exits 1 with the timed-out message when the deployment stays DEPLOYING past 20 minutes', async () => { + let clock = NOW; + jest.spyOn(watcher, 'defaultWatchTiming').mockImplementation(() => ({ + ...realWatchTiming(), + now: () => clock, + sleep: async (ms: number) => { + clock += ms; + }, + })); + ownedProject(); + hub().get(DEPLOYMENT_PATH).times(500).reply(200, { deployment: { uid: DEPLOYMENT_UID, status: 'DEPLOYING' } }); + hub().get(BUILD_LOGS).query(true).times(500).reply(200, { deploymentLogs: [] }); + + const { error, stdout } = await runCommand(getArgs('--deployment', DEPLOYMENT_UID), config); + + expect(error?.oclif?.exit).toBe(1); + expect(error?.message).toBe( + 'Stopped waiting after 20 minutes; the deployment was still DEPLOYING. ' + + `Run csdx launch:logs:get --org ${ORG_UID} --project ${PROJECT_UID} --env ${ENV_UID} ` + + `--deployment ${DEPLOYMENT_UID} again to keep following it.`, + ); + expect(clock - NOW).toBeGreaterThan(0); + expect(clock - NOW).toBeLessThanOrEqual(20 * 60 * 1000); + expect(stdout).not.toContain('is DEPLOYING'); + expect(onWire).toEqual([]); + }); + + it('T47: stops on Ctrl-C with the yellow line and exit 3, no Error line, no extra poll, nothing left behind', async () => { + jest.spyOn(watcher, 'defaultWatchTiming').mockImplementation(() => realWatchTiming()); + const restoreStdout = stdoutReportingTTY(true); + jest.spyOn(cliux, 'loaderV2').mockReturnValue(undefined as never); + const listenersBefore = process.listenerCount('SIGINT'); + const timersBefore = timeouts(); + let statusReads = 0; + let logReads = 0; + + try { + ownedProject(); + hub() + .get(DEPLOYMENT_PATH) + .times(5) + .reply(200, () => { + statusReads += 1; + return { deployment: { uid: DEPLOYMENT_UID, deploymentNumber: 4, status: 'DEPLOYING' } }; + }); + hub() + .get(BUILD_LOGS) + .query(true) + .times(5) + .reply(200, () => { + logReads += 1; + setImmediate(() => process.emit('SIGINT')); + return { deploymentLogs: [LINE_ONE] }; + }); + + const { error, stdout, stderr } = await runCommand(getArgs('--deployment', DEPLOYMENT_UID), config, { + stripAnsi: false, + }); + + expect(error?.oclif?.exit).toBe(3); + expect(stdout).toContain(`${ESCAPE}[33mStopped following the logs.${ESCAPE}[39m`); + expect(stderr).not.toContain('error'); + expect(error?.message).not.toContain('Error'); + expect(statusReads).toBe(2); + expect(logReads).toBe(1); + expect(process.listenerCount('SIGINT')).toBe(listenersBefore); + expect(timeouts()).toBe(timersBefore); + } finally { + restoreStdout(); + } + }); + + it('T47: prints the interrupt line plain on a pipe', async () => { + jest.spyOn(watcher, 'defaultWatchTiming').mockImplementation(() => realWatchTiming()); + ownedProject(); + hub().get(DEPLOYMENT_PATH).times(5).reply(200, { deployment: { uid: DEPLOYMENT_UID, status: 'DEPLOYING' } }); + hub() + .get(BUILD_LOGS) + .query(true) + .times(5) + .reply(200, () => { + setImmediate(() => process.emit('SIGINT')); + return { deploymentLogs: [] }; + }); + + const { error, stdout } = await runCommand(getArgs('--deployment', DEPLOYMENT_UID), config); + + expect(error?.oclif?.exit).toBe(3); + expect(outputLines(stdout)).toEqual(['Stopped following the logs.']); + }); + + it('T48: prints no read-failure notice, only the empty-logs line and the status line, when the log read fails', async () => { + ownedProject(); + deploymentGet('LIVE'); + deploymentGet('LIVE'); + hub() + .get(BUILD_LOGS) + .query(true) + .reply(500, { errors: [{ code: 'launch.UNKNOWN', message: 'logs are down' }] }); + + const { error, stdout } = await runCommand(getArgs('--deployment', DEPLOYMENT_UID), config); + + expect(error).toBeUndefined(); + expect(stdout).not.toContain('Could not read the deployment logs'); + expect(stdout).not.toContain('logs are down'); + expect(outputLines(stdout)).toEqual([`No deployment logs found for deployment ${DEPLOYMENT_UID}.`, 'Deployment #4 is LIVE.']); + expect(onWire).toEqual([]); + }); + + it('T49: exits 2 with the generic not-found wording and requests no logs for a deployment that is not here', async () => { + ownedProject(); + hub().get(DEPLOYMENT_PATH).reply(404, notFoundFixture); + const logs = hub().get(BUILD_LOGS).query(true).reply(200, { deploymentLogs: [] }); + + const { error, stdout } = await runCommand(getArgs('--deployment', DEPLOYMENT_UID), config); + + expect(error?.oclif?.exit).toBe(2); + expect(error?.message).toBe(`No deployment with UID "${DEPLOYMENT_UID}" found in this environment.`); + expect(error?.message).not.toContain(ENV_UID); + expect(stdout).toBe(''); + expect(logs.isDone()).toBe(false); + expect(onWire).toEqual([]); + }); + + it('T49: exits 2 for the same foreign deployment with --type server and reads no server logs', async () => { + ownedProject(); + hub().get(DEPLOYMENT_PATH).reply(404, notFoundFixture); + const logs = hub().get(SERVER_LOGS).query(true).reply(200, { serverLogs: [] }); + + const { error } = await runCommand(getArgs('--deployment', DEPLOYMENT_UID, '--type', 'server'), config); + + expect(error?.oclif?.exit).toBe(2); + expect(error?.message).toBe(`No deployment with UID "${DEPLOYMENT_UID}" found in this environment.`); + expect(logs.isDone()).toBe(false); + }); + + it('T49: exits 2 with the generic not-found wording when the deployment comes back as null and reads no logs', async () => { + ownedProject(); + hub().get(DEPLOYMENT_PATH).reply(200, { deployment: null }); + const logs = hub().get(BUILD_LOGS).query(true).reply(200, { deploymentLogs: [] }); + + const { error } = await runCommand(getArgs('--deployment', DEPLOYMENT_UID), config); + + expect(error?.oclif?.exit).toBe(2); + expect(error?.message).toBe(`No deployment with UID "${DEPLOYMENT_UID}" found in this environment.`); + expect(logs.isDone()).toBe(false); + }); + + it.each([ + [true, true], + [false, false], + ])('T50: exits 1 on a status GET 500, red on stdout TTY=%s', async (tty) => { + const restoreStdout = stdoutReportingTTY(tty); + + try { + ownedProject(); + hub() + .get(DEPLOYMENT_PATH) + .reply(500, { errors: [{ code: 'launch.UNKNOWN', message: 'boom' }] }); + const logs = hub().get(BUILD_LOGS).query(true).reply(200, { deploymentLogs: [] }); + + const { error, stderr } = await runCommand(getArgs('--deployment', DEPLOYMENT_UID), config, { stripAnsi: false }); + + expect(error?.oclif?.exit).toBe(1); + expect(stderr).toContain('error: boom'); + expect(stderr.includes(`${ESCAPE}[31m`)).toBe(tty); + expect(logs.isDone()).toBe(false); + } finally { + restoreStdout(); + } + }); + + it('T51: reads the window from the server-logs route with exact milliseconds and prints plain lines', async () => { + const startTime = Date.parse('2026-10-28T09:00:00Z'); + const endTime = Date.parse('2026-10-28T15:30:00+05:30'); + jest.spyOn(Date, 'now').mockReturnValue(NOW); + ownedProject(); + deploymentGet('LIVE'); + const read = hub() + .get(SERVER_LOGS) + .query({ startTime: String(startTime), endTime: String(endTime) }) + .reply(200, { + serverLogs: [ + { timestamp: '2026-10-28T09:15:00.123Z', message: 'GET /index 200', source: 'edge-fn-source' }, + { timestamp: '2026-10-28T09:16:00.000Z', message: `${ESCAPE}[31mboom${ESCAPE}[0m`, source: 'edge-fn-source' }, + ], + }); + + const { error, stdout } = await runCommand( + getArgs('--deployment', DEPLOYMENT_UID, '--type', 'server', '--since', '2026-10-28T09:00:00Z', '--until', '2026-10-28T15:30:00+05:30'), + config, + ); + + expect(error).toBeUndefined(); + expect(read.isDone()).toBe(true); + expect(outputLines(stdout)).toEqual(['2026-10-28 09:15:00.123: GET /index 200', '2026-10-28 09:16:00.000: boom']); + expect(stdout).not.toContain('edge-fn-source'); + expect(stdout).not.toContain(ESCAPE); + expect(onWire).toEqual([]); + }); + + it('T52: defaults the window to the last hour on the wire', async () => { + jest.spyOn(Date, 'now').mockReturnValue(NOW); + ownedProject(); + deploymentGet('LIVE'); + const read = serverLogs({ startTime: NOW - 3_600_000, endTime: NOW }, [{ timestamp: '2026-10-28T11:30:00.000Z', message: 'hi' }]); + + const { error, stdout } = await runCommand(getArgs('--deployment', DEPLOYMENT_UID, '--type', 'server'), config); + + expect(error).toBeUndefined(); + expect(read.isDone()).toBe(true); + expect(outputLines(stdout)).toEqual(['2026-10-28 11:30:00.000: hi']); + expect(onWire).toEqual([]); + }); + + it('T53: prints the yellow no-server-logs line for the resolved window and exits 0', async () => { + jest.spyOn(Date, 'now').mockReturnValue(NOW); + const restoreStdout = stdoutReportingTTY(true); + + try { + ownedProject(); + deploymentGet('LIVE'); + serverLogs({ startTime: NOW - 3_600_000, endTime: NOW }, []); + + const { error, stdout } = await runCommand(getArgs('--deployment', DEPLOYMENT_UID, '--type', 'server'), config, { + stripAnsi: false, + }); + + expect(error).toBeUndefined(); + expect(outputLines(stdout)).toEqual([ + `${ESCAPE}[33mNo server logs found between 2026-10-28T11:00:00.000Z and 2026-10-28T12:00:00.000Z.${ESCAPE}[39m`, + ]); + } finally { + restoreStdout(); + } + }); + + it('T53: prints the no-server-logs line plain on a pipe', async () => { + jest.spyOn(Date, 'now').mockReturnValue(NOW); + ownedProject(); + deploymentGet('LIVE'); + serverLogs({ startTime: NOW - 3_600_000, endTime: NOW }, []); + + const { stdout } = await runCommand(getArgs('--deployment', DEPLOYMENT_UID, '--type', 'server'), config); + + expect(outputLines(stdout)).toEqual([ + 'No server logs found between 2026-10-28T11:00:00.000Z and 2026-10-28T12:00:00.000Z.', + ]); + }); + + it.each([ + [5000, true], + [4999, false], + ])('T54: with %i server lines the cap notice shows is %s', async (count, shows) => { + jest.spyOn(Date, 'now').mockReturnValue(NOW); + ownedProject(); + deploymentGet('LIVE'); + serverLogs( + { startTime: NOW - 3_600_000, endTime: NOW }, + Array.from({ length: count }, (_, index) => ({ timestamp: '2026-10-28T11:30:00.000Z', message: `line ${index}` })), + ); + + const { error, stdout } = await runCommand(getArgs('--deployment', DEPLOYMENT_UID, '--type', 'server'), config); + const lines = outputLines(stdout); + + expect(error).toBeUndefined(); + expect(lines).toHaveLength(shows ? count + 1 : count); + expect(lines.at(-1)).toBe( + shows + ? 'Showing the newest 5000 server log lines in this window. Narrow --since/--until to see earlier ones.' + : `2026-10-28 11:30:00.000: line ${count - 1}`, + ); + }); + + it('T55: prints the 24 hour notice first for --since 2d and sends the user own start time', async () => { + jest.spyOn(Date, 'now').mockReturnValue(NOW); + ownedProject(); + deploymentGet('LIVE'); + serverLogs({ startTime: NOW - 172_800_000, endTime: NOW }, [{ timestamp: '2026-10-27T13:00:00.000Z', message: 'old' }]); + + const { error, stdout } = await runCommand(getArgs('--deployment', DEPLOYMENT_UID, '--type', 'server', '--since', '2d'), config); + + expect(error).toBeUndefined(); + expect(outputLines(stdout)).toEqual([ + 'Server logs are kept for 24 hours; showing from 2026-10-27T12:00:00.000Z.', + '2026-10-27 13:00:00.000: old', + ]); + }); + + it('T55: prints no notice for --since 24h', async () => { + jest.spyOn(Date, 'now').mockReturnValue(NOW); + ownedProject(); + deploymentGet('LIVE'); + serverLogs({ startTime: NOW - 86_400_000, endTime: NOW }, [{ timestamp: '2026-10-27T13:00:00.000Z', message: 'old' }]); + + const { error, stdout } = await runCommand(getArgs('--deployment', DEPLOYMENT_UID, '--type', 'server', '--since', '24h'), config); + + expect(error).toBeUndefined(); + expect(outputLines(stdout)).toEqual(['2026-10-27 13:00:00.000: old']); + }); + + it('T56: exits 1 when the server-logs body has no serverLogs array', async () => { + ownedProject(); + deploymentGet('LIVE'); + hub().get(SERVER_LOGS).query(true).reply(200, { logs: [] }); + + const { error } = await runCommand(getArgs('--deployment', DEPLOYMENT_UID, '--type', 'server'), config); + + expect(error?.oclif?.exit).toBe(1); + expect(error?.message).toBe('The Launch API returned a server log page without a serverLogs array.'); + }); + + it.each([ + [400, 'launch.SERVERLOGS.NOT_INTEGER', 'The Launch API could not read the time window of the server logs.'], + [ + 408, + 'launch.LOGS.QUERY_TIMEOUT', + 'The server logs query took too long. Narrow the window with --since and --until and try again.', + ], + [ + 408, + 'launch.LOGS.REQUEST_TIMEOUT', + 'The Launch API took too long to answer. Try again, or narrow the window with --since and --until.', + ], + [404, 'launch.PROJECT.NOT_FOUND', 'No project found with that UID.'], + [404, 'launch.DEPLOYMENT.NOT_FOUND', 'No deployment found with that UID.'], + [400, 'launch.DEPLOYMENT.PROJECT_MISMATCH', 'That deployment does not belong to this project.'], + [400, 'launch.DEPLOYMENT.ENVIRONMENT_MISMATCH', 'That deployment does not belong to this environment.'], + ])('T57: words a %i %s answer from the server logs in the CLI own words, exit 1', async (status, code, wording) => { + ownedProject(); + deploymentGet('LIVE'); + hub() + .get(SERVER_LOGS) + .query(true) + .times(4) + .reply(status, { errors: [{ code, message: 'raw server text' }], status }); + + const { error } = await runCommand(getArgs('--deployment', DEPLOYMENT_UID, '--type', 'server'), config); + + expect(error?.oclif?.exit).toBe(1); + expect(error?.message).toBe(wording); + expect(error?.message).not.toContain('raw server text'); + expect(onWire).toEqual([]); + }, 20_000); + + it('T58: prints a fallback for server entries missing their timestamp, message or everything', async () => { + jest.spyOn(Date, 'now').mockReturnValue(NOW); + ownedProject(); + deploymentGet('LIVE'); + serverLogs({ startTime: NOW - 3_600_000, endTime: NOW }, [ + {}, + { message: 'no time' }, + { timestamp: '2026-10-28T11:00:00.000Z' }, + { timestamp: Date.parse('2026-10-28T11:00:01.000Z'), message: 'epoch' }, + null, + ]); + + const { error, stdout } = await runCommand(getArgs('--deployment', DEPLOYMENT_UID, '--type', 'server'), config); + + expect(error).toBeUndefined(); + expect(stdout.split('\n')).toEqual(['', 'no time', '2026-10-28 11:00:00.000:', '2026-10-28 11:00:01.000: epoch', '', '']); + }); + + it('T59: a server run registers no SIGINT handler and starts no spinner', async () => { + const restoreStdout = stdoutReportingTTY(true); + const loader = jest.spyOn(cliux, 'loaderV2'); + const baseline = process.listenerCount('SIGINT'); + let during = -1; + + try { + jest.spyOn(Date, 'now').mockReturnValue(NOW); + ownedProject(); + deploymentGet('LIVE'); + hub() + .get(SERVER_LOGS) + .query(true) + .reply(200, () => { + during = process.listenerCount('SIGINT'); + return { serverLogs: [{ timestamp: '2026-10-28T11:30:00.000Z', message: 'hi' }] }; + }); + + const { error } = await runCommand(getArgs('--deployment', DEPLOYMENT_UID, '--type', 'server'), config); + + expect(error).toBeUndefined(); + expect(during).toBe(baseline); + expect(process.listenerCount('SIGINT')).toBe(baseline); + expect(loader).not.toHaveBeenCalled(); + } finally { + restoreStdout(); + } + }); + + it('T60: exits 2 naming --type for an unknown type and puts nothing on the wire', async () => { + const ownership = ownedProject(); + const verify = deploymentGet('LIVE'); + + const { error, stdout } = await runCommand(getArgs('--deployment', DEPLOYMENT_UID, '--type', 'build'), config); + + expect(error?.oclif?.exit).toBe(2); + expect(error?.message).toBe('--type must be one of deployment, server, live; "build" is not.'); + expect(stdout).toBe(''); + expect(ownership.isDone()).toBe(false); + expect(verify.isDone()).toBe(false); + expect(nock.pendingMocks()).toHaveLength(2); + expect(onWire).toEqual([]); + }); + + it('T60: accepts --type SERVER in any case and never asks for a project type on a terminal', async () => { + jest.spyOn(Date, 'now').mockReturnValue(NOW); + const answered = answerPrompts({}); + const restoreStdin = stdinReportingTTY(true); + ownedProject(); + deploymentGet('LIVE'); + const read = serverLogs({ startTime: NOW - 3_600_000, endTime: NOW }, [{ message: 'upper' }]); + + try { + const { error, stdout } = await runCommand(getArgs('--deployment', DEPLOYMENT_UID, '--type', 'SERVER'), config); + + expect(error).toBeUndefined(); + expect(read.isDone()).toBe(true); + expect(outputLines(stdout)).toEqual(['upper']); + expect(answered.messages).toEqual([]); + } finally { + restoreStdin(); + } + }); + + it('T76: streams the live route with the event-stream headers and prints the frames on a pipe, exit 0', async () => { + ownedProject(); + const verify = deploymentGet('LIVE'); + const live = liveStream( + `${SESSION_FRAME}${logFrame('first line')}data: \n\n${logFrame('second line', '2026-10-28T12:00:02.500Z')}${SESSION_ENDED_FRAME}`, + ); + + const { error, stdout } = await runCommand(getArgs('--deployment', DEPLOYMENT_UID, '--type', 'live'), config); + + expect(error).toBeUndefined(); + expect(verify.isDone()).toBe(true); + expect(live.isDone()).toBe(true); + expect(outputLines(stdout)).toEqual([ + '2026-10-28 12:00:01.000: first line', + '2026-10-28 12:00:02.500: second line', + SESSION_ENDED_LINE, + ]); + expect(stdout).not.toContain(ESCAPE); + expect(stdout).not.toContain('edge-function'); + expect(onWire).toEqual([]); + }); + + it('T88: ends on the server-limit frame with exit 0, one open and no reconnect', async () => { + ownedProject(); + deploymentGet('LIVE'); + const live = liveStream(SESSION_ENDED_FRAME); + + const { error, stdout } = await runCommand(getArgs('--deployment', DEPLOYMENT_UID, '--type', 'live'), config); + + expect(error).toBeUndefined(); + expect(live.isDone()).toBe(true); + expect(outputLines(stdout)).toEqual([SESSION_ENDED_LINE, 'No live server logs arrived during this session.']); + expect(onWire).toEqual([]); + }); + + it('T88: ends the command at the server-limit frame although the stream stays open with heartbeats and more frames', async () => { + jest.spyOn(watcher, 'defaultWatchTiming').mockImplementation(() => realWatchTiming()); + const listenersBefore = process.listenerCount('SIGINT'); + const timers = trackTimers(EVENT_STREAM_IDLE_TIMEOUT_MS); + const events: string[] = []; + let beats: NodeJS.Timeout | undefined; + + try { + ownedProject(); + deploymentGet('LIVE'); + const live = liveRoute().reply(200, function () { + (this as unknown as { req: NodeJS.EventEmitter }).req.once('close', () => events.push('request destroyed')); + const source = new Readable({ read: () => undefined }); + source.push(`${logFrame('before the end')}${SESSION_ENDED_FRAME}${logFrame('after the end')}`); + beats = setInterval(() => source.push(`: beat\n\n${logFrame('late line')}`), 10); + return source; + }, { 'content-type': 'text/event-stream' }); + const second = liveStream(SESSION_ENDED_FRAME); + + const { error, stdout } = await runCommand(getArgs('--deployment', DEPLOYMENT_UID, '--type', 'live'), config); + + expect(error).toBeUndefined(); + expect(live.isDone()).toBe(true); + expect(second.isDone()).toBe(false); + expect(outputLines(stdout)).toEqual(['2026-10-28 12:00:01.000: before the end', SESSION_ENDED_LINE]); + expect(events).toEqual(['request destroyed']); + expect(process.listenerCount('SIGINT')).toBe(listenersBefore); + expect(timers.pending()).toBe(0); + expect(onWire).toEqual([]); + } finally { + clearInterval(beats); + } + }); + + it('T86: prints the dimmed session line once on a terminal, with the time of the session end', async () => { + const restoreStdout = stdoutReportingTTY(true); + jest.spyOn(cliux, 'loaderV2').mockReturnValue(undefined as never); + + try { + ownedProject(); + deploymentGet('LIVE'); + liveStream(`${SESSION_FRAME}${logFrame('hello')}${SESSION_ENDED_FRAME}`); + + const { error, stdout } = await runCommand(getArgs('--deployment', DEPLOYMENT_UID, '--type', 'live'), config, { + stripAnsi: false, + }); + + expect(error).toBeUndefined(); + expect(stdout).toContain(`${ESCAPE}[2mLive session ends at 12:05:00; press Ctrl-C to stop.${ESCAPE}[22m`); + expect(stdout).toContain(`${ESCAPE}[2m12:00:01${ESCAPE}[22m hello`); + } finally { + restoreStdout(); + } + }); + + it('T94: follows the latest deployment when --deployment is absent, with no prompt and no status read', async () => { + ownedProject(); + const answered = answerPrompts({}); + const restoreStdin = stdinReportingTTY(true); + const latest = hub() + .get(DEPLOYMENTS) + .query({ limit: '1', skip: '0' }) + .reply(200, { ...listFixture, deployments: [{ uid: DEPLOYMENT_UID, deploymentNumber: 4, status: 'LIVE' }] }); + const live = liveStream(`${logFrame('from latest')}${SESSION_ENDED_FRAME}`); + + try { + const { error, stdout } = await runCommand(getArgs('--type', 'live'), config); + + expect(error).toBeUndefined(); + expect(latest.isDone()).toBe(true); + expect(live.isDone()).toBe(true); + expect(outputLines(stdout)[0]).toBe('2026-10-28 12:00:01.000: from latest'); + expect(answered.messages).toEqual([]); + expect(onWire).toEqual([]); + } finally { + restoreStdin(); + } + }); + + it('T94: exits 2 when the environment has no deployment, and opens no stream', async () => { + ownedProject(); + hub().get(DEPLOYMENTS).query({ limit: '1', skip: '0' }).reply(200, { ...listFixture, deployments: [] }); + const live = liveStream(SESSION_ENDED_FRAME); + + const { error } = await runCommand(getArgs('--type', 'live'), config); + + expect(error?.oclif?.exit).toBe(2); + expect(error?.message).toBe('No deployments found in this environment.'); + expect(live.isDone()).toBe(false); + }); + + it('T49: exits 2 for a deployment that is not in this environment with --type live and opens no stream', async () => { + ownedProject(); + hub().get(DEPLOYMENT_PATH).reply(404, notFoundFixture); + const live = liveStream(SESSION_ENDED_FRAME); + + const { error } = await runCommand(getArgs('--deployment', DEPLOYMENT_UID, '--type', 'live'), config); + + expect(error?.oclif?.exit).toBe(2); + expect(live.isDone()).toBe(false); + }); + + it('T80: exits 1 once on a refused open, in the CLI wording, without a reconnect', async () => { + ownedProject(); + deploymentGet('LIVE'); + const live = liveRoute().reply(404, { errors: [{ code: 'launch.DEPLOYMENT.NOT_FOUND', message: 'raw words' }] }); + + const { error, stdout } = await runCommand(getArgs('--deployment', DEPLOYMENT_UID, '--type', 'live'), config); + + expect(error?.oclif?.exit).toBe(1); + expect(error?.message).toBe('No deployment found with that UID.'); + expect(live.isDone()).toBe(true); + expect(stdout).toBe(''); + expect(onWire).toEqual([]); + }); + + it('T81: exits 1 with the session wording when a BASIC session is refused on the stream', async () => { + ownedProject(); + deploymentGet('LIVE'); + const live = liveRoute().reply(401, { errors: [{ code: 'launch.AUTH.UNAUTHORIZED', message: 'no' }] }); + + const { error } = await runCommand(getArgs('--deployment', DEPLOYMENT_UID, '--type', 'live'), config); + + expect(error?.oclif?.exit).toBe(1); + expect(error?.message).toBe('Your session has timed out. Run csdx auth:login to continue.'); + expect(live.isDone()).toBe(true); + }); + + it('T89: reconnects after a clean end of stream and after a reset socket, then ends on the server limit', async () => { + ownedProject(); + deploymentGet('LIVE'); + liveStream(logFrame('one')); + liveRoute().replyWithError({ code: 'ECONNRESET', message: 'socket hang up' }); + const last = liveStream(`${logFrame('two', 'later')}${SESSION_ENDED_FRAME}`); + + const { error, stdout } = await runCommand(getArgs('--deployment', DEPLOYMENT_UID, '--type', 'live'), config); + + expect(error).toBeUndefined(); + expect(last.isDone()).toBe(true); + expect(outputLines(stdout)).toEqual(['2026-10-28 12:00:01.000: one', 'two', SESSION_ENDED_LINE]); + }); + + it('T90: exits 1 after three consecutive failures with three opens and the CLI wording', async () => { + ownedProject(); + deploymentGet('LIVE'); + const sleeps: number[] = []; + jest.spyOn(watcher, 'defaultWatchTiming').mockImplementation(() => ({ + ...realWatchTiming(), + sleep: async (ms: number) => void sleeps.push(ms), + })); + const attempts = liveRoute().times(3).replyWithError({ code: 'ECONNRESET', message: 'socket hang up' }); + + const { error } = await runCommand(getArgs('--deployment', DEPLOYMENT_UID, '--type', 'live'), config); + + expect(error?.oclif?.exit).toBe(1); + expect(error?.message).toBe( + 'Lost the connection to the live server logs after 3 attempts. Check your network connection and run the command again.', + ); + expect(attempts.isDone()).toBe(true); + expect(sleeps).toEqual([1000, 2000]); + expect(onWire).toEqual([]); + }); + + it('T91: prints the lost-stream error red on a terminal while the log text printed before it stays uncoloured', async () => { + const restoreStdout = stdoutReportingTTY(true); + jest.spyOn(cliux, 'loaderV2').mockReturnValue(undefined as never); + + try { + ownedProject(); + deploymentGet('LIVE'); + liveStream(logFrame('plain words')); + liveRoute().times(2).replyWithError({ code: 'ECONNRESET', message: 'socket hang up' }); + + const { error, stdout, stderr } = await runCommand(getArgs('--deployment', DEPLOYMENT_UID, '--type', 'live'), config, { + stripAnsi: false, + }); + + expect(error?.oclif?.exit).toBe(1); + expect(stderr).toContain(`${ESCAPE}[31m`); + expect(stderr).toContain('Lost the connection to the live server logs after 3 attempts.'); + expect(stdout).toContain('plain words'); + expect(stdout).not.toContain(`${ESCAPE}[31m`); + } finally { + restoreStdout(); + } + }); + + it.each([ + [true, `${ESCAPE}[33mStopped following the logs.${ESCAPE}[39m`], + [false, 'Stopped following the logs.'], + ])('T92: Ctrl-C on a live stream (terminal=%s) prints the stop line, exits 3 and leaves nothing behind', async (tty, stopLine) => { + jest.spyOn(watcher, 'defaultWatchTiming').mockImplementation(() => realWatchTiming()); + const restoreStdout = stdoutReportingTTY(tty); + jest.spyOn(cliux, 'loaderV2').mockReturnValue(undefined as never); + const listenersBefore = process.listenerCount('SIGINT'); + const timers = trackTimers(EVENT_STREAM_IDLE_TIMEOUT_MS); + const events: string[] = []; + + try { + ownedProject(); + deploymentGet('LIVE'); + liveRoute().reply(200, function () { + (this as unknown as { req: NodeJS.EventEmitter }).req.once('close', () => events.push('request destroyed')); + const source = new Readable({ read: () => undefined }); + source.push(logFrame('only line')); + setTimeout(() => process.emit('SIGINT'), 50); + return source; + }, { 'content-type': 'text/event-stream' }); + + const { error, stdout, stderr } = await runCommand(getArgs('--deployment', DEPLOYMENT_UID, '--type', 'live'), config, { + stripAnsi: false, + }); + + expect(error?.oclif?.exit).toBe(3); + expect(stdout).toContain(stopLine); + expect(stdout).toContain('only line'); + expect(stderr).not.toContain('error'); + expect(error?.message).not.toContain('Error'); + expect(events).toEqual(['request destroyed']); + expect(onWire).toEqual([]); + expect(process.listenerCount('SIGINT')).toBe(listenersBefore); + expect(timers.created()).toBeGreaterThan(0); + expect(timers.pending()).toBe(0); + } finally { + restoreStdout(); + } + }); + + it('T93: Ctrl-C while the command waits to reconnect cancels the wait and opens nothing more', async () => { + jest.spyOn(watcher, 'defaultWatchTiming').mockImplementation(() => realWatchTiming()); + const listenersBefore = process.listenerCount('SIGINT'); + const timers = trackTimers(1000); + ownedProject(); + deploymentGet('LIVE'); + liveRoute().reply(200, () => { + setTimeout(() => process.emit('SIGINT'), 50); + return ''; + }, { 'content-type': 'text/event-stream' }); + const second = liveStream(SESSION_ENDED_FRAME); + + const { error, stdout } = await runCommand(getArgs('--deployment', DEPLOYMENT_UID, '--type', 'live'), config); + + expect(error?.oclif?.exit).toBe(3); + expect(outputLines(stdout)).toEqual(['Stopped following the logs.']); + expect(second.isDone()).toBe(false); + expect(process.listenerCount('SIGINT')).toBe(listenersBefore); + expect(timers.created()).toBe(1); + expect(timers.pending()).toBe(0); + }); + + it.each([ + [['--since', '1h'], '--since is only supported when --type is one of server; --type is deployment.'], + [['--until', '1h', '--type', 'live'], '--until is only supported when --type is one of server; --type is live.'], + [['--since', '12hr', '--until', '2026-10-28T10:00:00Z', '--type', 'server'], '--since and --until must both be relative (like 12hr) or both absolute (ISO 8601) timestamps.'], + [['--since', '30m', '--until', '2h', '--type', 'server'], '--since must not be later than --until.'], + ])('T61: exits 2 for %j with nothing read', async (flags, message) => { + ownedProject(); + const verify = deploymentGet('LIVE'); + const logs = hub().get(SERVER_LOGS).query(true).reply(200, { serverLogs: [] }); + + const { error } = await runCommand(getArgs('--deployment', DEPLOYMENT_UID, ...flags), config); + + expect(error?.oclif?.exit).toBe(2); + expect(error?.message).toBe(message); + expect(verify.isDone()).toBe(false); + expect(logs.isDone()).toBe(false); + expect(onWire).toEqual([]); + }); + + it('T62: exits 2 naming --env when it is missing and there is no terminal', async () => { + ownedProject(); + const { error } = await runCommand( + ['launch:logs:get', '--org', ORG_UID, '--project', PROJECT_UID, '--data-dir', DATA_DIR], + config, + ); + + expect(error?.oclif?.exit).toBe(2); + expect(error?.message).toContain('--env'); + expect(onWire).toEqual([]); + }); + + it('T62a: exits 2 naming --org with no flags at all and no terminal, and sends nothing', async () => { + const ownership = ownedProject(); + + const { error, stdout } = await runCommand(['launch:logs:get', '--data-dir', DATA_DIR], config); + + expect(error?.oclif?.exit).toBe(2); + expect(error?.message).toContain('--org'); + expect(stdout).toBe(''); + expect(ownership.isDone()).toBe(false); + expect(nock.pendingMocks()).toHaveLength(1); + expect(onWire).toEqual([]); + }); + + it('T62b: exits 2 naming --project when only --org is given and there is no terminal, and sends nothing', async () => { + const ownership = ownedProject(); + + const { error, stdout } = await runCommand(['launch:logs:get', '--org', ORG_UID, '--data-dir', DATA_DIR], config); + + expect(error?.oclif?.exit).toBe(2); + expect(error?.message).toContain('--project'); + expect(stdout).toBe(''); + expect(ownership.isDone()).toBe(false); + expect(nock.pendingMocks()).toHaveLength(1); + expect(onWire).toEqual([]); + }); + + describe('with no flags on a terminal', () => { + const CMA_URL = 'https://cma.integration.test'; + const ORGANIZATION_QUERY = { limit: '100', asc: 'name', include_count: 'true', skip: '0' }; + const PICKED = ['Choose an organization', 'Choose a project', 'Choose an environment']; + + let restoreStdin: () => void; + let restoreStdout: () => void; + + beforeEach(() => { + restoreStdin = stdinReportingTTY(true); + restoreStdout = stdoutReportingTTY(true); + }); + + afterEach(() => { + restoreStdout(); + restoreStdin(); + }); + + function pickerLists(): nock.Scope[] { + return [ + nock(CMA_URL) + .matchHeader('authtoken', 'test-authtoken') + .get('/v3/organizations') + .query(ORGANIZATION_QUERY) + .reply(200, { organizations: [{ uid: ORG_UID, name: 'Acme Production' }], count: 1 }), + nock(LAUNCH_HUB_URL) + .matchHeader('x-organization-uid', ORG_UID) + .get('/manage/projects') + .query({ limit: '100', skip: '0' }) + .reply(200, { pagination: { count: 1, limit: 100, skip: 0 }, projects: [{ uid: PROJECT_UID, name: 'sample-project' }] }), + hub() + .get(`/manage/projects/${PROJECT_UID}/environments`) + .query({ limit: '100', skip: '0' }) + .reply(200, { pagination: { count: 1, limit: 100, skip: 0 }, environments: [{ uid: ENV_UID, name: 'production' }] }), + ]; + } + + function latestDeployment(): nock.Scope { + return hub() + .get(DEPLOYMENTS) + .query({ limit: '1', skip: '0' }) + .reply(200, { ...listFixture, deployments: [{ uid: DEPLOYMENT_UID, deploymentNumber: 4, status: 'LIVE' }] }); + } + + it('T62c: asks organization, project, environment in order, never the deployment or the type, and prints the build logs', async () => { + const answered = answerPrompts({ + 'Choose an organization': ORG_UID, + 'Choose a project': PROJECT_UID, + 'Choose an environment': ENV_UID, + }); + const lists = pickerLists(); + const latest = latestDeployment(); + const other = hub().get(DEPLOYMENTS).query({ limit: '100', skip: '0' }).reply(200, listFixture); + const poll = deploymentGet('LIVE'); + const first = buildLogs([LINE_ONE]); + const drain = buildLogs([]); + const serverRead = hub().get(SERVER_LOGS).query(true).reply(200, { serverLogs: [] }); + const liveRead = liveRoute().reply(200, '', { 'content-type': 'text/event-stream' }); + + const { error, stdout } = await runCommand(['launch:logs:get', '--data-dir', DATA_DIR], config); + + expect(error).toBeUndefined(); + expect(process.exitCode).toBe(0); + expect(answered.messages).toEqual(PICKED); + expect(lists.every((scope) => scope.isDone())).toBe(true); + expect([latest, poll, first, drain].every((scope) => scope.isDone())).toBe(true); + expect(other.isDone()).toBe(false); + expect(serverRead.isDone()).toBe(false); + expect(liveRead.isDone()).toBe(false); + expect(outputLines(stdout)).toEqual(['10:00:00 Installing dependencies...', 'Deployment #4 is LIVE.']); + expect(onWire).toEqual([]); + }); + + it('T62d: with only --type server asks organization, project, environment, then reads the default one hour window', async () => { + jest.spyOn(Date, 'now').mockReturnValue(NOW); + const answered = answerPrompts({ + 'Choose an organization': ORG_UID, + 'Choose a project': PROJECT_UID, + 'Choose an environment': ENV_UID, + }); + const lists = pickerLists(); + const latest = latestDeployment(); + const read = serverLogs({ startTime: NOW - 3_600_000, endTime: NOW }, [ + { timestamp: '2026-10-28T11:30:00.000Z', message: 'GET /index 200', source: 'edge-fn-source' }, + ]); + const build = hub().get(BUILD_LOGS).query(true).reply(200, { deploymentLogs: [] }); + + const { error, stdout } = await runCommand(['launch:logs:get', '--type', 'server', '--data-dir', DATA_DIR], config); + + expect(error).toBeUndefined(); + expect(process.exitCode).toBe(0); + expect(answered.messages).toEqual(PICKED); + expect(lists.every((scope) => scope.isDone())).toBe(true); + expect([latest, read].every((scope) => scope.isDone())).toBe(true); + expect(build.isDone()).toBe(false); + expect(outputLines(stdout)).toEqual(['11:30:00 GET /index 200']); + expect(stdout).not.toContain('edge-fn-source'); + expect(onWire).toEqual([]); + }); + }); +}); diff --git a/test/integration/projects-create.test.ts b/test/integration/projects-create.test.ts index f58860bd..93c3ef19 100644 --- a/test/integration/projects-create.test.ts +++ b/test/integration/projects-create.test.ts @@ -197,11 +197,24 @@ function stubFollowUp(status: string, deploymentLogs: unknown[] = []): nock.Scop deployment: { uid: DEPLOYMENT_UID, deploymentNumber: 1, status, deploymentUrl: 'my-site.example.test' }, }); - return hub() - .get(`/logs/projects/${PROJECT_UID}/environments/${ENVIRONMENT_UID}/deployments/${DEPLOYMENT_UID}/logs/deployment-logs`) + const logsPath = `/logs/projects/${PROJECT_UID}/environments/${ENVIRONMENT_UID}/deployments/${DEPLOYMENT_UID}/logs/deployment-logs`; + const first = hub() + .get(logsPath) .matchHeader('x-project-uid', PROJECT_UID) .query({ timestamp: '1970-01-01T00:00:00.000Z' }) .reply(200, { deploymentLogs }); + + const last = (deploymentLogs.at(-1) as { timestamp?: string } | undefined)?.timestamp; + + if (last !== undefined) { + hub() + .get(logsPath) + .matchHeader('x-project-uid', PROJECT_UID) + .query({ timestamp: new Date(Date.parse(last) - 1).toISOString() }) + .reply(200, { deploymentLogs: [] }); + } + + return first; } function withoutFlags(args: string[], ...names: string[]): string[] { diff --git a/test/integration/projects-get.test.ts b/test/integration/projects-get.test.ts index 6c534ce9..a791287b 100644 --- a/test/integration/projects-get.test.ts +++ b/test/integration/projects-get.test.ts @@ -78,7 +78,7 @@ describe('integration: GET /projects/{project_uid}', () => { return [200, getFixture]; }); - await buildApi(buildClient(), UNUSED_CMA, {} as never).projects.get({ org: ORG_UID, project: PROJECT_UID }); + await buildApi(buildClient(), UNUSED_CMA, {} as never, {} as never).projects.get({ org: ORG_UID, project: PROJECT_UID }); expect(scope.isDone()).toBe(true); expect(capturedPath).toBe(`${BASE_PATH}/projects/${PROJECT_UID}`); @@ -92,7 +92,7 @@ describe('integration: GET /projects/{project_uid}', () => { it('unwraps the documented project envelope into a bare Project', async () => { nock(ORIGIN).get(`${BASE_PATH}/projects/${PROJECT_UID}`).query({}).reply(200, getFixture); - const project: Project = await buildApi(buildClient(), UNUSED_CMA, {} as never).projects.get({ org: ORG_UID, project: PROJECT_UID }); + const project: Project = await buildApi(buildClient(), UNUSED_CMA, {} as never, {} as never).projects.get({ org: ORG_UID, project: PROJECT_UID }); expect(project).not.toHaveProperty('project'); expect(project.uid).toBe(PROJECT_UID); @@ -116,7 +116,7 @@ describe('integration: GET /projects/{project_uid}', () => { nock(ORIGIN).get(`${BASE_PATH}/projects/${PROJECT_UID}`).query({}).reply(200, getFixture); const { ux, lines } = recordingUx(); - const project = await buildApi(buildClient(), UNUSED_CMA, {} as never).projects.get({ org: ORG_UID, project: PROJECT_UID }); + const project = await buildApi(buildClient(), UNUSED_CMA, {} as never, {} as never).projects.get({ org: ORG_UID, project: PROJECT_UID }); renderTable(ux, PROJECT_DETAIL_COLUMNS, [project], undefined, PROJECT_DESCRIPTION_COLUMN); expect(lines).toEqual([ @@ -131,7 +131,7 @@ describe('integration: GET /projects/{project_uid}', () => { it('unwraps a FileUpload project that carries neither repository nor description', async () => { nock(ORIGIN).get(`${BASE_PATH}/projects/${FILEUPLOAD_PROJECT_UID}`).query({}).reply(200, getFileUploadFixture); - const project: Project = await buildApi(buildClient(), UNUSED_CMA, {} as never).projects.get({ + const project: Project = await buildApi(buildClient(), UNUSED_CMA, {} as never, {} as never).projects.get({ org: ORG_UID, project: FILEUPLOAD_PROJECT_UID, }); @@ -146,7 +146,7 @@ describe('integration: GET /projects/{project_uid}', () => { nock(ORIGIN).get(`${BASE_PATH}/projects/${FILEUPLOAD_PROJECT_UID}`).query({}).reply(200, getFileUploadFixture); const { ux, lines } = recordingUx(); - const project = await buildApi(buildClient(), UNUSED_CMA, {} as never).projects.get({ org: ORG_UID, project: FILEUPLOAD_PROJECT_UID }); + const project = await buildApi(buildClient(), UNUSED_CMA, {} as never, {} as never).projects.get({ org: ORG_UID, project: FILEUPLOAD_PROJECT_UID }); renderTable(ux, PROJECT_DETAIL_COLUMNS, [project], undefined, PROJECT_DESCRIPTION_COLUMN); expect(lines).toEqual([ @@ -161,7 +161,7 @@ describe('integration: GET /projects/{project_uid}', () => { it('raises a LaunchApiError carrying the mapped message for the documented 404 body', async () => { nock(ORIGIN).get(`${BASE_PATH}/projects/${PROJECT_UID}`).query({}).reply(404, notFoundFixture); - const rejection = await buildApi(buildClient(), UNUSED_CMA, {} as never) + const rejection = await buildApi(buildClient(), UNUSED_CMA, {} as never, {} as never) .projects.get({ org: ORG_UID, project: PROJECT_UID }) .catch((error: unknown) => error); @@ -182,7 +182,7 @@ describe('integration: GET /projects/{project_uid}', () => { .reply(429, { errors: [{ code: 'launch.RATE_LIMITED', message: 'Too many requests.' }], status: 429 }); const succeeded = nock(ORIGIN).get(`${BASE_PATH}/projects/${PROJECT_UID}`).query({}).reply(200, getFixture); - const project = await buildApi(buildClient(), UNUSED_CMA, {} as never).projects.get({ org: ORG_UID, project: PROJECT_UID }); + const project = await buildApi(buildClient(), UNUSED_CMA, {} as never, {} as never).projects.get({ org: ORG_UID, project: PROJECT_UID }); expect(throttled.isDone()).toBe(true); expect(succeeded.isDone()).toBe(true); diff --git a/test/integration/projects-list.test.ts b/test/integration/projects-list.test.ts index 5f2be9df..73ee624c 100644 --- a/test/integration/projects-list.test.ts +++ b/test/integration/projects-list.test.ts @@ -74,7 +74,7 @@ describe('integration: GET /projects', () => { return [200, listFixture]; }); - await buildApi(buildClient(), UNUSED_CMA, {} as never).projects.list({ org: ORG_UID, limit: 50, skip: 0 }); + await buildApi(buildClient(), UNUSED_CMA, {} as never, {} as never).projects.list({ org: ORG_UID, limit: 50, skip: 0 }); expect(scope.isDone()).toBe(true); expect(capturedPath).toBe(`${BASE_PATH}/projects?limit=50&skip=0`); @@ -95,7 +95,7 @@ describe('integration: GET /projects', () => { return [200, listFixture]; }); - await buildApi(buildClient(), UNUSED_CMA, {} as never).projects.list({ org: ORG_UID }); + await buildApi(buildClient(), UNUSED_CMA, {} as never, {} as never).projects.list({ org: ORG_UID }); expect(scope.isDone()).toBe(true); expect(capturedPath).toBe(`${BASE_PATH}/projects`); @@ -104,7 +104,7 @@ describe('integration: GET /projects', () => { it('parses the documented bare envelope into a ProjectsPage', async () => { nock(ORIGIN).get(`${BASE_PATH}/projects`).query({}).reply(200, listFixture); - const page: ProjectsPage = await buildApi(buildClient(), UNUSED_CMA, {} as never).projects.list({ org: ORG_UID }); + const page: ProjectsPage = await buildApi(buildClient(), UNUSED_CMA, {} as never, {} as never).projects.list({ org: ORG_UID }); expect(page).not.toHaveProperty('projects.projects'); expect(page.pagination).toEqual({ count: 3, limit: 10, skip: null }); @@ -129,7 +129,7 @@ describe('integration: GET /projects', () => { it('parses a FileUpload project that carries neither repository nor description', async () => { nock(ORIGIN).get(`${BASE_PATH}/projects`).query({}).reply(200, listFixture); - const page: ProjectsPage = await buildApi(buildClient(), UNUSED_CMA, {} as never).projects.list({ org: ORG_UID }); + const page: ProjectsPage = await buildApi(buildClient(), UNUSED_CMA, {} as never, {} as never).projects.list({ org: ORG_UID }); expect(page.projects[2].projectType).toBe('FILEUPLOAD'); expect(page.projects[2].repository).toBeUndefined(); @@ -152,7 +152,7 @@ describe('integration: GET /projects', () => { nock(ORIGIN).get(`${BASE_PATH}/projects`).query({}).reply(200, listFixture); const { ux, lines } = recordingUx(); - const page = await buildApi(buildClient(), UNUSED_CMA, {} as never).projects.list({ org: ORG_UID }); + const page = await buildApi(buildClient(), UNUSED_CMA, {} as never, {} as never).projects.list({ org: ORG_UID }); renderTable(ux, PROJECT_COLUMNS, page.projects); renderPagination(ux, page.pagination, page.projects.length); @@ -177,7 +177,7 @@ describe('integration: GET /projects', () => { .reply(429, { errors: [{ code: 'launch.RATE_LIMITED', message: 'Too many requests.' }], status: 429 }); const succeeded = nock(ORIGIN).get(`${BASE_PATH}/projects`).query({}).reply(200, listFixture); - const page = await buildApi(buildClient(), UNUSED_CMA, {} as never).projects.list({ org: ORG_UID }); + const page = await buildApi(buildClient(), UNUSED_CMA, {} as never, {} as never).projects.list({ org: ORG_UID }); expect(throttled.isDone()).toBe(true); expect(succeeded.isDone()).toBe(true); @@ -189,7 +189,7 @@ describe('integration: GET /projects', () => { const body = { errors: [{ code: 'launch.RATE_LIMITED', message: 'Too many requests.' }], status: 429 }; nock(ORIGIN).get(`${BASE_PATH}/projects`).query({}).times(4).reply(429, body); - const rejection = await buildApi(buildClient(), UNUSED_CMA, {} as never) + const rejection = await buildApi(buildClient(), UNUSED_CMA, {} as never, {} as never) .projects.list({ org: ORG_UID }) .catch((error: unknown) => error); diff --git a/test/integration/projects-paging.test.ts b/test/integration/projects-paging.test.ts index 2e787c46..a8b4887c 100644 --- a/test/integration/projects-paging.test.ts +++ b/test/integration/projects-paging.test.ts @@ -43,7 +43,7 @@ function buildDeps() { }); const ux: UxLike = { print: () => undefined, inquire: async () => undefined as never }; - return { api: buildApi(client, UNUSED_CMA, {} as never), ux }; + return { api: buildApi(client, UNUSED_CMA, {} as never, {} as never), ux }; } function projectsOfSize(size: number, prefix: string) { diff --git a/test/integration/retired-commands.test.ts b/test/integration/retired-commands.test.ts index 91b9b7c5..9cbe9f43 100644 --- a/test/integration/retired-commands.test.ts +++ b/test/integration/retired-commands.test.ts @@ -29,7 +29,6 @@ const CONFIG: Record = { let config: Interfaces.Config; const PLANNED_COMMANDS: Record = { - 'launch:logs:get': 'CL-7171', }; function commandsNamedInSource(): string[] { @@ -135,6 +134,27 @@ describe('integration: retired V1 command names', () => { rmSync(projectDir, { recursive: true, force: true }); }); + it('leaves the live child of the retired logs topic reachable', async () => { + const registered = new Set(config.commands.map((command) => command.id)); + + const { error } = await runCommand(['launch:logs:get', '--org', 'o1', '--project', 'p1', '--type', 'build'], config); + + expect(registered.has('launch:logs:get')).toBe(true); + expect(PLANNED_COMMANDS['launch:logs:get']).toBeUndefined(); + expect(error?.oclif?.exit).toBe(2); + expect(error?.message).toBe('--type must be one of deployment, server, live; "build" is not.'); + expect(error?.message).not.toContain('was removed in Launch CLI v2'); + }); + + it('shows --type and never --log-type in launch:logs:get --help', async () => { + const { stdout } = await runCommand(['launch:logs:get', '--help'], config); + + expect(stdout).toContain('--type='); + expect(stdout).toContain('--since='); + expect(stdout).toContain('--until='); + expect(stdout).not.toContain('--log-type'); + }); + it('names only commands that exist or are planned in a ticket, wherever the CLI tells a user to run one', () => { const registered = new Set(config.commands.map((command) => command.id)); const named = commandsNamedInSource(); @@ -195,6 +215,19 @@ describe('integration: retired V1 command names', () => { expect(registered).not.toContain('launch:site:view'); }); + it('lists the launch:logs topic with its own description under launch --help', async () => { + const { stdout } = await runCommand(['launch', '--help'], config); + + expect(stdout).toContain('launch:logs'); + expect(stdout).toContain('Read Launch deployment, server and live logs'); + }); + + it("lists the logs resource's verb under launch:logs --help", async () => { + const { stdout } = await runCommand(['launch:logs', '--help'], config); + + expect(stdout).toContain('launch:logs:get'); + }); + it('lists the launch:cache topic with its own description under launch --help', async () => { const { stdout } = await runCommand(['launch', '--help'], config); diff --git a/test/support/timers.ts b/test/support/timers.ts new file mode 100644 index 00000000..16688d98 --- /dev/null +++ b/test/support/timers.ts @@ -0,0 +1,31 @@ +export interface TimerTracker { + created: () => number; + pending: () => number; +} + +export function trackTimers(...delaysMs: number[]): TimerTracker { + const created: NodeJS.Timeout[] = []; + const settled = new Set(); + const realSet = global.setTimeout; + const realClear = global.clearTimeout; + + jest.spyOn(global, 'setTimeout').mockImplementation(((callback: () => void, ms?: number) => { + if (ms === undefined || !delaysMs.includes(ms)) { + return realSet(callback, ms); + } + + const timer: NodeJS.Timeout = realSet(() => { + settled.add(timer); + callback(); + }, ms); + created.push(timer); + + return timer; + }) as unknown as typeof setTimeout); + jest.spyOn(global, 'clearTimeout').mockImplementation(((timer?: NodeJS.Timeout) => { + settled.add(timer as NodeJS.Timeout); + realClear(timer); + }) as typeof clearTimeout); + + return { created: () => created.length, pending: () => created.filter((timer) => !settled.has(timer)).length }; +}