-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathindex.ts
More file actions
366 lines (332 loc) · 10.8 KB
/
Copy pathindex.ts
File metadata and controls
366 lines (332 loc) · 10.8 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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
import type { KernelJson } from '@onkernel/sdk';
import { Command } from 'commander';
import fs from 'fs';
import getPort from 'get-port';
import os from 'os';
import path from 'path';
import { packageApp } from './lib/package';
import { getPackageVersion, isPnpmInstalled, isUvInstalled } from './lib/util';
const program = new Command();
// When we package a ts app, we have the option to use a custom kernel sdk dependency in package.json.
// This is useful for local dev.
// KERNEL_NODE_SDK_OVERRIDE=/Users/rafaelgarcia/code/onkernel/kernel/packages/sdk-node
// KERNEL_NODE_SDK_OVERRIDE_VERSION=0.0.1alpha.1
const KERNEL_NODE_SDK_OVERRIDE = process.env.KERNEL_NODE_SDK_OVERRIDE || undefined;
// Same for python...
// KERNEL_PYTHON_SDK_OVERRIDE=/Users/rafaelgarcia/code/onkernel/kernel/packages/sdk-python
// KERNEL_PYTHON_SDK_OVERRIDE_VERSION=0.0.1alpha.1
const KERNEL_PYTHON_SDK_OVERRIDE = process.env.KERNEL_PYTHON_SDK_OVERRIDE || undefined;
// Point to a local version of the boot loader or a specific version
const KERNEL_NODE_BOOT_LOADER_OVERRIDE = process.env.KERNEL_NODE_BOOT_LOADER_OVERRIDE;
const KERNEL_PYTHON_BOOT_LOADER_OVERRIDE = process.env.KERNEL_PYTHON_BOOT_LOADER_OVERRIDE;
program
.name('kernel')
.description('CLI for Kernel deployment and invocation')
.version(getPackageVersion());
program
.command('deploy')
.description('Deploy a Kernel application')
.argument('<entrypoint>', 'Path to entrypoint file (TypeScript or Python)')
.option(
'--local',
'Does not publish the app to Kernel, but installs it on disk for invoking locally',
)
.action(async (entrypoint, options) => {
const resolvedEntrypoint = path.resolve(entrypoint);
if (!fs.existsSync(resolvedEntrypoint)) {
console.error(`Error: Entrypoint ${resolvedEntrypoint} doesn't exist`);
process.exit(1);
}
// package up the app for either uploading or local deployment
const dotKernelDir = await packageApp({
sourceDir: path.dirname(resolvedEntrypoint), // TODO: handle nested entrypoint, i.e. ./src/entrypoint.ts
entrypoint: resolvedEntrypoint,
sdkOverrides: {
node: KERNEL_NODE_SDK_OVERRIDE,
python: KERNEL_PYTHON_SDK_OVERRIDE,
},
bootLoaderOverrides: {
node: KERNEL_NODE_BOOT_LOADER_OVERRIDE,
python: KERNEL_PYTHON_BOOT_LOADER_OVERRIDE,
},
});
if (options.local) {
const kernelJson = JSON.parse(
fs.readFileSync(path.join(dotKernelDir, 'app', 'kernel.json'), 'utf8'),
) as KernelJson;
for (const app of kernelJson.apps) {
if (!app.actions || app.actions.length === 0) {
console.error(`App "${app.name}" has no actions`);
process.exit(1);
}
console.log(
`App "${app.name}" successfully deployed locally and ready to \`kernel invoke --local ${quoteIfNeeded(app.name)} ${quoteIfNeeded(app.actions[0]!.name)}\``,
);
}
} else {
console.log(`Deploying ${resolvedEntrypoint} as "${options.name}"...`);
console.error('TODO: implement cloud :-p');
process.exit(1);
}
});
function quoteIfNeeded(str: string) {
if (str.includes(' ')) {
return `"${str}"`;
}
return str;
}
program
.command('invoke')
.description('Invoke a deployed Kernel application')
.option('--local', 'Invoke a locally deployed application')
.argument('<app_name>', 'Name of the application to invoke')
.argument('<action_name>', 'Name of the action to invoke')
.argument('<payload>', 'JSON payload to send to the application')
.action(async (appName, actionName, payload, options) => {
let parsedPayload;
try {
parsedPayload = JSON.parse(payload);
} catch (error) {
console.error('Error: Invalid JSON payload');
process.exit(1);
}
if (!options.local) {
console.log(`Invoking "${options.name}" in the cloud is not implemented yet`);
process.exit(1);
}
console.log(`Invoking "${appName}" with action "${actionName}" and payload:`);
console.log(JSON.stringify(parsedPayload, null, 2));
// Get the app directory
const cacheFile = path.join(
os.homedir(),
'.local',
'state',
'kernel',
'deploy',
'local',
appName,
);
if (!fs.existsSync(cacheFile)) {
console.error(`Error: App "${appName}" local deployment not found. `);
console.error('Did you `kernel deploy --local <entrypoint>`?');
process.exit(1);
}
const kernelLocalDir = fs.readFileSync(cacheFile, 'utf8').trim();
if (!fs.existsSync(kernelLocalDir)) {
console.error(
`Error: App "${appName}" local deployment has been corrupted, please re-deploy.`,
);
process.exit(1);
}
const isPythonApp = fs.existsSync(path.join(kernelLocalDir, 'pyproject.toml'));
const isTypeScriptApp = fs.existsSync(path.join(kernelLocalDir, 'package.json'));
const invokeOptions: InvokeLocalOptions = {
kernelLocalDir,
appName,
actionName,
parsedPayload,
};
try {
if (isPythonApp) {
await invokeLocalPython(invokeOptions);
} else if (isTypeScriptApp) {
await invokeLocalNode(invokeOptions);
} else {
throw new Error(`Unsupported app type in ${kernelLocalDir}`);
}
} catch (error) {
console.error('Error invoking application:', error);
process.exit(1);
}
});
/**
* Waits for a process to output a startup message while echoing stderr
*/
async function waitForStartupMessage(
childProcess: { stderr: ReadableStream },
timeoutMs: number = 30000,
): Promise<void> {
return new Promise<void>(async (resolve, reject) => {
const timeout = setTimeout(() => {
reject(new Error('Timeout waiting for application startup.'));
}, timeoutMs);
const reader = childProcess.stderr.getReader();
const decoder = new TextDecoder();
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
const text = decoder.decode(value);
process.stderr.write(text);
if (
text.includes('Application startup complete.') ||
text.includes('Kernel application running')
) {
clearTimeout(timeout);
resolve();
break;
}
}
} finally {
reader.releaseLock();
}
});
}
type InvokeLocalOptions = {
kernelLocalDir: string;
appName: string;
actionName: string;
parsedPayload: any;
};
/**
* Invokes a locally deployed Python app action
*/
async function invokeLocalPython({
kernelLocalDir,
appName,
actionName,
parsedPayload,
}: InvokeLocalOptions) {
const uvInstalled = await isUvInstalled();
if (!uvInstalled) {
console.error('Error: uv is not installed. Please install it with:');
console.error(' curl -LsSf https://astral.sh/uv/install.sh | sh');
process.exit(1);
}
// load kernel.json for entrypoint
const kernelJson = JSON.parse(
fs.readFileSync(path.join(kernelLocalDir, 'app', 'kernel.json'), 'utf8'),
) as KernelJson;
const entrypoint = kernelJson.entrypoint;
if (!entrypoint) {
throw new Error('Local deployment does not have an entrypoint, please try re-deploying.');
}
// Find an available port and start the boot loader
const port = await getPort();
const pythonProcess = Bun.spawn(
['uv', 'run', '--no-cache', 'python', 'main.py', './app', '--port', port.toString()],
{
cwd: kernelLocalDir,
stdio: ['inherit', 'inherit', 'pipe'],
env: process.env,
},
);
try {
await waitForStartupMessage(pythonProcess);
} catch (error) {
console.error('Error while waiting for application to start:', error);
pythonProcess.kill();
process.exit(1);
}
try {
await requestAppAction({ port, appName, actionName, parsedPayload });
} catch (error) {
console.error('Error invoking application:', error);
} finally {
console.log('Shutting down boot server...');
pythonProcess.kill();
}
}
/**
* Invokes a locally deployed TypeScript app action
*/
async function invokeLocalNode({
kernelLocalDir,
appName,
actionName,
parsedPayload,
}: InvokeLocalOptions) {
const pnpmInstalled = await isPnpmInstalled();
if (!pnpmInstalled) {
console.error('Error: pnpm is not installed. Please install it with:');
console.error(' npm install -g pnpm');
process.exit(1);
}
// load kernel.json for entrypoint
const kernelJson = JSON.parse(
fs.readFileSync(path.join(kernelLocalDir, 'app', 'kernel.json'), 'utf8'),
) as KernelJson;
const entrypoint = kernelJson.entrypoint;
if (!entrypoint) {
throw new Error('Local deployment does not have an entrypoint, please try re-deploying.');
}
// Find an available port and start the boot loader
const port = await getPort();
const tsProcess = Bun.spawn(
[
'pnpm',
'exec',
'tsx',
'index.ts',
'--port',
port.toString(),
path.join(kernelLocalDir, 'app'),
],
{
cwd: kernelLocalDir,
stdio: ['inherit', 'inherit', 'pipe'],
env: process.env,
},
);
try {
await waitForStartupMessage(tsProcess);
} catch (error) {
console.error('Error while waiting for application to start:', error);
tsProcess.kill();
process.exit(1);
}
try {
await requestAppAction({ port, appName, actionName, parsedPayload });
} catch (error) {
console.error('Error invoking application:', error);
} finally {
console.log('Shutting down boot server...');
tsProcess.kill();
}
}
async function requestAppAction({
port,
appName,
actionName,
parsedPayload,
}: {
port: number;
appName: string;
actionName: string;
parsedPayload: any;
}): Promise<any> {
let serverReached = false;
try {
const healthCheck = await fetch(`http://localhost:${port}/`, {
method: 'GET',
}).catch(() => null);
if (!healthCheck) {
throw new Error(`Could not connect to boot server at http://localhost:${port}/`);
}
serverReached = true;
} catch (error) {
console.error('Error connecting to boot server:', error);
console.error('The boot server might not have started correctly.');
process.exit(1);
}
const response = await fetch(`http://localhost:${port}/apps/${appName}/actions/${actionName}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(parsedPayload),
}).catch((error) => {
console.error(`Failed to connect to action endpoint: ${error.message}`);
throw new Error(
`Could not connect to action endpoint at http://localhost:${port}/apps/${appName}/actions/${actionName}`,
);
});
if (!response.ok) {
const errorText = await response.text().catch(() => 'Unknown error');
throw new Error(`HTTP error ${response.status}: ${errorText}`);
}
const result = await response.json();
console.log('Result:', JSON.stringify(result, null, 2));
return result;
}
program.parse();