@getenergy/gke-sandboxes 0.0.0-stage → 0.2.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,34 @@
1
+ export declare class KubernetesApiError extends Error {
2
+ readonly status: number;
3
+ constructor(status: number, message: string);
4
+ }
5
+ export type KubernetesExecResult = {
6
+ exitCode: number;
7
+ output: string;
8
+ };
9
+ /** The few Kubernetes API calls sandboxes need: JSON resources, watches and exec. */
10
+ export declare class KubernetesApi {
11
+ private readonly baseUrl;
12
+ private readonly accessToken;
13
+ constructor(baseUrl: string, accessToken: () => Promise<string>);
14
+ /**
15
+ * Returns `null` for a missing resource and throws `KubernetesApiError` for other failures. A
16
+ * POST has no resource to miss: its 404 means the namespace or resource type does not exist. A
17
+ * PATCH body is a JSON Patch when it is an array and a merge patch otherwise.
18
+ */
19
+ request(method: 'GET' | 'POST' | 'PATCH' | 'DELETE', path: string, body?: unknown): Promise<unknown>;
20
+ /**
21
+ * Waits for the resource `name` of `collection` to become what `until` accepts, and returns
22
+ * what `until` returned for it. `until` is given the resource, or `null` while there is none,
23
+ * and returns `undefined` to keep waiting. The resource is read once and then watched, so the
24
+ * server reports each change as it happens.
25
+ *
26
+ * Returns `undefined` when `deadline`, a time in milliseconds, passes first, and rejects with
27
+ * the signal's reason when it aborts.
28
+ */
29
+ watch<T>(collection: string, name: string, until: (resource: unknown) => T | undefined, deadline: number, signal: AbortSignal | null): Promise<T | undefined>;
30
+ /** One watch's events, until the server ends it, the connection breaks or `ended` aborts. */
31
+ private events;
32
+ /** Runs a command in a pod's container, feeding it `stdin` and collecting its output. */
33
+ exec(podPath: string, command: string[], stdin: Uint8Array, timeoutSeconds: number): Promise<KubernetesExecResult>;
34
+ }
@@ -0,0 +1,216 @@
1
+ import { z } from 'zod';
2
+ const ExecStatusSchema = z.object({
3
+ status: z.enum(['Success', 'Failure']),
4
+ message: z.string().optional(),
5
+ details: z
6
+ .object({ causes: z.array(z.object({ reason: z.string(), message: z.string() })).optional() })
7
+ .optional(),
8
+ });
9
+ // Kubernetes multiplexes an exec session's streams over one WebSocket: the first byte of every
10
+ // frame names the stream. Version 5 adds the close frame that ends stdin.
11
+ const EXEC_PROTOCOL = 'v5.channel.k8s.io';
12
+ const STDIN = 0;
13
+ const STDOUT = 1;
14
+ const STDERR = 2;
15
+ const STATUS = 3;
16
+ const CLOSE = 255;
17
+ const STDIN_CHUNK_BYTES = 256 * 1024;
18
+ const GONE = 410;
19
+ const WatchedSchema = z.object({ metadata: z.object({ resourceVersion: z.string() }) });
20
+ const WatchEventSchema = z.object({
21
+ type: z.enum(['ADDED', 'MODIFIED', 'DELETED', 'BOOKMARK', 'ERROR']),
22
+ object: z.unknown(),
23
+ });
24
+ // What an `ERROR` event carries.
25
+ const WatchStatusSchema = z.object({ code: z.number(), message: z.string().default('') });
26
+ export class KubernetesApiError extends Error {
27
+ status;
28
+ constructor(status, message) {
29
+ super(message);
30
+ this.status = status;
31
+ this.name = 'KubernetesApiError';
32
+ }
33
+ }
34
+ /** The few Kubernetes API calls sandboxes need: JSON resources, watches and exec. */
35
+ export class KubernetesApi {
36
+ baseUrl;
37
+ accessToken;
38
+ constructor(baseUrl, accessToken) {
39
+ this.baseUrl = baseUrl;
40
+ this.accessToken = accessToken;
41
+ }
42
+ /**
43
+ * Returns `null` for a missing resource and throws `KubernetesApiError` for other failures. A
44
+ * POST has no resource to miss: its 404 means the namespace or resource type does not exist. A
45
+ * PATCH body is a JSON Patch when it is an array and a merge patch otherwise.
46
+ */
47
+ async request(method, path, body) {
48
+ const response = await fetch(new URL(path, this.baseUrl), {
49
+ method,
50
+ headers: {
51
+ authorization: `Bearer ${await this.accessToken()}`,
52
+ ...(body === undefined
53
+ ? {}
54
+ : {
55
+ 'content-type': method !== 'PATCH'
56
+ ? 'application/json'
57
+ : Array.isArray(body)
58
+ ? 'application/json-patch+json'
59
+ : 'application/merge-patch+json',
60
+ }),
61
+ },
62
+ body: body === undefined ? undefined : JSON.stringify(body),
63
+ redirect: 'error',
64
+ signal: AbortSignal.timeout(60_000),
65
+ });
66
+ if (response.status === 404 && method !== 'POST')
67
+ return null;
68
+ if (!response.ok)
69
+ throw new KubernetesApiError(response.status, `Kubernetes ${method} ${path} failed (HTTP ${response.status}): ${(await response.text()).slice(0, 500)}`);
70
+ return response.json();
71
+ }
72
+ /**
73
+ * Waits for the resource `name` of `collection` to become what `until` accepts, and returns
74
+ * what `until` returned for it. `until` is given the resource, or `null` while there is none,
75
+ * and returns `undefined` to keep waiting. The resource is read once and then watched, so the
76
+ * server reports each change as it happens.
77
+ *
78
+ * Returns `undefined` when `deadline`, a time in milliseconds, passes first, and rejects with
79
+ * the signal's reason when it aborts.
80
+ */
81
+ async watch(collection, name, until, deadline, signal) {
82
+ const expired = AbortSignal.timeout(Math.max(0, deadline - Date.now()));
83
+ const ended = signal ? AbortSignal.any([signal, expired]) : expired;
84
+ // The server ends a watch whenever it likes, and refuses one from a version it no longer
85
+ // remembers. The resource is then read again and watched from the version it has by then, so
86
+ // no change is missed in between.
87
+ while (true) {
88
+ const resource = await this.request('GET', `${collection}/${name}`);
89
+ const found = until(resource);
90
+ if (found !== undefined)
91
+ return found;
92
+ const url = new URL(collection, this.baseUrl);
93
+ url.searchParams.set('watch', '1');
94
+ url.searchParams.set('fieldSelector', `metadata.name=${name}`);
95
+ // Without a version the server starts from what exists now, which is nothing.
96
+ if (resource)
97
+ url.searchParams.set('resourceVersion', WatchedSchema.parse(resource).metadata.resourceVersion);
98
+ for await (const event of this.events(url, ended)) {
99
+ if (event.type === 'BOOKMARK')
100
+ continue;
101
+ if (event.type === 'ERROR') {
102
+ const status = WatchStatusSchema.parse(event.object);
103
+ if (status.code === GONE)
104
+ break;
105
+ throw new KubernetesApiError(status.code, `Kubernetes watch of ${collection}/${name} failed (HTTP ${status.code}): ${status.message.slice(0, 500)}`);
106
+ }
107
+ const changed = until(event.type === 'DELETED' ? null : event.object);
108
+ if (changed !== undefined)
109
+ return changed;
110
+ }
111
+ signal?.throwIfAborted();
112
+ if (expired.aborted)
113
+ return undefined;
114
+ }
115
+ }
116
+ /** One watch's events, until the server ends it, the connection breaks or `ended` aborts. */
117
+ async *events(url, ended) {
118
+ // Whoever stops reading closes the connection.
119
+ const closed = new AbortController();
120
+ try {
121
+ const response = await fetch(url, {
122
+ headers: { authorization: `Bearer ${await this.accessToken()}` },
123
+ redirect: 'error',
124
+ signal: AbortSignal.any([ended, closed.signal]),
125
+ }).catch((error) => {
126
+ if (ended.aborted)
127
+ return null;
128
+ throw error;
129
+ });
130
+ if (!response || response.status === GONE)
131
+ return;
132
+ if (!response.ok || !response.body)
133
+ throw new KubernetesApiError(response.status, `Kubernetes watch ${url.pathname} failed (HTTP ${response.status}): ${(await response.text()).slice(0, 500)}`);
134
+ const reader = response.body.getReader();
135
+ const decoder = new TextDecoder();
136
+ // One event per line; a line may arrive in pieces.
137
+ let partial = '';
138
+ while (true) {
139
+ // A connection that breaks is a watch that ended early.
140
+ const chunk = await reader.read().catch(() => null);
141
+ if (!chunk || chunk.done)
142
+ return;
143
+ const lines = (partial + decoder.decode(chunk.value, { stream: true })).split('\n');
144
+ partial = lines.pop();
145
+ for (const line of lines)
146
+ if (line)
147
+ yield WatchEventSchema.parse(JSON.parse(line));
148
+ }
149
+ }
150
+ finally {
151
+ closed.abort();
152
+ }
153
+ }
154
+ /** Runs a command in a pod's container, feeding it `stdin` and collecting its output. */
155
+ async exec(podPath, command, stdin, timeoutSeconds) {
156
+ const url = new URL(`${podPath}/exec`, this.baseUrl);
157
+ url.protocol = 'wss:';
158
+ for (const stream of ['stdin', 'stdout', 'stderr'])
159
+ url.searchParams.set(stream, 'true');
160
+ for (const argument of command)
161
+ url.searchParams.append('command', argument);
162
+ // Bun's and Node's WebSocket accept request headers in an options object; the standard
163
+ // constructor has no way to send them.
164
+ const socket = new WebSocket(url, {
165
+ headers: { authorization: `Bearer ${await this.accessToken()}` },
166
+ protocols: [EXEC_PROTOCOL],
167
+ });
168
+ socket.binaryType = 'arraybuffer';
169
+ const finished = Promise.withResolvers();
170
+ const output = [];
171
+ const timer = setTimeout(() => {
172
+ finished.reject(new Error(`Sandbox command timed out after ${timeoutSeconds} seconds.`));
173
+ socket.close();
174
+ }, timeoutSeconds * 1000);
175
+ socket.onopen = () => {
176
+ for (let offset = 0; offset < stdin.byteLength; offset += STDIN_CHUNK_BYTES) {
177
+ const chunk = stdin.subarray(offset, offset + STDIN_CHUNK_BYTES);
178
+ const frame = new Uint8Array(chunk.byteLength + 1);
179
+ frame[0] = STDIN;
180
+ frame.set(chunk, 1);
181
+ socket.send(frame);
182
+ }
183
+ socket.send(new Uint8Array([CLOSE, STDIN]));
184
+ };
185
+ socket.onmessage = ({ data }) => {
186
+ const frame = new Uint8Array(data);
187
+ const payload = frame.subarray(1);
188
+ if (frame[0] === STDOUT || frame[0] === STDERR)
189
+ output.push(payload);
190
+ if (frame[0] !== STATUS)
191
+ return;
192
+ // GKE sends the final status after stdout and stderr. Node can keep the socket
193
+ // open after this frame, so waiting for a close event can time out a finished command.
194
+ try {
195
+ const status = ExecStatusSchema.parse(JSON.parse(new TextDecoder().decode(payload)));
196
+ const exitCode = status.details?.causes?.find(({ reason }) => reason === 'ExitCode');
197
+ if (status.status === 'Failure' && !exitCode) {
198
+ finished.reject(new Error(`Sandbox command failed: ${status.message}`));
199
+ }
200
+ else {
201
+ finished.resolve({
202
+ exitCode: exitCode ? Number(exitCode.message) : 0,
203
+ output: Buffer.concat(output).toString('utf8'),
204
+ });
205
+ }
206
+ }
207
+ catch (error) {
208
+ finished.reject(new Error('Sandbox command returned an unreadable status.', { cause: error }));
209
+ }
210
+ socket.close();
211
+ };
212
+ socket.onerror = () => finished.reject(new Error('Sandbox command connection failed.'));
213
+ socket.onclose = () => finished.reject(new Error('Sandbox command ended without a status.'));
214
+ return finished.promise.finally(() => clearTimeout(timer));
215
+ }
216
+ }
package/package.json CHANGED
@@ -1,6 +1,36 @@
1
1
  {
2
2
  "name": "@getenergy/gke-sandboxes",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "type": "module",
5
+ "exports": {
6
+ ".": {
7
+ "types": "./dist/index.d.ts",
8
+ "default": "./dist/index.js"
9
+ }
10
+ },
11
+ "engines": {
12
+ "node": ">=22",
13
+ "bun": ">=1.4.4"
14
+ },
15
+ "dependencies": {
16
+ "zod": "^4.4.3"
17
+ },
18
+ "description": "Run persistent, isolated workspaces on your own GKE cluster.",
19
+ "license": "Apache-2.0",
20
+ "files": [
21
+ "dist",
22
+ "README.md",
23
+ "LICENSE"
24
+ ],
25
+ "packageManager": "bun@1.4.4",
26
+ "scripts": {
27
+ "build": "rm -rf dist && tsc -p tsconfig.build.json",
28
+ "prepack": "bun run build",
29
+ "test": "bun test ./src",
30
+ "typecheck": "tsc --noEmit"
31
+ },
32
+ "devDependencies": {
33
+ "@types/bun": "^1.3.13",
34
+ "typescript": "^7.0.2"
35
+ }
36
+ }