mirror of
https://github.com/game-ci/unity-builder.git
synced 2026-06-01 06:16:14 -07:00
Compare commits
5 Commits
feature/ho
...
feature/pr
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e0e7b225a1 | ||
|
|
b9f70d35a1 | ||
|
|
1f3affe097 | ||
|
|
7f895304f4 | ||
|
|
e4c156e7b0 |
42
action.yml
42
action.yml
@@ -182,8 +182,8 @@ inputs:
|
||||
required: false
|
||||
default: ''
|
||||
description:
|
||||
'[Orchestrator] Run a custom job instead of the standard build automation for orchestrator (in yaml format with
|
||||
the keys image, secrets (name, value object array), command line string)'
|
||||
'[Orchestrator] Run a custom job instead of the standard build automation for orchestrator (in yaml format with the
|
||||
keys image, secrets (name, value object array), command line string)'
|
||||
awsStackName:
|
||||
default: 'game-ci'
|
||||
required: false
|
||||
@@ -194,6 +194,15 @@ inputs:
|
||||
description:
|
||||
'[Orchestrator] Either local, k8s or aws can be used to run builds on a remote cluster. Additional parameters must
|
||||
be configured.'
|
||||
secretSource:
|
||||
default: ''
|
||||
required: false
|
||||
description:
|
||||
'[Orchestrator] Premade secret source for pulling build secrets. Supported values: aws-secrets-manager,
|
||||
aws-parameter-store, gcp-secret-manager, azure-key-vault, hashicorp-vault, hashicorp-vault-kv1,
|
||||
vault (alias for hashicorp-vault), env. Can also be a custom shell command with {0} placeholder
|
||||
for the key, or a path to a YAML file defining custom sources. Takes precedence over
|
||||
inputPullCommand when set.'
|
||||
resourceTracking:
|
||||
default: 'false'
|
||||
required: false
|
||||
@@ -280,35 +289,6 @@ inputs:
|
||||
'[Orchestrator] Specifies the repo for the unity builder. Useful if you forked the repo for testing, features, or
|
||||
fixes.'
|
||||
|
||||
hotRunnerEnabled:
|
||||
description: '[HotRunner] Use persistent hot runner for builds (requires pre-registered runners)'
|
||||
required: false
|
||||
default: 'false'
|
||||
hotRunnerTransport:
|
||||
description: '[HotRunner] Transport protocol for hot runner communication: websocket, grpc, named-pipe'
|
||||
required: false
|
||||
default: 'websocket'
|
||||
hotRunnerHost:
|
||||
description: '[HotRunner] Hot runner host address'
|
||||
required: false
|
||||
default: 'localhost'
|
||||
hotRunnerPort:
|
||||
description: '[HotRunner] Hot runner port number'
|
||||
required: false
|
||||
default: '9090'
|
||||
hotRunnerHealthInterval:
|
||||
description: '[HotRunner] Health check interval in seconds'
|
||||
required: false
|
||||
default: '30'
|
||||
hotRunnerMaxIdle:
|
||||
description: '[HotRunner] Maximum idle time in seconds before recycling runner'
|
||||
required: false
|
||||
default: '3600'
|
||||
hotRunnerFallbackToCold:
|
||||
description: '[HotRunner] Fall back to cold build if no hot runner available'
|
||||
required: false
|
||||
default: 'true'
|
||||
|
||||
outputs:
|
||||
volume:
|
||||
description: 'The Persistent Volume (PV) where the build artifacts have been stored by Kubernetes'
|
||||
|
||||
1100
dist/index.js
generated
vendored
1100
dist/index.js
generated
vendored
File diff suppressed because it is too large
Load Diff
2
dist/index.js.map
generated
vendored
2
dist/index.js.map
generated
vendored
File diff suppressed because one or more lines are too long
75
src/index.ts
75
src/index.ts
@@ -3,8 +3,6 @@ import { Action, BuildParameters, Cache, Orchestrator, Docker, ImageTag, Output
|
||||
import { Cli } from './model/cli/cli';
|
||||
import MacBuilder from './model/mac-builder';
|
||||
import PlatformSetup from './model/platform-setup';
|
||||
import { HotRunnerService } from './model/orchestrator/services/hot-runner';
|
||||
import { HotRunnerConfig } from './model/orchestrator/services/hot-runner/hot-runner-types';
|
||||
|
||||
async function runMain() {
|
||||
try {
|
||||
@@ -23,46 +21,17 @@ async function runMain() {
|
||||
|
||||
let exitCode = -1;
|
||||
|
||||
// Hot runner path: attempt to use a persistent Unity editor instance
|
||||
if (buildParameters.hotRunnerEnabled) {
|
||||
core.info('[HotRunner] Hot runner mode enabled, attempting hot build...');
|
||||
|
||||
const hotRunnerConfig: HotRunnerConfig = {
|
||||
enabled: true,
|
||||
transport: buildParameters.hotRunnerTransport,
|
||||
host: buildParameters.hotRunnerHost,
|
||||
port: buildParameters.hotRunnerPort,
|
||||
healthCheckInterval: buildParameters.hotRunnerHealthInterval,
|
||||
maxIdleTime: buildParameters.hotRunnerMaxIdle,
|
||||
maxJobsBeforeRecycle: 0, // no automatic recycle by job count
|
||||
};
|
||||
|
||||
const hotRunnerService = new HotRunnerService();
|
||||
|
||||
try {
|
||||
await hotRunnerService.initialize(hotRunnerConfig);
|
||||
const result = await hotRunnerService.submitBuild(buildParameters, (output) => {
|
||||
core.info(output);
|
||||
});
|
||||
|
||||
exitCode = result.exitCode;
|
||||
core.info(`[HotRunner] Build completed with exit code ${exitCode}`);
|
||||
await hotRunnerService.shutdown();
|
||||
} catch (hotRunnerError) {
|
||||
await hotRunnerService.shutdown();
|
||||
|
||||
if (buildParameters.hotRunnerFallbackToCold) {
|
||||
core.warning(
|
||||
`[HotRunner] Hot runner failed: ${(hotRunnerError as Error).message}. Falling back to cold build.`,
|
||||
);
|
||||
exitCode = await runColdBuild(buildParameters, baseImage, workspace, actionFolder);
|
||||
} else {
|
||||
throw hotRunnerError;
|
||||
}
|
||||
}
|
||||
} else if (buildParameters.providerStrategy === 'local') {
|
||||
if (buildParameters.providerStrategy === 'local') {
|
||||
core.info('Building locally');
|
||||
exitCode = await runColdBuild(buildParameters, baseImage, workspace, actionFolder);
|
||||
await PlatformSetup.setup(buildParameters, actionFolder);
|
||||
exitCode =
|
||||
process.platform === 'darwin'
|
||||
? await MacBuilder.run(actionFolder)
|
||||
: await Docker.run(baseImage.toString(), {
|
||||
workspace,
|
||||
actionFolder,
|
||||
...buildParameters,
|
||||
});
|
||||
} else {
|
||||
await Orchestrator.run(buildParameters, baseImage.toString());
|
||||
exitCode = 0;
|
||||
@@ -81,28 +50,4 @@ async function runMain() {
|
||||
}
|
||||
}
|
||||
|
||||
async function runColdBuild(
|
||||
buildParameters: BuildParameters,
|
||||
baseImage: ImageTag,
|
||||
workspace: string,
|
||||
actionFolder: string,
|
||||
): Promise<number> {
|
||||
if (buildParameters.providerStrategy === 'local') {
|
||||
core.info('Building locally');
|
||||
await PlatformSetup.setup(buildParameters, actionFolder);
|
||||
|
||||
return process.platform === 'darwin'
|
||||
? await MacBuilder.run(actionFolder)
|
||||
: await Docker.run(baseImage.toString(), {
|
||||
workspace,
|
||||
actionFolder,
|
||||
...buildParameters,
|
||||
});
|
||||
} else {
|
||||
await Orchestrator.run(buildParameters, baseImage.toString());
|
||||
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
runMain();
|
||||
|
||||
@@ -106,13 +106,6 @@ class BuildParameters {
|
||||
public cacheUnityInstallationOnMac!: boolean;
|
||||
public unityHubVersionOnMac!: string;
|
||||
public dockerWorkspacePath!: string;
|
||||
public hotRunnerEnabled!: boolean;
|
||||
public hotRunnerTransport!: 'websocket' | 'grpc' | 'named-pipe';
|
||||
public hotRunnerHost!: string;
|
||||
public hotRunnerPort!: number;
|
||||
public hotRunnerHealthInterval!: number;
|
||||
public hotRunnerMaxIdle!: number;
|
||||
public hotRunnerFallbackToCold!: boolean;
|
||||
|
||||
public static shouldUseRetainedWorkspaceMode(buildParameters: BuildParameters) {
|
||||
return buildParameters.maxRetainedWorkspaces > 0 && Orchestrator.lockedWorkspace !== ``;
|
||||
@@ -249,13 +242,6 @@ class BuildParameters {
|
||||
cacheUnityInstallationOnMac: Input.cacheUnityInstallationOnMac,
|
||||
unityHubVersionOnMac: Input.unityHubVersionOnMac,
|
||||
dockerWorkspacePath: Input.dockerWorkspacePath,
|
||||
hotRunnerEnabled: Input.hotRunnerEnabled,
|
||||
hotRunnerTransport: Input.hotRunnerTransport,
|
||||
hotRunnerHost: Input.hotRunnerHost,
|
||||
hotRunnerPort: Input.hotRunnerPort,
|
||||
hotRunnerHealthInterval: Input.hotRunnerHealthInterval,
|
||||
hotRunnerMaxIdle: Input.hotRunnerMaxIdle,
|
||||
hotRunnerFallbackToCold: Input.hotRunnerFallbackToCold,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -282,38 +282,6 @@ class Input {
|
||||
return Input.getInput('skipActivation')?.toLowerCase() ?? 'false';
|
||||
}
|
||||
|
||||
static get hotRunnerEnabled(): boolean {
|
||||
const input = Input.getInput('hotRunnerEnabled') ?? false;
|
||||
|
||||
return input === 'true';
|
||||
}
|
||||
|
||||
static get hotRunnerTransport(): 'websocket' | 'grpc' | 'named-pipe' {
|
||||
return (Input.getInput('hotRunnerTransport') ?? 'websocket') as 'websocket' | 'grpc' | 'named-pipe';
|
||||
}
|
||||
|
||||
static get hotRunnerHost(): string {
|
||||
return Input.getInput('hotRunnerHost') ?? 'localhost';
|
||||
}
|
||||
|
||||
static get hotRunnerPort(): number {
|
||||
return Number.parseInt(Input.getInput('hotRunnerPort') ?? '9090', 10);
|
||||
}
|
||||
|
||||
static get hotRunnerHealthInterval(): number {
|
||||
return Number.parseInt(Input.getInput('hotRunnerHealthInterval') ?? '30', 10);
|
||||
}
|
||||
|
||||
static get hotRunnerMaxIdle(): number {
|
||||
return Number.parseInt(Input.getInput('hotRunnerMaxIdle') ?? '3600', 10);
|
||||
}
|
||||
|
||||
static get hotRunnerFallbackToCold(): boolean {
|
||||
const input = Input.getInput('hotRunnerFallbackToCold') ?? 'true';
|
||||
|
||||
return input === 'true';
|
||||
}
|
||||
|
||||
public static ToEnvVarFormat(input: string) {
|
||||
if (input.toUpperCase() === input) {
|
||||
return input;
|
||||
|
||||
@@ -190,6 +190,10 @@ class OrchestratorOptions {
|
||||
return OrchestratorOptions.getInput('pullInputList')?.split(`,`) || [];
|
||||
}
|
||||
|
||||
static get secretSource(): string {
|
||||
return OrchestratorOptions.getInput('secretSource') || '';
|
||||
}
|
||||
|
||||
static get inputPullCommand(): string {
|
||||
const value = OrchestratorOptions.getInput('inputPullCommand');
|
||||
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import * as core from '@actions/core';
|
||||
import Input from '../../input';
|
||||
import { GenericInputReader } from '../../input-readers/generic-input-reader';
|
||||
import OrchestratorOptions from './orchestrator-options';
|
||||
import { SecretSourceService, validateSecretKey } from '../services/secrets/secret-source-service';
|
||||
import OrchestratorLogger from '../services/core/orchestrator-logger';
|
||||
|
||||
const formatFunction = (value: string, arguments_: any[]) => {
|
||||
for (const element of arguments_) {
|
||||
@@ -13,8 +16,6 @@ const formatFunction = (value: string, arguments_: any[]) => {
|
||||
class OrchestratorQueryOverride {
|
||||
static queryOverrides: { [key: string]: string } | undefined;
|
||||
|
||||
// TODO accept premade secret sources or custom secret source definition yamls
|
||||
|
||||
public static query(key: string, alternativeKey: string) {
|
||||
if (OrchestratorQueryOverride.queryOverrides && OrchestratorQueryOverride.queryOverrides[key] !== undefined) {
|
||||
return OrchestratorQueryOverride.queryOverrides[key];
|
||||
@@ -49,14 +50,62 @@ class OrchestratorQueryOverride {
|
||||
throw new Error(`Should not be trying to run override query on ${query}`);
|
||||
}
|
||||
|
||||
return await GenericInputReader.Run(
|
||||
// Validate the query key before interpolating it into a shell command
|
||||
validateSecretKey(query);
|
||||
|
||||
const result = await GenericInputReader.Run(
|
||||
formatFunction(OrchestratorOptions.inputPullCommand, [{ key: 0, value: query }]),
|
||||
);
|
||||
|
||||
// Mask the fetched secret value so it does not appear in GitHub Actions logs
|
||||
if (result && result.trim().length > 0) {
|
||||
core.setSecret(result);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Populate query overrides using either:
|
||||
* 1. Premade/custom secret sources (via secretSource input), or
|
||||
* 2. Shell command (via inputPullCommand, legacy approach)
|
||||
*
|
||||
* The secretSource input takes precedence if set. It supports:
|
||||
* - Premade names: 'aws-secrets-manager', 'aws-parameter-store', 'gcp-secret-manager', 'azure-key-vault', 'env'
|
||||
* - Custom commands: any string containing {0} placeholder
|
||||
* - YAML file path: a path ending in .yml or .yaml containing custom source definitions
|
||||
*/
|
||||
public static async PopulateQueryOverrideInput() {
|
||||
const queries = OrchestratorOptions.pullInputList;
|
||||
OrchestratorQueryOverride.queryOverrides = {};
|
||||
|
||||
const secretSource = OrchestratorOptions.secretSource;
|
||||
|
||||
// Use SecretSourceService if secretSource is configured
|
||||
if (secretSource) {
|
||||
OrchestratorLogger.log(`Using secret source: ${secretSource}`);
|
||||
|
||||
// YAML file: load definitions and use the first source
|
||||
if (secretSource.endsWith('.yml') || secretSource.endsWith('.yaml')) {
|
||||
const definitions = SecretSourceService.loadFromYaml(secretSource);
|
||||
if (definitions.length > 0) {
|
||||
OrchestratorLogger.log(`Loaded ${definitions.length} secret source(s) from ${secretSource}`);
|
||||
for (const key of queries) {
|
||||
OrchestratorQueryOverride.queryOverrides[key] = await SecretSourceService.fetchSecret(definitions[0], key);
|
||||
}
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// Premade or custom command source
|
||||
const results = await SecretSourceService.fetchAll(secretSource, queries);
|
||||
Object.assign(OrchestratorQueryOverride.queryOverrides, results);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// Legacy: use inputPullCommand if set
|
||||
for (const element of queries) {
|
||||
if (OrchestratorQueryOverride.shouldUseOverride(element)) {
|
||||
OrchestratorQueryOverride.queryOverrides[element] = await OrchestratorQueryOverride.queryOverride(element);
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
# Hot Runner Protocol
|
||||
|
||||
Extensible runner registration and persistent Unity editor provider protocol.
|
||||
|
||||
See GitHub Issue for full specification.
|
||||
@@ -1,159 +0,0 @@
|
||||
import OrchestratorLogger from '../core/orchestrator-logger';
|
||||
import { HotRunnerRegistry } from './hot-runner-registry';
|
||||
import { HotRunnerJobRequest, HotRunnerJobResult, HotRunnerStatus, HotRunnerTransport } from './hot-runner-types';
|
||||
|
||||
const POLL_INTERVAL_MS = 1000;
|
||||
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
export type OutputCallback = (output: string) => void;
|
||||
|
||||
export class HotRunnerDispatcher {
|
||||
private transports: Map<string, HotRunnerTransport>;
|
||||
|
||||
constructor(transports: Map<string, HotRunnerTransport>) {
|
||||
this.transports = transports;
|
||||
}
|
||||
|
||||
/**
|
||||
* Dispatch a job to an available hot runner matching the request's build target.
|
||||
* If no runner is immediately available, waits up to the request timeout.
|
||||
* Returns the job result, or throws if no runner becomes available in time.
|
||||
*/
|
||||
async dispatchJob(
|
||||
request: HotRunnerJobRequest,
|
||||
registry: HotRunnerRegistry,
|
||||
unityVersion: string,
|
||||
onOutput?: OutputCallback,
|
||||
): Promise<HotRunnerJobResult> {
|
||||
OrchestratorLogger.log(`[HotRunner] Dispatching job ${request.jobId} (target: ${request.buildTarget})`);
|
||||
|
||||
// Find or wait for an available runner
|
||||
let runner = registry.findAvailableRunner({
|
||||
unityVersion,
|
||||
platform: request.buildTarget,
|
||||
});
|
||||
|
||||
if (!runner) {
|
||||
OrchestratorLogger.log(
|
||||
`[HotRunner] No idle runner available for ${unityVersion}/${request.buildTarget}, waiting...`,
|
||||
);
|
||||
runner = await this.waitForRunner({ unityVersion, platform: request.buildTarget }, request.timeout, registry);
|
||||
}
|
||||
|
||||
// Mark runner as busy
|
||||
registry.updateRunner(runner.id, {
|
||||
state: 'busy',
|
||||
currentJob: request.jobId,
|
||||
});
|
||||
|
||||
const transport = this.transports.get(runner.id);
|
||||
if (!transport) {
|
||||
registry.updateRunner(runner.id, { state: 'idle', currentJob: undefined });
|
||||
throw new Error(`[HotRunner] No transport available for runner ${runner.id}`);
|
||||
}
|
||||
|
||||
OrchestratorLogger.log(`[HotRunner] Sending job ${request.jobId} to runner ${runner.id}`);
|
||||
|
||||
const startTime = Date.now();
|
||||
|
||||
try {
|
||||
const result = await this.executeWithTimeout(transport, request);
|
||||
|
||||
const duration = Date.now() - startTime;
|
||||
OrchestratorLogger.log(
|
||||
`[HotRunner] Job ${request.jobId} completed on runner ${runner.id} in ${duration}ms (exit: ${result.exitCode})`,
|
||||
);
|
||||
|
||||
if (onOutput && result.output) {
|
||||
onOutput(result.output);
|
||||
}
|
||||
|
||||
// Mark runner as idle and increment job count
|
||||
const currentStatus = registry.getRunner(runner.id);
|
||||
registry.updateRunner(runner.id, {
|
||||
state: 'idle',
|
||||
currentJob: undefined,
|
||||
lastJobCompleted: request.jobId,
|
||||
jobsCompleted: (currentStatus?.jobsCompleted ?? 0) + 1,
|
||||
});
|
||||
|
||||
return result;
|
||||
} catch (error: any) {
|
||||
OrchestratorLogger.logWarning(`[HotRunner] Job ${request.jobId} failed on runner ${runner.id}: ${error.message}`);
|
||||
|
||||
// Mark runner as idle despite failure -- the health monitor will recycle if needed
|
||||
registry.updateRunner(runner.id, {
|
||||
state: 'idle',
|
||||
currentJob: undefined,
|
||||
});
|
||||
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Wait for an available runner matching the requirements.
|
||||
* Polls the registry at a fixed interval until one becomes available or timeout expires.
|
||||
*/
|
||||
async waitForRunner(
|
||||
requirements: { unityVersion: string; platform: string },
|
||||
timeoutMs: number,
|
||||
registry: HotRunnerRegistry,
|
||||
): Promise<HotRunnerStatus> {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
|
||||
while (Date.now() < deadline) {
|
||||
const runner = registry.findAvailableRunner(requirements);
|
||||
if (runner) {
|
||||
OrchestratorLogger.log(`[HotRunner] Runner ${runner.id} became available`);
|
||||
|
||||
return runner;
|
||||
}
|
||||
|
||||
await this.sleep(Math.min(POLL_INTERVAL_MS, deadline - Date.now()));
|
||||
}
|
||||
|
||||
throw new Error(
|
||||
`[HotRunner] Timed out waiting for available runner (${requirements.unityVersion}/${requirements.platform}) after ${timeoutMs}ms`,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute a job on a transport with a timeout guard.
|
||||
* On timeout, disconnects the transport to release the connection
|
||||
* and prevent the orphaned sendJob promise from holding resources.
|
||||
*/
|
||||
private async executeWithTimeout(
|
||||
transport: HotRunnerTransport,
|
||||
request: HotRunnerJobRequest,
|
||||
): Promise<HotRunnerJobResult> {
|
||||
const TIMEOUT_SENTINEL = Symbol('timeout');
|
||||
|
||||
const timeoutPromise = new Promise<typeof TIMEOUT_SENTINEL>((resolve) => {
|
||||
setTimeout(() => {
|
||||
resolve(TIMEOUT_SENTINEL);
|
||||
}, request.timeout);
|
||||
});
|
||||
|
||||
const result = await Promise.race([transport.sendJob(request), timeoutPromise]);
|
||||
|
||||
if (result === TIMEOUT_SENTINEL) {
|
||||
// Disconnect the transport to clean up the orphaned sendJob call
|
||||
try {
|
||||
await transport.disconnect();
|
||||
} catch (disconnectError: any) {
|
||||
OrchestratorLogger.logWarning(
|
||||
`[HotRunner] Error disconnecting transport after timeout for job ${request.jobId}: ${disconnectError.message}`,
|
||||
);
|
||||
}
|
||||
|
||||
throw new Error(`[HotRunner] Job ${request.jobId} timed out after ${request.timeout}ms`);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private sleep(ms: number): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||
}
|
||||
}
|
||||
@@ -1,186 +0,0 @@
|
||||
import OrchestratorLogger from '../core/orchestrator-logger';
|
||||
import { HotRunnerRegistry } from './hot-runner-registry';
|
||||
import { HotRunnerTransport } from './hot-runner-types';
|
||||
|
||||
export class HotRunnerHealthMonitor {
|
||||
private intervalHandle: ReturnType<typeof setInterval> | undefined;
|
||||
private registry: HotRunnerRegistry | undefined;
|
||||
private transports: Map<string, HotRunnerTransport> = new Map();
|
||||
|
||||
/**
|
||||
* Start periodic health monitoring for all registered runners.
|
||||
*/
|
||||
startMonitoring(registry: HotRunnerRegistry, interval: number, transports: Map<string, HotRunnerTransport>): void {
|
||||
if (this.intervalHandle) {
|
||||
this.stopMonitoring();
|
||||
}
|
||||
|
||||
this.registry = registry;
|
||||
this.transports = transports;
|
||||
|
||||
OrchestratorLogger.log(`[HotRunner] Starting health monitoring (interval: ${interval}s)`);
|
||||
|
||||
this.intervalHandle = setInterval(() => {
|
||||
this.runHealthChecks().catch((error: any) => {
|
||||
OrchestratorLogger.logWarning(`[HotRunner] Health check cycle failed: ${error.message}`);
|
||||
});
|
||||
}, interval * 1000);
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop periodic health monitoring.
|
||||
*/
|
||||
stopMonitoring(): void {
|
||||
if (this.intervalHandle) {
|
||||
clearInterval(this.intervalHandle);
|
||||
this.intervalHandle = undefined;
|
||||
OrchestratorLogger.log(`[HotRunner] Health monitoring stopped`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check health of a specific runner by ID. Returns true if healthy.
|
||||
*/
|
||||
async checkHealth(runnerId: string): Promise<boolean> {
|
||||
if (!this.registry) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const transport = this.transports.get(runnerId);
|
||||
if (!transport) {
|
||||
OrchestratorLogger.logWarning(`[HotRunner] No transport for runner ${runnerId}`);
|
||||
this.registry.updateRunner(runnerId, {
|
||||
state: 'unhealthy',
|
||||
lastHealthCheck: new Date().toISOString(),
|
||||
});
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
const healthy = await transport.healthCheck();
|
||||
if (healthy) {
|
||||
const status = await transport.getStatus();
|
||||
this.registry.updateRunner(runnerId, {
|
||||
lastHealthCheck: new Date().toISOString(),
|
||||
memoryUsageMB: status.memoryUsageMB,
|
||||
uptime: status.uptime,
|
||||
libraryHash: status.libraryHash,
|
||||
});
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
OrchestratorLogger.logWarning(`[HotRunner] Runner ${runnerId} health check returned false`);
|
||||
this.registry.updateRunner(runnerId, {
|
||||
state: 'unhealthy',
|
||||
lastHealthCheck: new Date().toISOString(),
|
||||
});
|
||||
|
||||
return false;
|
||||
} catch (error: any) {
|
||||
OrchestratorLogger.logWarning(`[HotRunner] Runner ${runnerId} health check failed: ${error.message}`);
|
||||
this.registry.updateRunner(runnerId, {
|
||||
state: 'unhealthy',
|
||||
lastHealthCheck: new Date().toISOString(),
|
||||
});
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Mark an unhealthy runner for cleanup and disconnect its transport.
|
||||
*/
|
||||
async recycleUnhealthyRunner(runnerId: string): Promise<void> {
|
||||
if (!this.registry) {
|
||||
return;
|
||||
}
|
||||
|
||||
OrchestratorLogger.log(`[HotRunner] Recycling unhealthy runner ${runnerId}`);
|
||||
this.registry.updateRunner(runnerId, { state: 'stopping' });
|
||||
|
||||
const transport = this.transports.get(runnerId);
|
||||
if (transport) {
|
||||
try {
|
||||
await transport.disconnect();
|
||||
} catch (error: any) {
|
||||
OrchestratorLogger.logWarning(`[HotRunner] Error disconnecting runner ${runnerId}: ${error.message}`);
|
||||
}
|
||||
this.transports.delete(runnerId);
|
||||
}
|
||||
|
||||
this.registry.unregisterRunner(runnerId);
|
||||
OrchestratorLogger.log(`[HotRunner] Runner ${runnerId} recycled and removed`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Recycle a runner that has been idle longer than the maximum idle time.
|
||||
*/
|
||||
async recycleIdleRunner(runnerId: string, maxIdleTime: number): Promise<void> {
|
||||
if (!this.registry) {
|
||||
return;
|
||||
}
|
||||
|
||||
const runner = this.registry.getRunner(runnerId);
|
||||
if (!runner || runner.state !== 'idle') {
|
||||
return;
|
||||
}
|
||||
|
||||
const lastCheckTime = new Date(runner.lastHealthCheck).getTime();
|
||||
const now = Date.now();
|
||||
const idleSeconds = (now - lastCheckTime) / 1000;
|
||||
|
||||
if (idleSeconds >= maxIdleTime) {
|
||||
OrchestratorLogger.log(
|
||||
`[HotRunner] Runner ${runnerId} idle for ${Math.floor(idleSeconds)}s (max: ${maxIdleTime}s), recycling`,
|
||||
);
|
||||
await this.recycleUnhealthyRunner(runnerId);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Run health checks and idle-recycle checks for all registered runners.
|
||||
*/
|
||||
private async runHealthChecks(): Promise<void> {
|
||||
if (!this.registry) {
|
||||
return;
|
||||
}
|
||||
|
||||
const runners = this.registry.listRunners();
|
||||
|
||||
for (const runner of runners) {
|
||||
if (runner.state === 'stopping') {
|
||||
continue;
|
||||
}
|
||||
|
||||
const healthy = await this.checkHealth(runner.id);
|
||||
|
||||
if (!healthy && runner.state !== 'starting') {
|
||||
await this.recycleUnhealthyRunner(runner.id);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Check for idle timeout
|
||||
const config = this.registry.getConfig(runner.id);
|
||||
if (config && runner.state === 'idle') {
|
||||
await this.recycleIdleRunner(runner.id, config.maxIdleTime);
|
||||
}
|
||||
|
||||
// Check for max jobs before recycle
|
||||
if (config && config.maxJobsBeforeRecycle > 0 && runner.jobsCompleted >= config.maxJobsBeforeRecycle) {
|
||||
OrchestratorLogger.log(
|
||||
`[HotRunner] Runner ${runner.id} reached max jobs (${runner.jobsCompleted}/${config.maxJobsBeforeRecycle}), recycling`,
|
||||
);
|
||||
await this.recycleUnhealthyRunner(runner.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether health monitoring is currently active.
|
||||
*/
|
||||
get isMonitoring(): boolean {
|
||||
return this.intervalHandle !== undefined;
|
||||
}
|
||||
}
|
||||
@@ -1,315 +0,0 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { customAlphabet } from 'nanoid';
|
||||
import OrchestratorLogger from '../core/orchestrator-logger';
|
||||
import { HotRunnerConfig, HotRunnerStatus } from './hot-runner-types';
|
||||
|
||||
const generateId = customAlphabet('abcdefghijklmnopqrstuvwxyz0123456789', 12);
|
||||
|
||||
const PERSISTENCE_FILENAME = 'hot-runners.json';
|
||||
|
||||
const VALID_RUNNER_STATES: ReadonlySet<string> = new Set(['idle', 'busy', 'starting', 'stopping', 'unhealthy']);
|
||||
|
||||
export interface HotRunnerFilter {
|
||||
platform?: string;
|
||||
state?: string;
|
||||
unityVersion?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate that a restored runner entry has all required fields with correct types.
|
||||
* Returns true if the entry is a valid HotRunnerStatus, false otherwise.
|
||||
*/
|
||||
function isValidRunnerStatus(entry: unknown): entry is HotRunnerStatus {
|
||||
if (typeof entry !== 'object' || entry === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const record = entry as Record<string, unknown>;
|
||||
|
||||
return (
|
||||
typeof record.id === 'string' &&
|
||||
record.id.length > 0 &&
|
||||
typeof record.state === 'string' &&
|
||||
VALID_RUNNER_STATES.has(record.state) &&
|
||||
typeof record.unityVersion === 'string' &&
|
||||
typeof record.platform === 'string' &&
|
||||
typeof record.uptime === 'number' &&
|
||||
typeof record.jobsCompleted === 'number' &&
|
||||
typeof record.lastHealthCheck === 'string' &&
|
||||
typeof record.memoryUsageMB === 'number'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate that a restored config entry has all required fields with correct types.
|
||||
* Returns true if the entry is a valid HotRunnerConfig, false otherwise.
|
||||
*/
|
||||
function isValidRunnerConfig(entry: unknown): entry is HotRunnerConfig {
|
||||
if (typeof entry !== 'object' || entry === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const record = entry as Record<string, unknown>;
|
||||
|
||||
return (
|
||||
typeof record.enabled === 'boolean' &&
|
||||
typeof record.transport === 'string' &&
|
||||
['websocket', 'grpc', 'named-pipe'].includes(record.transport) &&
|
||||
typeof record.host === 'string' &&
|
||||
typeof record.port === 'number' &&
|
||||
typeof record.healthCheckInterval === 'number' &&
|
||||
typeof record.maxIdleTime === 'number' &&
|
||||
typeof record.maxJobsBeforeRecycle === 'number'
|
||||
);
|
||||
}
|
||||
|
||||
export class HotRunnerRegistry {
|
||||
private runners: Map<string, HotRunnerStatus> = new Map();
|
||||
private configs: Map<string, HotRunnerConfig> = new Map();
|
||||
private persistencePath: string;
|
||||
|
||||
constructor(persistenceDirectory?: string) {
|
||||
this.persistencePath = persistenceDirectory ? path.join(persistenceDirectory, PERSISTENCE_FILENAME) : '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a new hot runner. Returns the generated runner ID.
|
||||
*/
|
||||
registerRunner(config: HotRunnerConfig): string {
|
||||
const id = `hr-${generateId()}`;
|
||||
|
||||
const status: HotRunnerStatus = {
|
||||
id,
|
||||
state: 'starting',
|
||||
unityVersion: config.unityVersion ?? 'unknown',
|
||||
platform: config.platform ?? 'unknown',
|
||||
uptime: 0,
|
||||
jobsCompleted: 0,
|
||||
lastHealthCheck: new Date().toISOString(),
|
||||
memoryUsageMB: 0,
|
||||
};
|
||||
|
||||
this.runners.set(id, status);
|
||||
this.configs.set(id, config);
|
||||
OrchestratorLogger.log(`[HotRunner] Registered runner ${id} (${status.unityVersion}/${status.platform})`);
|
||||
|
||||
this.persist();
|
||||
|
||||
return id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a runner from the registry.
|
||||
*/
|
||||
unregisterRunner(id: string): void {
|
||||
const existed = this.runners.delete(id);
|
||||
this.configs.delete(id);
|
||||
|
||||
if (existed) {
|
||||
OrchestratorLogger.log(`[HotRunner] Unregistered runner ${id}`);
|
||||
this.persist();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a runner's current status by ID.
|
||||
*/
|
||||
getRunner(id: string): HotRunnerStatus | undefined {
|
||||
return this.runners.get(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a runner's config by ID.
|
||||
*/
|
||||
getConfig(id: string): HotRunnerConfig | undefined {
|
||||
return this.configs.get(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* List all runners, optionally filtered by platform, state, or Unity version.
|
||||
*/
|
||||
listRunners(filter?: HotRunnerFilter): HotRunnerStatus[] {
|
||||
let results = [...this.runners.values()];
|
||||
|
||||
if (filter?.platform) {
|
||||
results = results.filter((runner) => runner.platform === filter.platform);
|
||||
}
|
||||
|
||||
if (filter?.state) {
|
||||
results = results.filter((runner) => runner.state === filter.state);
|
||||
}
|
||||
|
||||
if (filter?.unityVersion) {
|
||||
results = results.filter((runner) => runner.unityVersion === filter.unityVersion);
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find an idle runner matching the given Unity version and platform requirements.
|
||||
*/
|
||||
findAvailableRunner(requirements: { unityVersion: string; platform: string }): HotRunnerStatus | undefined {
|
||||
return this.listRunners({
|
||||
state: 'idle',
|
||||
unityVersion: requirements.unityVersion,
|
||||
platform: requirements.platform,
|
||||
})[0];
|
||||
}
|
||||
|
||||
/**
|
||||
* Update a runner's status fields. Merges partial updates into existing status.
|
||||
*/
|
||||
updateRunner(id: string, update: Partial<HotRunnerStatus>): void {
|
||||
const existing = this.runners.get(id);
|
||||
if (!existing) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.runners.set(id, { ...existing, ...update, id });
|
||||
this.persist();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the total number of registered runners.
|
||||
*/
|
||||
get size(): number {
|
||||
return this.runners.size;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate all runners in the registry and reset invalid ones to 'unhealthy'.
|
||||
* Returns the number of runners that were repaired.
|
||||
*/
|
||||
validateAndRepair(): number {
|
||||
let repaired = 0;
|
||||
|
||||
for (const [id, status] of this.runners) {
|
||||
// Cast to unknown to bypass the type guard narrowing to 'never',
|
||||
// since the Map is typed as HotRunnerStatus but entries may have
|
||||
// been corrupted via direct deserialization or unsafe casts.
|
||||
const entry = status as unknown as Record<string, unknown>;
|
||||
|
||||
if (!isValidRunnerStatus(entry)) {
|
||||
OrchestratorLogger.logWarning(`[HotRunner] Runner ${id} has invalid state, marking as unhealthy`);
|
||||
this.runners.set(id, {
|
||||
id,
|
||||
state: 'unhealthy',
|
||||
unityVersion: typeof entry.unityVersion === 'string' ? entry.unityVersion : 'unknown',
|
||||
platform: typeof entry.platform === 'string' ? entry.platform : 'unknown',
|
||||
uptime: typeof entry.uptime === 'number' ? entry.uptime : 0,
|
||||
jobsCompleted: typeof entry.jobsCompleted === 'number' ? entry.jobsCompleted : 0,
|
||||
lastHealthCheck: typeof entry.lastHealthCheck === 'string' ? entry.lastHealthCheck : new Date().toISOString(),
|
||||
memoryUsageMB: typeof entry.memoryUsageMB === 'number' ? entry.memoryUsageMB : 0,
|
||||
});
|
||||
repaired++;
|
||||
}
|
||||
}
|
||||
|
||||
if (repaired > 0) {
|
||||
this.persist();
|
||||
}
|
||||
|
||||
return repaired;
|
||||
}
|
||||
|
||||
/**
|
||||
* Persist current registry state to disk for crash recovery.
|
||||
* Validates data before writing to prevent persisting corrupt state.
|
||||
*/
|
||||
private persist(): void {
|
||||
if (!this.persistencePath) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// Validate data before persisting
|
||||
for (const [id, status] of this.runners) {
|
||||
if (!isValidRunnerStatus(status)) {
|
||||
OrchestratorLogger.logWarning(`[HotRunner] Skipping persistence -- runner ${id} has invalid state`);
|
||||
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const data = {
|
||||
runners: Object.fromEntries(this.runners),
|
||||
configs: Object.fromEntries(this.configs),
|
||||
};
|
||||
const directory = path.dirname(this.persistencePath);
|
||||
if (!fs.existsSync(directory)) {
|
||||
fs.mkdirSync(directory, { recursive: true });
|
||||
}
|
||||
|
||||
fs.writeFileSync(this.persistencePath, JSON.stringify(data, undefined, 2));
|
||||
} catch (error: any) {
|
||||
OrchestratorLogger.logWarning(`[HotRunner] Failed to persist registry: ${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Load registry state from disk. Returns the number of runners restored.
|
||||
* Validates each restored entry and discards corrupt entries with warnings.
|
||||
* If the persistence file itself is corrupt (invalid JSON), starts with
|
||||
* an empty registry.
|
||||
*/
|
||||
loadFromDisk(): number {
|
||||
if (!this.persistencePath || !fs.existsSync(this.persistencePath)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
let data: any;
|
||||
|
||||
try {
|
||||
const raw = fs.readFileSync(this.persistencePath, 'utf8');
|
||||
data = JSON.parse(raw);
|
||||
} catch (error: any) {
|
||||
OrchestratorLogger.logWarning(
|
||||
`[HotRunner] Persistence file is corrupt, starting with empty registry: ${error.message}`,
|
||||
);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (typeof data !== 'object' || data === null) {
|
||||
OrchestratorLogger.logWarning('[HotRunner] Persistence file has invalid structure, starting with empty registry');
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
let discarded = 0;
|
||||
|
||||
if (data.runners && typeof data.runners === 'object') {
|
||||
for (const [id, status] of Object.entries(data.runners)) {
|
||||
if (isValidRunnerStatus(status)) {
|
||||
this.runners.set(id, status);
|
||||
} else {
|
||||
OrchestratorLogger.logWarning(`[HotRunner] Discarding invalid runner entry '${id}' from persistence file`);
|
||||
discarded++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (data.configs && typeof data.configs === 'object') {
|
||||
for (const [id, config] of Object.entries(data.configs)) {
|
||||
// Only restore configs for runners that were successfully restored
|
||||
if (this.runners.has(id)) {
|
||||
if (isValidRunnerConfig(config)) {
|
||||
this.configs.set(id, config);
|
||||
} else {
|
||||
OrchestratorLogger.logWarning(`[HotRunner] Discarding invalid config entry '${id}' from persistence file`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (discarded > 0) {
|
||||
OrchestratorLogger.logWarning(`[HotRunner] Discarded ${discarded} invalid runner(s) from persistence file`);
|
||||
}
|
||||
|
||||
OrchestratorLogger.log(`[HotRunner] Restored ${this.runners.size} runner(s) from disk`);
|
||||
|
||||
return this.runners.size;
|
||||
}
|
||||
}
|
||||
@@ -1,166 +0,0 @@
|
||||
import OrchestratorLogger from '../core/orchestrator-logger';
|
||||
import { HotRunnerRegistry } from './hot-runner-registry';
|
||||
import { HotRunnerHealthMonitor } from './hot-runner-health-monitor';
|
||||
import { HotRunnerDispatcher, OutputCallback } from './hot-runner-dispatcher';
|
||||
import {
|
||||
HotRunnerConfig,
|
||||
HotRunnerJobRequest,
|
||||
HotRunnerJobResult,
|
||||
HotRunnerStatus,
|
||||
HotRunnerTransport,
|
||||
} from './hot-runner-types';
|
||||
import BuildParameters from '../../../build-parameters';
|
||||
|
||||
export class HotRunnerService {
|
||||
private registry: HotRunnerRegistry;
|
||||
private healthMonitor: HotRunnerHealthMonitor;
|
||||
private dispatcher: HotRunnerDispatcher;
|
||||
private transports: Map<string, HotRunnerTransport> = new Map();
|
||||
private config: HotRunnerConfig | undefined;
|
||||
|
||||
constructor(persistenceDirectory?: string) {
|
||||
this.registry = new HotRunnerRegistry(persistenceDirectory);
|
||||
this.healthMonitor = new HotRunnerHealthMonitor();
|
||||
this.dispatcher = new HotRunnerDispatcher(this.transports);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the hot runner service: load persisted state, start health monitoring.
|
||||
*/
|
||||
async initialize(config: HotRunnerConfig): Promise<void> {
|
||||
this.config = config;
|
||||
|
||||
OrchestratorLogger.log(
|
||||
`[HotRunner] Initializing service (transport: ${config.transport}, ${config.host}:${config.port})`,
|
||||
);
|
||||
|
||||
// Attempt to restore previously registered runners from disk
|
||||
const restored = this.registry.loadFromDisk();
|
||||
if (restored > 0) {
|
||||
OrchestratorLogger.log(`[HotRunner] Restored ${restored} runner(s) from persistence`);
|
||||
}
|
||||
|
||||
// Start health monitoring
|
||||
this.healthMonitor.startMonitoring(this.registry, config.healthCheckInterval, this.transports);
|
||||
|
||||
OrchestratorLogger.log(`[HotRunner] Service initialized`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a runner with a transport implementation.
|
||||
* Returns the runner ID.
|
||||
*/
|
||||
registerRunner(config: HotRunnerConfig, transport: HotRunnerTransport): string {
|
||||
const id = this.registry.registerRunner(config);
|
||||
this.transports.set(id, transport);
|
||||
|
||||
return id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Submit a build job to an available hot runner.
|
||||
* Converts BuildParameters to a HotRunnerJobRequest and dispatches.
|
||||
*/
|
||||
async submitBuild(params: BuildParameters, onOutput?: OutputCallback): Promise<HotRunnerJobResult> {
|
||||
const request: HotRunnerJobRequest = {
|
||||
jobId: params.buildGuid || `build-${Date.now()}`,
|
||||
buildMethod: params.buildMethod || undefined,
|
||||
buildTarget: params.targetPlatform,
|
||||
buildPath: params.buildPath,
|
||||
customParameters: params.customParameters ? this.parseCustomParameters(params.customParameters) : undefined,
|
||||
timeout: 30 * 60 * 1000, // 30 minutes default
|
||||
};
|
||||
|
||||
OrchestratorLogger.log(`[HotRunner] Submitting build: ${request.jobId} (target: ${request.buildTarget})`);
|
||||
|
||||
return this.dispatcher.dispatchJob(request, this.registry, params.editorVersion, onOutput);
|
||||
}
|
||||
|
||||
/**
|
||||
* Submit a test job to an available hot runner.
|
||||
* Converts BuildParameters and optional suite config to a test-mode HotRunnerJobRequest.
|
||||
*/
|
||||
async submitTest(
|
||||
params: BuildParameters,
|
||||
suiteConfig?: { testMode?: 'editmode' | 'playmode'; testSuitePath?: string },
|
||||
onOutput?: OutputCallback,
|
||||
): Promise<HotRunnerJobResult> {
|
||||
const request: HotRunnerJobRequest = {
|
||||
jobId: params.buildGuid || `test-${Date.now()}`,
|
||||
buildTarget: params.targetPlatform,
|
||||
customParameters: params.customParameters ? this.parseCustomParameters(params.customParameters) : undefined,
|
||||
timeout: 30 * 60 * 1000, // 30 minutes default
|
||||
testMode: suiteConfig?.testMode ?? 'editmode',
|
||||
testSuitePath: suiteConfig?.testSuitePath,
|
||||
};
|
||||
|
||||
OrchestratorLogger.log(`[HotRunner] Submitting test: ${request.jobId} (mode: ${request.testMode})`);
|
||||
|
||||
return this.dispatcher.dispatchJob(request, this.registry, params.editorVersion, onOutput);
|
||||
}
|
||||
|
||||
/**
|
||||
* Shut down the service: stop health monitoring, disconnect all transports,
|
||||
* and unregister all runners.
|
||||
*/
|
||||
async shutdown(): Promise<void> {
|
||||
OrchestratorLogger.log(`[HotRunner] Shutting down service`);
|
||||
|
||||
this.healthMonitor.stopMonitoring();
|
||||
|
||||
const disconnectPromises: Promise<void>[] = [];
|
||||
for (const [id, transport] of this.transports.entries()) {
|
||||
disconnectPromises.push(
|
||||
transport.disconnect().catch((error: any) => {
|
||||
OrchestratorLogger.logWarning(`[HotRunner] Error disconnecting runner ${id}: ${error.message}`);
|
||||
}),
|
||||
);
|
||||
}
|
||||
await Promise.all(disconnectPromises);
|
||||
|
||||
this.transports.clear();
|
||||
|
||||
OrchestratorLogger.log(`[HotRunner] Service shut down`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the status of all registered runners.
|
||||
*/
|
||||
getStatus(): HotRunnerStatus[] {
|
||||
return this.registry.listRunners();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the underlying registry (for testing or advanced use).
|
||||
*/
|
||||
getRegistry(): HotRunnerRegistry {
|
||||
return this.registry;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a space-separated custom parameters string into a key-value map.
|
||||
* Handles `-key value` and `-key=value` formats.
|
||||
*/
|
||||
private parseCustomParameters(raw: string): Record<string, string> {
|
||||
const result: Record<string, string> = {};
|
||||
const parts = raw.trim().split(/\s+/);
|
||||
|
||||
for (let i = 0; i < parts.length; i++) {
|
||||
const part = parts[i];
|
||||
if (part.startsWith('-')) {
|
||||
const key = part.replace(/^-+/, '');
|
||||
if (key.includes('=')) {
|
||||
const [k, ...v] = key.split('=');
|
||||
result[k] = v.join('=');
|
||||
} else if (i + 1 < parts.length && !parts[i + 1].startsWith('-')) {
|
||||
result[key] = parts[i + 1];
|
||||
i++;
|
||||
} else {
|
||||
result[key] = 'true';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
export interface HotRunnerConfig {
|
||||
enabled: boolean;
|
||||
transport: 'websocket' | 'grpc' | 'named-pipe';
|
||||
host: string;
|
||||
port: number;
|
||||
healthCheckInterval: number; // seconds
|
||||
maxIdleTime: number; // seconds before recycling
|
||||
maxJobsBeforeRecycle: number;
|
||||
unityVersion?: string;
|
||||
platform?: string;
|
||||
}
|
||||
|
||||
export interface HotRunnerStatus {
|
||||
id: string;
|
||||
state: 'idle' | 'busy' | 'starting' | 'stopping' | 'unhealthy';
|
||||
unityVersion: string;
|
||||
platform: string;
|
||||
currentJob?: string;
|
||||
lastJobCompleted?: string;
|
||||
uptime: number;
|
||||
jobsCompleted: number;
|
||||
lastHealthCheck: string;
|
||||
memoryUsageMB: number;
|
||||
libraryHash?: string;
|
||||
}
|
||||
|
||||
export interface HotRunnerJobRequest {
|
||||
jobId: string;
|
||||
buildMethod?: string;
|
||||
buildTarget: string;
|
||||
buildPath?: string;
|
||||
customParameters?: Record<string, string>;
|
||||
timeout: number;
|
||||
testMode?: 'editmode' | 'playmode';
|
||||
testSuitePath?: string;
|
||||
}
|
||||
|
||||
export interface HotRunnerJobResult {
|
||||
jobId: string;
|
||||
success: boolean;
|
||||
exitCode: number;
|
||||
duration: number;
|
||||
output: string;
|
||||
artifacts?: string[];
|
||||
testResults?: string; // path to test result file
|
||||
}
|
||||
|
||||
export interface HotRunnerTransport {
|
||||
connect(config: HotRunnerConfig): Promise<void>;
|
||||
disconnect(): Promise<void>;
|
||||
sendJob(request: HotRunnerJobRequest): Promise<HotRunnerJobResult>;
|
||||
getStatus(): Promise<HotRunnerStatus>;
|
||||
healthCheck(): Promise<boolean>;
|
||||
}
|
||||
@@ -1,740 +0,0 @@
|
||||
import fs from 'node:fs';
|
||||
import { HotRunnerRegistry } from './hot-runner-registry';
|
||||
import { HotRunnerHealthMonitor } from './hot-runner-health-monitor';
|
||||
import { HotRunnerDispatcher } from './hot-runner-dispatcher';
|
||||
import { HotRunnerService } from './hot-runner-service';
|
||||
import {
|
||||
HotRunnerConfig,
|
||||
HotRunnerJobRequest,
|
||||
HotRunnerJobResult,
|
||||
HotRunnerStatus,
|
||||
HotRunnerTransport,
|
||||
} from './hot-runner-types';
|
||||
|
||||
// Mock dependencies
|
||||
jest.mock('node:fs');
|
||||
jest.mock('../core/orchestrator-logger');
|
||||
|
||||
const mockFs = fs as jest.Mocked<typeof fs>;
|
||||
|
||||
function createMockConfig(overrides?: Partial<HotRunnerConfig>): HotRunnerConfig {
|
||||
return {
|
||||
enabled: true,
|
||||
transport: 'websocket',
|
||||
host: 'localhost',
|
||||
port: 9090,
|
||||
healthCheckInterval: 30,
|
||||
maxIdleTime: 3600,
|
||||
maxJobsBeforeRecycle: 100,
|
||||
unityVersion: '2022.3.0f1',
|
||||
platform: 'StandaloneWindows64',
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function createMockTransport(overrides?: Partial<HotRunnerTransport>): HotRunnerTransport {
|
||||
return {
|
||||
// eslint-disable-next-line unicorn/no-useless-undefined
|
||||
connect: jest.fn().mockResolvedValue(undefined),
|
||||
// eslint-disable-next-line unicorn/no-useless-undefined
|
||||
disconnect: jest.fn().mockResolvedValue(undefined),
|
||||
sendJob: jest.fn().mockResolvedValue({
|
||||
jobId: 'test-job',
|
||||
success: true,
|
||||
exitCode: 0,
|
||||
duration: 5000,
|
||||
output: 'Build succeeded',
|
||||
artifacts: ['build/output.exe'],
|
||||
} as HotRunnerJobResult),
|
||||
getStatus: jest.fn().mockResolvedValue({
|
||||
id: 'mock-runner',
|
||||
state: 'idle',
|
||||
unityVersion: '2022.3.0f1',
|
||||
platform: 'StandaloneWindows64',
|
||||
uptime: 3600,
|
||||
jobsCompleted: 5,
|
||||
lastHealthCheck: new Date().toISOString(),
|
||||
memoryUsageMB: 1024,
|
||||
} as HotRunnerStatus),
|
||||
healthCheck: jest.fn().mockResolvedValue(true),
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function createMockJobRequest(overrides?: Partial<HotRunnerJobRequest>): HotRunnerJobRequest {
|
||||
return {
|
||||
jobId: 'job-001',
|
||||
buildTarget: 'StandaloneWindows64',
|
||||
timeout: 60000,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
// --- Registry Tests ---
|
||||
|
||||
describe('HotRunnerRegistry', () => {
|
||||
let registry: HotRunnerRegistry;
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
registry = new HotRunnerRegistry();
|
||||
});
|
||||
|
||||
it('should register a runner and return an ID', () => {
|
||||
const config = createMockConfig();
|
||||
const id = registry.registerRunner(config);
|
||||
|
||||
expect(id).toMatch(/^hr-/);
|
||||
expect(registry.size).toBe(1);
|
||||
});
|
||||
|
||||
it('should retrieve a registered runner by ID', () => {
|
||||
const config = createMockConfig();
|
||||
const id = registry.registerRunner(config);
|
||||
const runner = registry.getRunner(id);
|
||||
|
||||
expect(runner).toBeDefined();
|
||||
expect(runner!.id).toBe(id);
|
||||
expect(runner!.state).toBe('starting');
|
||||
expect(runner!.unityVersion).toBe('2022.3.0f1');
|
||||
expect(runner!.platform).toBe('StandaloneWindows64');
|
||||
});
|
||||
|
||||
it('should return undefined for unknown runner ID', () => {
|
||||
const runner = registry.getRunner('nonexistent');
|
||||
expect(runner).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should unregister a runner', () => {
|
||||
const id = registry.registerRunner(createMockConfig());
|
||||
expect(registry.size).toBe(1);
|
||||
|
||||
registry.unregisterRunner(id);
|
||||
expect(registry.size).toBe(0);
|
||||
expect(registry.getRunner(id)).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should handle unregistering a nonexistent runner gracefully', () => {
|
||||
registry.unregisterRunner('nonexistent');
|
||||
expect(registry.size).toBe(0);
|
||||
});
|
||||
|
||||
it('should list all runners without filter', () => {
|
||||
registry.registerRunner(createMockConfig({ platform: 'StandaloneWindows64' }));
|
||||
registry.registerRunner(createMockConfig({ platform: 'StandaloneLinux64' }));
|
||||
registry.registerRunner(createMockConfig({ platform: 'StandaloneOSX' }));
|
||||
|
||||
const all = registry.listRunners();
|
||||
expect(all).toHaveLength(3);
|
||||
});
|
||||
|
||||
it('should filter runners by platform', () => {
|
||||
registry.registerRunner(createMockConfig({ platform: 'StandaloneWindows64' }));
|
||||
registry.registerRunner(createMockConfig({ platform: 'StandaloneLinux64' }));
|
||||
registry.registerRunner(createMockConfig({ platform: 'StandaloneWindows64' }));
|
||||
|
||||
const windows = registry.listRunners({ platform: 'StandaloneWindows64' });
|
||||
expect(windows).toHaveLength(2);
|
||||
|
||||
const linux = registry.listRunners({ platform: 'StandaloneLinux64' });
|
||||
expect(linux).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('should filter runners by state', () => {
|
||||
const id1 = registry.registerRunner(createMockConfig());
|
||||
registry.registerRunner(createMockConfig());
|
||||
|
||||
registry.updateRunner(id1, { state: 'idle' });
|
||||
|
||||
// second runner remains in 'starting' state
|
||||
|
||||
const idle = registry.listRunners({ state: 'idle' });
|
||||
expect(idle).toHaveLength(1);
|
||||
expect(idle[0].id).toBe(id1);
|
||||
});
|
||||
|
||||
it('should filter runners by Unity version', () => {
|
||||
registry.registerRunner(createMockConfig({ unityVersion: '2022.3.0f1' }));
|
||||
registry.registerRunner(createMockConfig({ unityVersion: '2023.1.0f1' }));
|
||||
registry.registerRunner(createMockConfig({ unityVersion: '2022.3.0f1' }));
|
||||
|
||||
const v2022 = registry.listRunners({ unityVersion: '2022.3.0f1' });
|
||||
expect(v2022).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('should find an available idle runner matching requirements', () => {
|
||||
const id1 = registry.registerRunner(
|
||||
createMockConfig({ unityVersion: '2022.3.0f1', platform: 'StandaloneWindows64' }),
|
||||
);
|
||||
registry.updateRunner(id1, { state: 'idle' });
|
||||
|
||||
const id2 = registry.registerRunner(
|
||||
createMockConfig({ unityVersion: '2023.1.0f1', platform: 'StandaloneLinux64' }),
|
||||
);
|
||||
registry.updateRunner(id2, { state: 'idle' });
|
||||
|
||||
const found = registry.findAvailableRunner({
|
||||
unityVersion: '2022.3.0f1',
|
||||
platform: 'StandaloneWindows64',
|
||||
});
|
||||
|
||||
expect(found).toBeDefined();
|
||||
expect(found!.id).toBe(id1);
|
||||
});
|
||||
|
||||
it('should return undefined when no runner matches requirements', () => {
|
||||
const id = registry.registerRunner(
|
||||
createMockConfig({ unityVersion: '2022.3.0f1', platform: 'StandaloneWindows64' }),
|
||||
);
|
||||
registry.updateRunner(id, { state: 'idle' });
|
||||
|
||||
const found = registry.findAvailableRunner({
|
||||
unityVersion: '2023.1.0f1',
|
||||
platform: 'StandaloneLinux64',
|
||||
});
|
||||
|
||||
expect(found).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should update runner status fields', () => {
|
||||
const id = registry.registerRunner(createMockConfig());
|
||||
registry.updateRunner(id, { state: 'idle', memoryUsageMB: 2048 });
|
||||
|
||||
const runner = registry.getRunner(id);
|
||||
expect(runner!.state).toBe('idle');
|
||||
expect(runner!.memoryUsageMB).toBe(2048);
|
||||
|
||||
// ID should not be overridden by the update
|
||||
expect(runner!.id).toBe(id);
|
||||
});
|
||||
|
||||
it('should persist and load registry from disk', () => {
|
||||
const persistenceRegistry = new HotRunnerRegistry('/tmp/test');
|
||||
mockFs.existsSync.mockReturnValue(true);
|
||||
mockFs.writeFileSync.mockImplementation(() => {});
|
||||
mockFs.mkdirSync.mockImplementation(() => '' as any);
|
||||
|
||||
const id = persistenceRegistry.registerRunner(createMockConfig());
|
||||
|
||||
// Verify writeFileSync was called for persistence
|
||||
expect(mockFs.writeFileSync).toHaveBeenCalled();
|
||||
const writtenData = JSON.parse((mockFs.writeFileSync as jest.Mock).mock.calls[0][1] as string);
|
||||
expect(writtenData.runners).toBeDefined();
|
||||
expect(writtenData.runners[id]).toBeDefined();
|
||||
});
|
||||
|
||||
it('should load runners from disk on loadFromDisk', () => {
|
||||
const persistenceRegistry = new HotRunnerRegistry('/tmp/test');
|
||||
const storedData = {
|
||||
runners: {
|
||||
'hr-restored': {
|
||||
id: 'hr-restored',
|
||||
state: 'idle',
|
||||
unityVersion: '2022.3.0f1',
|
||||
platform: 'StandaloneWindows64',
|
||||
uptime: 100,
|
||||
jobsCompleted: 3,
|
||||
lastHealthCheck: new Date().toISOString(),
|
||||
memoryUsageMB: 512,
|
||||
},
|
||||
},
|
||||
configs: {
|
||||
'hr-restored': createMockConfig(),
|
||||
},
|
||||
};
|
||||
|
||||
mockFs.existsSync.mockReturnValue(true);
|
||||
mockFs.readFileSync.mockReturnValue(JSON.stringify(storedData));
|
||||
|
||||
const count = persistenceRegistry.loadFromDisk();
|
||||
expect(count).toBe(1);
|
||||
expect(persistenceRegistry.getRunner('hr-restored')).toBeDefined();
|
||||
});
|
||||
|
||||
it('should discard invalid runner entries when loading from disk', () => {
|
||||
const persistenceRegistry = new HotRunnerRegistry('/tmp/test');
|
||||
const storedData = {
|
||||
runners: {
|
||||
'hr-valid': {
|
||||
id: 'hr-valid',
|
||||
state: 'idle',
|
||||
unityVersion: '2022.3.0f1',
|
||||
platform: 'StandaloneWindows64',
|
||||
uptime: 100,
|
||||
jobsCompleted: 3,
|
||||
lastHealthCheck: new Date().toISOString(),
|
||||
memoryUsageMB: 512,
|
||||
},
|
||||
'hr-invalid': {
|
||||
// Missing required fields like state, unityVersion
|
||||
id: 'hr-invalid',
|
||||
},
|
||||
'hr-bad-state': {
|
||||
id: 'hr-bad-state',
|
||||
state: 'nonexistent-state',
|
||||
unityVersion: '2022.3.0f1',
|
||||
platform: 'StandaloneWindows64',
|
||||
uptime: 0,
|
||||
jobsCompleted: 0,
|
||||
lastHealthCheck: new Date().toISOString(),
|
||||
memoryUsageMB: 0,
|
||||
},
|
||||
},
|
||||
configs: {
|
||||
'hr-valid': createMockConfig(),
|
||||
'hr-invalid': createMockConfig(),
|
||||
'hr-bad-state': createMockConfig(),
|
||||
},
|
||||
};
|
||||
|
||||
mockFs.existsSync.mockReturnValue(true);
|
||||
mockFs.readFileSync.mockReturnValue(JSON.stringify(storedData));
|
||||
|
||||
const count = persistenceRegistry.loadFromDisk();
|
||||
expect(count).toBe(1);
|
||||
expect(persistenceRegistry.getRunner('hr-valid')).toBeDefined();
|
||||
expect(persistenceRegistry.getRunner('hr-invalid')).toBeUndefined();
|
||||
expect(persistenceRegistry.getRunner('hr-bad-state')).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should handle corrupt JSON persistence file gracefully', () => {
|
||||
const persistenceRegistry = new HotRunnerRegistry('/tmp/test');
|
||||
|
||||
mockFs.existsSync.mockReturnValue(true);
|
||||
mockFs.readFileSync.mockReturnValue('{ invalid json !!!');
|
||||
|
||||
const count = persistenceRegistry.loadFromDisk();
|
||||
expect(count).toBe(0);
|
||||
expect(persistenceRegistry.size).toBe(0);
|
||||
});
|
||||
|
||||
it('should handle persistence file with invalid top-level structure', () => {
|
||||
const persistenceRegistry = new HotRunnerRegistry('/tmp/test');
|
||||
|
||||
mockFs.existsSync.mockReturnValue(true);
|
||||
mockFs.readFileSync.mockReturnValue('"just a string"');
|
||||
|
||||
const count = persistenceRegistry.loadFromDisk();
|
||||
expect(count).toBe(0);
|
||||
});
|
||||
|
||||
it('should handle persistence file with null runners', () => {
|
||||
const persistenceRegistry = new HotRunnerRegistry('/tmp/test');
|
||||
|
||||
mockFs.existsSync.mockReturnValue(true);
|
||||
mockFs.readFileSync.mockReturnValue('{"runners": null, "configs": null}');
|
||||
|
||||
const count = persistenceRegistry.loadFromDisk();
|
||||
expect(count).toBe(0);
|
||||
});
|
||||
|
||||
it('should validate and repair invalid runners', () => {
|
||||
const persistenceRegistry = new HotRunnerRegistry('/tmp/test');
|
||||
mockFs.existsSync.mockReturnValue(true);
|
||||
mockFs.writeFileSync.mockImplementation(() => {});
|
||||
mockFs.mkdirSync.mockImplementation(() => '' as any);
|
||||
|
||||
// Register a valid runner first
|
||||
const id = persistenceRegistry.registerRunner(createMockConfig());
|
||||
persistenceRegistry.updateRunner(id, { state: 'idle' });
|
||||
|
||||
// Manually corrupt the runner's state by setting an invalid state
|
||||
// (we access via the public API -- updateRunner with a cast)
|
||||
persistenceRegistry.updateRunner(id, { state: 'invalid-state' as any });
|
||||
|
||||
const repaired = persistenceRegistry.validateAndRepair();
|
||||
expect(repaired).toBe(1);
|
||||
|
||||
const runner = persistenceRegistry.getRunner(id);
|
||||
expect(runner!.state).toBe('unhealthy');
|
||||
});
|
||||
|
||||
it('should not discard configs for valid runners when loading from disk', () => {
|
||||
const persistenceRegistry = new HotRunnerRegistry('/tmp/test');
|
||||
const storedData = {
|
||||
runners: {
|
||||
'hr-valid': {
|
||||
id: 'hr-valid',
|
||||
state: 'idle',
|
||||
unityVersion: '2022.3.0f1',
|
||||
platform: 'StandaloneWindows64',
|
||||
uptime: 100,
|
||||
jobsCompleted: 3,
|
||||
lastHealthCheck: new Date().toISOString(),
|
||||
memoryUsageMB: 512,
|
||||
},
|
||||
},
|
||||
configs: {
|
||||
'hr-valid': createMockConfig(),
|
||||
},
|
||||
};
|
||||
|
||||
mockFs.existsSync.mockReturnValue(true);
|
||||
mockFs.readFileSync.mockReturnValue(JSON.stringify(storedData));
|
||||
|
||||
persistenceRegistry.loadFromDisk();
|
||||
expect(persistenceRegistry.getConfig('hr-valid')).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
// --- Health Monitor Tests ---
|
||||
|
||||
describe('HotRunnerHealthMonitor', () => {
|
||||
let monitor: HotRunnerHealthMonitor;
|
||||
let registry: HotRunnerRegistry;
|
||||
let transports: Map<string, HotRunnerTransport>;
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
jest.useFakeTimers();
|
||||
monitor = new HotRunnerHealthMonitor();
|
||||
registry = new HotRunnerRegistry();
|
||||
transports = new Map();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
monitor.stopMonitoring();
|
||||
jest.useRealTimers();
|
||||
});
|
||||
|
||||
it('should start and stop monitoring', () => {
|
||||
monitor.startMonitoring(registry, 30, transports);
|
||||
expect(monitor.isMonitoring).toBe(true);
|
||||
|
||||
monitor.stopMonitoring();
|
||||
expect(monitor.isMonitoring).toBe(false);
|
||||
});
|
||||
|
||||
it('should report healthy when transport health check passes', async () => {
|
||||
const id = registry.registerRunner(createMockConfig());
|
||||
registry.updateRunner(id, { state: 'idle' });
|
||||
|
||||
const transport = createMockTransport();
|
||||
transports.set(id, transport);
|
||||
monitor.startMonitoring(registry, 30, transports);
|
||||
|
||||
const healthy = await monitor.checkHealth(id);
|
||||
expect(healthy).toBe(true);
|
||||
expect(transport.healthCheck).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should mark runner as unhealthy when health check fails', async () => {
|
||||
const id = registry.registerRunner(createMockConfig());
|
||||
registry.updateRunner(id, { state: 'idle' });
|
||||
|
||||
const transport = createMockTransport({
|
||||
healthCheck: jest.fn().mockResolvedValue(false),
|
||||
});
|
||||
transports.set(id, transport);
|
||||
monitor.startMonitoring(registry, 30, transports);
|
||||
|
||||
const healthy = await monitor.checkHealth(id);
|
||||
expect(healthy).toBe(false);
|
||||
|
||||
const runner = registry.getRunner(id);
|
||||
expect(runner!.state).toBe('unhealthy');
|
||||
});
|
||||
|
||||
it('should mark runner as unhealthy when health check throws', async () => {
|
||||
const id = registry.registerRunner(createMockConfig());
|
||||
registry.updateRunner(id, { state: 'idle' });
|
||||
|
||||
const transport = createMockTransport({
|
||||
healthCheck: jest.fn().mockRejectedValue(new Error('Connection refused')),
|
||||
});
|
||||
transports.set(id, transport);
|
||||
monitor.startMonitoring(registry, 30, transports);
|
||||
|
||||
const healthy = await monitor.checkHealth(id);
|
||||
expect(healthy).toBe(false);
|
||||
});
|
||||
|
||||
it('should recycle unhealthy runner and remove from registry', async () => {
|
||||
const id = registry.registerRunner(createMockConfig());
|
||||
const transport = createMockTransport();
|
||||
transports.set(id, transport);
|
||||
monitor.startMonitoring(registry, 30, transports);
|
||||
|
||||
await monitor.recycleUnhealthyRunner(id);
|
||||
|
||||
expect(registry.getRunner(id)).toBeUndefined();
|
||||
expect(transport.disconnect).toHaveBeenCalled();
|
||||
expect(transports.has(id)).toBe(false);
|
||||
});
|
||||
|
||||
it('should recycle idle runner when max idle time exceeded', async () => {
|
||||
const id = registry.registerRunner(createMockConfig({ maxIdleTime: 60 }));
|
||||
|
||||
// Set lastHealthCheck to 120 seconds ago
|
||||
const oldDate = new Date(Date.now() - 120 * 1000).toISOString();
|
||||
registry.updateRunner(id, { state: 'idle', lastHealthCheck: oldDate });
|
||||
|
||||
const transport = createMockTransport();
|
||||
transports.set(id, transport);
|
||||
monitor.startMonitoring(registry, 30, transports);
|
||||
|
||||
await monitor.recycleIdleRunner(id, 60);
|
||||
|
||||
expect(registry.getRunner(id)).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should not recycle idle runner when within max idle time', async () => {
|
||||
const id = registry.registerRunner(createMockConfig({ maxIdleTime: 3600 }));
|
||||
registry.updateRunner(id, {
|
||||
state: 'idle',
|
||||
lastHealthCheck: new Date().toISOString(),
|
||||
});
|
||||
|
||||
const transport = createMockTransport();
|
||||
transports.set(id, transport);
|
||||
monitor.startMonitoring(registry, 30, transports);
|
||||
|
||||
await monitor.recycleIdleRunner(id, 3600);
|
||||
|
||||
// Runner should still exist
|
||||
expect(registry.getRunner(id)).toBeDefined();
|
||||
});
|
||||
|
||||
it('should return false when no transport exists for runner', async () => {
|
||||
const id = registry.registerRunner(createMockConfig());
|
||||
|
||||
// Do not set any transport for this runner
|
||||
monitor.startMonitoring(registry, 30, transports);
|
||||
|
||||
const healthy = await monitor.checkHealth(id);
|
||||
expect(healthy).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
// --- Dispatcher Tests ---
|
||||
|
||||
describe('HotRunnerDispatcher', () => {
|
||||
let registry: HotRunnerRegistry;
|
||||
let transports: Map<string, HotRunnerTransport>;
|
||||
let dispatcher: HotRunnerDispatcher;
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
registry = new HotRunnerRegistry();
|
||||
transports = new Map();
|
||||
dispatcher = new HotRunnerDispatcher(transports);
|
||||
});
|
||||
|
||||
it('should dispatch a job to an available runner', async () => {
|
||||
const id = registry.registerRunner(createMockConfig());
|
||||
registry.updateRunner(id, { state: 'idle' });
|
||||
|
||||
const transport = createMockTransport();
|
||||
transports.set(id, transport);
|
||||
|
||||
const request = createMockJobRequest();
|
||||
const result = await dispatcher.dispatchJob(request, registry, '2022.3.0f1');
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(transport.sendJob).toHaveBeenCalledWith(request);
|
||||
});
|
||||
|
||||
it('should mark runner as busy during job execution', async () => {
|
||||
const id = registry.registerRunner(createMockConfig());
|
||||
registry.updateRunner(id, { state: 'idle' });
|
||||
|
||||
const statesDuringJob: string[] = [];
|
||||
const transport = createMockTransport({
|
||||
sendJob: jest.fn().mockImplementation(async () => {
|
||||
const runner = registry.getRunner(id);
|
||||
if (runner) statesDuringJob.push(runner.state);
|
||||
|
||||
return {
|
||||
jobId: 'job-001',
|
||||
success: true,
|
||||
exitCode: 0,
|
||||
duration: 1000,
|
||||
output: 'ok',
|
||||
};
|
||||
}),
|
||||
});
|
||||
transports.set(id, transport);
|
||||
|
||||
await dispatcher.dispatchJob(createMockJobRequest(), registry, '2022.3.0f1');
|
||||
|
||||
expect(statesDuringJob).toContain('busy');
|
||||
|
||||
// After completion, should be idle again
|
||||
const runner = registry.getRunner(id);
|
||||
expect(runner!.state).toBe('idle');
|
||||
});
|
||||
|
||||
it('should increment jobsCompleted after successful dispatch', async () => {
|
||||
const id = registry.registerRunner(createMockConfig());
|
||||
registry.updateRunner(id, { state: 'idle', jobsCompleted: 5 });
|
||||
|
||||
const transport = createMockTransport();
|
||||
transports.set(id, transport);
|
||||
|
||||
await dispatcher.dispatchJob(createMockJobRequest(), registry, '2022.3.0f1');
|
||||
|
||||
const runner = registry.getRunner(id);
|
||||
expect(runner!.jobsCompleted).toBe(6);
|
||||
});
|
||||
|
||||
it('should throw when no runner is available and wait times out', async () => {
|
||||
// No runners registered at all
|
||||
const request = createMockJobRequest({ timeout: 100 });
|
||||
|
||||
await expect(dispatcher.dispatchJob(request, registry, '2022.3.0f1')).rejects.toThrow(/Timed out waiting/);
|
||||
});
|
||||
|
||||
it('should throw when runner has no transport', async () => {
|
||||
const id = registry.registerRunner(createMockConfig());
|
||||
registry.updateRunner(id, { state: 'idle' });
|
||||
|
||||
// No transport set for this runner
|
||||
|
||||
const request = createMockJobRequest();
|
||||
|
||||
await expect(dispatcher.dispatchJob(request, registry, '2022.3.0f1')).rejects.toThrow(/No transport available/);
|
||||
});
|
||||
|
||||
it('should handle job failure and return runner to idle', async () => {
|
||||
const id = registry.registerRunner(createMockConfig());
|
||||
registry.updateRunner(id, { state: 'idle' });
|
||||
|
||||
const transport = createMockTransport({
|
||||
sendJob: jest.fn().mockRejectedValue(new Error('Unity crashed')),
|
||||
});
|
||||
transports.set(id, transport);
|
||||
|
||||
await expect(dispatcher.dispatchJob(createMockJobRequest(), registry, '2022.3.0f1')).rejects.toThrow(
|
||||
'Unity crashed',
|
||||
);
|
||||
|
||||
// Runner should be back to idle despite failure
|
||||
const runner = registry.getRunner(id);
|
||||
expect(runner!.state).toBe('idle');
|
||||
});
|
||||
|
||||
it('should handle job timeout', async () => {
|
||||
const id = registry.registerRunner(createMockConfig());
|
||||
registry.updateRunner(id, { state: 'idle' });
|
||||
|
||||
const transport = createMockTransport({
|
||||
sendJob: jest.fn().mockImplementation(
|
||||
() => new Promise((resolve) => setTimeout(resolve, 60000)), // never resolves within timeout
|
||||
),
|
||||
});
|
||||
transports.set(id, transport);
|
||||
|
||||
const request = createMockJobRequest({ timeout: 50 });
|
||||
|
||||
await expect(dispatcher.dispatchJob(request, registry, '2022.3.0f1')).rejects.toThrow(/timed out/);
|
||||
});
|
||||
|
||||
it('should disconnect transport on job timeout', async () => {
|
||||
const id = registry.registerRunner(createMockConfig());
|
||||
registry.updateRunner(id, { state: 'idle' });
|
||||
|
||||
const transport = createMockTransport({
|
||||
sendJob: jest.fn().mockImplementation(
|
||||
() => new Promise((resolve) => setTimeout(resolve, 60000)), // never resolves within timeout
|
||||
),
|
||||
});
|
||||
transports.set(id, transport);
|
||||
|
||||
const request = createMockJobRequest({ timeout: 50 });
|
||||
|
||||
await expect(dispatcher.dispatchJob(request, registry, '2022.3.0f1')).rejects.toThrow(/timed out/);
|
||||
|
||||
// Transport should have been disconnected to clean up orphaned connection
|
||||
expect(transport.disconnect).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should call output callback with job output', async () => {
|
||||
const id = registry.registerRunner(createMockConfig());
|
||||
registry.updateRunner(id, { state: 'idle' });
|
||||
|
||||
const transport = createMockTransport();
|
||||
transports.set(id, transport);
|
||||
|
||||
const outputCallback = jest.fn();
|
||||
await dispatcher.dispatchJob(createMockJobRequest(), registry, '2022.3.0f1', outputCallback);
|
||||
|
||||
expect(outputCallback).toHaveBeenCalledWith('Build succeeded');
|
||||
});
|
||||
|
||||
it('should wait for runner to become available', async () => {
|
||||
const id = registry.registerRunner(createMockConfig());
|
||||
|
||||
// Runner starts in 'starting' state, not idle
|
||||
|
||||
const transport = createMockTransport();
|
||||
transports.set(id, transport);
|
||||
|
||||
// Simulate runner becoming idle after a short delay
|
||||
setTimeout(() => {
|
||||
registry.updateRunner(id, { state: 'idle' });
|
||||
}, 50);
|
||||
|
||||
const request = createMockJobRequest({ timeout: 5000 });
|
||||
const result = await dispatcher.dispatchJob(request, registry, '2022.3.0f1');
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
// --- Service Integration Tests ---
|
||||
|
||||
describe('HotRunnerService', () => {
|
||||
let service: HotRunnerService;
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
mockFs.existsSync.mockReturnValue(false);
|
||||
service = new HotRunnerService();
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await service.shutdown();
|
||||
});
|
||||
|
||||
it('should initialize and shut down cleanly', async () => {
|
||||
const config = createMockConfig();
|
||||
await service.initialize(config);
|
||||
|
||||
const status = service.getStatus();
|
||||
expect(status).toEqual([]);
|
||||
|
||||
await service.shutdown();
|
||||
});
|
||||
|
||||
it('should register a runner with transport', async () => {
|
||||
await service.initialize(createMockConfig());
|
||||
|
||||
const transport = createMockTransport();
|
||||
const id = service.registerRunner(createMockConfig(), transport);
|
||||
|
||||
expect(id).toMatch(/^hr-/);
|
||||
expect(service.getStatus()).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('should disconnect all transports on shutdown', async () => {
|
||||
await service.initialize(createMockConfig());
|
||||
|
||||
const transport1 = createMockTransport();
|
||||
const transport2 = createMockTransport();
|
||||
service.registerRunner(createMockConfig(), transport1);
|
||||
service.registerRunner(createMockConfig(), transport2);
|
||||
|
||||
await service.shutdown();
|
||||
|
||||
expect(transport1.disconnect).toHaveBeenCalled();
|
||||
expect(transport2.disconnect).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should expose the underlying registry', async () => {
|
||||
await service.initialize(createMockConfig());
|
||||
const registry = service.getRegistry();
|
||||
|
||||
expect(registry).toBeInstanceOf(HotRunnerRegistry);
|
||||
});
|
||||
});
|
||||
@@ -1,11 +0,0 @@
|
||||
export { HotRunnerService } from './hot-runner-service';
|
||||
export { HotRunnerRegistry } from './hot-runner-registry';
|
||||
export { HotRunnerHealthMonitor } from './hot-runner-health-monitor';
|
||||
export { HotRunnerDispatcher } from './hot-runner-dispatcher';
|
||||
export type {
|
||||
HotRunnerConfig,
|
||||
HotRunnerStatus,
|
||||
HotRunnerJobRequest,
|
||||
HotRunnerJobResult,
|
||||
HotRunnerTransport,
|
||||
} from './hot-runner-types';
|
||||
@@ -0,0 +1,446 @@
|
||||
import fs from 'node:fs';
|
||||
import * as core from '@actions/core';
|
||||
import { SecretSourceService, validateSecretKey } from './secret-source-service';
|
||||
|
||||
jest.mock('node:fs');
|
||||
jest.mock('@actions/core', () => ({
|
||||
setSecret: jest.fn(),
|
||||
info: jest.fn(),
|
||||
warning: jest.fn(),
|
||||
error: jest.fn(),
|
||||
}));
|
||||
jest.mock('../core/orchestrator-system', () => ({
|
||||
OrchestratorSystem: {
|
||||
Run: jest.fn().mockResolvedValue(''),
|
||||
},
|
||||
}));
|
||||
jest.mock('../core/orchestrator-logger', () => ({
|
||||
__esModule: true,
|
||||
default: {
|
||||
log: jest.fn(),
|
||||
logWarning: jest.fn(),
|
||||
error: jest.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
const mockFs = fs as jest.Mocked<typeof fs>;
|
||||
|
||||
describe('SecretSourceService', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
describe('validateSecretKey', () => {
|
||||
it('should accept alphanumeric keys', () => {
|
||||
expect(validateSecretKey('MY_SECRET_KEY')).toBe('MY_SECRET_KEY');
|
||||
});
|
||||
|
||||
it('should accept keys with hyphens', () => {
|
||||
expect(validateSecretKey('my-secret-key')).toBe('my-secret-key');
|
||||
});
|
||||
|
||||
it('should accept keys with dots', () => {
|
||||
expect(validateSecretKey('my.secret.key')).toBe('my.secret.key');
|
||||
});
|
||||
|
||||
it('should accept keys with forward slashes', () => {
|
||||
expect(validateSecretKey('path/to/secret')).toBe('path/to/secret');
|
||||
});
|
||||
|
||||
it('should accept keys with mixed valid characters', () => {
|
||||
expect(validateSecretKey('my-app/prod_db.password')).toBe('my-app/prod_db.password');
|
||||
});
|
||||
|
||||
it('should reject keys with semicolons (shell injection)', () => {
|
||||
expect(() => validateSecretKey('; rm -rf /')).toThrow('Invalid secret key name');
|
||||
});
|
||||
|
||||
it('should reject keys with backticks (command substitution)', () => {
|
||||
expect(() => validateSecretKey('`whoami`')).toThrow('Invalid secret key name');
|
||||
});
|
||||
|
||||
it('should reject keys with dollar signs (variable expansion)', () => {
|
||||
expect(() => validateSecretKey('$HOME')).toThrow('Invalid secret key name');
|
||||
});
|
||||
|
||||
it('should reject keys with pipe characters', () => {
|
||||
expect(() => validateSecretKey('key | cat /etc/passwd')).toThrow('Invalid secret key name');
|
||||
});
|
||||
|
||||
it('should reject keys with ampersands', () => {
|
||||
expect(() => validateSecretKey('key && echo pwned')).toThrow('Invalid secret key name');
|
||||
});
|
||||
|
||||
it('should reject keys with newlines', () => {
|
||||
expect(() => validateSecretKey('key\nmalicious')).toThrow('Invalid secret key name');
|
||||
});
|
||||
|
||||
it('should reject keys with quotes', () => {
|
||||
expect(() => validateSecretKey('"key"')).toThrow('Invalid secret key name');
|
||||
expect(() => validateSecretKey("'key'")).toThrow('Invalid secret key name');
|
||||
});
|
||||
|
||||
it('should reject keys with parentheses (subshell)', () => {
|
||||
expect(() => validateSecretKey('$(whoami)')).toThrow('Invalid secret key name');
|
||||
});
|
||||
|
||||
it('should reject empty keys', () => {
|
||||
expect(() => validateSecretKey('')).toThrow('Invalid secret key name');
|
||||
});
|
||||
|
||||
it('should reject keys with spaces', () => {
|
||||
expect(() => validateSecretKey('key with spaces')).toThrow('Invalid secret key name');
|
||||
});
|
||||
});
|
||||
|
||||
describe('isPremadeSource', () => {
|
||||
it('should return true for aws-secrets-manager', () => {
|
||||
expect(SecretSourceService.isPremadeSource('aws-secrets-manager')).toBe(true);
|
||||
});
|
||||
|
||||
it('should return true for aws-secret-manager (legacy alias)', () => {
|
||||
expect(SecretSourceService.isPremadeSource('aws-secret-manager')).toBe(true);
|
||||
});
|
||||
|
||||
it('should return true for aws-parameter-store', () => {
|
||||
expect(SecretSourceService.isPremadeSource('aws-parameter-store')).toBe(true);
|
||||
});
|
||||
|
||||
it('should return true for gcp-secret-manager', () => {
|
||||
expect(SecretSourceService.isPremadeSource('gcp-secret-manager')).toBe(true);
|
||||
});
|
||||
|
||||
it('should return true for azure-key-vault', () => {
|
||||
expect(SecretSourceService.isPremadeSource('azure-key-vault')).toBe(true);
|
||||
});
|
||||
|
||||
it('should return true for hashicorp-vault', () => {
|
||||
expect(SecretSourceService.isPremadeSource('hashicorp-vault')).toBe(true);
|
||||
});
|
||||
|
||||
it('should return true for hashicorp-vault-kv1', () => {
|
||||
expect(SecretSourceService.isPremadeSource('hashicorp-vault-kv1')).toBe(true);
|
||||
});
|
||||
|
||||
it('should return true for vault (short alias)', () => {
|
||||
expect(SecretSourceService.isPremadeSource('vault')).toBe(true);
|
||||
});
|
||||
|
||||
it('should return false for unknown source', () => {
|
||||
expect(SecretSourceService.isPremadeSource('unknown-source')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getAvailableSources', () => {
|
||||
it('should return all premade source names', () => {
|
||||
const sources = SecretSourceService.getAvailableSources();
|
||||
expect(sources).toContain('aws-secrets-manager');
|
||||
expect(sources).toContain('aws-parameter-store');
|
||||
expect(sources).toContain('gcp-secret-manager');
|
||||
expect(sources).toContain('azure-key-vault');
|
||||
expect(sources).toContain('hashicorp-vault');
|
||||
expect(sources).toContain('hashicorp-vault-kv1');
|
||||
expect(sources).toContain('vault');
|
||||
expect(sources.length).toBeGreaterThanOrEqual(8);
|
||||
});
|
||||
});
|
||||
|
||||
describe('resolveSource', () => {
|
||||
it('should resolve premade source by name', () => {
|
||||
const source = SecretSourceService.resolveSource('aws-secrets-manager');
|
||||
expect(source).toBeDefined();
|
||||
expect(source!.name).toBe('aws-secrets-manager');
|
||||
expect(source!.command).toContain('secretsmanager');
|
||||
});
|
||||
|
||||
it('should resolve custom command with {0} placeholder', () => {
|
||||
const source = SecretSourceService.resolveSource('vault kv get -field=value secret/{0}');
|
||||
expect(source).toBeDefined();
|
||||
expect(source!.name).toBe('custom-command');
|
||||
expect(source!.command).toContain('{0}');
|
||||
});
|
||||
|
||||
it('should resolve command with spaces as custom command', () => {
|
||||
const source = SecretSourceService.resolveSource('my-tool get-secret');
|
||||
expect(source).toBeDefined();
|
||||
expect(source!.name).toBe('custom-command');
|
||||
});
|
||||
|
||||
it('should return undefined for unknown single-word source', () => {
|
||||
const source = SecretSourceService.resolveSource('unknown');
|
||||
expect(source).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('fetchSecret', () => {
|
||||
it('should run the command with {0} replaced by key', async () => {
|
||||
const { OrchestratorSystem } = require('../core/orchestrator-system');
|
||||
OrchestratorSystem.Run.mockResolvedValue('my-secret-value');
|
||||
|
||||
const source = SecretSourceService.resolveSource('aws-secrets-manager')!;
|
||||
const result = await SecretSourceService.fetchSecret(source, 'MY_SECRET');
|
||||
|
||||
expect(result).toBe('my-secret-value');
|
||||
expect(OrchestratorSystem.Run).toHaveBeenCalledWith(expect.stringContaining('MY_SECRET'), false, true);
|
||||
});
|
||||
|
||||
it('should parse JSON output when parseOutput is json-field', async () => {
|
||||
const { OrchestratorSystem } = require('../core/orchestrator-system');
|
||||
OrchestratorSystem.Run.mockResolvedValue(JSON.stringify({ value: 'extracted-secret' }));
|
||||
|
||||
const source = {
|
||||
name: 'test-source',
|
||||
command: 'fetch {0}',
|
||||
parseOutput: 'json-field' as const,
|
||||
jsonField: 'value',
|
||||
};
|
||||
const result = await SecretSourceService.fetchSecret(source, 'KEY');
|
||||
|
||||
expect(result).toBe('extracted-secret');
|
||||
});
|
||||
|
||||
it('should fall back to raw output on invalid JSON with json-field mode', async () => {
|
||||
const { OrchestratorSystem } = require('../core/orchestrator-system');
|
||||
OrchestratorSystem.Run.mockResolvedValue('not-json');
|
||||
|
||||
const source = {
|
||||
name: 'test-source',
|
||||
command: 'fetch {0}',
|
||||
parseOutput: 'json-field' as const,
|
||||
jsonField: 'value',
|
||||
};
|
||||
const result = await SecretSourceService.fetchSecret(source, 'KEY');
|
||||
|
||||
expect(result).toBe('not-json');
|
||||
});
|
||||
|
||||
it('should return empty string on command failure', async () => {
|
||||
const { OrchestratorSystem } = require('../core/orchestrator-system');
|
||||
OrchestratorSystem.Run.mockRejectedValue(new Error('command not found'));
|
||||
|
||||
const source = SecretSourceService.resolveSource('aws-secrets-manager')!;
|
||||
const result = await SecretSourceService.fetchSecret(source, 'KEY');
|
||||
|
||||
expect(result).toBe('');
|
||||
});
|
||||
|
||||
it('should reject keys with shell injection characters', async () => {
|
||||
const source = SecretSourceService.resolveSource('aws-secrets-manager')!;
|
||||
|
||||
await expect(SecretSourceService.fetchSecret(source, '; rm -rf /')).rejects.toThrow('Invalid secret key name');
|
||||
});
|
||||
|
||||
it('should reject keys with command substitution', async () => {
|
||||
const source = SecretSourceService.resolveSource('aws-secrets-manager')!;
|
||||
|
||||
await expect(SecretSourceService.fetchSecret(source, '$(whoami)')).rejects.toThrow('Invalid secret key name');
|
||||
});
|
||||
|
||||
it('should reject keys with backtick command substitution', async () => {
|
||||
const source = SecretSourceService.resolveSource('aws-secrets-manager')!;
|
||||
|
||||
await expect(SecretSourceService.fetchSecret(source, '`cat /etc/passwd`')).rejects.toThrow(
|
||||
'Invalid secret key name',
|
||||
);
|
||||
});
|
||||
|
||||
it('should accept keys with valid path-like patterns', async () => {
|
||||
const { OrchestratorSystem } = require('../core/orchestrator-system');
|
||||
OrchestratorSystem.Run.mockResolvedValue('secret-value');
|
||||
|
||||
const source = SecretSourceService.resolveSource('aws-secrets-manager')!;
|
||||
const result = await SecretSourceService.fetchSecret(source, 'prod/database/password');
|
||||
|
||||
expect(result).toBe('secret-value');
|
||||
});
|
||||
|
||||
it('should mask fetched secret values with core.setSecret', async () => {
|
||||
const { OrchestratorSystem } = require('../core/orchestrator-system');
|
||||
OrchestratorSystem.Run.mockResolvedValue('super-secret-value');
|
||||
|
||||
const source = SecretSourceService.resolveSource('aws-secrets-manager')!;
|
||||
await SecretSourceService.fetchSecret(source, 'MY_SECRET');
|
||||
|
||||
expect(core.setSecret).toHaveBeenCalledWith('super-secret-value');
|
||||
});
|
||||
|
||||
it('should not mask empty secret values', async () => {
|
||||
const { OrchestratorSystem } = require('../core/orchestrator-system');
|
||||
OrchestratorSystem.Run.mockResolvedValue('');
|
||||
|
||||
const source = SecretSourceService.resolveSource('aws-secrets-manager')!;
|
||||
await SecretSourceService.fetchSecret(source, 'MY_SECRET');
|
||||
|
||||
expect(core.setSecret).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should mask JSON-extracted secret values', async () => {
|
||||
const { OrchestratorSystem } = require('../core/orchestrator-system');
|
||||
OrchestratorSystem.Run.mockResolvedValue(JSON.stringify({ value: 'json-secret' }));
|
||||
|
||||
const source = {
|
||||
name: 'test-source',
|
||||
command: 'fetch {0}',
|
||||
parseOutput: 'json-field' as const,
|
||||
jsonField: 'value',
|
||||
};
|
||||
await SecretSourceService.fetchSecret(source, 'KEY');
|
||||
|
||||
expect(core.setSecret).toHaveBeenCalledWith('json-secret');
|
||||
});
|
||||
});
|
||||
|
||||
describe('fetchFromEnv', () => {
|
||||
it('should return env var value when set', () => {
|
||||
process.env.TEST_SECRET_KEY = 'env-value';
|
||||
const result = SecretSourceService.fetchFromEnv('TEST_SECRET_KEY');
|
||||
expect(result).toBe('env-value');
|
||||
delete process.env.TEST_SECRET_KEY;
|
||||
});
|
||||
|
||||
it('should return empty string when env var is not set', () => {
|
||||
const result = SecretSourceService.fetchFromEnv('NONEXISTENT_KEY_12345');
|
||||
expect(result).toBe('');
|
||||
});
|
||||
|
||||
it('should mask env var values with core.setSecret', () => {
|
||||
process.env.TEST_MASK_KEY = 'masked-env-value';
|
||||
SecretSourceService.fetchFromEnv('TEST_MASK_KEY');
|
||||
expect(core.setSecret).toHaveBeenCalledWith('masked-env-value');
|
||||
delete process.env.TEST_MASK_KEY;
|
||||
});
|
||||
|
||||
it('should not mask empty env var values', () => {
|
||||
const result = SecretSourceService.fetchFromEnv('NONEXISTENT_KEY_99999');
|
||||
expect(result).toBe('');
|
||||
expect(core.setSecret).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('fetchAll', () => {
|
||||
it('should fetch all keys from env source', async () => {
|
||||
process.env.KEY_A = 'val-a';
|
||||
process.env.KEY_B = 'val-b';
|
||||
|
||||
const results = await SecretSourceService.fetchAll('env', ['KEY_A', 'KEY_B']);
|
||||
|
||||
expect(results.KEY_A).toBe('val-a');
|
||||
expect(results.KEY_B).toBe('val-b');
|
||||
|
||||
delete process.env.KEY_A;
|
||||
delete process.env.KEY_B;
|
||||
});
|
||||
|
||||
it('should fetch all keys from premade source', async () => {
|
||||
const { OrchestratorSystem } = require('../core/orchestrator-system');
|
||||
OrchestratorSystem.Run.mockResolvedValueOnce('secret-1').mockResolvedValueOnce('secret-2');
|
||||
|
||||
const results = await SecretSourceService.fetchAll('aws-parameter-store', ['param1', 'param2']);
|
||||
|
||||
expect(results.param1).toBe('secret-1');
|
||||
expect(results.param2).toBe('secret-2');
|
||||
expect(OrchestratorSystem.Run).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('should return empty results for unknown source', async () => {
|
||||
const results = await SecretSourceService.fetchAll('unknown', ['key1']);
|
||||
expect(results).toEqual({});
|
||||
});
|
||||
});
|
||||
|
||||
describe('loadFromYaml', () => {
|
||||
it('should return empty array when file does not exist', () => {
|
||||
(mockFs.existsSync as jest.Mock).mockReturnValue(false);
|
||||
const result = SecretSourceService.loadFromYaml('/nonexistent.yml');
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
|
||||
it('should parse valid YAML source definitions', () => {
|
||||
(mockFs.existsSync as jest.Mock).mockReturnValue(true);
|
||||
(mockFs.readFileSync as jest.Mock).mockReturnValue(`
|
||||
sources:
|
||||
- name: my-vault
|
||||
command: 'vault kv get -field=value secret/{0}'
|
||||
- name: my-api
|
||||
command: 'curl -s https://api.example.com/{0}'
|
||||
parseOutput: json-field
|
||||
jsonField: secret_value
|
||||
`);
|
||||
|
||||
const result = SecretSourceService.loadFromYaml('/sources.yml');
|
||||
|
||||
expect(result).toHaveLength(2);
|
||||
expect(result[0].name).toBe('my-vault');
|
||||
expect(result[0].command).toBe('vault kv get -field=value secret/{0}');
|
||||
expect(result[1].name).toBe('my-api');
|
||||
expect(result[1].parseOutput).toBe('json-field');
|
||||
expect(result[1].jsonField).toBe('secret_value');
|
||||
});
|
||||
|
||||
it('should handle YAML with single source', () => {
|
||||
(mockFs.existsSync as jest.Mock).mockReturnValue(true);
|
||||
(mockFs.readFileSync as jest.Mock).mockReturnValue(`
|
||||
sources:
|
||||
- name: simple
|
||||
command: echo {0}
|
||||
`);
|
||||
|
||||
const result = SecretSourceService.loadFromYaml('/simple.yml');
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0].name).toBe('simple');
|
||||
});
|
||||
|
||||
it('should return empty array on parse error', () => {
|
||||
(mockFs.existsSync as jest.Mock).mockReturnValue(true);
|
||||
(mockFs.readFileSync as jest.Mock).mockImplementation(() => {
|
||||
throw new Error('Permission denied');
|
||||
});
|
||||
|
||||
const result = SecretSourceService.loadFromYaml('/error.yml');
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('premade source commands', () => {
|
||||
it('aws-secrets-manager uses --query SecretString', () => {
|
||||
const source = SecretSourceService.resolveSource('aws-secrets-manager')!;
|
||||
expect(source.command).toContain('--query SecretString');
|
||||
expect(source.command).toContain('--output text');
|
||||
});
|
||||
|
||||
it('aws-parameter-store uses --with-decryption', () => {
|
||||
const source = SecretSourceService.resolveSource('aws-parameter-store')!;
|
||||
expect(source.command).toContain('--with-decryption');
|
||||
expect(source.command).toContain('--query Parameter.Value');
|
||||
});
|
||||
|
||||
it('gcp-secret-manager uses latest version', () => {
|
||||
const source = SecretSourceService.resolveSource('gcp-secret-manager')!;
|
||||
expect(source.command).toContain('latest');
|
||||
});
|
||||
|
||||
it('azure-key-vault uses AZURE_VAULT_NAME env var', () => {
|
||||
const source = SecretSourceService.resolveSource('azure-key-vault')!;
|
||||
expect(source.command).toContain('$AZURE_VAULT_NAME');
|
||||
});
|
||||
|
||||
it('hashicorp-vault uses vault kv get with VAULT_MOUNT', () => {
|
||||
const source = SecretSourceService.resolveSource('hashicorp-vault')!;
|
||||
expect(source.command).toContain('vault kv get');
|
||||
expect(source.command).toContain('VAULT_MOUNT');
|
||||
expect(source.command).toContain('-field=value');
|
||||
});
|
||||
|
||||
it('hashicorp-vault-kv1 uses vault read for KV v1', () => {
|
||||
const source = SecretSourceService.resolveSource('hashicorp-vault-kv1')!;
|
||||
expect(source.command).toContain('vault read');
|
||||
expect(source.command).toContain('-field=value');
|
||||
});
|
||||
|
||||
it('vault alias resolves to same command as hashicorp-vault', () => {
|
||||
const vault = SecretSourceService.resolveSource('vault')!;
|
||||
const hashicorpVault = SecretSourceService.resolveSource('hashicorp-vault')!;
|
||||
expect(vault.command).toBe(hashicorpVault.command);
|
||||
});
|
||||
});
|
||||
});
|
||||
337
src/model/orchestrator/services/secrets/secret-source-service.ts
Normal file
337
src/model/orchestrator/services/secrets/secret-source-service.ts
Normal file
@@ -0,0 +1,337 @@
|
||||
import fs from 'node:fs';
|
||||
import * as core from '@actions/core';
|
||||
import OrchestratorLogger from '../core/orchestrator-logger';
|
||||
import { OrchestratorSystem } from '../core/orchestrator-system';
|
||||
|
||||
/**
|
||||
* A secret source definition: how to fetch a secret value by key.
|
||||
*/
|
||||
export interface SecretSourceDefinition {
|
||||
name: string;
|
||||
command: string;
|
||||
parseOutput?: 'raw' | 'json-field';
|
||||
jsonField?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate that a secret key name contains only safe characters.
|
||||
* Prevents shell injection when keys are interpolated into commands.
|
||||
*
|
||||
* Allowed characters: alphanumeric, hyphens, underscores, dots, forward slashes.
|
||||
*
|
||||
* @param key - The secret key name to validate
|
||||
* @returns The validated key (unchanged)
|
||||
* @throws Error if the key contains disallowed characters
|
||||
*/
|
||||
export function validateSecretKey(key: string): string {
|
||||
if (!/^[a-zA-Z0-9\-_./]+$/.test(key)) {
|
||||
throw new Error(
|
||||
`Invalid secret key name: "${key}". Keys may only contain alphanumeric characters, hyphens, underscores, dots, and forward slashes.`,
|
||||
);
|
||||
}
|
||||
|
||||
return key;
|
||||
}
|
||||
|
||||
/**
|
||||
* Mask a secret value so it does not appear in GitHub Actions logs.
|
||||
* Empty or whitespace-only values are skipped (core.setSecret would be a no-op).
|
||||
*/
|
||||
function maskSecretValue(value: string): void {
|
||||
if (value.trim().length > 0) {
|
||||
core.setSecret(value);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Premade secret sources and custom YAML-based secret source definitions.
|
||||
*
|
||||
* Premade sources are string shortcuts that expand to shell commands:
|
||||
* - `aws-secrets-manager` -- AWS Secrets Manager
|
||||
* - `aws-parameter-store` -- AWS Systems Manager Parameter Store
|
||||
* - `gcp-secret-manager` -- Google Cloud Secret Manager
|
||||
* - `azure-key-vault` -- Azure Key Vault (requires AZURE_VAULT_NAME env var)
|
||||
* - `hashicorp-vault` -- HashiCorp Vault KV v2 (requires VAULT_ADDR, optionally VAULT_MOUNT)
|
||||
* - `hashicorp-vault-kv1` -- HashiCorp Vault KV v1 (requires VAULT_ADDR, optionally VAULT_MOUNT)
|
||||
* - `env` -- Read from environment variables (no shell command needed)
|
||||
*
|
||||
* Custom YAML format:
|
||||
* sources:
|
||||
* - name: my-vault
|
||||
* command: 'vault kv get -field=value secret/{0}'
|
||||
* - name: my-api
|
||||
* command: 'curl -s https://secrets.example.com/api/{0}'
|
||||
* parseOutput: json-field
|
||||
* jsonField: value
|
||||
*/
|
||||
export class SecretSourceService {
|
||||
private static readonly premadeSources: Record<string, SecretSourceDefinition> = {
|
||||
'aws-secrets-manager': {
|
||||
name: 'aws-secrets-manager',
|
||||
command: 'aws secretsmanager get-secret-value --secret-id {0} --query SecretString --output text',
|
||||
parseOutput: 'raw',
|
||||
},
|
||||
'aws-secret-manager': {
|
||||
// Alias for backward compatibility (original name in inputPullCommand)
|
||||
name: 'aws-secret-manager',
|
||||
command: 'aws secretsmanager get-secret-value --secret-id {0} --query SecretString --output text',
|
||||
parseOutput: 'raw',
|
||||
},
|
||||
'aws-parameter-store': {
|
||||
name: 'aws-parameter-store',
|
||||
command: 'aws ssm get-parameter --name {0} --with-decryption --query Parameter.Value --output text',
|
||||
parseOutput: 'raw',
|
||||
},
|
||||
'gcp-secret-manager': {
|
||||
name: 'gcp-secret-manager',
|
||||
command: 'gcloud secrets versions access latest --secret="{0}"',
|
||||
parseOutput: 'raw',
|
||||
},
|
||||
'azure-key-vault': {
|
||||
name: 'azure-key-vault',
|
||||
command: 'az keyvault secret show --vault-name "$AZURE_VAULT_NAME" --name {0} --query value --output tsv',
|
||||
parseOutput: 'raw',
|
||||
},
|
||||
'hashicorp-vault': {
|
||||
// HashiCorp Vault KV v2 (default). Requires VAULT_ADDR env var.
|
||||
// Optionally set VAULT_MOUNT to override the mount path (default: 'secret').
|
||||
// Authentication is handled by VAULT_TOKEN or other Vault auth env vars.
|
||||
name: 'hashicorp-vault',
|
||||
command: 'vault kv get -mount="${VAULT_MOUNT:-secret}" -field=value {0}',
|
||||
parseOutput: 'raw',
|
||||
},
|
||||
'hashicorp-vault-kv1': {
|
||||
// HashiCorp Vault KV v1. Requires VAULT_ADDR env var.
|
||||
// Optionally set VAULT_MOUNT to override the mount path (default: 'secret').
|
||||
name: 'hashicorp-vault-kv1',
|
||||
command: 'vault read -mount="${VAULT_MOUNT:-secret}" -field=value {0}',
|
||||
parseOutput: 'raw',
|
||||
},
|
||||
vault: {
|
||||
// Short alias for hashicorp-vault (KV v2)
|
||||
name: 'vault',
|
||||
command: 'vault kv get -mount="${VAULT_MOUNT:-secret}" -field=value {0}',
|
||||
parseOutput: 'raw',
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* Check if a source name is a known premade source.
|
||||
*/
|
||||
static isPremadeSource(sourceName: string): boolean {
|
||||
return sourceName in SecretSourceService.premadeSources;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the list of available premade source names.
|
||||
*/
|
||||
static getAvailableSources(): string[] {
|
||||
return Object.keys(SecretSourceService.premadeSources);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a source name to a SecretSourceDefinition.
|
||||
*
|
||||
* - If the name matches a premade source, returns that definition.
|
||||
* - If it looks like a shell command (contains spaces or {0}), wraps it as a custom command.
|
||||
* - Otherwise, returns undefined.
|
||||
*/
|
||||
static resolveSource(sourceName: string): SecretSourceDefinition | undefined {
|
||||
// Check premade sources
|
||||
if (SecretSourceService.isPremadeSource(sourceName)) {
|
||||
return SecretSourceService.premadeSources[sourceName];
|
||||
}
|
||||
|
||||
// If it contains a placeholder or spaces, treat it as a raw command
|
||||
if (sourceName.includes('{0}') || sourceName.includes(' ')) {
|
||||
return {
|
||||
name: 'custom-command',
|
||||
command: sourceName,
|
||||
parseOutput: 'raw',
|
||||
};
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Load custom secret source definitions from a YAML file.
|
||||
*
|
||||
* Expected format:
|
||||
* sources:
|
||||
* - name: my-source
|
||||
* command: 'my-tool get-secret {0}'
|
||||
* - name: my-api
|
||||
* command: 'curl -s https://api.example.com/secrets/{0}'
|
||||
* parseOutput: json-field
|
||||
* jsonField: value
|
||||
*/
|
||||
static loadFromYaml(filePath: string): SecretSourceDefinition[] {
|
||||
if (!fs.existsSync(filePath)) {
|
||||
OrchestratorLogger.logWarning(`Secret source YAML not found: ${filePath}`);
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
try {
|
||||
const content = fs.readFileSync(filePath, 'utf8');
|
||||
const parsed = SecretSourceService.parseSimpleYaml(content);
|
||||
|
||||
return parsed;
|
||||
} catch (error: any) {
|
||||
OrchestratorLogger.logWarning(`Failed to parse secret source YAML: ${error.message}`);
|
||||
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch a secret value using the given source definition.
|
||||
*
|
||||
* Validates the key against an allowlist pattern before interpolating it
|
||||
* into the command string to prevent shell injection. The fetched secret
|
||||
* value is masked via core.setSecret() so it does not leak in logs.
|
||||
*
|
||||
* @param source - The secret source definition to use
|
||||
* @param key - The secret key to fetch
|
||||
* @returns The secret value, or empty string on failure
|
||||
*/
|
||||
static async fetchSecret(source: SecretSourceDefinition, key: string): Promise<string> {
|
||||
// Validate the key to prevent shell injection
|
||||
validateSecretKey(key);
|
||||
|
||||
const command = source.command.replace(/\{0\}/g, key);
|
||||
|
||||
try {
|
||||
const output = await OrchestratorSystem.Run(command, false, true);
|
||||
|
||||
let value: string;
|
||||
|
||||
if (source.parseOutput === 'json-field' && source.jsonField) {
|
||||
try {
|
||||
const parsed = JSON.parse(output);
|
||||
value = parsed[source.jsonField] || '';
|
||||
} catch {
|
||||
OrchestratorLogger.logWarning(`Failed to parse JSON output from ${source.name} for key ${key}`);
|
||||
value = output.trim();
|
||||
}
|
||||
} else {
|
||||
value = output.trim();
|
||||
}
|
||||
|
||||
// Mask the secret value so it does not appear in GitHub Actions logs
|
||||
maskSecretValue(value);
|
||||
|
||||
return value;
|
||||
} catch (error: any) {
|
||||
OrchestratorLogger.logWarning(`Failed to fetch secret '${key}' from ${source.name}: ${error.message}`);
|
||||
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch a secret from an environment variable. No shell command needed.
|
||||
* The value is masked via core.setSecret() so it does not leak in logs.
|
||||
*/
|
||||
static fetchFromEnv(key: string): string {
|
||||
const value = process.env[key] || '';
|
||||
maskSecretValue(value);
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a source name and fetch all secrets from it.
|
||||
*
|
||||
* @param sourceName - Premade source name, shell command, or 'env'
|
||||
* @param keys - List of secret keys to fetch
|
||||
* @returns Map of key -> value
|
||||
*/
|
||||
static async fetchAll(sourceName: string, keys: string[]): Promise<Record<string, string>> {
|
||||
const results: Record<string, string> = {};
|
||||
|
||||
if (sourceName === 'env') {
|
||||
for (const key of keys) {
|
||||
results[key] = SecretSourceService.fetchFromEnv(key);
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
const source = SecretSourceService.resolveSource(sourceName);
|
||||
if (!source) {
|
||||
OrchestratorLogger.logWarning(
|
||||
`Unknown secret source '${sourceName}'. Available sources: ${SecretSourceService.getAvailableSources().join(
|
||||
', ',
|
||||
)}`,
|
||||
);
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
OrchestratorLogger.log(`Fetching ${keys.length} secret(s) from ${source.name}`);
|
||||
|
||||
for (const key of keys) {
|
||||
results[key] = await SecretSourceService.fetchSecret(source, key);
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
/**
|
||||
* Simple YAML parser for secret source definitions.
|
||||
* Handles the specific structure we expect without requiring a YAML library.
|
||||
*/
|
||||
private static parseSimpleYaml(content: string): SecretSourceDefinition[] {
|
||||
const definitions: SecretSourceDefinition[] = [];
|
||||
const lines = content.split('\n');
|
||||
let current: Partial<SecretSourceDefinition> | null = null;
|
||||
|
||||
for (const rawLine of lines) {
|
||||
const line = rawLine.replace(/\r$/, '');
|
||||
const trimmed = line.trim();
|
||||
|
||||
if (trimmed === '' || trimmed.startsWith('#')) continue;
|
||||
|
||||
if (trimmed === '- name:' || trimmed.startsWith('- name:')) {
|
||||
if (current?.name && current?.command) {
|
||||
definitions.push(current as SecretSourceDefinition);
|
||||
}
|
||||
|
||||
current = {
|
||||
name: trimmed
|
||||
.replace('- name:', '')
|
||||
.trim()
|
||||
.replace(/^['"]|['"]$/g, ''),
|
||||
parseOutput: 'raw',
|
||||
};
|
||||
continue;
|
||||
}
|
||||
|
||||
if (current && trimmed.startsWith('command:')) {
|
||||
current.command = trimmed
|
||||
.replace('command:', '')
|
||||
.trim()
|
||||
.replace(/^['"]|['"]$/g, '');
|
||||
} else if (current && trimmed.startsWith('parseOutput:')) {
|
||||
const value = trimmed
|
||||
.replace('parseOutput:', '')
|
||||
.trim()
|
||||
.replace(/^['"]|['"]$/g, '');
|
||||
current.parseOutput = value as 'raw' | 'json-field';
|
||||
} else if (current && trimmed.startsWith('jsonField:')) {
|
||||
current.jsonField = trimmed
|
||||
.replace('jsonField:', '')
|
||||
.trim()
|
||||
.replace(/^['"]|['"]$/g, '');
|
||||
}
|
||||
}
|
||||
|
||||
if (current?.name && current?.command) {
|
||||
definitions.push(current as SecretSourceDefinition);
|
||||
}
|
||||
|
||||
return definitions;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user