mirror of
https://github.com/game-ci/unity-builder.git
synced 2026-06-01 06:16:14 -07:00
Compare commits
6 Commits
feature/ho
...
feature/ge
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
55b45a4a0c | ||
|
|
ae03bd2f13 | ||
|
|
1e2bb889bf | ||
|
|
7615bbd9dd | ||
|
|
aa2e05d468 | ||
|
|
b3e1639029 |
57
action.yml
57
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
|
||||
@@ -269,6 +269,28 @@ inputs:
|
||||
default: 'false'
|
||||
required: false
|
||||
description: 'Skip the activation/deactivation of Unity. This assumes Unity is already activated.'
|
||||
artifactOutputTypes:
|
||||
description: 'Comma-separated list of output types to collect (build, logs, test-results, coverage, images, metrics, data-export, server-build, custom)'
|
||||
required: false
|
||||
default: 'build,logs,test-results'
|
||||
artifactUploadTarget:
|
||||
description: 'Where to upload artifacts: github-artifacts, storage, local, none'
|
||||
required: false
|
||||
default: 'github-artifacts'
|
||||
artifactUploadPath:
|
||||
description: 'Destination path for artifact upload (storage URI or local path)'
|
||||
required: false
|
||||
artifactCompression:
|
||||
description: 'Compression for artifacts: none, gzip, lz4'
|
||||
required: false
|
||||
default: 'gzip'
|
||||
artifactRetentionDays:
|
||||
description: 'Retention period for uploaded artifacts in days'
|
||||
required: false
|
||||
default: '30'
|
||||
artifactCustomTypes:
|
||||
description: 'JSON string defining custom output types [{name, defaultPath, description}]'
|
||||
required: false
|
||||
cloneDepth:
|
||||
default: '50'
|
||||
required: false
|
||||
@@ -280,35 +302,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'
|
||||
@@ -321,6 +314,8 @@ outputs:
|
||||
'Returns the exit code from the build scripts. This code is 0 if the build was successful. If there was an error
|
||||
during activation, the code is from the activation step. If activation is successful, the code is from the project
|
||||
build step.'
|
||||
artifactManifestPath:
|
||||
description: 'Path to the generated artifact manifest JSON file'
|
||||
branding:
|
||||
icon: 'box'
|
||||
color: 'gray-dark'
|
||||
|
||||
1253
dist/index.js
generated
vendored
1253
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
137
src/index.ts
137
src/index.ts
@@ -1,10 +1,12 @@
|
||||
import * as core from '@actions/core';
|
||||
import path from 'node:path';
|
||||
import { Action, BuildParameters, Cache, Orchestrator, Docker, ImageTag, Output } from './model';
|
||||
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';
|
||||
import { OutputService } from './model/orchestrator/services/output/output-service';
|
||||
import { OutputTypeRegistry } from './model/orchestrator/services/output/output-type-registry';
|
||||
import { ArtifactUploadHandler } from './model/orchestrator/services/output/artifact-upload-handler';
|
||||
|
||||
async function runMain() {
|
||||
try {
|
||||
@@ -23,46 +25,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;
|
||||
@@ -73,6 +46,64 @@ async function runMain() {
|
||||
await Output.setAndroidVersionCode(buildParameters.androidVersionCode);
|
||||
await Output.setEngineExitCode(exitCode);
|
||||
|
||||
// Artifact collection and upload (runs on both success and failure)
|
||||
try {
|
||||
// Register custom output types if provided
|
||||
if (buildParameters.artifactCustomTypes) {
|
||||
try {
|
||||
const customTypes = JSON.parse(buildParameters.artifactCustomTypes);
|
||||
if (Array.isArray(customTypes)) {
|
||||
for (const ct of customTypes) {
|
||||
OutputTypeRegistry.registerType({
|
||||
name: ct.name,
|
||||
defaultPath: ct.defaultPath || ct.pattern || `./${ct.name}/`,
|
||||
description: ct.description || `Custom output type: ${ct.name}`,
|
||||
builtIn: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
} catch (parseError) {
|
||||
core.warning(`Failed to parse artifactCustomTypes: ${(parseError as Error).message}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Collect outputs and generate manifest
|
||||
const manifestPath = path.join(buildParameters.projectPath, 'output-manifest.json');
|
||||
const manifest = await OutputService.collectOutputs(
|
||||
buildParameters.projectPath,
|
||||
buildParameters.buildGuid,
|
||||
buildParameters.artifactOutputTypes,
|
||||
manifestPath,
|
||||
);
|
||||
|
||||
core.setOutput('artifactManifestPath', manifestPath);
|
||||
|
||||
// Upload artifacts
|
||||
const uploadConfig = ArtifactUploadHandler.parseConfig(
|
||||
buildParameters.artifactUploadTarget,
|
||||
buildParameters.artifactUploadPath || undefined,
|
||||
buildParameters.artifactCompression,
|
||||
buildParameters.artifactRetentionDays,
|
||||
);
|
||||
|
||||
const uploadResult = await ArtifactUploadHandler.uploadArtifacts(
|
||||
manifest,
|
||||
uploadConfig,
|
||||
buildParameters.projectPath,
|
||||
);
|
||||
|
||||
if (!uploadResult.success) {
|
||||
core.warning(
|
||||
`Artifact upload completed with errors: ${uploadResult.entries
|
||||
.filter((e) => !e.success)
|
||||
.map((e) => `${e.type}: ${e.error}`)
|
||||
.join('; ')}`,
|
||||
);
|
||||
}
|
||||
} catch (artifactError) {
|
||||
core.warning(`Artifact collection/upload failed: ${(artifactError as Error).message}`);
|
||||
}
|
||||
|
||||
if (exitCode !== 0) {
|
||||
core.setFailed(`Build failed with exit code ${exitCode}`);
|
||||
}
|
||||
@@ -81,28 +112,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,12 @@ 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 artifactOutputTypes!: string;
|
||||
public artifactUploadTarget!: string;
|
||||
public artifactUploadPath!: string;
|
||||
public artifactCompression!: string;
|
||||
public artifactRetentionDays!: string;
|
||||
public artifactCustomTypes!: string;
|
||||
|
||||
public static shouldUseRetainedWorkspaceMode(buildParameters: BuildParameters) {
|
||||
return buildParameters.maxRetainedWorkspaces > 0 && Orchestrator.lockedWorkspace !== ``;
|
||||
@@ -249,13 +248,12 @@ 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,
|
||||
artifactOutputTypes: Input.artifactOutputTypes,
|
||||
artifactUploadTarget: Input.artifactUploadTarget,
|
||||
artifactUploadPath: Input.artifactUploadPath,
|
||||
artifactCompression: Input.artifactCompression,
|
||||
artifactRetentionDays: Input.artifactRetentionDays,
|
||||
artifactCustomTypes: Input.artifactCustomTypes,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -278,42 +278,34 @@ class Input {
|
||||
return Input.getInput('containerRegistryImageVersion') ?? '3';
|
||||
}
|
||||
|
||||
static get artifactOutputTypes(): string {
|
||||
return Input.getInput('artifactOutputTypes') ?? 'build,logs,test-results';
|
||||
}
|
||||
|
||||
static get artifactUploadTarget(): string {
|
||||
return Input.getInput('artifactUploadTarget') ?? 'github-artifacts';
|
||||
}
|
||||
|
||||
static get artifactUploadPath(): string {
|
||||
return Input.getInput('artifactUploadPath') ?? '';
|
||||
}
|
||||
|
||||
static get artifactCompression(): string {
|
||||
return Input.getInput('artifactCompression') ?? 'gzip';
|
||||
}
|
||||
|
||||
static get artifactRetentionDays(): string {
|
||||
return Input.getInput('artifactRetentionDays') ?? '30';
|
||||
}
|
||||
|
||||
static get artifactCustomTypes(): string {
|
||||
return Input.getInput('artifactCustomTypes') ?? '';
|
||||
}
|
||||
|
||||
static get skipActivation(): string {
|
||||
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;
|
||||
|
||||
@@ -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';
|
||||
607
src/model/orchestrator/services/output/artifact-service.test.ts
Normal file
607
src/model/orchestrator/services/output/artifact-service.test.ts
Normal file
@@ -0,0 +1,607 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { OutputTypeRegistry, OutputTypeDefinition } from './output-type-registry';
|
||||
import { OutputService } from './output-service';
|
||||
import { OutputManifest } from './output-manifest';
|
||||
import { ArtifactUploadHandler, ArtifactUploadConfig } from './artifact-upload-handler';
|
||||
|
||||
// Mock node:fs
|
||||
jest.mock('node:fs');
|
||||
const mockedFs = fs as jest.Mocked<typeof fs>;
|
||||
|
||||
// Mock @actions/core (used by OrchestratorLogger)
|
||||
jest.mock('@actions/core', () => ({
|
||||
info: jest.fn(),
|
||||
warning: jest.fn(),
|
||||
error: jest.fn(),
|
||||
setOutput: jest.fn(),
|
||||
getInput: jest.fn(),
|
||||
setFailed: jest.fn(),
|
||||
setSecret: jest.fn(),
|
||||
}));
|
||||
|
||||
// Mock @actions/exec (used by upload handler for rclone)
|
||||
jest.mock('@actions/exec', () => ({
|
||||
exec: jest.fn().mockResolvedValue(0),
|
||||
}));
|
||||
|
||||
afterEach(() => {
|
||||
jest.restoreAllMocks();
|
||||
OutputTypeRegistry.resetCustomTypes();
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// OutputTypeRegistry Tests
|
||||
// ---------------------------------------------------------------------------
|
||||
describe('OutputTypeRegistry', () => {
|
||||
describe('built-in types', () => {
|
||||
it('should have 8 built-in types', () => {
|
||||
const allTypes = OutputTypeRegistry.getAllTypes();
|
||||
const builtInTypes = allTypes.filter((t) => t.builtIn);
|
||||
expect(builtInTypes).toHaveLength(8);
|
||||
});
|
||||
|
||||
it.each(['build', 'test-results', 'server-build', 'data-export', 'images', 'logs', 'metrics', 'coverage'])(
|
||||
'should include built-in type "%s"',
|
||||
(typeName) => {
|
||||
const typeDef = OutputTypeRegistry.getType(typeName);
|
||||
expect(typeDef).toBeDefined();
|
||||
expect(typeDef!.name).toBe(typeName);
|
||||
expect(typeDef!.builtIn).toBe(true);
|
||||
},
|
||||
);
|
||||
|
||||
it('should return undefined for unknown types', () => {
|
||||
const typeDef = OutputTypeRegistry.getType('nonexistent');
|
||||
expect(typeDef).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should include default paths for all built-in types', () => {
|
||||
const allTypes = OutputTypeRegistry.getAllTypes();
|
||||
for (const typeDef of allTypes) {
|
||||
expect(typeDef.defaultPath).toBeTruthy();
|
||||
expect(typeof typeDef.defaultPath).toBe('string');
|
||||
}
|
||||
});
|
||||
|
||||
it('should include descriptions for all built-in types', () => {
|
||||
const allTypes = OutputTypeRegistry.getAllTypes();
|
||||
for (const typeDef of allTypes) {
|
||||
expect(typeDef.description).toBeTruthy();
|
||||
expect(typeof typeDef.description).toBe('string');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('custom type registration', () => {
|
||||
it('should register a custom type', () => {
|
||||
const customType: OutputTypeDefinition = {
|
||||
name: 'custom-reports',
|
||||
defaultPath: './Reports/',
|
||||
description: 'Custom generated reports',
|
||||
builtIn: false,
|
||||
};
|
||||
|
||||
OutputTypeRegistry.registerType(customType);
|
||||
const retrieved = OutputTypeRegistry.getType('custom-reports');
|
||||
expect(retrieved).toBeDefined();
|
||||
expect(retrieved!.name).toBe('custom-reports');
|
||||
expect(retrieved!.builtIn).toBe(false);
|
||||
});
|
||||
|
||||
it('should not override built-in types', () => {
|
||||
const override: OutputTypeDefinition = {
|
||||
name: 'build',
|
||||
defaultPath: './Override/',
|
||||
description: 'Should not override',
|
||||
builtIn: false,
|
||||
};
|
||||
|
||||
OutputTypeRegistry.registerType(override);
|
||||
const buildType = OutputTypeRegistry.getType('build');
|
||||
expect(buildType!.defaultPath).not.toBe('./Override/');
|
||||
expect(buildType!.builtIn).toBe(true);
|
||||
});
|
||||
|
||||
it('should include custom types in getAllTypes', () => {
|
||||
OutputTypeRegistry.registerType({
|
||||
name: 'custom-a',
|
||||
defaultPath: './A/',
|
||||
description: 'Custom A',
|
||||
builtIn: false,
|
||||
});
|
||||
|
||||
const allTypes = OutputTypeRegistry.getAllTypes();
|
||||
expect(allTypes.length).toBe(9); // 8 built-in + 1 custom
|
||||
expect(allTypes.some((t) => t.name === 'custom-a')).toBe(true);
|
||||
});
|
||||
|
||||
it('should reset custom types', () => {
|
||||
OutputTypeRegistry.registerType({
|
||||
name: 'temp-type',
|
||||
defaultPath: './Temp/',
|
||||
description: 'Temporary type',
|
||||
builtIn: false,
|
||||
});
|
||||
|
||||
expect(OutputTypeRegistry.getType('temp-type')).toBeDefined();
|
||||
OutputTypeRegistry.resetCustomTypes();
|
||||
expect(OutputTypeRegistry.getType('temp-type')).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should force builtIn to false when registering custom types', () => {
|
||||
OutputTypeRegistry.registerType({
|
||||
name: 'sneaky',
|
||||
defaultPath: './Sneaky/',
|
||||
description: 'Tries to be built-in',
|
||||
builtIn: true, // Intentionally setting to true
|
||||
});
|
||||
|
||||
const retrieved = OutputTypeRegistry.getType('sneaky');
|
||||
expect(retrieved).toBeDefined();
|
||||
expect(retrieved!.builtIn).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('parseOutputTypes', () => {
|
||||
it('should parse a comma-separated string of valid types', () => {
|
||||
const types = OutputTypeRegistry.parseOutputTypes('build,logs,coverage');
|
||||
expect(types).toHaveLength(3);
|
||||
expect(types.map((t) => t.name)).toEqual(['build', 'logs', 'coverage']);
|
||||
});
|
||||
|
||||
it('should skip unknown types', () => {
|
||||
const types = OutputTypeRegistry.parseOutputTypes('build,unknown,logs');
|
||||
expect(types).toHaveLength(2);
|
||||
expect(types.map((t) => t.name)).toEqual(['build', 'logs']);
|
||||
});
|
||||
|
||||
it('should handle empty string', () => {
|
||||
const types = OutputTypeRegistry.parseOutputTypes('');
|
||||
expect(types).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('should handle whitespace in type names', () => {
|
||||
const types = OutputTypeRegistry.parseOutputTypes(' build , logs , coverage ');
|
||||
expect(types).toHaveLength(3);
|
||||
});
|
||||
|
||||
it('should include custom types when parsing', () => {
|
||||
OutputTypeRegistry.registerType({
|
||||
name: 'my-reports',
|
||||
defaultPath: './Reports/',
|
||||
description: 'Custom reports',
|
||||
builtIn: false,
|
||||
});
|
||||
|
||||
const types = OutputTypeRegistry.parseOutputTypes('build,my-reports');
|
||||
expect(types).toHaveLength(2);
|
||||
expect(types[1].name).toBe('my-reports');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// OutputService Tests
|
||||
// ---------------------------------------------------------------------------
|
||||
describe('OutputService', () => {
|
||||
const projectPath = '/project';
|
||||
const buildGuid = 'test-guid-1234';
|
||||
|
||||
beforeEach(() => {
|
||||
// Reset all fs mocks
|
||||
mockedFs.existsSync.mockReset();
|
||||
mockedFs.statSync.mockReset();
|
||||
mockedFs.readdirSync.mockReset();
|
||||
mockedFs.writeFileSync.mockReset();
|
||||
mockedFs.mkdirSync.mockReset();
|
||||
});
|
||||
|
||||
describe('collectOutputs', () => {
|
||||
it('should return an empty manifest when no output types are declared', async () => {
|
||||
const manifest = await OutputService.collectOutputs(projectPath, buildGuid, '');
|
||||
expect(manifest.buildGuid).toBe(buildGuid);
|
||||
expect(manifest.outputs).toHaveLength(0);
|
||||
expect(manifest.timestamp).toBeTruthy();
|
||||
});
|
||||
|
||||
it('should skip outputs where the path does not exist', async () => {
|
||||
mockedFs.existsSync.mockReturnValue(false);
|
||||
|
||||
const manifest = await OutputService.collectOutputs(projectPath, buildGuid, 'build,logs');
|
||||
expect(manifest.outputs).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('should collect directory outputs with file listings', async () => {
|
||||
mockedFs.existsSync.mockReturnValue(true);
|
||||
mockedFs.statSync.mockReturnValue({ isDirectory: () => true, size: 0 } as any);
|
||||
mockedFs.readdirSync.mockImplementation((_dirPath: any, options?: any) => {
|
||||
if (options?.withFileTypes) {
|
||||
return [
|
||||
{ name: 'file1.txt', isDirectory: () => false },
|
||||
{ name: 'file2.txt', isDirectory: () => false },
|
||||
] as any;
|
||||
}
|
||||
|
||||
return ['file1.txt', 'file2.txt'] as any;
|
||||
});
|
||||
|
||||
const manifest = await OutputService.collectOutputs(projectPath, buildGuid, 'logs');
|
||||
expect(manifest.outputs).toHaveLength(1);
|
||||
expect(manifest.outputs[0].type).toBe('logs');
|
||||
expect(manifest.outputs[0].files).toEqual(['file1.txt', 'file2.txt']);
|
||||
});
|
||||
|
||||
it('should collect file output with correct size', async () => {
|
||||
mockedFs.existsSync.mockReturnValue(true);
|
||||
mockedFs.statSync.mockReturnValue({ isDirectory: () => false, size: 4096 } as any);
|
||||
|
||||
const manifest = await OutputService.collectOutputs(projectPath, buildGuid, 'coverage');
|
||||
expect(manifest.outputs).toHaveLength(1);
|
||||
expect(manifest.outputs[0].size).toBe(4096);
|
||||
});
|
||||
|
||||
it('should write manifest to disk when manifestPath is provided', async () => {
|
||||
// existsSync returns false for output paths (no outputs found) but mkdirSync/writeFileSync should still be called
|
||||
// The service only writes manifest when at least one output type is declared and types are resolved
|
||||
// So we need to provide a valid output type and have its path exist
|
||||
mockedFs.existsSync.mockReturnValue(true);
|
||||
mockedFs.statSync.mockReturnValue({ isDirectory: () => false, size: 100 } as any);
|
||||
mockedFs.mkdirSync.mockReturnValue(undefined);
|
||||
mockedFs.writeFileSync.mockImplementation(() => {});
|
||||
|
||||
const manifestPath = '/output/manifest.json';
|
||||
await OutputService.collectOutputs(projectPath, buildGuid, 'logs', manifestPath);
|
||||
|
||||
expect(mockedFs.mkdirSync).toHaveBeenCalledWith(path.dirname(manifestPath), { recursive: true });
|
||||
expect(mockedFs.writeFileSync).toHaveBeenCalledWith(manifestPath, expect.any(String), 'utf8');
|
||||
});
|
||||
|
||||
it('should generate valid JSON in the manifest file', async () => {
|
||||
mockedFs.existsSync.mockReturnValue(true);
|
||||
mockedFs.statSync.mockReturnValue({ isDirectory: () => false, size: 200 } as any);
|
||||
mockedFs.mkdirSync.mockReturnValue(undefined);
|
||||
mockedFs.writeFileSync.mockImplementation(() => {});
|
||||
|
||||
const manifestPath = '/output/manifest.json';
|
||||
await OutputService.collectOutputs(projectPath, buildGuid, 'coverage', manifestPath);
|
||||
|
||||
const writtenContent = (mockedFs.writeFileSync as jest.Mock).mock.calls[0][1];
|
||||
const parsed = JSON.parse(writtenContent);
|
||||
expect(parsed.buildGuid).toBe(buildGuid);
|
||||
expect(Array.isArray(parsed.outputs)).toBe(true);
|
||||
expect(parsed.outputs.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('should set a valid ISO 8601 timestamp', async () => {
|
||||
const manifest = await OutputService.collectOutputs(projectPath, buildGuid, '');
|
||||
const parsed = new Date(manifest.timestamp);
|
||||
expect(parsed.toISOString()).toBe(manifest.timestamp);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// ArtifactUploadHandler Tests
|
||||
// ---------------------------------------------------------------------------
|
||||
describe('ArtifactUploadHandler', () => {
|
||||
const projectPath = '/project';
|
||||
|
||||
beforeEach(() => {
|
||||
mockedFs.existsSync.mockReset();
|
||||
mockedFs.statSync.mockReset();
|
||||
mockedFs.readdirSync.mockReset();
|
||||
mockedFs.mkdirSync.mockReset();
|
||||
mockedFs.copyFileSync.mockReset();
|
||||
});
|
||||
|
||||
describe('parseConfig', () => {
|
||||
it('should parse valid config values', () => {
|
||||
const config = ArtifactUploadHandler.parseConfig('github-artifacts', '/dest', 'gzip', '14');
|
||||
expect(config.target).toBe('github-artifacts');
|
||||
expect(config.destination).toBe('/dest');
|
||||
expect(config.compression).toBe('gzip');
|
||||
expect(config.retentionDays).toBe(14);
|
||||
});
|
||||
|
||||
it('should default invalid target to github-artifacts', () => {
|
||||
const config = ArtifactUploadHandler.parseConfig('invalid', undefined, 'none', '30');
|
||||
expect(config.target).toBe('github-artifacts');
|
||||
});
|
||||
|
||||
it('should default invalid compression to gzip', () => {
|
||||
const config = ArtifactUploadHandler.parseConfig('local', '/dest', 'brotli', '30');
|
||||
expect(config.compression).toBe('gzip');
|
||||
});
|
||||
|
||||
it('should default invalid retention to 30 days', () => {
|
||||
const config = ArtifactUploadHandler.parseConfig('local', '/dest', 'gzip', 'abc');
|
||||
expect(config.retentionDays).toBe(30);
|
||||
});
|
||||
|
||||
it('should default negative retention to 30 days', () => {
|
||||
const config = ArtifactUploadHandler.parseConfig('local', '/dest', 'gzip', '-5');
|
||||
expect(config.retentionDays).toBe(30);
|
||||
});
|
||||
|
||||
it('should set destination to undefined when empty string', () => {
|
||||
const config = ArtifactUploadHandler.parseConfig('storage', '', 'none', '7');
|
||||
expect(config.destination).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('uploadArtifacts', () => {
|
||||
it('should skip upload when target is none', async () => {
|
||||
const manifest: OutputManifest = {
|
||||
buildGuid: 'test-guid',
|
||||
timestamp: new Date().toISOString(),
|
||||
outputs: [{ type: 'build', path: './Builds/' }],
|
||||
};
|
||||
|
||||
const config: ArtifactUploadConfig = {
|
||||
target: 'none',
|
||||
compression: 'gzip',
|
||||
retentionDays: 30,
|
||||
};
|
||||
|
||||
const result = await ArtifactUploadHandler.uploadArtifacts(manifest, config, projectPath);
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.entries).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('should return success with no entries for empty manifest', async () => {
|
||||
const manifest: OutputManifest = {
|
||||
buildGuid: 'test-guid',
|
||||
timestamp: new Date().toISOString(),
|
||||
outputs: [],
|
||||
};
|
||||
|
||||
const config: ArtifactUploadConfig = {
|
||||
target: 'github-artifacts',
|
||||
compression: 'gzip',
|
||||
retentionDays: 30,
|
||||
};
|
||||
|
||||
const result = await ArtifactUploadHandler.uploadArtifacts(manifest, config, projectPath);
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.entries).toHaveLength(0);
|
||||
expect(result.totalBytes).toBe(0);
|
||||
});
|
||||
|
||||
it('should fail entry when output path does not exist', async () => {
|
||||
mockedFs.existsSync.mockReturnValue(false);
|
||||
|
||||
const manifest: OutputManifest = {
|
||||
buildGuid: 'test-guid',
|
||||
timestamp: new Date().toISOString(),
|
||||
outputs: [{ type: 'build', path: './Builds/Missing/' }],
|
||||
};
|
||||
|
||||
const config: ArtifactUploadConfig = {
|
||||
target: 'local',
|
||||
destination: '/output',
|
||||
compression: 'none',
|
||||
retentionDays: 30,
|
||||
};
|
||||
|
||||
const result = await ArtifactUploadHandler.uploadArtifacts(manifest, config, projectPath);
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.entries).toHaveLength(1);
|
||||
expect(result.entries[0].success).toBe(false);
|
||||
expect(result.entries[0].error).toContain('does not exist');
|
||||
});
|
||||
|
||||
it('should copy files for local upload target', async () => {
|
||||
mockedFs.existsSync.mockReturnValue(true);
|
||||
mockedFs.statSync.mockReturnValue({ isDirectory: () => false, size: 1024 } as any);
|
||||
mockedFs.mkdirSync.mockReturnValue(undefined);
|
||||
mockedFs.copyFileSync.mockReturnValue(undefined);
|
||||
|
||||
const manifest: OutputManifest = {
|
||||
buildGuid: 'test-guid',
|
||||
timestamp: new Date().toISOString(),
|
||||
outputs: [{ type: 'logs', path: './Logs/build.log', size: 1024 }],
|
||||
};
|
||||
|
||||
const config: ArtifactUploadConfig = {
|
||||
target: 'local',
|
||||
destination: '/output',
|
||||
compression: 'none',
|
||||
retentionDays: 30,
|
||||
};
|
||||
|
||||
const result = await ArtifactUploadHandler.uploadArtifacts(manifest, config, projectPath);
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.entries).toHaveLength(1);
|
||||
expect(result.entries[0].success).toBe(true);
|
||||
expect(result.totalBytes).toBe(1024);
|
||||
});
|
||||
|
||||
it('should fail local upload when no destination is provided', async () => {
|
||||
mockedFs.existsSync.mockReturnValue(true);
|
||||
mockedFs.statSync.mockReturnValue({ isDirectory: () => false, size: 512 } as any);
|
||||
|
||||
const manifest: OutputManifest = {
|
||||
buildGuid: 'test-guid',
|
||||
timestamp: new Date().toISOString(),
|
||||
outputs: [{ type: 'logs', path: './Logs/build.log', size: 512 }],
|
||||
};
|
||||
|
||||
const config: ArtifactUploadConfig = {
|
||||
target: 'local',
|
||||
compression: 'none',
|
||||
retentionDays: 30,
|
||||
};
|
||||
|
||||
const result = await ArtifactUploadHandler.uploadArtifacts(manifest, config, projectPath);
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.entries[0].success).toBe(false);
|
||||
expect(result.entries[0].error).toContain('destination path');
|
||||
});
|
||||
|
||||
it('should report correct duration', async () => {
|
||||
const manifest: OutputManifest = {
|
||||
buildGuid: 'test-guid',
|
||||
timestamp: new Date().toISOString(),
|
||||
outputs: [],
|
||||
};
|
||||
|
||||
const config: ArtifactUploadConfig = {
|
||||
target: 'none',
|
||||
compression: 'gzip',
|
||||
retentionDays: 30,
|
||||
};
|
||||
|
||||
const result = await ArtifactUploadHandler.uploadArtifacts(manifest, config, projectPath);
|
||||
expect(result.durationMs).toBeGreaterThanOrEqual(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('collectFiles', () => {
|
||||
it('should return single file for a file path', () => {
|
||||
mockedFs.statSync.mockReturnValue({ isDirectory: () => false } as any);
|
||||
|
||||
const files = ArtifactUploadHandler.collectFiles('/path/to/file.txt');
|
||||
expect(files).toEqual(['/path/to/file.txt']);
|
||||
});
|
||||
|
||||
it('should return all files recursively for a directory', () => {
|
||||
mockedFs.statSync.mockImplementation((p: any) => {
|
||||
const pathStr = typeof p === 'string' ? p : p.toString();
|
||||
if (pathStr.endsWith('.txt') || pathStr.endsWith('.log')) {
|
||||
return { isDirectory: () => false } as any;
|
||||
}
|
||||
|
||||
return { isDirectory: () => true } as any;
|
||||
});
|
||||
|
||||
mockedFs.readdirSync.mockImplementation((dirPath: any, _options?: any) => {
|
||||
const dirStr = typeof dirPath === 'string' ? dirPath : dirPath.toString();
|
||||
if (dirStr === '/root') {
|
||||
return [
|
||||
{ name: 'file1.txt', isDirectory: () => false },
|
||||
{ name: 'sub', isDirectory: () => true },
|
||||
] as any;
|
||||
}
|
||||
if (dirStr.endsWith('sub')) {
|
||||
return [{ name: 'file2.log', isDirectory: () => false }] as any;
|
||||
}
|
||||
|
||||
return [] as any;
|
||||
});
|
||||
|
||||
const files = ArtifactUploadHandler.collectFiles('/root');
|
||||
expect(files).toHaveLength(2);
|
||||
expect(files).toContain(path.join('/root', 'file1.txt'));
|
||||
expect(files).toContain(path.join('/root', 'sub', 'file2.log'));
|
||||
});
|
||||
});
|
||||
|
||||
describe('storage upload validation', () => {
|
||||
it('should fail storage upload when no destination is provided', async () => {
|
||||
mockedFs.existsSync.mockReturnValue(true);
|
||||
mockedFs.statSync.mockReturnValue({ isDirectory: () => false, size: 256 } as any);
|
||||
|
||||
const manifest: OutputManifest = {
|
||||
buildGuid: 'test-guid',
|
||||
timestamp: new Date().toISOString(),
|
||||
outputs: [{ type: 'build', path: './Builds/', size: 256 }],
|
||||
};
|
||||
|
||||
const config: ArtifactUploadConfig = {
|
||||
target: 'storage',
|
||||
compression: 'gzip',
|
||||
retentionDays: 30,
|
||||
};
|
||||
|
||||
const result = await ArtifactUploadHandler.uploadArtifacts(manifest, config, projectPath);
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.entries[0].error).toContain('destination URI');
|
||||
});
|
||||
|
||||
it('should fail storage upload when destination URI has invalid format', async () => {
|
||||
mockedFs.existsSync.mockReturnValue(true);
|
||||
mockedFs.statSync.mockReturnValue({ isDirectory: () => false, size: 256 } as any);
|
||||
|
||||
const manifest: OutputManifest = {
|
||||
buildGuid: 'test-guid',
|
||||
timestamp: new Date().toISOString(),
|
||||
outputs: [{ type: 'build', path: './Builds/', size: 256 }],
|
||||
};
|
||||
|
||||
const config: ArtifactUploadConfig = {
|
||||
target: 'storage',
|
||||
destination: '/just/a/local/path',
|
||||
compression: 'gzip',
|
||||
retentionDays: 30,
|
||||
};
|
||||
|
||||
const result = await ArtifactUploadHandler.uploadArtifacts(manifest, config, projectPath);
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.entries[0].error).toContain('Invalid storage destination URI');
|
||||
});
|
||||
|
||||
it('should fail storage upload when rclone is not installed', async () => {
|
||||
// Mock child_process.execFileSync to throw (rclone not found)
|
||||
const childProcess = require('node:child_process');
|
||||
const originalExecFileSync = childProcess.execFileSync;
|
||||
childProcess.execFileSync = jest.fn(() => {
|
||||
throw new Error('ENOENT');
|
||||
});
|
||||
|
||||
mockedFs.existsSync.mockReturnValue(true);
|
||||
mockedFs.statSync.mockReturnValue({ isDirectory: () => false, size: 256 } as any);
|
||||
|
||||
const manifest: OutputManifest = {
|
||||
buildGuid: 'test-guid',
|
||||
timestamp: new Date().toISOString(),
|
||||
outputs: [{ type: 'build', path: './Builds/', size: 256 }],
|
||||
};
|
||||
|
||||
const config: ArtifactUploadConfig = {
|
||||
target: 'storage',
|
||||
destination: 's3:my-bucket/artifacts',
|
||||
compression: 'gzip',
|
||||
retentionDays: 30,
|
||||
};
|
||||
|
||||
const result = await ArtifactUploadHandler.uploadArtifacts(manifest, config, projectPath);
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.entries[0].error).toContain('rclone is not installed');
|
||||
|
||||
// Restore
|
||||
childProcess.execFileSync = originalExecFileSync;
|
||||
});
|
||||
|
||||
it('should accept valid rclone storage URI formats', async () => {
|
||||
// Mock child_process.execFileSync to succeed (rclone available)
|
||||
const childProcess = require('node:child_process');
|
||||
const originalExecFileSync = childProcess.execFileSync;
|
||||
childProcess.execFileSync = jest.fn(() => 'rclone v1.65.0');
|
||||
|
||||
mockedFs.existsSync.mockReturnValue(true);
|
||||
mockedFs.statSync.mockReturnValue({ isDirectory: () => false, size: 256 } as any);
|
||||
|
||||
const manifest: OutputManifest = {
|
||||
buildGuid: 'test-guid',
|
||||
timestamp: new Date().toISOString(),
|
||||
outputs: [{ type: 'build', path: './Builds/', size: 256 }],
|
||||
};
|
||||
|
||||
// s3:bucket format should pass URI validation and reach the exec call
|
||||
const config: ArtifactUploadConfig = {
|
||||
target: 'storage',
|
||||
destination: 's3:my-bucket/artifacts',
|
||||
compression: 'gzip',
|
||||
retentionDays: 30,
|
||||
};
|
||||
|
||||
const result = await ArtifactUploadHandler.uploadArtifacts(manifest, config, projectPath);
|
||||
// Should succeed because exec is mocked to return 0
|
||||
expect(result.entries[0].success).toBe(true);
|
||||
|
||||
// Restore
|
||||
childProcess.execFileSync = originalExecFileSync;
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,474 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { exec } from '@actions/exec';
|
||||
import OrchestratorLogger from '../core/orchestrator-logger';
|
||||
import { OutputManifest, OutputEntry } from './output-manifest';
|
||||
|
||||
/**
|
||||
* Configuration for artifact upload.
|
||||
*/
|
||||
export interface ArtifactUploadConfig {
|
||||
/** Upload target: 'github-artifacts', 'storage', 'local', 'none' */
|
||||
target: 'github-artifacts' | 'storage' | 'local' | 'none';
|
||||
|
||||
/** Destination path — storage URI for 'storage', local path for 'local' */
|
||||
destination?: string;
|
||||
|
||||
/** Compression method */
|
||||
compression: 'none' | 'gzip' | 'lz4';
|
||||
|
||||
/** Retention period in days (GitHub Artifacts only) */
|
||||
retentionDays: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Result of an artifact upload operation.
|
||||
*/
|
||||
export interface UploadResult {
|
||||
/** Whether the upload succeeded overall */
|
||||
success: boolean;
|
||||
|
||||
/** Per-entry upload results */
|
||||
entries: UploadEntryResult[];
|
||||
|
||||
/** Total bytes uploaded */
|
||||
totalBytes: number;
|
||||
|
||||
/** Duration in milliseconds */
|
||||
durationMs: number;
|
||||
}
|
||||
|
||||
export interface UploadEntryResult {
|
||||
/** The output type name */
|
||||
type: string;
|
||||
|
||||
/** The output path */
|
||||
path: string;
|
||||
|
||||
/** Whether this entry uploaded successfully */
|
||||
success: boolean;
|
||||
|
||||
/** Bytes uploaded for this entry */
|
||||
bytes: number;
|
||||
|
||||
/** Error message if upload failed */
|
||||
error?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* GitHub Artifacts size limit per artifact (10 GB).
|
||||
* Files larger than this must be split.
|
||||
*/
|
||||
const GITHUB_ARTIFACT_SIZE_LIMIT = 10 * 1024 * 1024 * 1024;
|
||||
|
||||
/**
|
||||
* Minimum valid storage URI pattern: "remote:path" or "remote:".
|
||||
* rclone requires at least a remote name followed by a colon.
|
||||
*/
|
||||
const STORAGE_URI_PATTERN = /^[a-zA-Z][\w-]*:/;
|
||||
|
||||
/**
|
||||
* Check whether rclone is installed and available on PATH.
|
||||
* Returns true if `rclone version` executes successfully.
|
||||
*/
|
||||
function isRcloneAvailable(): boolean {
|
||||
try {
|
||||
execFileSync('rclone', ['version'], { stdio: 'pipe', timeout: 5000 });
|
||||
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate that a storage destination URI has the correct rclone format.
|
||||
* Valid format: "remoteName:path" (e.g., "s3:bucket/prefix", "gdrive:folder").
|
||||
*/
|
||||
function isValidStorageUri(uri: string): boolean {
|
||||
return STORAGE_URI_PATTERN.test(uri);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles uploading build artifacts to various targets.
|
||||
*/
|
||||
export class ArtifactUploadHandler {
|
||||
/**
|
||||
* Upload artifacts described by a manifest to the configured target.
|
||||
*/
|
||||
static async uploadArtifacts(
|
||||
manifest: OutputManifest,
|
||||
config: ArtifactUploadConfig,
|
||||
projectPath: string,
|
||||
): Promise<UploadResult> {
|
||||
const startTime = Date.now();
|
||||
const result: UploadResult = {
|
||||
success: true,
|
||||
entries: [],
|
||||
totalBytes: 0,
|
||||
durationMs: 0,
|
||||
};
|
||||
|
||||
if (config.target === 'none') {
|
||||
OrchestratorLogger.log('[ArtifactUpload] Upload target is "none", skipping upload');
|
||||
result.durationMs = Date.now() - startTime;
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
if (manifest.outputs.length === 0) {
|
||||
OrchestratorLogger.log('[ArtifactUpload] No outputs in manifest, nothing to upload');
|
||||
result.durationMs = Date.now() - startTime;
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
OrchestratorLogger.log(`[ArtifactUpload] Uploading ${manifest.outputs.length} output(s) to ${config.target}`);
|
||||
|
||||
for (const entry of manifest.outputs) {
|
||||
const entryResult = await ArtifactUploadHandler.uploadEntry(entry, config, projectPath);
|
||||
result.entries.push(entryResult);
|
||||
result.totalBytes += entryResult.bytes;
|
||||
|
||||
if (!entryResult.success) {
|
||||
result.success = false;
|
||||
}
|
||||
}
|
||||
|
||||
result.durationMs = Date.now() - startTime;
|
||||
|
||||
OrchestratorLogger.log(
|
||||
`[ArtifactUpload] Upload complete: ${result.entries.filter((e) => e.success).length}/${
|
||||
result.entries.length
|
||||
} succeeded, ${result.totalBytes} bytes, ${result.durationMs}ms`,
|
||||
);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Upload a single output entry.
|
||||
*/
|
||||
private static async uploadEntry(
|
||||
entry: OutputEntry,
|
||||
config: ArtifactUploadConfig,
|
||||
projectPath: string,
|
||||
): Promise<UploadEntryResult> {
|
||||
const entryResult: UploadEntryResult = {
|
||||
type: entry.type,
|
||||
path: entry.path,
|
||||
success: false,
|
||||
bytes: entry.size || 0,
|
||||
};
|
||||
|
||||
const resolvedPath = path.resolve(
|
||||
projectPath,
|
||||
entry.path.replace('{platform}', process.env.BUILD_TARGET || 'Unknown'),
|
||||
);
|
||||
|
||||
if (!fs.existsSync(resolvedPath)) {
|
||||
entryResult.error = `Output path does not exist: ${resolvedPath}`;
|
||||
OrchestratorLogger.logWarning(`[ArtifactUpload] ${entryResult.error}`);
|
||||
|
||||
return entryResult;
|
||||
}
|
||||
|
||||
try {
|
||||
switch (config.target) {
|
||||
case 'github-artifacts':
|
||||
await ArtifactUploadHandler.uploadToGitHubArtifacts(entry, resolvedPath, config);
|
||||
break;
|
||||
case 'storage':
|
||||
await ArtifactUploadHandler.uploadToStorage(entry, resolvedPath, config);
|
||||
break;
|
||||
case 'local':
|
||||
await ArtifactUploadHandler.uploadToLocal(entry, resolvedPath, config);
|
||||
break;
|
||||
}
|
||||
entryResult.success = true;
|
||||
OrchestratorLogger.log(
|
||||
`[ArtifactUpload] Uploaded '${entry.type}' (${entryResult.bytes} bytes) to ${config.target}`,
|
||||
);
|
||||
} catch (error: any) {
|
||||
entryResult.error = error.message || String(error);
|
||||
OrchestratorLogger.logWarning(`[ArtifactUpload] Failed to upload '${entry.type}': ${entryResult.error}`);
|
||||
}
|
||||
|
||||
return entryResult;
|
||||
}
|
||||
|
||||
/**
|
||||
* Upload to GitHub Artifacts via @actions/artifact.
|
||||
* Handles large file splitting if artifacts exceed the size limit.
|
||||
*/
|
||||
private static async uploadToGitHubArtifacts(
|
||||
entry: OutputEntry,
|
||||
resolvedPath: string,
|
||||
config: ArtifactUploadConfig,
|
||||
): Promise<void> {
|
||||
// Dynamically require @actions/artifact — it may not be available in all environments.
|
||||
// Using a variable to prevent TypeScript from resolving the module at compile time.
|
||||
let artifact: any;
|
||||
try {
|
||||
const artifactModule = '@actions/artifact';
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||
artifact = require(artifactModule);
|
||||
} catch {
|
||||
throw new Error('@actions/artifact package is not available. Install it to use github-artifacts upload target.');
|
||||
}
|
||||
|
||||
const artifactClient = artifact.DefaultArtifactClient
|
||||
? new artifact.DefaultArtifactClient()
|
||||
: artifact.default
|
||||
? new artifact.default()
|
||||
: artifact;
|
||||
|
||||
const files = ArtifactUploadHandler.collectFiles(resolvedPath);
|
||||
|
||||
if (files.length === 0) {
|
||||
OrchestratorLogger.logWarning(`[ArtifactUpload] No files found at ${resolvedPath} for '${entry.type}'`);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
const totalSize = entry.size || 0;
|
||||
const artifactName = `unity-output-${entry.type}`;
|
||||
|
||||
if (totalSize > GITHUB_ARTIFACT_SIZE_LIMIT) {
|
||||
OrchestratorLogger.log(
|
||||
`[ArtifactUpload] Output '${entry.type}' exceeds GitHub Artifacts size limit (${totalSize} > ${GITHUB_ARTIFACT_SIZE_LIMIT}), splitting into chunks`,
|
||||
);
|
||||
await ArtifactUploadHandler.uploadChunked(artifactClient, artifactName, files, resolvedPath, config);
|
||||
} else {
|
||||
const rootDirectory = fs.statSync(resolvedPath).isDirectory() ? resolvedPath : path.dirname(resolvedPath);
|
||||
|
||||
if (typeof artifactClient.uploadArtifact === 'function') {
|
||||
await artifactClient.uploadArtifact(artifactName, files, rootDirectory, {
|
||||
retentionDays: config.retentionDays,
|
||||
compressionLevel: config.compression === 'none' ? 0 : 6,
|
||||
});
|
||||
} else {
|
||||
throw new Error(
|
||||
'@actions/artifact client does not have uploadArtifact method. Ensure the package version is compatible.',
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Upload large artifacts in chunks to stay within GitHub size limits.
|
||||
*/
|
||||
private static async uploadChunked(
|
||||
artifactClient: any,
|
||||
baseName: string,
|
||||
files: string[],
|
||||
rootDirectory: string,
|
||||
config: ArtifactUploadConfig,
|
||||
): Promise<void> {
|
||||
const chunkSize = GITHUB_ARTIFACT_SIZE_LIMIT;
|
||||
let currentChunkFiles: string[] = [];
|
||||
let currentChunkSize = 0;
|
||||
let chunkIndex = 0;
|
||||
|
||||
for (const filePath of files) {
|
||||
const fileSize = fs.statSync(filePath).size;
|
||||
|
||||
if (currentChunkSize + fileSize > chunkSize && currentChunkFiles.length > 0) {
|
||||
await ArtifactUploadHandler.uploadSingleChunk(
|
||||
artifactClient,
|
||||
`${baseName}-part${chunkIndex}`,
|
||||
currentChunkFiles,
|
||||
rootDirectory,
|
||||
config,
|
||||
);
|
||||
chunkIndex++;
|
||||
currentChunkFiles = [];
|
||||
currentChunkSize = 0;
|
||||
}
|
||||
|
||||
currentChunkFiles.push(filePath);
|
||||
currentChunkSize += fileSize;
|
||||
}
|
||||
|
||||
if (currentChunkFiles.length > 0) {
|
||||
await ArtifactUploadHandler.uploadSingleChunk(
|
||||
artifactClient,
|
||||
chunkIndex > 0 ? `${baseName}-part${chunkIndex}` : baseName,
|
||||
currentChunkFiles,
|
||||
rootDirectory,
|
||||
config,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private static async uploadSingleChunk(
|
||||
artifactClient: any,
|
||||
name: string,
|
||||
files: string[],
|
||||
rootDirectory: string,
|
||||
config: ArtifactUploadConfig,
|
||||
): Promise<void> {
|
||||
OrchestratorLogger.log(`[ArtifactUpload] Uploading chunk '${name}' with ${files.length} file(s)`);
|
||||
|
||||
if (typeof artifactClient.uploadArtifact === 'function') {
|
||||
await artifactClient.uploadArtifact(name, files, rootDirectory, {
|
||||
retentionDays: config.retentionDays,
|
||||
compressionLevel: config.compression === 'none' ? 0 : 6,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Upload to remote storage via rclone.
|
||||
*
|
||||
* Validates rclone availability and destination URI format before attempting
|
||||
* the upload. If rclone is not installed, falls back to local copy when a
|
||||
* local-compatible destination is provided, or skips with a clear error.
|
||||
*/
|
||||
private static async uploadToStorage(
|
||||
entry: OutputEntry,
|
||||
resolvedPath: string,
|
||||
config: ArtifactUploadConfig,
|
||||
): Promise<void> {
|
||||
if (!config.destination) {
|
||||
throw new Error('Storage upload requires a destination URI in artifactUploadPath');
|
||||
}
|
||||
|
||||
// Validate storage URI format before attempting upload
|
||||
if (!isValidStorageUri(config.destination)) {
|
||||
throw new Error(
|
||||
`Invalid storage destination URI: "${config.destination}". ` +
|
||||
'Expected rclone remote format "remoteName:path" (e.g., "s3:my-bucket/artifacts", "gdrive:builds").',
|
||||
);
|
||||
}
|
||||
|
||||
// Check rclone availability before attempting upload
|
||||
if (!isRcloneAvailable()) {
|
||||
OrchestratorLogger.error(
|
||||
'rclone is not installed or not in PATH. ' +
|
||||
'Install rclone (https://rclone.org/install/) to use storage-based artifact upload. ' +
|
||||
'Falling back to local copy.',
|
||||
);
|
||||
|
||||
// Attempt local copy fallback using the destination as a hint
|
||||
// Strip the remote prefix to get a local-ish path for fallback
|
||||
OrchestratorLogger.logWarning(
|
||||
`[ArtifactUpload] Storage upload skipped for '${entry.type}' — rclone not available`,
|
||||
);
|
||||
throw new Error(
|
||||
'rclone is not installed or not in PATH. ' +
|
||||
'Install rclone from https://rclone.org/install/ to use storage-based artifact upload.',
|
||||
);
|
||||
}
|
||||
|
||||
const destination = `${config.destination}/${entry.type}`;
|
||||
|
||||
OrchestratorLogger.log(`[ArtifactUpload] Uploading '${entry.type}' to storage: ${destination}`);
|
||||
|
||||
const args = ['copy', resolvedPath, destination, '--progress'];
|
||||
|
||||
if (config.compression !== 'none') {
|
||||
// rclone doesn't have built-in compression flags for copy;
|
||||
// compression is typically handled by the remote configuration.
|
||||
// Log as informational.
|
||||
OrchestratorLogger.log(
|
||||
`[ArtifactUpload] Note: compression '${config.compression}' is configured at the remote level for rclone`,
|
||||
);
|
||||
}
|
||||
|
||||
await exec('rclone', args);
|
||||
}
|
||||
|
||||
/**
|
||||
* Upload to a local path (copy).
|
||||
*/
|
||||
private static async uploadToLocal(
|
||||
entry: OutputEntry,
|
||||
resolvedPath: string,
|
||||
config: ArtifactUploadConfig,
|
||||
): Promise<void> {
|
||||
if (!config.destination) {
|
||||
throw new Error('Local upload requires a destination path in artifactUploadPath');
|
||||
}
|
||||
|
||||
const destination = path.join(config.destination, entry.type);
|
||||
fs.mkdirSync(destination, { recursive: true });
|
||||
|
||||
OrchestratorLogger.log(`[ArtifactUpload] Copying '${entry.type}' to local path: ${destination}`);
|
||||
|
||||
ArtifactUploadHandler.copyRecursive(resolvedPath, destination);
|
||||
}
|
||||
|
||||
/**
|
||||
* Recursively copy files from source to destination.
|
||||
*/
|
||||
private static copyRecursive(source: string, destination: string): void {
|
||||
const stat = fs.statSync(source);
|
||||
|
||||
if (stat.isDirectory()) {
|
||||
fs.mkdirSync(destination, { recursive: true });
|
||||
const entries = fs.readdirSync(source);
|
||||
for (const entry of entries) {
|
||||
ArtifactUploadHandler.copyRecursive(path.join(source, entry), path.join(destination, entry));
|
||||
}
|
||||
} else {
|
||||
fs.copyFileSync(source, destination);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Collect all files at a given path (recursively if directory).
|
||||
*/
|
||||
static collectFiles(targetPath: string): string[] {
|
||||
const stat = fs.statSync(targetPath);
|
||||
|
||||
if (!stat.isDirectory()) {
|
||||
return [targetPath];
|
||||
}
|
||||
|
||||
const files: string[] = [];
|
||||
const entries = fs.readdirSync(targetPath, { withFileTypes: true });
|
||||
|
||||
for (const entry of entries) {
|
||||
const fullPath = path.join(targetPath, entry.name);
|
||||
if (entry.isDirectory()) {
|
||||
files.push(...ArtifactUploadHandler.collectFiles(fullPath));
|
||||
} else {
|
||||
files.push(fullPath);
|
||||
}
|
||||
}
|
||||
|
||||
return files;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse an ArtifactUploadConfig from action inputs.
|
||||
*/
|
||||
static parseConfig(
|
||||
target: string,
|
||||
destination: string | undefined,
|
||||
compression: string,
|
||||
retentionDays: string,
|
||||
): ArtifactUploadConfig {
|
||||
const validTargets = ['github-artifacts', 'storage', 'local', 'none'] as const;
|
||||
const resolvedTarget = validTargets.includes(target as any)
|
||||
? (target as ArtifactUploadConfig['target'])
|
||||
: 'github-artifacts';
|
||||
|
||||
const validCompressions = ['none', 'gzip', 'lz4'] as const;
|
||||
const resolvedCompression = validCompressions.includes(compression as any)
|
||||
? (compression as ArtifactUploadConfig['compression'])
|
||||
: 'gzip';
|
||||
|
||||
const parsedRetention = Number.parseInt(retentionDays, 10);
|
||||
const resolvedRetention = Number.isNaN(parsedRetention) || parsedRetention <= 0 ? 30 : parsedRetention;
|
||||
|
||||
return {
|
||||
target: resolvedTarget,
|
||||
destination: destination || undefined,
|
||||
compression: resolvedCompression,
|
||||
retentionDays: resolvedRetention,
|
||||
};
|
||||
}
|
||||
}
|
||||
3
src/model/orchestrator/services/output/index.ts
Normal file
3
src/model/orchestrator/services/output/index.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
export { OutputManifest, OutputEntry } from './output-manifest';
|
||||
export { OutputTypeRegistry, OutputTypeDefinition } from './output-type-registry';
|
||||
export { OutputService } from './output-service';
|
||||
41
src/model/orchestrator/services/output/output-manifest.ts
Normal file
41
src/model/orchestrator/services/output/output-manifest.ts
Normal file
@@ -0,0 +1,41 @@
|
||||
/**
|
||||
* Structured build output manifest.
|
||||
* Describes all artifacts produced by a build with type, path, size, hash, and metadata.
|
||||
*/
|
||||
|
||||
export interface OutputEntry {
|
||||
/** Output type identifier (e.g., 'build', 'test-results', 'images') */
|
||||
type: string;
|
||||
|
||||
/** Relative path to the output */
|
||||
path: string;
|
||||
|
||||
/** Output format (e.g., 'nunit3', 'junit', 'json') */
|
||||
format?: string;
|
||||
|
||||
/** File size in bytes */
|
||||
size?: number;
|
||||
|
||||
/** Content hash (e.g., 'sha256:abc...') */
|
||||
hash?: string;
|
||||
|
||||
/** Individual files within the output path */
|
||||
files?: string[];
|
||||
|
||||
/** Type-specific summary (e.g., test counts, build size) */
|
||||
summary?: Record<string, unknown>;
|
||||
|
||||
/** Arbitrary metadata */
|
||||
metadata?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface OutputManifest {
|
||||
/** Unique build identifier */
|
||||
buildGuid: string;
|
||||
|
||||
/** ISO 8601 timestamp */
|
||||
timestamp: string;
|
||||
|
||||
/** All outputs produced by this build */
|
||||
outputs: OutputEntry[];
|
||||
}
|
||||
118
src/model/orchestrator/services/output/output-service.ts
Normal file
118
src/model/orchestrator/services/output/output-service.ts
Normal file
@@ -0,0 +1,118 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import OrchestratorLogger from '../core/orchestrator-logger';
|
||||
import { OutputManifest, OutputEntry } from './output-manifest';
|
||||
import { OutputTypeRegistry } from './output-type-registry';
|
||||
|
||||
/**
|
||||
* Service for collecting, manifesting, and managing build outputs.
|
||||
*
|
||||
* After a build completes, this service scans declared output paths,
|
||||
* generates a structured manifest, and prepares outputs for post-processing.
|
||||
*/
|
||||
export class OutputService {
|
||||
/**
|
||||
* Collect outputs from the workspace and generate a manifest.
|
||||
*
|
||||
* @param projectPath - Path to the Unity project root
|
||||
* @param buildGuid - Unique build identifier
|
||||
* @param outputTypesInput - Comma-separated output type names
|
||||
* @param manifestPath - Where to write the manifest JSON (optional)
|
||||
* @returns The generated output manifest
|
||||
*/
|
||||
static async collectOutputs(
|
||||
projectPath: string,
|
||||
buildGuid: string,
|
||||
outputTypesInput: string,
|
||||
manifestPath?: string,
|
||||
): Promise<OutputManifest> {
|
||||
const types = OutputTypeRegistry.parseOutputTypes(outputTypesInput);
|
||||
const manifest: OutputManifest = {
|
||||
buildGuid,
|
||||
timestamp: new Date().toISOString(),
|
||||
outputs: [],
|
||||
};
|
||||
|
||||
if (types.length === 0) {
|
||||
OrchestratorLogger.log('[Output] No output types declared, skipping collection');
|
||||
|
||||
return manifest;
|
||||
}
|
||||
|
||||
OrchestratorLogger.log(
|
||||
`[Output] Collecting ${types.length} output type(s): ${types.map((t) => t.name).join(', ')}`,
|
||||
);
|
||||
|
||||
for (const typeDef of types) {
|
||||
const outputPath = path.join(
|
||||
projectPath,
|
||||
typeDef.defaultPath.replace('{platform}', process.env.BUILD_TARGET || 'Unknown'),
|
||||
);
|
||||
|
||||
if (!fs.existsSync(outputPath)) {
|
||||
OrchestratorLogger.log(`[Output] No output found for '${typeDef.name}' at ${outputPath}`);
|
||||
continue;
|
||||
}
|
||||
|
||||
const entry: OutputEntry = {
|
||||
type: typeDef.name,
|
||||
path: typeDef.defaultPath,
|
||||
};
|
||||
|
||||
// Collect file listing for directory outputs
|
||||
try {
|
||||
const stat = fs.statSync(outputPath);
|
||||
if (stat.isDirectory()) {
|
||||
entry.files = fs.readdirSync(outputPath);
|
||||
entry.size = OutputService.getDirectorySize(outputPath);
|
||||
} else {
|
||||
entry.size = stat.size;
|
||||
}
|
||||
} catch {
|
||||
OrchestratorLogger.logWarning(`[Output] Failed to stat output '${typeDef.name}' at ${outputPath}`);
|
||||
}
|
||||
|
||||
manifest.outputs.push(entry);
|
||||
OrchestratorLogger.log(
|
||||
`[Output] Collected '${typeDef.name}': ${entry.files?.length || 1} file(s), ${entry.size || 0} bytes`,
|
||||
);
|
||||
}
|
||||
|
||||
// Write manifest to disk
|
||||
if (manifestPath) {
|
||||
try {
|
||||
const manifestDir = path.dirname(manifestPath);
|
||||
fs.mkdirSync(manifestDir, { recursive: true });
|
||||
fs.writeFileSync(manifestPath, JSON.stringify(manifest, null, 2), 'utf8');
|
||||
OrchestratorLogger.log(`[Output] Manifest written to ${manifestPath}`);
|
||||
} catch (error: any) {
|
||||
OrchestratorLogger.logWarning(`[Output] Failed to write manifest: ${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
return manifest;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate total size of a directory recursively.
|
||||
*/
|
||||
private static getDirectorySize(dirPath: string): number {
|
||||
let totalSize = 0;
|
||||
|
||||
try {
|
||||
const entries = fs.readdirSync(dirPath, { withFileTypes: true });
|
||||
for (const entry of entries) {
|
||||
const fullPath = path.join(dirPath, entry.name);
|
||||
if (entry.isDirectory()) {
|
||||
totalSize += OutputService.getDirectorySize(fullPath);
|
||||
} else {
|
||||
totalSize += fs.statSync(fullPath).size;
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Ignore errors in size calculation
|
||||
}
|
||||
|
||||
return totalSize;
|
||||
}
|
||||
}
|
||||
136
src/model/orchestrator/services/output/output-type-registry.ts
Normal file
136
src/model/orchestrator/services/output/output-type-registry.ts
Normal file
@@ -0,0 +1,136 @@
|
||||
import OrchestratorLogger from '../core/orchestrator-logger';
|
||||
|
||||
/**
|
||||
* Registry of known output types with default paths and processing hints.
|
||||
*/
|
||||
|
||||
export interface OutputTypeDefinition {
|
||||
/** Type identifier */
|
||||
name: string;
|
||||
|
||||
/** Default output path (relative to project root) */
|
||||
defaultPath: string;
|
||||
|
||||
/** Human-readable description */
|
||||
description: string;
|
||||
|
||||
/** Whether this type is built-in or user-registered */
|
||||
builtIn: boolean;
|
||||
}
|
||||
|
||||
export class OutputTypeRegistry {
|
||||
private static readonly builtInTypes: Record<string, OutputTypeDefinition> = {
|
||||
build: {
|
||||
name: 'build',
|
||||
defaultPath: './Builds/{platform}/',
|
||||
description: 'Standard game build artifact',
|
||||
builtIn: true,
|
||||
},
|
||||
'test-results': {
|
||||
name: 'test-results',
|
||||
defaultPath: './TestResults/',
|
||||
description: 'NUnit/JUnit XML test results',
|
||||
builtIn: true,
|
||||
},
|
||||
'server-build': {
|
||||
name: 'server-build',
|
||||
defaultPath: './Builds/{platform}-server/',
|
||||
description: 'Dedicated server build artifact',
|
||||
builtIn: true,
|
||||
},
|
||||
'data-export': {
|
||||
name: 'data-export',
|
||||
defaultPath: './Exports/',
|
||||
description: 'Exported data files (CSV, JSON, binary)',
|
||||
builtIn: true,
|
||||
},
|
||||
images: {
|
||||
name: 'images',
|
||||
defaultPath: './Captures/',
|
||||
description: 'Screenshots, render captures, atlas previews',
|
||||
builtIn: true,
|
||||
},
|
||||
logs: {
|
||||
name: 'logs',
|
||||
defaultPath: './Logs/',
|
||||
description: 'Structured build and test logs',
|
||||
builtIn: true,
|
||||
},
|
||||
metrics: {
|
||||
name: 'metrics',
|
||||
defaultPath: './Metrics/',
|
||||
description: 'Build performance metrics and asset statistics',
|
||||
builtIn: true,
|
||||
},
|
||||
coverage: {
|
||||
name: 'coverage',
|
||||
defaultPath: './Coverage/',
|
||||
description: 'Code coverage reports',
|
||||
builtIn: true,
|
||||
},
|
||||
};
|
||||
|
||||
private static customTypes: Record<string, OutputTypeDefinition> = {};
|
||||
|
||||
/**
|
||||
* Get a type definition by name. Checks custom types first, then built-in.
|
||||
*/
|
||||
static getType(name: string): OutputTypeDefinition | undefined {
|
||||
return OutputTypeRegistry.customTypes[name] || OutputTypeRegistry.builtInTypes[name];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all registered types (built-in + custom).
|
||||
*/
|
||||
static getAllTypes(): OutputTypeDefinition[] {
|
||||
return [...Object.values(OutputTypeRegistry.builtInTypes), ...Object.values(OutputTypeRegistry.customTypes)];
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a custom output type.
|
||||
*/
|
||||
static registerType(definition: OutputTypeDefinition): void {
|
||||
if (OutputTypeRegistry.builtInTypes[definition.name]) {
|
||||
OrchestratorLogger.logWarning(`[OutputTypes] Cannot override built-in type '${definition.name}'`);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
OutputTypeRegistry.customTypes[definition.name] = { ...definition, builtIn: false };
|
||||
OrchestratorLogger.log(`[OutputTypes] Registered custom type '${definition.name}'`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a comma-separated output types string into type definitions.
|
||||
* Unknown types are logged as warnings and skipped.
|
||||
*/
|
||||
static parseOutputTypes(outputTypesInput: string): OutputTypeDefinition[] {
|
||||
if (!outputTypesInput) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const names = outputTypesInput
|
||||
.split(',')
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean);
|
||||
const types: OutputTypeDefinition[] = [];
|
||||
|
||||
for (const name of names) {
|
||||
const typeDef = OutputTypeRegistry.getType(name);
|
||||
if (typeDef) {
|
||||
types.push(typeDef);
|
||||
} else {
|
||||
OrchestratorLogger.logWarning(`[OutputTypes] Unknown output type '${name}', skipping`);
|
||||
}
|
||||
}
|
||||
|
||||
return types;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reset custom types (for testing).
|
||||
*/
|
||||
static resetCustomTypes(): void {
|
||||
OutputTypeRegistry.customTypes = {};
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user