@sharedots/cli 0.1.2 → 0.1.3
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.
- package/bin/.gitkeep +1 -0
- package/bin/sharedots-daemon.exe +0 -0
- package/dist/index.js +43567 -430
- package/dist/node-worker.js +8457 -0
- package/package.json +13 -6
- package/dist/daemon-runner.d.ts +0 -32
- package/dist/daemon-runner.d.ts.map +0 -1
- package/dist/daemon-runner.js +0 -132
- package/dist/daemon-runner.js.map +0 -1
- package/dist/index.d.ts +0 -3
- package/dist/index.d.ts.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/job-runner.d.ts +0 -81
- package/dist/job-runner.d.ts.map +0 -1
- package/dist/job-runner.js +0 -544
- package/dist/job-runner.js.map +0 -1
- package/dist/parser.d.ts +0 -5
- package/dist/parser.d.ts.map +0 -1
- package/dist/parser.js +0 -81
- package/dist/parser.js.map +0 -1
- package/dist/up-wizard.d.ts +0 -21
- package/dist/up-wizard.d.ts.map +0 -1
- package/dist/up-wizard.js +0 -298
- package/dist/up-wizard.js.map +0 -1
- package/src/cli.test.ts +0 -69
- package/src/daemon-runner.ts +0 -165
- package/src/index.ts +0 -526
- package/src/job-runner.test.ts +0 -287
- package/src/job-runner.ts +0 -645
- package/src/parser.ts +0 -77
- package/src/up-wizard.ts +0 -339
- package/tsconfig.json +0 -12
package/src/job-runner.ts
DELETED
|
@@ -1,645 +0,0 @@
|
|
|
1
|
-
import { spawnSync } from "node:child_process";
|
|
2
|
-
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
3
|
-
import os from "node:os";
|
|
4
|
-
import { basename, dirname, join, resolve } from "node:path";
|
|
5
|
-
import readline from "node:readline";
|
|
6
|
-
import type { ArtifactRef, JobSpecInput, TaskSpec } from "@sharedots/protocol";
|
|
7
|
-
import { Room, Sharedots } from "sharedots";
|
|
8
|
-
import { readConfig } from "./daemon-runner.js";
|
|
9
|
-
|
|
10
|
-
const DEFAULT_COORDINATOR = "https://sharedots.onrender.com";
|
|
11
|
-
|
|
12
|
-
const EMBEDDED_MONTE_CARLO_PY = `"""Sharedots Monte Carlo Pi Estimation Task"""
|
|
13
|
-
import argparse
|
|
14
|
-
import json
|
|
15
|
-
import os
|
|
16
|
-
import random
|
|
17
|
-
import sys
|
|
18
|
-
import time
|
|
19
|
-
|
|
20
|
-
def main():
|
|
21
|
-
parser = argparse.ArgumentParser()
|
|
22
|
-
parser.add_argument("--trials", type=int, default=5000)
|
|
23
|
-
parser.add_argument("--seed", type=int, default=1000)
|
|
24
|
-
parser.add_argument("--partition", type=int, default=0)
|
|
25
|
-
parser.add_argument("--partitions", type=int, default=1)
|
|
26
|
-
args, _ = parser.parse_known_args()
|
|
27
|
-
|
|
28
|
-
random.seed(args.seed + args.partition * 42)
|
|
29
|
-
start = time.time()
|
|
30
|
-
inside = 0
|
|
31
|
-
for _ in range(args.trials):
|
|
32
|
-
x = random.random()
|
|
33
|
-
y = random.random()
|
|
34
|
-
if x * x + y * y <= 1.0:
|
|
35
|
-
inside += 1
|
|
36
|
-
|
|
37
|
-
duration = time.time() - start
|
|
38
|
-
pi_estimate = 4.0 * inside / max(1, args.trials)
|
|
39
|
-
|
|
40
|
-
output = {
|
|
41
|
-
"partition": args.partition,
|
|
42
|
-
"partitions": args.partitions,
|
|
43
|
-
"trials": args.trials,
|
|
44
|
-
"seed": args.seed,
|
|
45
|
-
"inside": inside,
|
|
46
|
-
"pi_estimate": pi_estimate,
|
|
47
|
-
"duration_sec": round(duration, 4),
|
|
48
|
-
"worker_pid": os.getpid(),
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
output_path = os.environ.get("SHAREDOTS_OUTPUT_PATH")
|
|
52
|
-
if output_path:
|
|
53
|
-
os.makedirs(os.path.dirname(output_path), exist_ok=True)
|
|
54
|
-
with open(output_path, "w", encoding="utf-8") as f:
|
|
55
|
-
json.dump(output, f, indent=2)
|
|
56
|
-
|
|
57
|
-
print(json.dumps(output))
|
|
58
|
-
|
|
59
|
-
if __name__ == "__main__":
|
|
60
|
-
main()
|
|
61
|
-
`;
|
|
62
|
-
|
|
63
|
-
const EMBEDDED_MATMUL_PY = `"""Sharedots Synthetic Block Matrix Multiplication Task"""
|
|
64
|
-
import argparse
|
|
65
|
-
import json
|
|
66
|
-
import os
|
|
67
|
-
import sys
|
|
68
|
-
import time
|
|
69
|
-
|
|
70
|
-
def main():
|
|
71
|
-
parser = argparse.ArgumentParser()
|
|
72
|
-
parser.add_argument("--size", type=int, default=512)
|
|
73
|
-
parser.add_argument("--partition", type=int, default=0)
|
|
74
|
-
parser.add_argument("--partitions", type=int, default=4)
|
|
75
|
-
args, _ = parser.parse_known_args()
|
|
76
|
-
|
|
77
|
-
start = time.time()
|
|
78
|
-
rows = max(1, args.size // args.partitions)
|
|
79
|
-
# Simulate block computation
|
|
80
|
-
checksum = sum((args.partition + 1) * (i + 1) for i in range(rows * 100))
|
|
81
|
-
duration = time.time() - start
|
|
82
|
-
|
|
83
|
-
output = {
|
|
84
|
-
"partition": args.partition,
|
|
85
|
-
"partitions": args.partitions,
|
|
86
|
-
"size": args.size,
|
|
87
|
-
"rows": rows,
|
|
88
|
-
"checksum": checksum,
|
|
89
|
-
"duration_sec": round(duration, 4),
|
|
90
|
-
"worker_pid": os.getpid(),
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
output_path = os.environ.get("SHAREDOTS_OUTPUT_PATH")
|
|
94
|
-
if output_path:
|
|
95
|
-
os.makedirs(os.path.dirname(output_path), exist_ok=True)
|
|
96
|
-
with open(output_path, "w", encoding="utf-8") as f:
|
|
97
|
-
json.dump(output, f, indent=2)
|
|
98
|
-
|
|
99
|
-
print(json.dumps(output))
|
|
100
|
-
|
|
101
|
-
if __name__ == "__main__":
|
|
102
|
-
main()
|
|
103
|
-
`;
|
|
104
|
-
|
|
105
|
-
export function promptUser(query: string): Promise<string> {
|
|
106
|
-
const rl = readline.createInterface({
|
|
107
|
-
input: process.stdin,
|
|
108
|
-
output: process.stdout,
|
|
109
|
-
});
|
|
110
|
-
return new Promise((res) => {
|
|
111
|
-
rl.question(query, (ans) => {
|
|
112
|
-
rl.close();
|
|
113
|
-
res(ans.trim());
|
|
114
|
-
});
|
|
115
|
-
});
|
|
116
|
-
}
|
|
117
|
-
|
|
118
|
-
export interface ScriptRunOptions {
|
|
119
|
-
scriptPath: string;
|
|
120
|
-
coordinator?: string;
|
|
121
|
-
roomId?: string;
|
|
122
|
-
token?: string;
|
|
123
|
-
partitions?: number;
|
|
124
|
-
args?: string[];
|
|
125
|
-
cpu?: number;
|
|
126
|
-
memory?: string;
|
|
127
|
-
gpu?: boolean;
|
|
128
|
-
timeout?: number;
|
|
129
|
-
priority?: number;
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
export function buildScriptJobSpec(options: {
|
|
133
|
-
scriptName: string;
|
|
134
|
-
artifact: ArtifactRef;
|
|
135
|
-
partitions?: number;
|
|
136
|
-
args?: string[];
|
|
137
|
-
cpu?: number;
|
|
138
|
-
memory?: string;
|
|
139
|
-
gpu?: boolean;
|
|
140
|
-
timeout?: number;
|
|
141
|
-
priority?: number;
|
|
142
|
-
}): JobSpecInput {
|
|
143
|
-
const partitions = options.partitions && options.partitions > 0 ? options.partitions : 4;
|
|
144
|
-
const scriptBase = basename(options.scriptName, options.scriptName.includes(".") ? options.scriptName.slice(options.scriptName.lastIndexOf(".")) : "");
|
|
145
|
-
const extraArgs = options.args ?? [];
|
|
146
|
-
|
|
147
|
-
const tasks: TaskSpec[] = [];
|
|
148
|
-
for (let i = 0; i < partitions; i++) {
|
|
149
|
-
tasks.push({
|
|
150
|
-
index: i,
|
|
151
|
-
name: `${scriptBase}-task-${i + 1}`,
|
|
152
|
-
entrypoint: options.scriptName,
|
|
153
|
-
args: [...extraArgs, "--partition", String(i), "--partitions", String(partitions)],
|
|
154
|
-
env: {},
|
|
155
|
-
inputs: [options.artifact],
|
|
156
|
-
outputFilename: `output_task_${i}.json`,
|
|
157
|
-
metadata: { partition: i, partitions },
|
|
158
|
-
});
|
|
159
|
-
}
|
|
160
|
-
|
|
161
|
-
const isWasm = options.scriptName.endsWith(".wasm");
|
|
162
|
-
|
|
163
|
-
return {
|
|
164
|
-
specVersion: 1,
|
|
165
|
-
name: `run-${scriptBase}`,
|
|
166
|
-
runtime: isWasm ? "wasm" : "python",
|
|
167
|
-
execution: {
|
|
168
|
-
strategy: "task-parallel",
|
|
169
|
-
workers: "auto",
|
|
170
|
-
partitions,
|
|
171
|
-
},
|
|
172
|
-
resources: {
|
|
173
|
-
cpu: options.cpu ?? 1,
|
|
174
|
-
memory: options.memory ?? "512MB",
|
|
175
|
-
gpu: options.gpu ? "required" : "optional",
|
|
176
|
-
},
|
|
177
|
-
timeoutSec: options.timeout ?? 300,
|
|
178
|
-
retry: { maxAttempts: 2 },
|
|
179
|
-
priority: options.priority ?? 60,
|
|
180
|
-
sharedArtifacts: [options.artifact],
|
|
181
|
-
tasks,
|
|
182
|
-
aggregation: {
|
|
183
|
-
type: "collect-json",
|
|
184
|
-
outputFilename: "aggregated_output.json",
|
|
185
|
-
},
|
|
186
|
-
};
|
|
187
|
-
}
|
|
188
|
-
|
|
189
|
-
export function buildPresetMonteCarloSpec(options: {
|
|
190
|
-
trials?: number;
|
|
191
|
-
partitions?: number;
|
|
192
|
-
artifact?: ArtifactRef;
|
|
193
|
-
}): JobSpecInput {
|
|
194
|
-
const totalTrials = options.trials ?? 20000;
|
|
195
|
-
const partitions = options.partitions ?? 4;
|
|
196
|
-
const trialsPerTask = Math.floor(totalTrials / partitions);
|
|
197
|
-
|
|
198
|
-
const tasks: TaskSpec[] = [];
|
|
199
|
-
for (let i = 0; i < partitions; i++) {
|
|
200
|
-
const taskTrials = i === partitions - 1 ? totalTrials - i * trialsPerTask : trialsPerTask;
|
|
201
|
-
tasks.push({
|
|
202
|
-
index: i,
|
|
203
|
-
name: `monte-carlo-batch-${i + 1}`,
|
|
204
|
-
entrypoint: "monte_carlo.py",
|
|
205
|
-
args: ["--trials", String(taskTrials), "--seed", String(1000 + i * 42), "--partition", String(i), "--partitions", String(partitions)],
|
|
206
|
-
env: {},
|
|
207
|
-
inputs: options.artifact ? [options.artifact] : [],
|
|
208
|
-
outputFilename: `trials_${i}.json`,
|
|
209
|
-
metadata: { trials: taskTrials, batchIndex: i },
|
|
210
|
-
});
|
|
211
|
-
}
|
|
212
|
-
|
|
213
|
-
return {
|
|
214
|
-
specVersion: 1,
|
|
215
|
-
name: `monte-carlo-sweep-${totalTrials}-trials`,
|
|
216
|
-
runtime: "python",
|
|
217
|
-
execution: {
|
|
218
|
-
strategy: "task-parallel",
|
|
219
|
-
workers: "auto",
|
|
220
|
-
partitions,
|
|
221
|
-
},
|
|
222
|
-
resources: { cpu: 1, memory: "256MB", gpu: "none" },
|
|
223
|
-
timeoutSec: 180,
|
|
224
|
-
retry: { maxAttempts: 2 },
|
|
225
|
-
priority: 50,
|
|
226
|
-
sharedArtifacts: options.artifact ? [options.artifact] : [],
|
|
227
|
-
tasks,
|
|
228
|
-
aggregation: {
|
|
229
|
-
type: "collect-json",
|
|
230
|
-
outputFilename: "simulation_summary.json",
|
|
231
|
-
},
|
|
232
|
-
};
|
|
233
|
-
}
|
|
234
|
-
|
|
235
|
-
export function buildPresetMatrixMultSpec(options: {
|
|
236
|
-
matrixSize?: number;
|
|
237
|
-
partitions?: number;
|
|
238
|
-
artifact?: ArtifactRef;
|
|
239
|
-
}): JobSpecInput {
|
|
240
|
-
const size = options.matrixSize ?? 1024;
|
|
241
|
-
const partitions = options.partitions ?? 4;
|
|
242
|
-
const rowsPerPartition = Math.floor(size / partitions);
|
|
243
|
-
|
|
244
|
-
const tasks: TaskSpec[] = [];
|
|
245
|
-
for (let i = 0; i < partitions; i++) {
|
|
246
|
-
const rowStart = i * rowsPerPartition;
|
|
247
|
-
const rowEnd = i === partitions - 1 ? size : (i + 1) * rowsPerPartition;
|
|
248
|
-
tasks.push({
|
|
249
|
-
index: i,
|
|
250
|
-
name: `matmul-block-${i + 1}`,
|
|
251
|
-
entrypoint: "matrix_block.py",
|
|
252
|
-
args: ["--size", String(size), "--row-start", String(rowStart), "--row-end", String(rowEnd), "--partition", String(i), "--partitions", String(partitions)],
|
|
253
|
-
env: {},
|
|
254
|
-
inputs: options.artifact ? [options.artifact] : [],
|
|
255
|
-
outputFilename: `block_${i}.json`,
|
|
256
|
-
metadata: { rowStart, rowEnd, size },
|
|
257
|
-
});
|
|
258
|
-
}
|
|
259
|
-
|
|
260
|
-
return {
|
|
261
|
-
specVersion: 1,
|
|
262
|
-
name: `distributed-matmul-${size}x${size}`,
|
|
263
|
-
runtime: "python",
|
|
264
|
-
execution: {
|
|
265
|
-
strategy: "task-parallel",
|
|
266
|
-
workers: "auto",
|
|
267
|
-
partitions,
|
|
268
|
-
},
|
|
269
|
-
resources: { cpu: 1, memory: "512MB", gpu: "optional" },
|
|
270
|
-
timeoutSec: 300,
|
|
271
|
-
retry: { maxAttempts: 2 },
|
|
272
|
-
priority: 70,
|
|
273
|
-
sharedArtifacts: options.artifact ? [options.artifact] : [],
|
|
274
|
-
tasks,
|
|
275
|
-
aggregation: {
|
|
276
|
-
type: "collect-json",
|
|
277
|
-
outputFilename: "matrix_result.json",
|
|
278
|
-
},
|
|
279
|
-
};
|
|
280
|
-
}
|
|
281
|
-
|
|
282
|
-
export function buildPresetWasmSpec(options: {
|
|
283
|
-
fuelLimit?: number;
|
|
284
|
-
partitions?: number;
|
|
285
|
-
artifact?: ArtifactRef;
|
|
286
|
-
}): JobSpecInput {
|
|
287
|
-
const partitions = options.partitions ?? 2;
|
|
288
|
-
const fuel = options.fuelLimit ?? 1000000;
|
|
289
|
-
|
|
290
|
-
const tasks: TaskSpec[] = [];
|
|
291
|
-
for (let i = 0; i < partitions; i++) {
|
|
292
|
-
tasks.push({
|
|
293
|
-
index: i,
|
|
294
|
-
name: `wasm-task-${i + 1}`,
|
|
295
|
-
entrypoint: "compute.wasm",
|
|
296
|
-
args: ["--fuel", String(fuel), "--partition", String(i), "--partitions", String(partitions)],
|
|
297
|
-
env: {},
|
|
298
|
-
inputs: options.artifact ? [options.artifact] : [],
|
|
299
|
-
outputFilename: `wasm_out_${i}.bin`,
|
|
300
|
-
metadata: { fuel, partition: i },
|
|
301
|
-
});
|
|
302
|
-
}
|
|
303
|
-
|
|
304
|
-
return {
|
|
305
|
-
specVersion: 1,
|
|
306
|
-
name: `wasm-sandboxed-compute-${partitions}-tasks`,
|
|
307
|
-
runtime: "wasm",
|
|
308
|
-
execution: {
|
|
309
|
-
strategy: "task-parallel",
|
|
310
|
-
workers: "auto",
|
|
311
|
-
partitions,
|
|
312
|
-
},
|
|
313
|
-
resources: { cpu: 1, memory: "256MB", gpu: "none" },
|
|
314
|
-
timeoutSec: 120,
|
|
315
|
-
retry: { maxAttempts: 2 },
|
|
316
|
-
priority: 40,
|
|
317
|
-
sharedArtifacts: options.artifact ? [options.artifact] : [],
|
|
318
|
-
tasks,
|
|
319
|
-
aggregation: {
|
|
320
|
-
type: "none",
|
|
321
|
-
},
|
|
322
|
-
};
|
|
323
|
-
}
|
|
324
|
-
|
|
325
|
-
export async function resolveOrConnectRoom(options: {
|
|
326
|
-
coordinator?: string;
|
|
327
|
-
roomId?: string;
|
|
328
|
-
token?: string;
|
|
329
|
-
}): Promise<{ client: Sharedots; room: Room; coordinator: string; roomId: string; token: string }> {
|
|
330
|
-
const cfg = readConfig();
|
|
331
|
-
const coordinator = (options.coordinator ?? process.env.SHAREDOTS_COORDINATOR ?? cfg?.coordinator ?? DEFAULT_COORDINATOR).replace(/\/$/, "");
|
|
332
|
-
let roomId = options.roomId ?? process.env.SHAREDOTS_ROOM_ID ?? cfg?.roomId;
|
|
333
|
-
let token = options.token ?? process.env.SHAREDOTS_TOKEN ?? (options.roomId && options.roomId !== cfg?.roomId ? undefined : cfg?.token);
|
|
334
|
-
|
|
335
|
-
const client = new Sharedots({ coordinator, token });
|
|
336
|
-
|
|
337
|
-
if (!roomId || !token) {
|
|
338
|
-
process.stdout.write(`No active room configured. Creating ephemeral compute room on ${coordinator}... `);
|
|
339
|
-
const created = await client.createRoom(`run-${Date.now().toString(36)}`);
|
|
340
|
-
roomId = created.roomId;
|
|
341
|
-
token = created.secret;
|
|
342
|
-
console.log(`\x1b[32m✔ Created (${roomId})\x1b[0m`);
|
|
343
|
-
}
|
|
344
|
-
|
|
345
|
-
const room = await client.connect(roomId, token);
|
|
346
|
-
return { client, room, coordinator, roomId, token };
|
|
347
|
-
}
|
|
348
|
-
|
|
349
|
-
export async function runScript(options: ScriptRunOptions): Promise<void> {
|
|
350
|
-
const absPath = resolve(options.scriptPath);
|
|
351
|
-
if (!existsSync(absPath)) {
|
|
352
|
-
throw new Error(`Script file not found at ${absPath}`);
|
|
353
|
-
}
|
|
354
|
-
|
|
355
|
-
console.log(`\n\x1b[1m\x1b[36m⚡ SHAREDOTS SCRIPT RUNNER\x1b[0m\n`);
|
|
356
|
-
console.log(`Script: ${absPath}`);
|
|
357
|
-
const partitions = options.partitions ?? 4;
|
|
358
|
-
console.log(`Partitions: ${partitions}`);
|
|
359
|
-
|
|
360
|
-
const { room, coordinator, roomId } = await resolveOrConnectRoom({
|
|
361
|
-
coordinator: options.coordinator,
|
|
362
|
-
roomId: options.roomId,
|
|
363
|
-
token: options.token,
|
|
364
|
-
});
|
|
365
|
-
|
|
366
|
-
console.log(`Coordinator: ${coordinator}`);
|
|
367
|
-
console.log(`Room ID: ${roomId}`);
|
|
368
|
-
|
|
369
|
-
// Upload script artifact
|
|
370
|
-
const scriptName = basename(absPath);
|
|
371
|
-
process.stdout.write(`Packaging script '${scriptName}' as input artifact... `);
|
|
372
|
-
const artifact = await room.uploadArtifact(absPath, scriptName, { shared: true });
|
|
373
|
-
console.log(`\x1b[32m✔ Uploaded (${artifact.artifactId}, ${artifact.sizeBytes} bytes)\x1b[0m`);
|
|
374
|
-
|
|
375
|
-
// Build JobSpec
|
|
376
|
-
const spec = buildScriptJobSpec({
|
|
377
|
-
scriptName,
|
|
378
|
-
artifact,
|
|
379
|
-
partitions,
|
|
380
|
-
args: options.args,
|
|
381
|
-
cpu: options.cpu,
|
|
382
|
-
memory: options.memory,
|
|
383
|
-
gpu: options.gpu,
|
|
384
|
-
timeout: options.timeout,
|
|
385
|
-
priority: options.priority,
|
|
386
|
-
});
|
|
387
|
-
|
|
388
|
-
console.log(`Submitting distributed job '${spec.name}'...`);
|
|
389
|
-
const job = await room.submit(spec);
|
|
390
|
-
console.log(`\x1b[32m✔ Dispatched job ${job.jobId}\x1b[0m\n`);
|
|
391
|
-
|
|
392
|
-
// Stream progress
|
|
393
|
-
job.on("progress", (p) => {
|
|
394
|
-
const percent = Math.min(100, Math.max(0, p.percent));
|
|
395
|
-
const completed = p.completedTasks ?? 0;
|
|
396
|
-
const total = p.totalTasks ?? partitions;
|
|
397
|
-
const barLen = 24;
|
|
398
|
-
const filled = Math.round((percent / 100) * barLen);
|
|
399
|
-
const bar = "█".repeat(filled) + "░".repeat(Math.max(0, barLen - filled));
|
|
400
|
-
process.stdout.write(`\r [${bar}] ${percent}% (${completed}/${total} tasks finished)`);
|
|
401
|
-
});
|
|
402
|
-
|
|
403
|
-
const result = await job.result();
|
|
404
|
-
console.log(`\n\n\x1b[32m✔ Job ${result.jobId} completed successfully! Status: ${result.status.toUpperCase()}\x1b[0m`);
|
|
405
|
-
|
|
406
|
-
if (result.resultArtifactId) {
|
|
407
|
-
console.log(`Result Artifact ID: ${result.resultArtifactId}`);
|
|
408
|
-
try {
|
|
409
|
-
const outBuffer = await room.downloadArtifact(result.resultArtifactId);
|
|
410
|
-
console.log(`\n\x1b[1m--- Aggregated Task Output ---\x1b[0m`);
|
|
411
|
-
console.log(outBuffer.toString("utf8"));
|
|
412
|
-
} catch {
|
|
413
|
-
// Artifact preview unavailable
|
|
414
|
-
}
|
|
415
|
-
}
|
|
416
|
-
}
|
|
417
|
-
|
|
418
|
-
export async function runInteractiveJobRunner(options: {
|
|
419
|
-
coordinator?: string;
|
|
420
|
-
roomId?: string;
|
|
421
|
-
token?: string;
|
|
422
|
-
preset?: string;
|
|
423
|
-
partitions?: number;
|
|
424
|
-
}): Promise<void> {
|
|
425
|
-
console.log(`\n\x1b[1m\x1b[36m⚡ SHAREDOTS INTERACTIVE JOB RUNNER STUDIO\x1b[0m\n`);
|
|
426
|
-
|
|
427
|
-
let presetChoice = options.preset;
|
|
428
|
-
if (!presetChoice) {
|
|
429
|
-
if (process.stdin.isTTY) {
|
|
430
|
-
console.log(`Select a compute workload preset:`);
|
|
431
|
-
console.log(` [1] Monte Carlo Pi (Distributed stochastic sweep)`);
|
|
432
|
-
console.log(` [2] Matrix Multiplication (Distributed block matrix mult)`);
|
|
433
|
-
console.log(` [3] Custom Python (Execute custom Python script)`);
|
|
434
|
-
console.log(` [4] WASM (WebAssembly compute execution)\n`);
|
|
435
|
-
presetChoice = await promptUser(`Select preset [1-4] (default 1): `);
|
|
436
|
-
} else {
|
|
437
|
-
presetChoice = "1";
|
|
438
|
-
}
|
|
439
|
-
}
|
|
440
|
-
|
|
441
|
-
let partitions = options.partitions;
|
|
442
|
-
if (!partitions) {
|
|
443
|
-
if (process.stdin.isTTY) {
|
|
444
|
-
const pAns = await promptUser(`Partitions count [1-16] (default 4): `);
|
|
445
|
-
partitions = parseInt(pAns, 10) || 4;
|
|
446
|
-
} else {
|
|
447
|
-
partitions = 4;
|
|
448
|
-
}
|
|
449
|
-
}
|
|
450
|
-
|
|
451
|
-
const { room, coordinator, roomId } = await resolveOrConnectRoom({
|
|
452
|
-
coordinator: options.coordinator,
|
|
453
|
-
roomId: options.roomId,
|
|
454
|
-
token: options.token,
|
|
455
|
-
});
|
|
456
|
-
|
|
457
|
-
console.log(`\nCoordinator: ${coordinator}`);
|
|
458
|
-
console.log(`Room ID: ${roomId}`);
|
|
459
|
-
console.log(`Partitions: ${partitions}\n`);
|
|
460
|
-
|
|
461
|
-
let spec: JobSpecInput;
|
|
462
|
-
|
|
463
|
-
if (presetChoice === "2") {
|
|
464
|
-
// Matrix Multiplication
|
|
465
|
-
let size = 1024;
|
|
466
|
-
if (process.stdin.isTTY) {
|
|
467
|
-
const sAns = await promptUser(`Matrix dimension N (default 1024): `);
|
|
468
|
-
size = parseInt(sAns, 10) || 1024;
|
|
469
|
-
}
|
|
470
|
-
const matmulPath = existsSync(resolve("matrix_block.py"))
|
|
471
|
-
? resolve("matrix_block.py")
|
|
472
|
-
: join(os.tmpdir(), "sharedots_matrix_block.py");
|
|
473
|
-
if (!existsSync(matmulPath)) {
|
|
474
|
-
writeFileSync(matmulPath, EMBEDDED_MATMUL_PY, "utf8");
|
|
475
|
-
}
|
|
476
|
-
const artifact = await room.uploadArtifact(matmulPath, "matrix_block.py", { shared: true });
|
|
477
|
-
spec = buildPresetMatrixMultSpec({ matrixSize: size, partitions, artifact });
|
|
478
|
-
} else if (presetChoice === "3") {
|
|
479
|
-
// Custom Python
|
|
480
|
-
let scriptPath = "monte_carlo.py";
|
|
481
|
-
if (process.stdin.isTTY) {
|
|
482
|
-
const sAns = await promptUser(`Script file path (default monte_carlo.py): `);
|
|
483
|
-
if (sAns) scriptPath = sAns;
|
|
484
|
-
}
|
|
485
|
-
const resolvedScript = resolve(scriptPath);
|
|
486
|
-
if (!existsSync(resolvedScript)) {
|
|
487
|
-
writeFileSync(resolvedScript, EMBEDDED_MONTE_CARLO_PY, "utf8");
|
|
488
|
-
console.log(`Created sample script at ${resolvedScript}`);
|
|
489
|
-
}
|
|
490
|
-
const artifact = await room.uploadArtifact(resolvedScript, basename(resolvedScript), { shared: true });
|
|
491
|
-
spec = buildScriptJobSpec({
|
|
492
|
-
scriptName: basename(resolvedScript),
|
|
493
|
-
artifact,
|
|
494
|
-
partitions,
|
|
495
|
-
});
|
|
496
|
-
} else if (presetChoice === "4") {
|
|
497
|
-
// WASM
|
|
498
|
-
let fuel = 1000000;
|
|
499
|
-
if (process.stdin.isTTY) {
|
|
500
|
-
const fAns = await promptUser(`Fuel limit per task (default 1000000): `);
|
|
501
|
-
fuel = parseInt(fAns, 10) || 1000000;
|
|
502
|
-
}
|
|
503
|
-
const wasmPath = existsSync(resolve("compute.wasm")) ? resolve("compute.wasm") : undefined;
|
|
504
|
-
let artifact: ArtifactRef | undefined;
|
|
505
|
-
if (wasmPath) {
|
|
506
|
-
artifact = await room.uploadArtifact(wasmPath, "compute.wasm", { shared: true });
|
|
507
|
-
}
|
|
508
|
-
spec = buildPresetWasmSpec({ fuelLimit: fuel, partitions, artifact });
|
|
509
|
-
} else {
|
|
510
|
-
// Monte Carlo Pi (Default)
|
|
511
|
-
let trials = 20000;
|
|
512
|
-
if (process.stdin.isTTY) {
|
|
513
|
-
const tAns = await promptUser(`Total simulation trials (default 20000): `);
|
|
514
|
-
trials = parseInt(tAns, 10) || 20000;
|
|
515
|
-
}
|
|
516
|
-
const mcPath = existsSync(resolve("monte_carlo.py"))
|
|
517
|
-
? resolve("monte_carlo.py")
|
|
518
|
-
: join(os.tmpdir(), "sharedots_monte_carlo.py");
|
|
519
|
-
if (!existsSync(mcPath)) {
|
|
520
|
-
writeFileSync(mcPath, EMBEDDED_MONTE_CARLO_PY, "utf8");
|
|
521
|
-
}
|
|
522
|
-
const artifact = await room.uploadArtifact(mcPath, "monte_carlo.py", { shared: true });
|
|
523
|
-
spec = buildPresetMonteCarloSpec({ trials, partitions, artifact });
|
|
524
|
-
}
|
|
525
|
-
|
|
526
|
-
console.log(`Submitting preset job '${spec.name}'...`);
|
|
527
|
-
const job = await room.submit(spec);
|
|
528
|
-
console.log(`\x1b[32m✔ Dispatched job ${job.jobId}\x1b[0m\n`);
|
|
529
|
-
|
|
530
|
-
job.on("progress", (p) => {
|
|
531
|
-
const percent = Math.min(100, Math.max(0, p.percent));
|
|
532
|
-
const completed = p.completedTasks ?? 0;
|
|
533
|
-
const total = p.totalTasks ?? partitions;
|
|
534
|
-
const barLen = 24;
|
|
535
|
-
const filled = Math.round((percent / 100) * barLen);
|
|
536
|
-
const bar = "█".repeat(filled) + "░".repeat(Math.max(0, barLen - filled));
|
|
537
|
-
process.stdout.write(`\r [${bar}] ${percent}% (${completed}/${total} tasks finished)`);
|
|
538
|
-
});
|
|
539
|
-
|
|
540
|
-
const result = await job.result();
|
|
541
|
-
console.log(`\n\n\x1b[32m✔ Job ${result.jobId} completed successfully! Status: ${result.status.toUpperCase()}\x1b[0m`);
|
|
542
|
-
|
|
543
|
-
if (result.resultArtifactId) {
|
|
544
|
-
console.log(`Result Artifact ID: ${result.resultArtifactId}`);
|
|
545
|
-
try {
|
|
546
|
-
const outBuffer = await room.downloadArtifact(result.resultArtifactId);
|
|
547
|
-
console.log(`\n\x1b[1m--- Simulation Results ---\x1b[0m`);
|
|
548
|
-
console.log(outBuffer.toString("utf8"));
|
|
549
|
-
} catch {
|
|
550
|
-
// preview unavailable
|
|
551
|
-
}
|
|
552
|
-
}
|
|
553
|
-
}
|
|
554
|
-
|
|
555
|
-
export function constructDashboardUrl(options: {
|
|
556
|
-
coordinator?: string;
|
|
557
|
-
roomId?: string;
|
|
558
|
-
token?: string;
|
|
559
|
-
port?: string;
|
|
560
|
-
hosted?: boolean;
|
|
561
|
-
}): { localUrl: string; hostedUrl: string; effectiveUrl: string } {
|
|
562
|
-
const cfg = readConfig();
|
|
563
|
-
const coordinator = (options.coordinator ?? process.env.SHAREDOTS_COORDINATOR ?? cfg?.coordinator ?? DEFAULT_COORDINATOR).replace(/\/$/, "");
|
|
564
|
-
const roomId = options.roomId ?? process.env.SHAREDOTS_ROOM_ID ?? cfg?.roomId ?? "default-room";
|
|
565
|
-
const token = options.token ?? process.env.SHAREDOTS_TOKEN ?? (options.roomId && options.roomId !== cfg?.roomId ? undefined : cfg?.token) ?? "sec_default";
|
|
566
|
-
const port = options.port ?? "3000";
|
|
567
|
-
|
|
568
|
-
const qs = new URLSearchParams({
|
|
569
|
-
room: roomId,
|
|
570
|
-
token,
|
|
571
|
-
coordinator,
|
|
572
|
-
}).toString();
|
|
573
|
-
|
|
574
|
-
const localUrl = `http://localhost:${port}/?${qs}`;
|
|
575
|
-
const hostedUrl = `https://sharedots.onrender.com/?${qs}`;
|
|
576
|
-
const effectiveUrl = options.hosted ? hostedUrl : localUrl;
|
|
577
|
-
|
|
578
|
-
return { localUrl, hostedUrl, effectiveUrl };
|
|
579
|
-
}
|
|
580
|
-
|
|
581
|
-
export async function openDashboardBridge(options: {
|
|
582
|
-
coordinator?: string;
|
|
583
|
-
roomId?: string;
|
|
584
|
-
token?: string;
|
|
585
|
-
port?: string;
|
|
586
|
-
hosted?: boolean;
|
|
587
|
-
openBrowser?: boolean;
|
|
588
|
-
}): Promise<string> {
|
|
589
|
-
const cfg = readConfig();
|
|
590
|
-
const coordinator = (options.coordinator ?? process.env.SHAREDOTS_COORDINATOR ?? cfg?.coordinator ?? DEFAULT_COORDINATOR).replace(/\/$/, "");
|
|
591
|
-
const roomId = options.roomId ?? process.env.SHAREDOTS_ROOM_ID ?? cfg?.roomId ?? "default-room";
|
|
592
|
-
const token = options.token ?? process.env.SHAREDOTS_TOKEN ?? (options.roomId && options.roomId !== cfg?.roomId ? undefined : cfg?.token) ?? "sec_default";
|
|
593
|
-
const port = options.port ?? "3000";
|
|
594
|
-
|
|
595
|
-
const { localUrl, hostedUrl } = constructDashboardUrl({
|
|
596
|
-
coordinator,
|
|
597
|
-
roomId,
|
|
598
|
-
token,
|
|
599
|
-
port,
|
|
600
|
-
hosted: options.hosted,
|
|
601
|
-
});
|
|
602
|
-
|
|
603
|
-
let isLocalRunning = false;
|
|
604
|
-
try {
|
|
605
|
-
const res = await fetch(`http://localhost:${port}`, { signal: AbortSignal.timeout(1000) });
|
|
606
|
-
if (res.ok || res.status < 500) {
|
|
607
|
-
isLocalRunning = true;
|
|
608
|
-
}
|
|
609
|
-
} catch {
|
|
610
|
-
isLocalRunning = false;
|
|
611
|
-
}
|
|
612
|
-
|
|
613
|
-
const targetUrl = isLocalRunning ? localUrl : (options.hosted ? hostedUrl : localUrl);
|
|
614
|
-
|
|
615
|
-
console.log(`\n\x1b[1m\x1b[36m⚡ SHAREDOTS WEB DASHBOARD CONTROL BRIDGE\x1b[0m\n`);
|
|
616
|
-
console.log(` Room ID: ${roomId}`);
|
|
617
|
-
console.log(` Token: ${token}`);
|
|
618
|
-
console.log(` Coordinator: ${coordinator}`);
|
|
619
|
-
console.log(` Target URL: ${targetUrl}\n`);
|
|
620
|
-
|
|
621
|
-
if (!isLocalRunning && !options.hosted) {
|
|
622
|
-
console.log(`\x1b[33mNotice: Local dashboard is not running on port ${port}.\x1b[0m`);
|
|
623
|
-
console.log(`To start it locally: \x1b[36mpnpm dashboard:dev\x1b[0m`);
|
|
624
|
-
console.log(`Hosted dashboard: \x1b[36m${hostedUrl}\x1b[0m\n`);
|
|
625
|
-
}
|
|
626
|
-
|
|
627
|
-
if (options.openBrowser !== false) {
|
|
628
|
-
console.log(`Opening browser...`);
|
|
629
|
-
try {
|
|
630
|
-
if (process.platform === "win32") {
|
|
631
|
-
const winUrl = targetUrl.replace(/&/g, "^&");
|
|
632
|
-
spawnSync("cmd.exe", ["/c", "start", "", winUrl], { stdio: "ignore" });
|
|
633
|
-
} else if (process.platform === "darwin") {
|
|
634
|
-
spawnSync("open", [targetUrl], { stdio: "ignore" });
|
|
635
|
-
} else {
|
|
636
|
-
spawnSync("xdg-open", [targetUrl], { stdio: "ignore" });
|
|
637
|
-
}
|
|
638
|
-
console.log(`\x1b[32m✔ Browser opened to dashboard.\x1b[0m\n`);
|
|
639
|
-
} catch (err) {
|
|
640
|
-
console.log(`Could not open browser automatically (${err instanceof Error ? err.message : String(err)}).`);
|
|
641
|
-
}
|
|
642
|
-
}
|
|
643
|
-
|
|
644
|
-
return targetUrl;
|
|
645
|
-
}
|