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

@@ -0,0 +1,111 @@
import { describe, it, expect } from 'vitest';
import { CodeRunnerStub } from '@tests/unit/shared/Stubs/CodeRunnerStub';
import { IpcChannelDefinitions } from '@/presentation/electron/shared/IpcBridging/IpcChannelDefinitions';
import { CodeRunnerFactory, IpcRegistrar, registerAllIpcChannels } from '@/presentation/electron/main/IpcRegistration';
import { IpcChannel } from '@/presentation/electron/shared/IpcBridging/IpcChannel';
import { expectExists } from '@tests/shared/Assertions/ExpectExists';
import { collectExceptionMessage } from '@tests/unit/shared/ExceptionCollector';
describe('IpcRegistration', () => {
describe('registerAllIpcChannels', () => {
it('registers all defined IPC channels', () => {
Object.entries(IpcChannelDefinitions).forEach(([key, expectedChannel]) => {
it(key, () => {
// arrange
const { registrarMock, isChannelRegistered } = createIpcRegistrarMock();
const context = new IpcRegistrationTestSetup()
.withRegistrar(registrarMock);
// act
context.run();
// assert
expect(isChannelRegistered(expectedChannel)).to.equal(true);
});
});
});
describe('registers expected instances', () => {
const testScenarios: Record<keyof typeof IpcChannelDefinitions, {
buildContext: (context: IpcRegistrationTestSetup) => IpcRegistrationTestSetup,
expectedInstance: object,
}> = {
CodeRunner: (() => {
const expectedInstance = new CodeRunnerStub();
return {
buildContext: (c) => c.withCodeRunnerFactory(() => expectedInstance),
expectedInstance,
};
})(),
};
Object.entries(testScenarios).forEach(([
key, { buildContext, expectedInstance },
]) => {
it(key, () => {
// arrange
const { registrarMock, getRegisteredInstance } = createIpcRegistrarMock();
const context = buildContext(new IpcRegistrationTestSetup()
.withRegistrar(registrarMock));
// act
context.run();
// assert
const actualInstance = getRegisteredInstance(IpcChannelDefinitions.CodeRunner);
expect(actualInstance).to.equal(expectedInstance);
});
});
});
it('throws an error if registration fails', () => {
// arrange
const expectedError = 'registrar error';
const registrarMock: IpcRegistrar = () => {
throw new Error(expectedError);
};
const context = new IpcRegistrationTestSetup()
.withRegistrar(registrarMock);
// act
const exceptionMessage = collectExceptionMessage(() => context.run());
// assert
expect(exceptionMessage).to.include(expectedError);
});
});
});
class IpcRegistrationTestSetup {
private codeRunnerFactory: CodeRunnerFactory = () => new CodeRunnerStub();
private registrar: IpcRegistrar = () => { /* NOOP */ };
public withRegistrar(registrar: IpcRegistrar): this {
this.registrar = registrar;
return this;
}
public withCodeRunnerFactory(codeRunnerFactory: CodeRunnerFactory): this {
this.codeRunnerFactory = codeRunnerFactory;
return this;
}
public run() {
registerAllIpcChannels(
this.codeRunnerFactory,
this.registrar,
);
}
}
function createIpcRegistrarMock() {
const registeredChannels = new Array<Parameters<IpcRegistrar>>();
const registrarMock: IpcRegistrar = <T>(channel: IpcChannel<T>, obj: T) => {
registeredChannels.push([channel as IpcChannel<unknown>, obj]);
};
const isChannelRegistered = <T>(channel: IpcChannel<T>): boolean => {
return registeredChannels.some((i) => i[0] === channel);
};
const getRegisteredInstance = <T>(channel: IpcChannel<T>): unknown => {
const registration = registeredChannels.find((i) => i[0] === channel);
expectExists(registration);
return registration[1];
};
return {
registrarMock,
isChannelRegistered,
getRegisteredInstance,
};
}

View File

@@ -1,61 +0,0 @@
import { describe } from 'vitest';
import { OperatingSystem } from '@/domain/OperatingSystem';
import { convertPlatformToOs } from '@/presentation/electron/preload/ContextBridging/NodeOsMapper';
import { formatAssertionMessage } from '@tests/shared/FormatAssertionMessage';
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

