-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathdeployRenderer.ts
More file actions
196 lines (182 loc) · 7.07 KB
/
Copy pathdeployRenderer.ts
File metadata and controls
196 lines (182 loc) · 7.07 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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
import { Transform } from 'node:stream';
// cli-progress is already a runtime dep of harper (see package.json); using its
// SingleBar to render the upload phase here doesn't add a new dependency.
import cliProgress from 'cli-progress';
import type { SSEMessage } from './sseConsumer.ts';
interface RendererOptions {
uploadTotal?: number;
output?: NodeJS.WritableStream;
}
interface UploadState {
bar: cliProgress.SingleBar | null;
sent: number;
finished: boolean;
}
interface PhaseState {
current?: string;
installManager?: string;
installLineCount: number;
}
/**
* Deploy-time renderer that owns the progress display across two phases:
*
* 1. Local upload — driven by `tapUploadStream`, which wraps the multipart body so we
* can update a `cli-progress` bar against the precomputed uncompressed source-tree
* total. The bar moves as gzipped bytes are sent and snaps to 100% on completion.
* In a non-TTY environment a single "Uploaded X MiB" line is printed on completion.
*
* 2. Server-side phases — driven by `renderEvent`, called for each SSE message the
* CLI receives from the operations API. Phase events print one-liners; live
* `install` events (npm/pnpm/yarn stdout) are throttled to one line under a
* "[install]" header so a noisy `npm install` doesn't drown the terminal.
*
* Designed so the two phases hand off cleanly: `endUpload()` tears the bar down (so
* it doesn't compete with subsequent prints) before any SSE events render.
*/
export class DeployRenderer {
private upload: UploadState = { bar: null, sent: 0, finished: false };
private phase: PhaseState = { installLineCount: 0 };
private output: NodeJS.WritableStream;
private isTty: boolean;
private uploadTotal: number;
constructor(options: RendererOptions = {}) {
this.output = options.output ?? process.stderr;
// Only render a bar when stderr is a real terminal. CI runners, log redirection,
// and pipes look identical from Node's perspective: !isTTY.
this.isTty = Boolean((this.output as NodeJS.WriteStream).isTTY);
this.uploadTotal = options.uploadTotal ?? 0;
}
/**
* Wrap an outbound stream so each byte flowing through it advances the upload bar.
* The Transform is identity — chunks pass through unmodified.
*/
tapUploadStream<T extends NodeJS.ReadableStream>(stream: T): NodeJS.ReadableStream {
this.upload.bar = this.isTty
? new cliProgress.SingleBar(
{
// {value_fmt} and {total_fmt} are payload tokens updated in tickUpload/endUpload.
// uploadTotal is the uncompressed source size; gzip output is smaller so the
// bar won't naturally reach 100% — endUpload() snaps it on completion.
format: 'Uploading [{bar}] {percentage}% | {value_fmt} / ~{total_fmt}',
barCompleteChar: '█',
barIncompleteChar: '░',
hideCursor: true,
stream: this.output,
},
cliProgress.Presets.shades_classic
)
: null;
this.upload.bar?.start(this.uploadTotal || 1, 0, {
value_fmt: formatBytes(0),
total_fmt: formatBytes(this.uploadTotal),
});
const counter = new Transform({
transform: (chunk, _enc, cb) => {
// Bytes are counted externally via countUploadBytes() on the pre-gzip tar
// stream so progress and total are both in uncompressed units. The Transform
// is kept here solely to get the flush callback that signals upload completion.
cb(null, chunk);
},
flush: (cb) => {
this.endUpload();
cb();
},
});
stream.on('error', (err) => counter.destroy(err));
stream.pipe(counter);
return counter;
}
/**
* Record `n` pre-gzip bytes read from the tar pack stream. Called for each
* raw tar chunk by the `onBytes` callback passed to `streamPackagedDirectory`,
* keeping progress and total in the same (uncompressed) unit so the bar
* tracks smoothly and doesn't terminate far short of 100%.
*/
countUploadBytes(n: number): void {
if (this.upload.finished) return;
this.upload.sent += n;
this.tickUpload();
}
endUpload(): void {
if (this.upload.finished) return;
this.upload.finished = true;
if (this.upload.bar) {
// Snap to total so the bar shows 100% even when our uncompressed-total estimate
// is slightly off (gzip output is usually smaller than the source tree).
const finalPayload = { value_fmt: formatBytes(this.upload.sent), total_fmt: formatBytes(this.uploadTotal) };
if (this.uploadTotal > 0) this.upload.bar.update(this.uploadTotal, finalPayload);
this.upload.bar.stop();
this.upload.bar = null;
} else {
// Non-TTY: single completion line, no intermediate chatter.
this.output.write(`Uploaded ${formatBytes(this.upload.sent)}\n`);
}
}
private tickUpload(): void {
if (this.upload.finished) return;
if (this.upload.bar) {
this.upload.bar.update(this.upload.sent, { value_fmt: formatBytes(this.upload.sent) });
}
// Non-TTY: no intermediate lines — endUpload() prints the final size on completion.
}
renderEvent(message: SSEMessage): void {
let parsed: unknown;
try {
parsed = JSON.parse(message.data);
} catch {
parsed = message.data;
}
switch (message.event) {
case 'phase':
this.renderPhase(parsed as { phase?: string; status?: string; message?: string });
break;
case 'install':
this.renderInstall(parsed as { manager?: string; stream?: string; line?: string });
break;
case 'error': {
const e = parsed as { message?: string; code?: string | number };
this.output.write(`error: ${e.message ?? message.data}${e.code ? ` (${e.code})` : ''}\n`);
break;
}
case 'done':
// Caller picks up final result via the SSE iterator; nothing to render here.
break;
}
}
private renderPhase(data: { phase?: string; status?: string; message?: string }): void {
const label = data.phase ?? '?';
if (data.status === 'start') {
if (this.phase.current !== label) {
this.output.write(`${label}…\n`);
this.phase.current = label;
this.phase.installLineCount = 0;
}
} else if (data.status === 'done') {
if (label === 'install' && this.phase.installLineCount > 0) {
this.output.write(`install done (${this.phase.installLineCount} log lines)\n`);
} else {
this.output.write(`${label} done\n`);
}
} else if (data.status === 'error') {
this.output.write(`${label} ERROR: ${data.message ?? 'failed'}\n`);
}
}
private renderInstall(data: { manager?: string; stream?: string; line?: string }): void {
const line = (data.line ?? '').trimEnd();
if (!line) return;
if (data.manager && data.manager !== this.phase.installManager) {
this.phase.installManager = data.manager;
this.output.write(`install: using ${data.manager}\n`);
}
this.phase.installLineCount++;
// Prefix with stream so users can distinguish stderr noise from stdout warnings.
const tag = data.stream === 'stderr' ? '!' : '|';
this.output.write(` ${tag} ${line}\n`);
}
}
function formatBytes(bytes: number): string {
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KiB`;
if (bytes < 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MiB`;
return `${(bytes / (1024 * 1024 * 1024)).toFixed(2)} GiB`;
}