Repository navigation
Expand file tree
/
Copy pathdaemonLogs.ts
More file actions
138 lines (130 loc) · 5.18 KB
/
Copy pathdaemonLogs.ts
File metadata and controls
138 lines (130 loc) · 5.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
// See LICENSE in the project root for license information.
import { constants, type Stats } from 'node:fs';
import { lstat, open, type FileHandle } from 'node:fs/promises';
import type { Writable } from 'node:stream';
import { setTimeout as delayAsync } from 'node:timers/promises';
import { getDaemonLogFilePath } from '@rushstack/rush-client-core';
import type { IDaemonPaths } from '@rushstack/rush-daemon-transport';
import { writeStreamAsync } from './writeStreamAsync';
import { DaemonLogOutput } from './DaemonLogOutput';
import { MAX_LOG_OUTPUT_BYTES } from './DaemonLogOutputProtocol';
const FOLLOW_POLL_INTERVAL_MS: number = 100;
export interface IDaemonLogOptions {
readonly follow?: boolean;
readonly abortSignal?: AbortSignal;
readonly output?: Writable;
}
/** Reads a snapshot, optionally following appends, without connecting to or starting the daemon. */
export async function printDaemonLogAsync(
paths: IDaemonPaths,
options: IDaemonLogOptions = {}
): Promise<void> {
if (options.abortSignal?.aborted) return;
const logFilePath: string = getDaemonLogFilePath(paths);
let file: FileHandle;
let ownedOutput: DaemonLogOutput | undefined;
try {
// These distinct native flags have non-overlapping values.
file = await open(
logFilePath,
constants.O_RDONLY + (process.platform === 'win32' ? 0 : constants.O_NOFOLLOW + constants.O_NONBLOCK)
);
} catch (error) {
if (typeof error === 'object' && error !== null && 'code' in error && error.code === 'ENOENT') {
throw new Error(
`No launcher log exists at ${logFilePath}. Logs are created when this client starts a daemon.`,
{ cause: error }
);
}
throw error;
}
try {
const stats: Stats = await file.stat();
if (!stats.isFile() || stats.nlink !== 1) {
throw new Error(`Launcher log must be a regular, unshared file: ${logFilePath}`);
}
if (!Number.isSafeInteger(stats.size) || stats.size < 0) {
throw new Error(`Launcher log size cannot be represented safely: ${logFilePath}`);
}
if (options.follow && !options.output && process.platform === 'win32' && !process.stdout.isTTY) {
ownedOutput = new DaemonLogOutput(options.abortSignal);
}
const signal: AbortSignal | undefined = ownedOutput
? AbortSignal.any([ownedOutput.failureSignal, ...(options.abortSignal ? [options.abortSignal] : [])])
: options.abortSignal;
const buffer: Buffer = Buffer.alloc(MAX_LOG_OUTPUT_BYTES);
let position: number = 0;
let size: number = stats.size;
while (!signal?.aborted) {
if (position === size) {
if (!options.follow) break;
await waitForAppendAsync(signal);
if (signal?.aborted) break;
const current: Stats = await file.stat();
const named: Stats = await lstat(logFilePath);
if (current.nlink !== 1 || !named.isFile() || named.dev !== stats.dev || named.ino !== stats.ino) {
throw new Error(
`Launcher log was replaced or unlinked while following ${logFilePath}; reopen the log.`
);
}
if (!Number.isSafeInteger(current.size) || current.size < position) {
throw new Error(
`Launcher log was truncated or has an invalid size while following ${logFilePath}.`
);
}
size = current.size;
continue;
}
const { bytesRead } = await file.read(buffer, 0, Math.min(buffer.length, size - position), position);
if (bytesRead === 0)
throw new Error(`Launcher log was truncated while reading ${logFilePath}; retry the command.`);
if (ownedOutput) await ownedOutput.writeAsync(buffer.subarray(0, bytesRead));
else await writeLogChunkAsync(options, buffer.subarray(0, bytesRead));
position += bytesRead;
}
ownedOutput?.failureSignal.throwIfAborted();
} catch (error) {
if (!options.abortSignal?.aborted || error !== options.abortSignal.reason) throw error;
} finally {
try {
await file.close();
} finally {
await ownedOutput?.closeAsync();
}
}
}
async function waitForAppendAsync(signal: AbortSignal | undefined): Promise<void> {
try {
await delayAsync(FOLLOW_POLL_INTERVAL_MS, undefined, { signal });
} catch (error) {
if (
!signal?.aborted ||
typeof error !== 'object' ||
error === null ||
!('name' in error) ||
error.name !== 'AbortError' ||
!('cause' in error) ||
error.cause !== signal.reason
)
throw error;
}
}
async function writeLogChunkAsync(options: IDaemonLogOptions, bytes: Uint8Array): Promise<void> {
const output: Writable = options.output ?? process.stdout;
const signal: AbortSignal | undefined = options.abortSignal;
signal?.throwIfAborted();
let onAbort: (() => void) | undefined;
try {
await new Promise<void>((resolve, reject) => {
onAbort = () => {
reject(signal!.reason);
output.destroy(signal!.reason);
};
signal?.addEventListener('abort', onAbort, { once: true });
void writeStreamAsync(output, bytes).then(resolve, reject);
});
} finally {
if (onAbort) signal?.removeEventListener('abort', onAbort);
}
}