@@ -1,12 +1,12 @@
import { describe, it, expect } from 'vitest';
import { ApiFacadeFactory, provideWindowVariables } from '@/presentation/electron/preload/ContextBridging/RendererApiProvider';
import { ApiFacadeFactory, IpcConsumerProxyCreator, provideWindowVariables } from '@/presentation/electron/preload/ContextBridging/RendererApiProvider';
import { OperatingSystem } from '@/domain/OperatingSystem';
import { Logger } from '@/application/Common/Log/Logger';
import { LoggerStub } from '@tests/unit/shared/Stubs/LoggerStub';
import { CodeRunner } from '@/application/CodeRunner';
import { CodeRunnerStub } from '@tests/unit/shared/Stubs/CodeRunnerStub';
import { PropertyKeys } from '@/TypeHelpers';
import { WindowVariables } from '@/infrastructure/WindowVariables/WindowVariables';
import { IpcChannelDefinitions } from '@/presentation/electron/shared/IpcBridging/IpcChannelDefinitions';
import { IpcChannel } from '@/presentation/electron/shared/IpcBridging/IpcChannel';
describe('RendererApiProvider', () => {
describe('provideWindowVariables', () => {
@@ -21,17 +21,7 @@ describe('RendererApiProvider', () => {
setupContext: (context) => context,
expectedValue: true,
},
codeRunner: (() => {
const codeRunner = new CodeRunnerStub();
const createFacadeMock: ApiFacadeFactory = (obj) => obj;
return {
description: 'encapsulates correctly',
setupContext: (context) => context
.withCodeRunner(codeRunner)
.withApiFacadeCreator(createFacadeMock),
expectedValue: codeRunner,
};
})(),
codeRunner: expectIpcConsumer(IpcChannelDefinitions.CodeRunner),
os: (() => {
const operatingSystem = OperatingSystem.WindowsPhone;
return {
@@ -40,17 +30,10 @@ describe('RendererApiProvider', () => {
expectedValue: operatingSystem,
};
})(),
log: (() => {
const logger = new LoggerStub();
const createFacadeMock: ApiFacadeFactory = (obj) => obj;
return {
description: 'encapsulates correctly',
setupContext: (context) => context
.withLogger(logger)
.withApiFacadeCreator(createFacadeMock),
expectedValue: logger,
};
})(),
log: expectFacade({
instance: new LoggerStub(),
setupContext: (c, logger) => c.withLogger(logger),
}),
};
Object.entries(testScenarios).forEach((
[property, { description, setupContext, expectedValue }],
@@ -65,22 +48,43 @@ describe('RendererApiProvider', () => {
expect(actualValue).to.equal(expectedValue);
});
});
function expectIpcConsumer<T>(expectedDefinition: IpcChannel<T>): WindowVariableTestCase {
const ipcConsumerCreator: IpcConsumerProxyCreator = (definition) => definition as never;
return {
description: 'creates correct IPC consumer',
setupContext: (context) => context
.withIpcConsumerCreator(ipcConsumerCreator),
expectedValue: expectedDefinition,
};
}
function expectFacade<T>(options: {
readonly instance: T;
setupContext: (
context: RendererApiProviderTestContext,
instance: T,
) => RendererApiProviderTestContext;
}): WindowVariableTestCase {
const createFacadeMock: ApiFacadeFactory = (obj) => obj;
return {
description: 'creates correct facade',
setupContext: (context) => options.setupContext(
context.withApiFacadeCreator(createFacadeMock),
options.instance,
),
expectedValue: options.instance,
};
}
});
});
class RendererApiProviderTestContext {
private codeRunner: CodeRunner = new CodeRunnerStub();
private os: OperatingSystem = OperatingSystem.Android;
private log: Logger = new LoggerStub();
private apiFacadeCreator: ApiFacadeFactory = (obj) => obj;
public withCodeRunner(codeRunner: CodeRunner): this {
this.codeRunner = codeRunner;
return this;
}
private ipcConsumerCreator: IpcConsumerProxyCreator = () => { return {} as never; };
public withOs(os: OperatingSystem): this {
this.os = os;
@@ -97,12 +101,17 @@ class RendererApiProviderTestContext {
return this;
}
public withIpcConsumerCreator(ipcConsumerCreator: IpcConsumerProxyCreator): this {
this.ipcConsumerCreator = ipcConsumerCreator;
return this;
}
public provideWindowVariables() {
return provideWindowVariables(
() => this.codeRunner,
() => this.log,
() => this.os,
this.apiFacadeCreator,
this.ipcConsumerCreator,
);
}
}

View File

@@ -0,0 +1,61 @@
import { describe, it, expect } from 'vitest';
import { IpcChannel } from '@/presentation/electron/shared/IpcBridging/IpcChannel';
import { IpcChannelDefinitions } from '@/presentation/electron/shared/IpcBridging/IpcChannelDefinitions';
describe('IpcChannelDefinitions', () => {
it('defines IPC channels correctly', () => {
const testScenarios: Record<keyof typeof IpcChannelDefinitions, {
readonly expectedNamespace: string;
readonly expectedAccessibleMembers: readonly string[];
}> = {
CodeRunner: {
expectedNamespace: 'code-run',
expectedAccessibleMembers: ['runCode'],
},
};
Object.entries(testScenarios).forEach((
[definitionKey, { expectedNamespace, expectedAccessibleMembers }],
) => {
describe(`channel: "${definitionKey}"`, () => {
const ipcChannelUnderTest = IpcChannelDefinitions[definitionKey] as IpcChannel<unknown>;
it('has expected namespace', () => {
// act
const actualNamespace = ipcChannelUnderTest.namespace;
// assert
expect(actualNamespace).to.equal(expectedNamespace);
});
it('has expected accessible members', () => {
// act
const actualAccessibleMembers = ipcChannelUnderTest.accessibleMembers;
// assert
expect(actualAccessibleMembers).to.have.lengthOf(expectedAccessibleMembers.length);
expect(actualAccessibleMembers).to.have.members(expectedAccessibleMembers);
});
});
});
});
describe('IPC channel uniqueness', () => {
it('has unique namespaces', () => {
// arrange
const extractedNamespacesFromDefinitions = Object
.values(IpcChannelDefinitions)
.map((channel) => channel.namespace);
// act
const duplicateNamespaceEntries = extractedNamespacesFromDefinitions
.filter((item, index) => extractedNamespacesFromDefinitions.indexOf(item) !== index);
// assert
expect(duplicateNamespaceEntries).to.have.lengthOf(0);
});
it('has unique accessible members within each channel', () => {
Object.values(IpcChannelDefinitions).forEach((channel) => {
// arrange
const { accessibleMembers: accessibleMembersOfChannel } = channel;
// act
const repeatedAccessibleMembersInChannel = accessibleMembersOfChannel
.filter((item, index) => accessibleMembersOfChannel.indexOf(item) !== index);
// assert
expect(repeatedAccessibleMembersInChannel).to.have.lengthOf(0);
});
});
});
});

View File

@@ -0,0 +1,260 @@
import { describe, it, expect } from 'vitest';
import { createIpcConsumerProxy, registerIpcChannel } from '@/presentation/electron/shared/IpcBridging/IpcProxy';
import { IpcChannel } from '@/presentation/electron/shared/IpcBridging/IpcChannel';
describe('IpcProxy', () => {
describe('createIpcConsumerProxy', () => {
describe('argument handling', () => {
it('sync method in proxy correctly receives and forwards arguments', async () => {
// arrange
const expectedArg1 = 'expected-arg-1';
const expectedArg2 = 2;
interface TestSyncMethods {
syncMethod(stringArg: string, numberArg: number): void;
}
const ipcChannelMock: IpcChannel<TestSyncMethods> = {
namespace: 'testNamespace',
accessibleMembers: ['syncMethod'],
};
const { registeredCallArgs, ipcRendererMock } = mockIpcRenderer();
// act
const proxy = createIpcConsumerProxy(ipcChannelMock, ipcRendererMock);
await proxy.syncMethod(expectedArg1, expectedArg2);
// assert
expect(registeredCallArgs).to.have.lengthOf(1);
const actualFunctionArgs = registeredCallArgs[0];
expect(actualFunctionArgs).to.have.lengthOf(3);
expect(actualFunctionArgs[1]).to.equal(expectedArg1);
expect(actualFunctionArgs[2]).to.equal(expectedArg2);
});
it('sync method in proxy correctly returns expected value', async () => {
// arrange
const expectedArg1 = 'expected-arg-1';
const expectedArg2 = 2;
interface TestAsyncMethods {
asyncMethod(stringArg: string, numberArg: number): Promise<void>;
}
const mockedIpcChannel: IpcChannel<TestAsyncMethods> = {
namespace: 'testNamespace',
accessibleMembers: ['asyncMethod'],
};
const { registeredCallArgs, ipcRendererMock } = mockIpcRenderer();
// act
const proxy = createIpcConsumerProxy(mockedIpcChannel, ipcRendererMock);
await proxy.asyncMethod(expectedArg1, expectedArg2);
// assert
expect(registeredCallArgs).to.have.lengthOf(1);
const actualFunctionArgs = registeredCallArgs[0];
expect(actualFunctionArgs).to.have.lengthOf(3);
expect(actualFunctionArgs[1]).to.equal(expectedArg1);
expect(actualFunctionArgs[2]).to.equal(expectedArg2);
});
});
describe('return value handling', () => {
it('sync function returns correct value', async () => {
// arrange
const expectedReturnValue = 'expected-return-value';
interface TestSyncMethods {
syncMethod(): typeof expectedReturnValue;
}
const ipcChannelMock: IpcChannel<TestSyncMethods> = {
namespace: 'testNamespace',
accessibleMembers: ['syncMethod'],
};
const { ipcRendererMock } = mockIpcRenderer(Promise.resolve(expectedReturnValue));
// act
const proxy = createIpcConsumerProxy(ipcChannelMock, ipcRendererMock);
const actualReturnValue = await proxy.syncMethod();
// assert
expect(actualReturnValue).to.equal(expectedReturnValue);
});
it('async function returns correct value', async () => {
// arrange
const expectedReturnValue = 'expected-return-value';
interface TestAsyncMethods {
asyncMethod(): Promise<typeof expectedReturnValue>;
}
const ipcChannelMock: IpcChannel<TestAsyncMethods> = {
namespace: 'testNamespace',
accessibleMembers: ['asyncMethod'],
};
const { ipcRendererMock } = mockIpcRenderer(Promise.resolve(expectedReturnValue));
// act
const proxy = createIpcConsumerProxy(ipcChannelMock, ipcRendererMock);
const actualReturnValue = await proxy.asyncMethod();
// assert
expect(actualReturnValue).to.equal(expectedReturnValue);
});
});
});
describe('registerIpcChannel', () => {
describe('original function invocation', () => {
it('sync function is called with correct arguments', () => {
// arrange
const expectedArgumentValues = ['first-argument-value', 42];
const syncMethodName = 'syncMethod';
const testObject = {
[syncMethodName]: (stringArg: string, numberArg: number) => {
recordedMethodArguments.push([stringArg, numberArg]);
},
};
const recordedMethodArguments = new Array<Parameters<typeof testObject['syncMethod']>>();
const testIpcChannel: IpcChannel<typeof testObject> = {
namespace: 'testNamespace',
accessibleMembers: [syncMethodName],
};
const { ipcMainMock, registeredHandlersByChannel } = mockIpcMain();
// act
registerIpcChannel(testIpcChannel, testObject, ipcMainMock);
const proxyFunction = registeredHandlersByChannel[
Object.keys(registeredHandlersByChannel)[0]];
proxyFunction(null, ...expectedArgumentValues);
// assert
expect(recordedMethodArguments).to.have.lengthOf(1);
const actualArgumentValues = recordedMethodArguments[0];
expect(actualArgumentValues).to.deep.equal(expectedArgumentValues);
});
it('async function is called with correct arguments', async () => {
// arrange
const expectedArgumentValues = ['first-argument-value', 42];
const asyncMethodName = 'asyncMethod';
const testObject = {
[asyncMethodName]: (stringArg: string, numberArg: number) => {
recordedMethodArguments.push([stringArg, numberArg]);
return Promise.resolve();
},
};
const recordedMethodArguments = new Array<Parameters<typeof testObject['asyncMethod']>>();
const testIpcChannel: IpcChannel<typeof testObject> = {
namespace: 'testNamespace',
accessibleMembers: [asyncMethodName],
};
const { ipcMainMock, registeredHandlersByChannel } = mockIpcMain();
// act
registerIpcChannel(testIpcChannel, testObject, ipcMainMock);
const proxyFunction = registeredHandlersByChannel[
Object.keys(registeredHandlersByChannel)[0]];
await proxyFunction(null, ...expectedArgumentValues);
// assert
expect(recordedMethodArguments).to.have.lengthOf(1);
expect(recordedMethodArguments[0]).to.deep.equal(expectedArgumentValues);
});
});
describe('return value handling', () => {
it('sync function returns correct value', () => {
// arrange
const expectedReturnValue = 'expected-return-value';
const syncMethodName = 'syncMethod';
const testObject = {
[syncMethodName]: () => expectedReturnValue,
};
const testIpcChannel: IpcChannel<typeof testObject> = {
namespace: 'testNamespace',
accessibleMembers: [syncMethodName],
};
const { ipcMainMock, registeredHandlersByChannel } = mockIpcMain();
// act
registerIpcChannel(testIpcChannel, testObject, ipcMainMock);
const proxyFunction = registeredHandlersByChannel[
Object.keys(registeredHandlersByChannel)[0]];
const actualReturnValue = proxyFunction(null);
// assert
expect(actualReturnValue).to.equal(expectedReturnValue);
});
it('async function returns correct value', async () => {
// arrange
const expectedReturnValue = 'expected-return-value';
const asyncMethodName = 'asyncMethod';
const testObject = {
[asyncMethodName]: () => Promise.resolve(expectedReturnValue),
};
const testIpcChannel: IpcChannel<typeof testObject> = {
namespace: 'testNamespace',
accessibleMembers: [asyncMethodName],
};
const { ipcMainMock, registeredHandlersByChannel } = mockIpcMain();
// act
registerIpcChannel(testIpcChannel, testObject, ipcMainMock);
const proxyFunction = registeredHandlersByChannel[
Object.keys(registeredHandlersByChannel)[0]];
const actualReturnValue = await proxyFunction(null);
// assert
expect(actualReturnValue).to.equal(expectedReturnValue);
});
});
it('registers channel names for each member', () => {
// arrange
const namespace = 'testNamespace';
const method1Name = 'method1';
const method2Name = 'method2';
const expectedChannelNames = [
`proxy:${namespace}:${method1Name}`,
`proxy:${namespace}:${method2Name}`,
];
const testObject = {
[`${method1Name}`]: () => {},
[`${method2Name}`]: () => Promise.resolve(),
};
const testIpcChannel: IpcChannel<typeof testObject> = {
namespace: 'testNamespace',
accessibleMembers: [method1Name, method2Name],
};
const { ipcMainMock, registeredHandlersByChannel } = mockIpcMain();
// act
registerIpcChannel(testIpcChannel, testObject, ipcMainMock);
// assert
const actualChannelNames = Object.keys(registeredHandlersByChannel);
expect(actualChannelNames).to.have.lengthOf(expectedChannelNames.length);
expect(actualChannelNames).to.have.members(expectedChannelNames);
});
it('throws error for non-function members', () => {
// arrange
const expectedError = 'Non-function members are not yet supported';
const propertyName = 'propertyKey';
const testObject = { [`${propertyName}`]: 123 };
const testIpcChannel: IpcChannel<typeof testObject> = {
namespace: 'testNamespace',
accessibleMembers: [propertyName] as never,
};
// act
const act = () => registerIpcChannel(testIpcChannel, testObject, mockIpcMain().ipcMainMock);
// assert
expect(act).to.throw(expectedError);
});
});
});
function mockIpcMain() {
const registeredHandlersByChannel: Record<string, (...args: unknown[]) => unknown> = {};
const ipcMainMock: Partial<Electron.IpcMain> = {
handle: (channel, handler) => {
registeredHandlersByChannel[channel] = handler;
},
};
return {
ipcMainMock: ipcMainMock as Electron.IpcMain,
registeredHandlersByChannel,
};
}
function mockIpcRenderer(returnValuePromise: Promise<unknown> = Promise.resolve()) {
const registeredCallArgs = new Array<Parameters<Electron.IpcRenderer['invoke']>>();
const ipcRendererMock: Partial<Electron.IpcRenderer> = {
invoke: (...args) => {
registeredCallArgs.push([...args]);
return returnValuePromise;
},
};
return {
ipcRendererMock: ipcRendererMock as Electron.IpcRenderer,
registeredCallArgs,
};
}