tinypool icon indicating copy to clipboard operation
tinypool copied to clipboard

feat: implement Runner proxy

Open Dimava opened this issue 1 year ago • 4 comments

Runner proxy allows easily consume Typescript (and typed JS) modules the same way as if they would be imported as import * as runner Async functions are typed the same, sync functions are mapped to async (this loses generics), non-functions are removed worker_threads pool supports passing multiple arguments by using Object.assign(argsArray, { __tinypool_args__: true }

test('runner worker_threads test', async () => {
  const { runner } = new Tinypool({
    filename: resolve(__dirname, 'fixtures/multiple.js'),
    // runtime: both work same,
  }).withRunner<typeof import('./fixtures/multiple.js')>()

  expect((await runner.a()) satisfies 'a').toBe('a')
  expect((await runner.b()) satisfies 'b').toBe('b')
  expect(await runner.foobar({ foobar: 1 })).toBe(1)
  expect((await runner.asyncFoobar({ foobar: 1 })) satisfies 1).toBe(1)
  expect(await runner.args(1, 2, 3)).toThrow() // and type error
  expect((await runner.asyncArgs(1, 2, 3)).toThrow() // and type error
// fixtures/multiple.d.ts
export function a(): 'a'
export function b(): 'b'
export function foobar<V>(o: { foobar: V }): V
export function asyncFoobar<V>(o: { foobar: V }): Promise<V>
export function args<A>(...args: A[]): A
export function asyncArgs<A extends any[]>(...args: A): Promise<A>
export const digit: 4

Dimava avatar Oct 16 '24 20:10 Dimava

Open in Stackblitz

pnpm add https://pkg.pr.new/tinypool@106

commit: 30333bd

pkg-pr-new[bot] avatar Oct 16 '24 20:10 pkg-pr-new[bot]

What is the cost of that encapsulation?

jerome-benoit avatar Oct 22 '24 11:10 jerome-benoit

@jerome-benoit: What is the cost of that encapsulation?

Runner proxy is free (Proxy creation + a couple of function calls, completely free if you cache the r.runner.fn) Argument wrapping doesn't work with cloning (as cloning can't keep array properties) but otherwise also should be almost free

If you choose to exclude argarray from this PR I can split it into another PR

Dimava avatar Oct 22 '24 15:10 Dimava

@AriPerkkio I've removed all the args code, now it's as simple as I could get it

Dimava avatar Oct 29 '24 10:10 Dimava