Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 54 additions & 1 deletion src/shared-resources.ts
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,54 @@ const remoteProcedureCall = async (
return response.value;
};

const isPlainObject = (v: unknown): v is Record<string, unknown> =>
v !== null && typeof v === 'object' && !Array.isArray(v);

const writeBackArray = (original: unknown[], mutated: unknown[]): void => {
const minLen = Math.min(original.length, mutated.length);

for (let i = 0; i < minLen; i++) {
const origItem = original[i];
const mutItem = mutated[i];

if (isPlainObject(origItem) && isPlainObject(mutItem))
writeBackObject(origItem, mutItem);
else if (Array.isArray(origItem) && Array.isArray(mutItem))
writeBackArray(origItem, mutItem);
else original[i] = mutated[i];
}

if (original.length > mutated.length) original.splice(mutated.length);

for (let i = original.length; i < mutated.length; i++)
original.push(mutated[i]);
};

const writeBackObject = (
orig: Record<string, unknown>,
mut: Record<string, unknown>
): void => {
for (const key of Object.keys(orig)) if (!(key in mut)) delete orig[key];

for (const key of Object.keys(mut)) {
if (isPlainObject(orig[key]) && isPlainObject(mut[key]))
writeBackObject(
orig[key] as Record<string, unknown>,
mut[key] as Record<string, unknown>
);
else if (Array.isArray(orig[key]) && Array.isArray(mut[key]))
writeBackArray(orig[key] as unknown[], mut[key] as unknown[]);
else orig[key] = mut[key];
}
};

export const writeBack = (original: unknown, mutated: unknown): void => {
if (Array.isArray(original) && Array.isArray(mutated))
writeBackArray(original, mutated);
else if (isPlainObject(original) && isPlainObject(mutated))
writeBackObject(original, mutated);
};

export const extractFunctionNames = (obj: Record<string, unknown>) => {
const seen = new Set<string>();
let current = obj;
Expand Down Expand Up @@ -335,14 +383,16 @@ export const handleRemoteProcedureCall = async (

try {
const method = methodCandidate.bind(entry.state);
const result = await method(...(message.args || []));
const callArgs = message.args || [];
const result = await method(...callArgs);

child.send({
type: SHARED_RESOURCE_MESSAGE_TYPES.REMOTE_PROCEDURE_CALL_RESULT,
id: message.id,
value: {
result,
latest: state,
mutatedArgs: callArgs,
},
} satisfies IPCResponse);
} catch (error) {
Expand All @@ -367,6 +417,9 @@ const constructSharedResourceWithRPCs = (
return async (...args: unknown[]) => {
const rpcResult = await remoteProcedureCall(name, prop, args);

for (let i = 0; i < args.length; i++)
writeBack(args[i], rpcResult.mutatedArgs[i]);

for (const rpcKey of rpcs) {
if (rpcKey in rpcResult.latest) {
delete rpcResult.latest[rpcKey];
Expand Down
6 changes: 5 additions & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,11 @@ export type IPCResourceResultMessage = {
export type IPCRemoteProcedureCallResultMessage = {
type: typeof SHARED_RESOURCE_MESSAGE_TYPES.REMOTE_PROCEDURE_CALL_RESULT;
id: string;
value?: { result: unknown; latest: Record<string, unknown> };
value?: {
result: unknown;
latest: Record<string, unknown>;
mutatedArgs: unknown[];
};
error?: string;
};

Expand Down
17 changes: 17 additions & 0 deletions test/__fixtures__/references/mutation-resource.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { assert, test, waitForExpectedResult } from 'poku';
import { resource } from '../../../src/index.js';
import { MutatorContext } from './resource.js';

test('Test second resource only', async () => {
const mutator = await resource.use(MutatorContext);
const value = await mutator.getValue();
const array: number[] = [];

await mutator.mutateArray(array);

assert.strictEqual(
array[0],
value,
'Array should contain the value returned by getValue()'
);
});
43 changes: 43 additions & 0 deletions test/__fixtures__/references/nested-mutation.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { assert, test } from 'poku';
import { resource } from '../../../src/index.js';
import { NestedMutatorContext } from './resource.js';

test('Deeply nested array mutation via IPC', async () => {
const mutator = await resource.use(NestedMutatorContext);
const value = await mutator.getValue();
const obj = { nested: { arr: [] as number[] } };

await mutator.pushToNestedArray(obj);

assert.strictEqual(
obj.nested.arr[0],
value,
'Nested array should contain the value pushed by the remote method'
);
});

test('Array of objects mutation via IPC', async () => {
const mutator = await resource.use(NestedMutatorContext);
const arr = [{ x: 1 }, { x: 2 }, { x: 3 }];

await mutator.mutateArrayOfObjects(arr);

assert.deepStrictEqual(
arr,
[{ x: 2 }, { x: 3 }, { x: 4 }],
'Each object in the array should have its x property incremented'
);
});

test('Array truncation via IPC', async () => {
const mutator = await resource.use(NestedMutatorContext);
const arr = [10, 20, 30, 40];

await mutator.truncateArray(arr);

assert.deepStrictEqual(
arr,
[10, 20, 30],
'Array should be truncated to all but the last element'
);
});
31 changes: 31 additions & 0 deletions test/__fixtures__/references/object-mutation.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { assert, test } from 'poku';
import { resource } from '../../../src/index.js';
import { ObjectMutatorContext } from './resource.js';

test('Object property mutation via IPC', async () => {
const mutator = await resource.use(ObjectMutatorContext);
const value = await mutator.getValue();
const obj: Record<string, unknown> = {};

await mutator.mutateObject(obj);

assert.strictEqual(
obj.key,
value,
'Object property should be set by the remote method'
);
});

test('Object property deletion via IPC', async () => {
const mutator = await resource.use(ObjectMutatorContext);
const obj: Record<string, unknown> = { toDelete: 'remove-me', keep: 42 };

await mutator.deleteKey(obj);

assert.strictEqual(
'toDelete' in obj,
false,
'Deleted property should not exist on the original object'
);
assert.strictEqual(obj.keep, 42, 'Non-deleted property should remain');
});
46 changes: 46 additions & 0 deletions test/__fixtures__/references/resource.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { resource } from '../../../src/index.js';

export const MutatorContext = resource.create(() => {
const value = Math.random();
return {
mutateArray(arr: number[]) {
arr.push(value);
},
getValue() {
return value;
},
};
});

export const ObjectMutatorContext = resource.create(() => {
const value = Math.random();
return {
mutateObject(obj: Record<string, unknown>) {
obj.key = value;
},
deleteKey(obj: Record<string, unknown>) {
delete obj.toDelete;
},
getValue() {
return value;
},
};
});

export const NestedMutatorContext = resource.create(() => {
const value = Math.random();
return {
pushToNestedArray(obj: { nested: { arr: number[] } }) {
obj.nested.arr.push(value);
},
mutateArrayOfObjects(arr: Array<{ x: number }>) {
for (const item of arr) item.x += 1;
},
truncateArray(arr: number[]) {
arr.splice(arr.length - 1);
},
getValue() {
return value;
},
};
});
10 changes: 10 additions & 0 deletions test/integration/shared-resources.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,14 @@ describe('Shared Resources', async () => {

assert.strictEqual(exitCode, 1, 'Exit Code needs to be 1');
});

await it('Reference tests', async () => {
const code = await poku('test/__fixtures__/references', {
noExit: true,
plugins: [sharedResources()],
concurrency: 0,
});

assert.strictEqual(code, 0, 'Exit Code needs to be 0');
});
});
Loading
Loading