@ship.zone/runner 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,134 @@
1
+ import { ProtocolError } from './errors.ts';
2
+ import type { IJobIdentity, ILogAcknowledgement, ILogChunk, TLogStream } from './interfaces.ts';
3
+ import { StreamingSecretRedactor } from './redactor.ts';
4
+ import { utf8Length } from './validation.ts';
5
+
6
+ export interface ILogApi {
7
+ appendLog(chunk: ILogChunk, signal?: AbortSignal): Promise<ILogAcknowledgement>;
8
+ }
9
+
10
+ interface ILogWrite {
11
+ stream: TLogStream;
12
+ data: string;
13
+ }
14
+
15
+ const splitByUtf8Bytes = (value: string, maximumBytes: number): string[] => {
16
+ const chunks: string[] = [];
17
+ let current = '';
18
+ let currentBytes = 0;
19
+ for (const codePoint of value) {
20
+ const codePointBytes = utf8Length(codePoint);
21
+ if (codePointBytes > maximumBytes) {
22
+ throw new ProtocolError('A log code point exceeds the negotiated chunk limit');
23
+ }
24
+ if (currentBytes + codePointBytes > maximumBytes) {
25
+ chunks.push(current);
26
+ current = '';
27
+ currentBytes = 0;
28
+ }
29
+ current += codePoint;
30
+ currentBytes += codePointBytes;
31
+ }
32
+ if (current) chunks.push(current);
33
+ return chunks;
34
+ };
35
+
36
+ export class LogSender {
37
+ private readonly redactors: Record<'stdout' | 'stderr', StreamingSecretRedactor>;
38
+ private sequence = 0;
39
+ private sentBytes = 0;
40
+ private operationQueue: Promise<void> = Promise.resolve();
41
+ private terminalError: unknown;
42
+ private observationSequence = 0;
43
+ private readonly lastObservation = { stdout: 0, stderr: 0 };
44
+
45
+ constructor(
46
+ private readonly api: ILogApi,
47
+ private readonly identity: IJobIdentity,
48
+ secrets: Iterable<string>,
49
+ private readonly maximumBytes: number,
50
+ private readonly maximumChunkBytes: number,
51
+ private readonly signal?: AbortSignal,
52
+ ) {
53
+ if (!Number.isSafeInteger(maximumBytes) || maximumBytes < 0) {
54
+ throw new ProtocolError('Maximum total log bytes must be a non-negative integer');
55
+ }
56
+ if (!Number.isSafeInteger(maximumChunkBytes) || maximumChunkBytes <= 0) {
57
+ throw new ProtocolError('Maximum log chunk bytes must be a positive integer');
58
+ }
59
+ const secretValues = [...secrets];
60
+ this.redactors = {
61
+ stdout: new StreamingSecretRedactor(secretValues),
62
+ stderr: new StreamingSecretRedactor(secretValues),
63
+ };
64
+ }
65
+
66
+ write(stream: 'stdout' | 'stderr', rawData: string): Promise<void> {
67
+ return this.schedule(async () => {
68
+ this.lastObservation[stream] = ++this.observationSequence;
69
+ await this.sendBatch([{ stream, data: this.redactors[stream].push(rawData) }]);
70
+ });
71
+ }
72
+
73
+ writeRunnerMessage(data: string): Promise<void> {
74
+ return this.schedule(() => this.sendBatch([{ stream: 'runner', data }]));
75
+ }
76
+
77
+ flush(): Promise<void> {
78
+ return this.schedule(async () => {
79
+ const streams: Array<'stdout' | 'stderr'> = ['stdout', 'stderr'];
80
+ streams.sort((left, right) => this.lastObservation[left] - this.lastObservation[right]);
81
+ const writes = streams.map((stream) => ({ stream, data: this.redactors[stream].flush() }));
82
+ await this.sendBatch(writes);
83
+ });
84
+ }
85
+
86
+ private schedule(operation: () => Promise<void>): Promise<void> {
87
+ const result = this.operationQueue.then(async () => {
88
+ if (this.terminalError !== undefined) throw this.terminalError;
89
+ try {
90
+ await operation();
91
+ } catch (error) {
92
+ this.terminalError = error;
93
+ throw error;
94
+ }
95
+ });
96
+ this.operationQueue = result.catch(() => undefined);
97
+ return result;
98
+ }
99
+
100
+ private async sendBatch(writes: ILogWrite[]): Promise<void> {
101
+ const nonEmpty = writes.filter((write) => write.data.length > 0);
102
+ const batchBytes = nonEmpty.reduce((total, write) => {
103
+ const next = total + utf8Length(write.data);
104
+ if (!Number.isSafeInteger(next)) throw new ProtocolError('Log byte count overflow');
105
+ return next;
106
+ }, 0);
107
+ if (batchBytes > this.maximumBytes - this.sentBytes) {
108
+ throw new ProtocolError('Redacted log output exceeds the negotiated total byte limit');
109
+ }
110
+ const chunks = nonEmpty.flatMap((write) =>
111
+ splitByUtf8Bytes(write.data, this.maximumChunkBytes).map((data) => ({
112
+ stream: write.stream,
113
+ data,
114
+ }))
115
+ );
116
+ for (const value of chunks) {
117
+ if (this.signal?.aborted) throw this.signal.reason;
118
+ const sequence = this.sequence;
119
+ const chunk: ILogChunk = {
120
+ identity: this.identity,
121
+ sequence,
122
+ stream: value.stream,
123
+ data: value.data,
124
+ timestamp: new Date().toISOString(),
125
+ };
126
+ const acknowledgement = await this.api.appendLog(chunk, this.signal);
127
+ if (acknowledgement.nextSequence !== sequence + 1) {
128
+ throw new ProtocolError('Coordinator returned an invalid log acknowledgement');
129
+ }
130
+ this.sequence++;
131
+ this.sentBytes += utf8Length(value.data);
132
+ }
133
+ }
134
+ }