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:
undergroundwires
2024-01-06 18:47:58 +01:00
parent bf7fb0732c
commit c84a1bb74c
75 changed files with 1809 additions and 574 deletions

View File

@@ -1,6 +1,6 @@
import { describe, it, expect } from 'vitest';
import { BrowserCondition, TouchSupportExpectation } from '@/infrastructure/RuntimeEnvironment/BrowserOs/BrowserCondition';
import { ConditionBasedOsDetector } from '@/infrastructure/RuntimeEnvironment/BrowserOs/ConditionBasedOsDetector';
import { BrowserCondition, TouchSupportExpectation } from '@/infrastructure/RuntimeEnvironment/Browser/BrowserOs/BrowserCondition';
import { ConditionBasedOsDetector } from '@/infrastructure/RuntimeEnvironment/Browser/BrowserOs/ConditionBasedOsDetector';
import { getAbsentStringTestCases, itEachAbsentCollectionValue } from '@tests/unit/shared/TestCases/AbsentTests';
import { OperatingSystem } from '@/domain/OperatingSystem';
import { BrowserEnvironmentStub } from '@tests/unit/shared/Stubs/BrowserEnvironmentStub';

View File

@@ -1,15 +1,15 @@
// eslint-disable-next-line max-classes-per-file
import { describe, it, expect } from 'vitest';
import { BrowserOsDetector } from '@/infrastructure/RuntimeEnvironment/BrowserOs/BrowserOsDetector';
import { BrowserOsDetector } from '@/infrastructure/RuntimeEnvironment/Browser/BrowserOs/BrowserOsDetector';
import { OperatingSystem } from '@/domain/OperatingSystem';
import { HostRuntimeEnvironment } from '@/infrastructure/RuntimeEnvironment/HostRuntimeEnvironment';
import { BrowserRuntimeEnvironment } from '@/infrastructure/RuntimeEnvironment/Browser/BrowserRuntimeEnvironment';
import { itEachAbsentObjectValue } from '@tests/unit/shared/TestCases/AbsentTests';
import { BrowserOsDetectorStub } from '@tests/unit/shared/Stubs/BrowserOsDetectorStub';
import { IEnvironmentVariables } from '@/infrastructure/EnvironmentVariables/IEnvironmentVariables';
import { EnvironmentVariablesStub } from '@tests/unit/shared/Stubs/EnvironmentVariablesStub';
import { expectExists } from '@tests/shared/Assertions/ExpectExists';
describe('HostRuntimeEnvironment', () => {
describe('BrowserRuntimeEnvironment', () => {
describe('ctor', () => {
describe('throws if window is absent', () => {
itEachAbsentObjectValue((absentValue) => {
@@ -17,9 +17,9 @@ describe('HostRuntimeEnvironment', () => {
const expectedError = 'missing window';
const absentWindow = absentValue;
// act
const act = () => createEnvironment({
window: absentWindow as never,
});
const act = () => new BrowserRuntimeEnvironmentBuilder()
.withWindow(absentWindow as never)
.build();
// assert
expect(act).to.throw(expectedError);
});
@@ -28,12 +28,13 @@ describe('HostRuntimeEnvironment', () => {
// arrange
const expectedTouchSupport = true;
const osDetector = new BrowserOsDetectorStub();
const window = { os: undefined, navigator: { userAgent: 'Forcing touch detection' } } as Partial<Window>;
// act
createEnvironment({
window: { os: undefined, navigator: { userAgent: 'Forcing touch detection' } } as Partial<Window>,
isTouchSupported: expectedTouchSupport,
browserOsDetector: osDetector,
});
new BrowserRuntimeEnvironmentBuilder()
.withWindow(window)
.withBrowserOsDetector(osDetector)
.withTouchSupported(expectedTouchSupport)
.build();
// assert
const actualCall = osDetector.callHistory.find((c) => c.methodName === 'detect');
expectExists(actualCall);
@@ -48,9 +49,9 @@ describe('HostRuntimeEnvironment', () => {
isDesktop: true,
};
// act
const sut = createEnvironment({
window: desktopWindow,
});
const sut = new BrowserRuntimeEnvironmentBuilder()
.withWindow(desktopWindow)
.build();
// assert
expect(sut.isDesktop).to.equal(true);
});
@@ -61,9 +62,9 @@ describe('HostRuntimeEnvironment', () => {
isDesktop: false,
};
// act
const sut = createEnvironment({
window: browserWindow,
});
const sut = new BrowserRuntimeEnvironmentBuilder()
.withWindow(browserWindow)
.build();
// assert
expect(sut.isDesktop).to.equal(expectedValue);
});
@@ -77,9 +78,9 @@ describe('HostRuntimeEnvironment', () => {
throw new Error('should not reach here');
},
};
const sut = createEnvironment({
browserOsDetector: browserDetectorMock,
});
const sut = new BrowserRuntimeEnvironmentBuilder()
.withBrowserOsDetector(browserDetectorMock)
.build();
// act
const actual = sut.os;
// assert
@@ -103,10 +104,10 @@ describe('HostRuntimeEnvironment', () => {
},
};
// act
const sut = createEnvironment({
window: windowWithUserAgent as Partial<Window>,
browserOsDetector: browserDetectorMock,
});
const sut = new BrowserRuntimeEnvironmentBuilder()
.withWindow(windowWithUserAgent as Partial<Window>)
.withBrowserOsDetector(browserDetectorMock)
.build();
const actual = sut.os;
// assert
expect(actual).to.equal(expected);
@@ -127,9 +128,9 @@ describe('HostRuntimeEnvironment', () => {
os: expectedOs,
};
// act
const sut = createEnvironment({
window: desktopWindowWithOs,
});
const sut = new BrowserRuntimeEnvironmentBuilder()
.withWindow(desktopWindowWithOs)
.build();
// assert
const actualOs = sut.os;
expect(actualOs).to.equal(expectedOs);
@@ -144,9 +145,9 @@ describe('HostRuntimeEnvironment', () => {
os: absentValue as never,
};
// act
const sut = createEnvironment({
window: windowWithAbsentOs,
});
const sut = new BrowserRuntimeEnvironmentBuilder()
.withWindow(windowWithAbsentOs)
.build();
// assert
expect(sut.os).to.equal(expectedValue);
});
@@ -161,9 +162,9 @@ describe('HostRuntimeEnvironment', () => {
const environment = new EnvironmentVariablesStub()
.withIsNonProduction(expectedValue);
// act
const sut = createEnvironment({
environmentVariables: environment,
});
const sut = new BrowserRuntimeEnvironmentBuilder()
.withEnvironmentVariables(environment)
.build();
// assert
const actualValue = sut.isNonProduction;
expect(actualValue).to.equal(expectedValue);
@@ -172,32 +173,41 @@ describe('HostRuntimeEnvironment', () => {
});
});
interface EnvironmentOptions {
readonly window?: Partial<Window>;
readonly browserOsDetector?: BrowserOsDetector;
readonly environmentVariables?: IEnvironmentVariables;
readonly isTouchSupported?: boolean;
}
class BrowserRuntimeEnvironmentBuilder {
private window: Partial<Window> = {};
function createEnvironment(options: Partial<EnvironmentOptions> = {}): TestableRuntimeEnvironment {
const defaultOptions: Required<EnvironmentOptions> = {
window: {},
browserOsDetector: new BrowserOsDetectorStub(),
environmentVariables: new EnvironmentVariablesStub(),
isTouchSupported: false,
};
private browserOsDetector: BrowserOsDetector = new BrowserOsDetectorStub();
return new TestableRuntimeEnvironment({ ...defaultOptions, ...options });
}
private environmentVariables: IEnvironmentVariables = new EnvironmentVariablesStub();
class TestableRuntimeEnvironment extends HostRuntimeEnvironment {
/* Using a separate object instead of `ConstructorParameter<..>` */
public constructor(options: Required<EnvironmentOptions>) {
super(
options.window,
options.environmentVariables,
options.browserOsDetector,
() => options.isTouchSupported,
private isTouchSupported = false;
public withEnvironmentVariables(environmentVariables: IEnvironmentVariables): this {
this.environmentVariables = environmentVariables;
return this;
}
public withWindow(window: Partial<Window>): this {
this.window = window;
return this;
}
public withBrowserOsDetector(browserOsDetector: BrowserOsDetector): this {
this.browserOsDetector = browserOsDetector;
return this;
}
public withTouchSupported(isTouchSupported: boolean): this {
this.isTouchSupported = isTouchSupported;
return this;
}
public build() {
return new BrowserRuntimeEnvironment(
this.window,
this.environmentVariables,
this.browserOsDetector,
() => this.isTouchSupported,
);
}
}

View File

@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest';
import { BrowserTouchSupportAccessor, isTouchEnabledDevice } from '@/infrastructure/RuntimeEnvironment/TouchSupportDetection';
import { BrowserTouchSupportAccessor, isTouchEnabledDevice } from '@/infrastructure/RuntimeEnvironment/Browser/TouchSupportDetection';
describe('TouchSupportDetection', () => {
describe('isTouchEnabledDevice', () => {

View File

@@ -0,0 +1,61 @@
import { describe } from 'vitest';
import { OperatingSystem } from '@/domain/OperatingSystem';
import { formatAssertionMessage } from '@tests/shared/FormatAssertionMessage';
import { convertPlatformToOs } from '@/infrastructure/RuntimeEnvironment/Node/NodeOsMapper';
describe('NodeOsMapper', () => {
describe('convertPlatformToOs', () => {
describe('determines desktop OS', () => {
// arrange
interface IDesktopTestCase {
readonly nodePlatform: NodeJS.Platform;
readonly expectedOs: ReturnType<typeof convertPlatformToOs>;
}
const testScenarios: readonly IDesktopTestCase[] = [ // https://nodejs.org/api/process.html#process_process_platform
{
nodePlatform: 'aix',
expectedOs: undefined,
},
{
nodePlatform: 'darwin',
expectedOs: OperatingSystem.macOS,
},
{
nodePlatform: 'freebsd',
expectedOs: undefined,
},
{
nodePlatform: 'linux',
expectedOs: OperatingSystem.Linux,
},
{
nodePlatform: 'openbsd',
expectedOs: undefined,
},
{
nodePlatform: 'sunos',
expectedOs: undefined,
},
{
nodePlatform: 'win32',
expectedOs: OperatingSystem.Windows,
},
];
testScenarios.forEach(({ nodePlatform, expectedOs }) => {
it(nodePlatform, () => {
// act
const actualOs = convertPlatformToOs(nodePlatform);
// assert
expect(actualOs).to.equal(expectedOs, formatAssertionMessage([
`Expected: "${printResult(expectedOs)}"\n`,
`Actual: "${printResult(actualOs)}"\n`,
`Platform: "${nodePlatform}"`,
]));
function printResult(os: ReturnType<typeof convertPlatformToOs>): string {
return os === undefined ? 'undefined' : OperatingSystem[os];
}
});
});
});
});
});

View File

@@ -0,0 +1,146 @@
// eslint-disable-next-line max-classes-per-file
import { describe, it, expect } from 'vitest';
import { NodeJSProcessAccessor, NodeRuntimeEnvironment, PlatformToOperatingSystemConverter } from '@/infrastructure/RuntimeEnvironment/Node/NodeRuntimeEnvironment';
import { itEachAbsentObjectValue } from '@tests/unit/shared/TestCases/AbsentTests';
import { OperatingSystem } from '@/domain/OperatingSystem';
describe('NodeRuntimeEnvironment', () => {
describe('constructor', () => {
describe('throws with missing process', () => {
itEachAbsentObjectValue((absentValue) => {
// arrange
const expectedError = 'missing process';
const absentProcess = absentValue;
// act
const act = () => new NodeRuntimeEnvironmentBuilder()
.withProcess(absentProcess as never)
.build();
// assert
expect(act).to.throw(expectedError);
}, { excludeUndefined: true });
});
});
describe('os', () => {
it('matches specified OS', () => {
// arrange
const expectedOs = OperatingSystem.Android;
const osConverterMock: PlatformToOperatingSystemConverter = () => expectedOs;
// act
const environment = new NodeRuntimeEnvironmentBuilder()
.withOsConverter(osConverterMock)
.build();
// assert
expect(environment.os).to.equal(expectedOs);
});
it('uses process platform to determine OS', () => {
// arrange
const expectedPlatform: NodeJS.Platform = 'win32';
let actualPlatform: NodeJS.Platform | undefined;
const osConverterMock: PlatformToOperatingSystemConverter = (platform) => {
actualPlatform = platform;
return undefined;
};
const nodeProcessMock = new NodeJSProcessAccessorStub()
.withPlatform(expectedPlatform);
// act
new NodeRuntimeEnvironmentBuilder()
.withOsConverter(osConverterMock)
.withProcess(nodeProcessMock)
.build();
// assert
expect(expectedPlatform).to.equal(actualPlatform);
});
it('is undefined for unknown platforms', () => {
// arrange
const expectedOs = undefined;
const osConverterMock: PlatformToOperatingSystemConverter = () => undefined;
// act
const environment = new NodeRuntimeEnvironmentBuilder()
.withOsConverter(osConverterMock)
.build();
// assert
expect(environment.os).to.equal(expectedOs);
});
});
describe('isDesktop', () => {
it('is always true', () => {
// arrange
const expectedDesktopCondition = true;
// act
const environment = new NodeRuntimeEnvironment();
/// assert
expect(environment.isDesktop).to.equal(expectedDesktopCondition);
});
});
describe('isNonProduction', () => {
it('identifies development mode', () => {
// arrange
const expectedNonProductionCondition = true;
const nodeProcess = new NodeJSProcessAccessorStub()
.withNodeEnv('development');
// act
const environment = new NodeRuntimeEnvironmentBuilder()
.withProcess(nodeProcess)
.build();
/// assert
expect(environment.isNonProduction).to.equal(expectedNonProductionCondition);
});
it('identifies production mode', () => {
// arrange
const expectedNonProductionCondition = false;
const nodeProcess = new NodeJSProcessAccessorStub()
.withNodeEnv('production');
// act
const environment = new NodeRuntimeEnvironmentBuilder()
.withProcess(nodeProcess)
.build();
/// assert
expect(environment.isNonProduction).to.equal(expectedNonProductionCondition);
});
});
});
class NodeJSProcessAccessorStub implements NodeJSProcessAccessor {
private nodeEnv?: string = 'development';
public platform: NodeJS.Platform = 'linux';
public get env() {
return {
NODE_ENV: this.nodeEnv,
};
}
public withNodeEnv(nodeEnv?: string): this {
this.nodeEnv = nodeEnv;
return this;
}
public withPlatform(platform: NodeJS.Platform): this {
this.platform = platform;
return this;
}
}
class NodeRuntimeEnvironmentBuilder {
private process?: NodeJSProcessAccessor = new NodeJSProcessAccessorStub();
private osConverter?: PlatformToOperatingSystemConverter = () => OperatingSystem.Windows;
public withProcess(process?: NodeJSProcessAccessor): this {
this.process = process;
return this;
}
public withOsConverter(osConverter?: PlatformToOperatingSystemConverter): this {
this.osConverter = osConverter;
return this;
}
public build(): NodeRuntimeEnvironment {
return new NodeRuntimeEnvironment(
this.process,
this.osConverter,
);
}
}

View File

@@ -0,0 +1,88 @@
import { describe, it, expect } from 'vitest';
import {
BrowserRuntimeEnvironmentFactory, NodeRuntimeEnvironmentFactory,
WindowAccessor, determineAndCreateRuntimeEnvironment,
} from '@/infrastructure/RuntimeEnvironment/RuntimeEnvironmentFactory';
import { RuntimeEnvironmentStub } from '@tests/unit/shared/Stubs/RuntimeEnvironmentStub';
describe('RuntimeEnvironmentFactory', () => {
describe('determineAndCreateRuntimeEnvironment', () => {
it('uses browser environment when window exists', () => {
// arrange
const expectedEnvironment = new RuntimeEnvironmentStub();
const context = new RuntimeEnvironmentFactoryTestSetup()
.withWindowAccessor(() => { return {} as Window; })
.withBrowserEnvironmentFactory(() => expectedEnvironment);
// act
const actualEnvironment = context.buildEnvironment();
// assert
expect(actualEnvironment).to.equal(expectedEnvironment);
});
it('passes correct window to browser environment', () => {
// arrange
const expectedWindow = {} as Window;
let actualWindow: Window | undefined;
const browserEnvironmentFactoryMock: BrowserRuntimeEnvironmentFactory = (providedWindow) => {
actualWindow = providedWindow;
return new RuntimeEnvironmentStub();
};
const context = new RuntimeEnvironmentFactoryTestSetup()
.withWindowAccessor(() => expectedWindow)
.withBrowserEnvironmentFactory(browserEnvironmentFactoryMock);
// act
context.buildEnvironment();
// assert
expect(actualWindow).to.equal(expectedWindow);
});
it('uses node environment when window is absent', () => {
// arrange
const expectedEnvironment = new RuntimeEnvironmentStub();
const context = new RuntimeEnvironmentFactoryTestSetup()
.withWindowAccessor(() => undefined)
.withNodeEnvironmentFactory(() => expectedEnvironment);
// act
const actualEnvironment = context.buildEnvironment();
// assert
expect(actualEnvironment).to.equal(expectedEnvironment);
});
});
});
export class RuntimeEnvironmentFactoryTestSetup {
private windowAccessor: WindowAccessor = () => undefined;
private browserEnvironmentFactory
: BrowserRuntimeEnvironmentFactory = () => new RuntimeEnvironmentStub();
private nodeEnvironmentFactory
: NodeRuntimeEnvironmentFactory = () => new RuntimeEnvironmentStub();
public withWindowAccessor(windowAccessor: WindowAccessor): this {
this.windowAccessor = windowAccessor;
return this;
}
public withNodeEnvironmentFactory(
nodeEnvironmentFactory: NodeRuntimeEnvironmentFactory,
): this {
this.nodeEnvironmentFactory = nodeEnvironmentFactory;
return this;
}
public withBrowserEnvironmentFactory(
browserEnvironmentFactory: BrowserRuntimeEnvironmentFactory,
): this {
this.browserEnvironmentFactory = browserEnvironmentFactory;
return this;
}
public buildEnvironment(): ReturnType<typeof determineAndCreateRuntimeEnvironment> {
return determineAndCreateRuntimeEnvironment(
this.windowAccessor,
this.browserEnvironmentFactory,
this.nodeEnvironmentFactory,
);
}
}