Repository navigation
Expand file tree
/
Copy pathtasks.js
More file actions
723 lines (645 loc) · 25.8 KB
/
Copy pathtasks.js
File metadata and controls
723 lines (645 loc) · 25.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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
// =============================================================================
// MIT License
// Copyright (c) 2026 Aparavi Software AG
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// =============================================================================
/**
* Build tasks for @rocketride/nodes
*
* Commands:
* build - Sync nodes to dist
* test - Run node integration tests (starts test server automatically)
* clean - Remove build artifacts
*/
const path = require('path');
const os = require('os');
const fs = require('fs');
const crypto = require('crypto');
const AdmZip = require('adm-zip');
const { stripComments } = require('jsonc-parser');
const {
syncDir,
syncFile,
formatSyncStats,
isDirectory,
removeDir,
setState,
readDirSafe,
PROJECT_ROOT,
DIST_ROOT,
OVERLAY_ROOT,
startServer,
stopServer,
execCommand,
runPytest,
splitPytestOpts,
withoutXdistArgs,
hasDistMode,
collectPytestReport,
parallel,
bracket,
parseServerAddress,
isLinux,
loadPackageJson,
} = require('../../scripts/lib');
const { nodeLibrary, stageNodeLibrary, makeNodeModule } = require('./node-build');
const PACKAGE_DIR = path.join(__dirname, '..');
// Map of node name -> project or overlay src/nodes directory. Overlay node wins over project node.
const SRC_NODE_DIRS = new Map(
[
path.join(PACKAGE_DIR, 'src', 'nodes'),
...(OVERLAY_ROOT ? [path.join(OVERLAY_ROOT, 'nodes', 'src', 'nodes')] : []),
]
.filter((srcDir) => fs.existsSync(srcDir))
.flatMap((srcDir) => fs.readdirSync(srcDir).map((name) => [name, srcDir]))
);
const TEST_DIR = path.join(PACKAGE_DIR, 'test');
const DIST_DIR = path.join(DIST_ROOT, 'server', 'nodes');
// The Python nodes ship in one archive, each under <name>/, beside the index.json that names it
const PACKAGES_DIR = path.join(DIST_ROOT, 'nodes');
// A packaged node's requirement files stay in the server, without its code, for the
// constraints solve and the image's wheel cache; the dash keeps it from importing
const REQUIREMENTS_DIR = path.join(DIST_DIR, 'node-requirements');
// The index format the engine reads; bump it when that format changes
const NODES_CONTRACT = 1;
// The nodes the engine itself needs stay in the server; so do the C++ ones
const SERVER_NODES = new Set(['core', 'autopipe']);
// Build inputs or runtime files - none of it belongs in dist.
const IGNORE = ['**/CMakeLists.txt', '**/src/**', '**/lib/**', '**/scripts/**', '**/target/**', '**/__pycache__/**'];
// Engine (built by server:build; execCommand resolves extension on Windows)
const ENGINE = path.join(DIST_ROOT, 'server', 'engine');
// A builder module of a node's own, by the names the registry discovers
const hasOwnModule = (nodeDir) =>
['tasks.js', 'tasks.cjs'].some((file) => fs.existsSync(path.join(nodeDir, 'scripts', file)));
// A c++ node is one with a CMakeLists.txt and without a module of its own.
const CPP_NODES = [...SRC_NODE_DIRS]
.filter(
([name, srcDir]) =>
fs.existsSync(path.join(srcDir, name, 'CMakeLists.txt')) && !hasOwnModule(path.join(srcDir, name))
)
.map(([name, srcDir]) => ({ name, srcDir }));
const CPP_NODE_BUILDS = [...SRC_NODE_DIRS]
.filter(([name, srcDir]) => fs.existsSync(path.join(srcDir, name, 'CMakeLists.txt')))
.map(([name]) => `${name}:build`);
// ============================================================================
// Action Factories
// ============================================================================
function makeSyncNodesAction() {
return {
run: async (ctx, task) => {
task.output = 'Scanning for changes...';
const stats = {};
const packages = await syncNodes(stats);
task.output = `${formatSyncStats(stats)}, ${Object.keys(packages).length} packages`;
},
};
}
// Where the build puts each node, and the helpers that copy and record it; a test passes its own
const SYNC = {
srcNodeDirs: SRC_NODE_DIRS,
distDir: DIST_DIR,
packagesDir: PACKAGES_DIR,
archiveName: async () => `rocketride-nodes-v${(await loadPackageJson()).version}.zip`,
libraryOf: nodeLibrary,
copyFile: (src, dest, stats) => syncFile(src, dest, { package: true }, stats),
copyNode: (name, src, stats) => syncNode(name, src, stats),
forget: (src) => setState(['package', src], null),
};
// The server keeps core, autopipe and the C++ nodes; every other node goes into the archive beside
// index.json, and only its requirement files stay in the server. Returns the index's nodes
async function syncNodes(stats, sync = SYNC) {
sync = { ...SYNC, ...sync };
const requirementsDir = path.join(sync.distDir, path.basename(REQUIREMENTS_DIR));
const archive = await sync.archiveName();
const { zip, packages, sources } = await packageNodes(stats, sync, requirementsDir);
await dropStale(sync, packages, sources, requirementsDir, archive);
await writeIndex(stats, sync, archive, zip, packages);
return packages;
}
// Copies the server's nodes into it and packs every other one into the archive, with only its
// requirement files left in the server; the archive, the index's entries and each node's source folder
async function packageNodes(stats, { srcNodeDirs, distDir, libraryOf, copyFile, copyNode, forget }, requirementsDir) {
const zip = new AdmZip();
const packages = {};
const sources = {};
for (const [name, srcDir] of srcNodeDirs) {
const src = path.join(srcDir, name);
if (!(await isDirectory(src))) {
await copyFile(src, path.join(distDir, name), stats);
continue;
}
const lib = await libraryOf(name, src);
if (lib || SERVER_NODES.has(name)) {
await copyNode(name, src, stats);
continue;
}
const { files, entry } = await packageNode(name, src);
for (const [file, data] of Object.entries(files)) zip.addFile(`${name}/${file}`, data);
packages[name] = entry;
sources[name] = src;
// It no longer ships inside the server archive, but its requirements do
await removeDir(path.join(distDir, name));
await forget(src);
for (const file of await readDirSafe(src)) {
if (!/^(requirement.*\.txt|overrides\.txt)$/.test(file)) continue;
await copyFile(path.join(src, file), path.join(requirementsDir, name, file), stats);
}
}
// A node it needs that the server keeps is on disk already; only packaged ones are listed
for (const entry of Object.values(packages)) {
entry.requires = entry.requires.filter((other) => other in packages);
}
return { zip, packages, sources };
}
// Removes what this build no longer ships: a file an older build left in the server, another
// version's archive, and the requirement files of a node that is gone or no longer has them
async function dropStale({ srcNodeDirs, distDir, packagesDir, forget }, packages, sources, requirementsDir, archive) {
// Such as a nodes/__init__.py
for (const name of await readDirSafe(distDir)) {
if (srcNodeDirs.has(name) || name === path.basename(requirementsDir)) continue;
await fs.promises.rm(path.join(distDir, name), { recursive: true, force: true });
await forget(path.join(PACKAGE_DIR, 'src', 'nodes', name));
}
// Another version's archive, so it is not published again
for (const file of await readDirSafe(packagesDir)) {
if (file !== archive && file !== 'index.json') {
await fs.promises.rm(path.join(packagesDir, file), { recursive: true, force: true });
}
}
for (const name of await readDirSafe(requirementsDir)) {
for (const file of await readDirSafe(path.join(requirementsDir, name))) {
if (name in packages && fs.existsSync(path.join(sources[name], file))) continue;
await fs.promises.rm(path.join(requirementsDir, name, file), { force: true });
// Or server:package still lists the copy
await forget(path.join(sources[name] ?? path.join(PACKAGE_DIR, 'src', 'nodes', name), file));
}
if (!(name in packages)) {
await fs.promises.rm(path.join(requirementsDir, name), { recursive: true, force: true });
}
}
}
// Writes the archive and its index beside the server, and the index into the server too
async function writeIndex(stats, { distDir, packagesDir, copyFile }, archive, zip, packages) {
const index = { contract: NODES_CONTRACT, archive, nodes: packages };
await fs.promises.mkdir(packagesDir, { recursive: true });
await fs.promises.writeFile(path.join(packagesDir, archive), zip.toBuffer());
await fs.promises.writeFile(path.join(packagesDir, 'index.json'), JSON.stringify(index));
// The server archive carries its own copy, so an engine reads the index of the build that made it
await copyFile(path.join(packagesDir, 'index.json'), path.join(distDir, 'index.json'), stats);
}
// The digest of a node's files ({path inside the node: bytes}), as ai.common.node_packages.content_digest:
// the sha256 of '<path>\0<sha256 hex of the file>\n' for each file in path order (code point, as Python sorts)
function contentDigest(files) {
const digest = crypto.createHash('sha256');
for (const file of Object.keys(files).sort((a, b) => Buffer.compare(Buffer.from(a), Buffer.from(b)))) {
digest.update(`${file}\0${crypto.createHash('sha256').update(files[file]).digest('hex')}\n`);
}
return digest.digest('hex');
}
// A node's files with its .rrnode marker, keyed by their path inside the node, and its index entry
async function packageNode(name, srcDir) {
const { glob } = require('glob');
// Definitions travel as text so Python reads 1.0 as a float; JSON.parse checks they are plain JSON
const services = {};
const icons = {};
const requires = new Set();
const files = {};
// Paths with '/' on every OS: they are part of the digest
const found = await glob('**', { cwd: srcDir, nodir: true, ignore: IGNORE });
for (const file of found.map((entry) => entry.replace(/\\/g, '/')).sort()) {
const data = await fs.promises.readFile(path.join(srcDir, file));
files[file] = data;
// Another node it imports must be on disk beside it
if (file.endsWith('.py')) {
for (const [, other] of data.toString('utf8').matchAll(/^\s*(?:from|import)\s+nodes\.(\w+)/gm)) {
if (other !== name) requires.add(other);
}
}
if (!/^services.*\.json$/.test(file)) continue;
const text = stripComments(data.toString('utf8'));
const { icon } = JSON.parse(text);
services[file] = text;
if (icon) icons[icon] = await fs.promises.readFile(path.join(srcDir, icon), 'utf8');
}
files['.rrnode'] = Buffer.from(JSON.stringify({ name }));
const sha256 = contentDigest(files);
return { files, entry: { sha256, services, icons, requires: [...requires].sort() } };
}
function makeStartTestServerAction(options = {}) {
return {
run: async (ctx, task) => {
const taskserver = options.taskserver || ctx.options?.taskserver;
if (taskserver) {
const parsed = parseServerAddress(taskserver);
ctx.port = parsed.port;
task.output = `Using existing server at ${parsed.uri}`;
return { port: parsed.port, server: null, serverUri: parsed.uri };
}
task.output = 'Starting server...';
let taskComplete = false;
// Set ROCKETRIDE_MOCK to enable mock modules for testing
const mocksPath = path.join(PACKAGE_DIR, 'test', 'mocks');
const result = await startServer({
script: 'ai/eaas.py',
trace: options.trace,
logName: 'nodes',
verbose: ctx.options?.verbose,
basePort: 40000, // Use 40000 range for node tests
env: {
ROCKETRIDE_MOCK: mocksPath,
},
onOutput: (text) => {
if (taskComplete) return;
const lines = text.trim().split('\n');
if (lines.length > 0) {
task.output = lines[lines.length - 1];
}
},
});
ctx.port = result.port;
task.output = `Server ready on port ${ctx.port} (mocks enabled)`;
taskComplete = true;
return { port: result.port, server: result.server, serverUri: result.uri };
},
};
}
function makeStopTestServerAction() {
return {
run: async (ctx, task) => {
const bracket = ctx.brackets?.['node-test-server'];
if (bracket?.server) {
task.output = 'Stopping server...';
await stopServer({ server: bracket.server });
task.output = 'Server stopped';
} else {
task.output = 'No server to stop';
}
},
};
}
// Modes: 'run' (the tests), 'warmup' (download the models of the selected heavy
// tests; options.warmup === 'plan' only lists them), 'list-skipped' (report the
// selected tests that will be skipped). Only 'run' needs the test server.
function makeRunPytestAction(options = {}) {
const mode = options.mode || 'run';
return {
run: async (ctx, task) => {
// Load .env for test configuration
require('dotenv').config({ path: path.join(PROJECT_ROOT, '.env') });
const testEnv = {
...process.env,
ROCKETRIDE_MOCK: path.join(PACKAGE_DIR, 'test', 'mocks'),
};
if (mode === 'run') {
const bracket = ctx.brackets?.['node-test-server'];
if (!bracket?.serverUri) throw new Error('node-test-server bracket missing — server did not start');
testEnv.ROCKETRIDE_URI = bracket.serverUri;
} else if (options.taskserver) {
// The hardware gate needs to know the tests would run on another machine.
testEnv.ROCKETRIDE_URI = parseServerAddress(options.taskserver).uri;
}
// Use absolute paths since cwd is dist/server
const extraArgs = ['-v', '--rootdir', PACKAGE_DIR];
// Warmup only concerns the dynamic tests; collecting just those keeps it quick.
const testsDir = mode === 'warmup' ? path.join(TEST_DIR, 'test_dynamic_full.py') : TEST_DIR;
if (mode === 'warmup') {
extraArgs.unshift(path.join(TEST_DIR, 'test_dynamic.py'));
}
if (!options.test_full) {
extraArgs.push('--ignore-glob', '**/test_*_full.py', '--ignore-glob', '**/test_*_full/**');
}
// Exclude skip_node tests by default (same as skip_nodes in pytest_generate_tests for dynamic tests)
const pytestTokens = splitPytestOpts(options.pytest);
const hasExplicitMarkers =
!!options.markers ||
pytestTokens.some((t) => t === '-m' || (t.startsWith('-m') && !t.startsWith('--')));
if (!hasExplicitMarkers) {
extraArgs.push('-m', 'not skip_node');
}
// Additional pytest options from --pytest="-s -v"; the collect-only
// modes run in one process, so xdist options are dropped for them.
extraArgs.push(...(mode === 'run' ? pytestTokens : withoutXdistArgs(pytestTokens)));
// Allow filtering tests by marker or pattern
const markers = options.markers;
const pattern = options.pytestPattern;
if (markers) {
extraArgs.push('-m', markers);
}
if (pattern) {
extraArgs.push('-k', pattern);
}
if (mode === 'warmup') {
extraArgs.push(`--warmup-models=${options.warmup === 'plan' ? 'plan' : 'download'}`);
} else if (mode === 'list-skipped') {
extraArgs.push(`--list-skipped=${options.listSkipped}`);
} else {
// Parallel execution via pytest-xdist. Defaults to min(cpus, 8) when the
// flag is not set: empirically, cloud-LLM rate limits + node-subprocess
// fan-out make >8 workers counterproductive on this test shape. Explicit
// values (numeric or 'auto') pass through; 'off'/'0' disables xdist.
const parallelRaw = options.pytestParallel ?? String(Math.min(os.cpus().length, 8));
const parallelVal = String(parallelRaw).trim().toLowerCase();
if (parallelVal && parallelVal !== 'off' && parallelVal !== '0') {
extraArgs.push('-n', parallelVal);
// Honor @pytest.mark.xdist_group (set in conftest._params): heavy
// tests (requiresHardware) share lanes, each lane on one worker, so
// they don't OOM-crash workers. The marker is ignored under other
// --dist modes, which conftest refuses when heavy tests are selected.
// Skip if the caller already chose a distribution mode via --pytest.
if (!hasDistMode(extraArgs)) {
extraArgs.push('--dist', 'loadgroup');
}
}
}
const pytest = (extra = []) =>
runPytest({
engine: ENGINE,
testsDir,
extraArgs: [...extraArgs, ...extra],
execOpts: { task, cwd: PACKAGE_DIR, env: testEnv },
});
// Reports the user asked for are printed once the builder finishes.
if (mode === 'list-skipped' || (mode === 'warmup' && options.warmup === 'plan')) {
await collectPytestReport(ctx, (reportArg) => pytest([reportArg]));
return;
}
await pytest();
if (mode !== 'run') return;
// The node README schema validator's own tests live at the repo
// root; they are part of the node contract, so they run here.
await runPytest({
engine: ENGINE,
testsDir: path.join(PROJECT_ROOT, 'tests', 'test_validate_node_readme.py'),
execOpts: { task, cwd: PROJECT_ROOT, env: testEnv },
});
},
};
}
function makeDocsGenerateAction() {
return {
run: async (ctx, task) => {
await execCommand('node', [path.join(__dirname, 'gen-node-tables.mjs')], { task, cwd: PACKAGE_DIR });
},
};
}
function makeCredentialsGenerateAction() {
return {
run: async (ctx, task) => {
await execCommand('node', [path.join(__dirname, 'gen-credentials.mjs')], { task, cwd: PACKAGE_DIR });
},
};
}
function makeCredentialsCheckAction() {
return {
run: async (ctx, task) => {
await execCommand('node', [path.join(__dirname, 'gen-credentials.mjs'), '--check'], {
task,
cwd: PACKAGE_DIR,
});
},
};
}
function makeRunContractTestsAction() {
return {
run: async (ctx, task) => {
await runPytest({
engine: ENGINE,
testsDir: path.join(TEST_DIR, 'test_contracts.py'),
extraArgs: ['-v', '--rootdir', PACKAGE_DIR],
execOpts: { task, cwd: PACKAGE_DIR },
});
},
};
}
// Installs nodes/test/requirements.txt: the test harness plus the node packages
// the tests import directly, which the nodes themselves install only when a
// pipeline first loads them. depends() applies the engine constraints.
function makeInstallTestDepsAction() {
return {
run: async (ctx, task) => {
task.output = 'Installing node test dependencies...';
await execCommand(
ENGINE,
[
'-c',
'import sys; from depends import depends; depends(sys.argv[1])',
path.join(TEST_DIR, 'requirements.txt'),
],
{ task, cwd: PACKAGE_DIR }
);
},
};
}
function makeTestAction(options = {}) {
if (options.warmup && !['plan', 'off'].includes(options.warmup)) {
throw new Error(`--warmup=${options.warmup}: expected 'plan' or 'off'`);
}
const runName = options.test_full ? 'nodes:run-pytest-full' : 'nodes:run-pytest';
const steps = ['server:build', parallel(['nodes:build', 'ai:build', 'client-python:build'], 'Build dependencies')];
// Collect-only modes need no test server.
if (options.listSkipped) {
steps.push({
name: `${runName}:list-skipped`,
action: makeRunPytestAction({ ...options, mode: 'list-skipped' }),
});
return { description: 'Listing skipped node tests', steps };
}
if (options.test_full && options.warmup === 'plan') {
steps.push({ name: 'nodes:warmup-models', action: makeRunPytestAction({ ...options, mode: 'warmup' }) });
return { description: 'Planning node test model downloads', steps };
}
// The collect-only modes above report the environment as it is; test runs complete it.
steps.push({ name: 'nodes:install-test-deps', action: makeInstallTestDepsAction() });
// Download the selected heavy tests' models before the server starts, so the
// downloads don't count against test timeouts. Pointless for a remote server.
if (options.test_full && options.warmup !== 'off' && !options.taskserver) {
steps.push({ name: 'nodes:warmup-models', action: makeRunPytestAction({ ...options, mode: 'warmup' }) });
}
steps.push(
bracket({
name: 'node-test-server',
setup: makeStartTestServerAction(options),
teardown: makeStopTestServerAction(options),
steps: [{ name: runName, action: makeRunPytestAction(options) }],
})
);
return { description: 'Testing nodes', steps };
}
// Builds engine-base from dist/server, then the node image FROM it.
function makeBuildImageAction(options = {}) {
return {
run: async (ctx, task) => {
const reason = await containerUnavailable();
if (reason) return skipLoudly('nodes:build-container', task, reason);
const { base, node } = await imageNames();
const dockerDir = path.join(PROJECT_ROOT, 'docker');
// The per-Dockerfile .dockerignore files need BuildKit
const env = { ...process.env, DOCKER_BUILDKIT: '1' };
task.output = `Building ${base}...`;
await execCommand(
'docker',
['build', '-f', path.join(dockerDir, 'Dockerfile.engine-base'), '-t', base, path.dirname(DIST_ROOT)],
{ task, env, verbose: options.verbose }
);
task.output = `Building ${node}...`;
await execCommand(
'docker',
[
'build',
'-f',
path.join(dockerDir, 'Dockerfile.node'),
'--build-arg',
`ENGINE_BASE=${base}`,
'-t',
node,
PROJECT_ROOT,
],
{ task, env, verbose: options.verbose }
);
task.output = `Built ${node}`;
},
};
}
// Stage 0 of the container tests: the node image as a run gets it, checked by
// docker/test-node-image.sh (the release workflow runs the same script before
// signing). The runtime itself (a pipeline through the container) comes with
// its Launcher.
function makeTestImageAction(options = {}) {
return {
run: async (ctx, task) => {
const reason = await containerUnavailable();
if (reason) return skipLoudly('nodes:test-container', task, reason);
const { node } = await imageNames();
task.output = `Checking ${node}...`;
await execCommand('sh', [path.join(PROJECT_ROOT, 'docker', 'test-node-image.sh'), node], {
task,
verbose: options.verbose,
});
task.output = `${node}: engine probe and offline installs passed`;
},
};
}
// ============================================================================
// Utilities
// ============================================================================
async function syncNode(name, srcDir, stats) {
const distDir = path.join(DIST_DIR, name);
await syncDir(srcDir, distDir, { mirror: false, package: true, ignore: IGNORE }, stats);
await stageNodeLibrary(name, srcDir, stats);
}
async function containerUnavailable() {
if (!isLinux()) return 'Linux only; dist/server here is not a Linux engine. Pull a published engine-base instead';
try {
await execCommand('docker', ['info'], { stdio: 'ignore', silent: true });
} catch {
return 'no Docker daemon reachable';
}
return null;
}
function skipLoudly(taskName, task, reason) {
task.output = `Skipped: ${reason}`;
console.warn(`WARNING: ${taskName} skipped — ${reason}`);
}
// Both images carry the engine version: the task protocol is not versioned.
async function imageNames() {
const { version } = await loadPackageJson();
return { base: `rocketride/engine-base:${version}`, node: `rocketride/node:${version}` };
}
// ============================================================================
// Module Export
// ============================================================================
module.exports = {
name: 'nodes',
description: 'Pipeline Nodes',
actions: [
// Internal actions
{ name: 'nodes:sync', action: makeSyncNodesAction },
{ name: 'nodes:start-server', action: makeStartTestServerAction },
{ name: 'nodes:stop-server', action: makeStopTestServerAction },
{ name: 'nodes:run-contracts', action: makeRunContractTestsAction },
{ name: 'nodes:docs-generate', action: makeDocsGenerateAction },
{ name: 'nodes:credentials-generate', action: makeCredentialsGenerateAction },
{ name: 'nodes:credentials-check', action: makeCredentialsCheckAction },
{
name: 'nodes:submodule-build',
action: () => ({
// Each node builds itself; the sync stages every node's sources
steps: [parallel(CPP_NODE_BUILDS, 'Build c++ nodes'), 'nodes:sync'],
}),
},
// Public actions (have descriptions)
{
name: 'nodes:build',
action: () => ({
description: 'Build nodes',
steps: [
'server:build-core',
'nodes:submodule-build',
'nodes:docs-generate',
'nodes:credentials-generate',
],
}),
},
{
name: 'nodes:build-container',
action: (options) => ({
description: 'Build the node container image',
steps: ['nodes:build', { name: 'nodes:build-image', action: makeBuildImageAction(options) }],
}),
},
// Not part of nodes:test: it needs a daemon, and skips loudly without one
{
name: 'nodes:test-container',
action: (options) => ({
description: 'Test the node container image',
steps: ['nodes:build-container', { name: 'nodes:test-image', action: makeTestImageAction(options) }],
}),
},
{ name: 'nodes:test', action: (options) => makeTestAction({ ...options, test_full: false }) },
{ name: 'nodes:test-full', action: (options) => makeTestAction({ ...options, test_full: true }) },
{
name: 'nodes:test-contracts',
action: () => ({
description: 'Testing nodes (contracts)',
steps: ['server:build', 'nodes:run-contracts'],
}),
},
{
name: 'nodes:clean',
action: () => ({
description: 'Cleaning nodes',
run: async (ctx, task) => {
await removeDir(DIST_DIR);
await removeDir(PACKAGES_DIR);
task.output = 'Cleaned nodes';
},
}),
},
],
};
// C++ node actions
module.exports = [module.exports, ...CPP_NODES.map(makeNodeModule)];
// Export paths for external use
module.exports.DIST_DIR = DIST_DIR;
module.exports.TEST_DIR = TEST_DIR;
module.exports.packageNode = packageNode;
module.exports.contentDigest = contentDigest;
module.exports.syncNodes = syncNodes;
module.exports.NODES_CONTRACT = NODES_CONTRACT;