Fix script deletion during execution on desktop
This commit fixes an issue seen on certain Windows environments (Windows 10 22H2 and 11 23H2 Pro Azure VMs) where scripts were being deleted during execution due to temporary directory usage. To resolve this, scripts are now stored in a persistent directory, enhancing reliability for long-running scripts and improving auditability along with troubleshooting. Key changes: - Move script execution logic to the `main` process from `preloader` to utilize Electron's `app.getPath`. - Improve runtime environment detection for non-browser environments to allow its usage in Electron main process. - Introduce a secure module to expose IPC channels from the main process to the renderer via the preloader process. Supporting refactorings include: - Simplify `CodeRunner` interface by removing the `tempScriptFolderName` parameter. - Rename `NodeSystemOperations` to `NodeElectronSystemOperations` as it now wraps electron APIs too, and convert it to class for simplicity. - Rename `TemporaryFileCodeRunner` to `ScriptFileCodeRunner` to reflect its new functinoality. - Rename `SystemOperations` folder to `System` for simplicity. - Rename `HostRuntimeEnvironment` to `BrowserRuntimeEnvironment` for clarity. - Refactor main Electron process configuration to align with latest Electron documentation/recommendations. - Refactor unit tests `BrowserRuntimeEnvironment` to simplify singleton workaround. - Use alias imports like `electron/main` and `electron/common` for better clarity.
This commit is contained in:
@@ -0,0 +1,40 @@
|
||||
import { Logger } from '@/application/Common/Log/Logger';
|
||||
import { ElectronLogger } from '@/infrastructure/Log/ElectronLogger';
|
||||
import { SystemOperations } from '../../System/SystemOperations';
|
||||
import { NodeElectronSystemOperations } from '../../System/NodeElectronSystemOperations';
|
||||
import { ScriptDirectoryProvider } from './ScriptDirectoryProvider';
|
||||
|
||||
export const ExecutionSubdirectory = 'runs';
|
||||
|
||||
export class PersistentDirectoryProvider implements ScriptDirectoryProvider {
|
||||
constructor(
|
||||
private readonly system: SystemOperations = new NodeElectronSystemOperations(),
|
||||
private readonly logger: Logger = ElectronLogger,
|
||||
) { }
|
||||
|
||||
async provideScriptDirectory(): Promise<string> {
|
||||
const scriptsDirectory = this.system.location.combinePaths(
|
||||
/*
|
||||
Switched from temporary to persistent directory for script storage for improved reliability.
|
||||
|
||||
Temporary directories in some environments, such certain Windows Pro Azure VMs, showed
|
||||
issues where scripts were interrupted due to directory cleanup during script execution.
|
||||
This was observed with system temp directories (e.g., `%LOCALAPPDATA%\Temp`).
|
||||
|
||||
Persistent directories offer better stability during long executions and aid in auditability
|
||||
and troubleshooting.
|
||||
*/
|
||||
this.system.operatingSystem.getUserDataDirectory(),
|
||||
ExecutionSubdirectory,
|
||||
);
|
||||
this.logger.info(`Attempting to create script directory at path: ${scriptsDirectory}`);
|
||||
try {
|
||||
await this.system.fileSystem.createDirectory(scriptsDirectory, true);
|
||||
this.logger.info(`Script directory successfully created at: ${scriptsDirectory}`);
|
||||
} catch (error) {
|
||||
this.logger.error(`Error creating script directory at ${scriptsDirectory}: ${error.message}`, error);
|
||||
throw error;
|
||||
}
|
||||
return scriptsDirectory;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
export interface ScriptDirectoryProvider {
|
||||
provideScriptDirectory(): Promise<string>;
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
export interface FilenameGenerator {
|
||||
generateFilename(): string;
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import { OperatingSystem } from '@/domain/OperatingSystem';
|
||||
import { RuntimeEnvironment } from '@/infrastructure/RuntimeEnvironment/RuntimeEnvironment';
|
||||
import { CurrentEnvironment } from '@/infrastructure/RuntimeEnvironment/RuntimeEnvironmentFactory';
|
||||
import { FilenameGenerator } from './FilenameGenerator';
|
||||
|
||||
/**
|
||||
* Generates a timestamped filename specific to the given operating system.
|
||||
*
|
||||
* The filename includes:
|
||||
* - A timestamp for uniqueness and easier auditability.
|
||||
* - File extension based on the operating system.
|
||||
*/
|
||||
export class OsTimestampedFilenameGenerator implements FilenameGenerator {
|
||||
private readonly currentOs?: OperatingSystem;
|
||||
|
||||
constructor(
|
||||
environment: RuntimeEnvironment = CurrentEnvironment,
|
||||
) {
|
||||
this.currentOs = environment.os;
|
||||
}
|
||||
|
||||
public generateFilename(
|
||||
date = new Date(),
|
||||
): string {
|
||||
const baseFileName = `run-${createTimeStampForFile(date)}`;
|
||||
const extension = this.currentOs === undefined ? undefined : FileExtensions[this.currentOs];
|
||||
return extension ? `${baseFileName}.${extension}` : baseFileName;
|
||||
}
|
||||
}
|
||||
|
||||
const FileExtensions: Partial<Record<OperatingSystem, string>> = {
|
||||
// '.bat' for Windows batch files; required for executability.
|
||||
[OperatingSystem.Windows]: 'bat',
|
||||
|
||||
// '.sh' for Unix-like systems; enhances recognition as a shell script
|
||||
[OperatingSystem.macOS]: 'sh',
|
||||
[OperatingSystem.Linux]: 'sh',
|
||||
};
|
||||
|
||||
/** Generates a timestamp for the filename in 'YYYY-MM-DD_HH-MM-SS' format. */
|
||||
function createTimeStampForFile(date: Date): string {
|
||||
return date
|
||||
.toISOString()
|
||||
.replace(/T/, '_')
|
||||
.replace(/:/g, '-')
|
||||
.replace(/\..+/, '');
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import { ElectronLogger } from '@/infrastructure/Log/ElectronLogger';
|
||||
import { Logger } from '@/application/Common/Log/Logger';
|
||||
import { SystemOperations } from '../System/SystemOperations';
|
||||
import { NodeElectronSystemOperations } from '../System/NodeElectronSystemOperations';
|
||||
import { FilenameGenerator } from './Filename/FilenameGenerator';
|
||||
import { ScriptFileCreator } from './ScriptFileCreator';
|
||||
import { OsTimestampedFilenameGenerator } from './Filename/OsTimestampedFilenameGenerator';
|
||||
import { ScriptDirectoryProvider } from './Directory/ScriptDirectoryProvider';
|
||||
import { PersistentDirectoryProvider } from './Directory/PersistentDirectoryProvider';
|
||||
|
||||
export class ScriptFileCreationOrchestrator implements ScriptFileCreator {
|
||||
constructor(
|
||||
private readonly system: SystemOperations = new NodeElectronSystemOperations(),
|
||||
private readonly filenameGenerator: FilenameGenerator = new OsTimestampedFilenameGenerator(),
|
||||
private readonly directoryProvider: ScriptDirectoryProvider = new PersistentDirectoryProvider(),
|
||||
private readonly logger: Logger = ElectronLogger,
|
||||
) { }
|
||||
|
||||
public async createScriptFile(contents: string): Promise<string> {
|
||||
const filePath = await this.provideFilePath();
|
||||
await this.createFile(filePath, contents);
|
||||
return filePath;
|
||||
}
|
||||
|
||||
private async provideFilePath(): Promise<string> {
|
||||
const filename = this.filenameGenerator.generateFilename();
|
||||
const directoryPath = await this.directoryProvider.provideScriptDirectory();
|
||||
const filePath = this.system.location.combinePaths(directoryPath, filename);
|
||||
return filePath;
|
||||
}
|
||||
|
||||
private async createFile(filePath: string, contents: string): Promise<void> {
|
||||
this.logger.info(`Creating file at ${filePath}, size: ${contents.length} characters`);
|
||||
await this.system.fileSystem.writeToFile(filePath, contents);
|
||||
this.logger.info(`File created successfully at ${filePath}`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
export interface ScriptFileCreator {
|
||||
createScriptFile(contents: string): Promise<string>;
|
||||
}
|
||||
Reference in New Issue
Block a user