viniciusestevam / ts-worker

:construction_worker: A simple shorthand to use Node worker_threads with Typescript.
3 stars 1 forks source link

cannot find module in jest #2

Open robbiemu opened 3 years ago

robbiemu commented 3 years ago

I am getting the error:

events.js:291
      throw er; // Unhandled 'error' event
      ^
Error: Cannot find module '/usr/local/lib/node_modules/jest/node_modules/jest-runtime/build/get-block-at-difficulty.worker.ts'
Require stack:
- /Users/robertotomas/Public/Github/learning-chain/node_modules/ts-worker/dist/register.js
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:880:15)
    at Function.Module._load (internal/modules/cjs/loader.js:725:27)
    at Module.require (internal/modules/cjs/loader.js:952:19)
    at require (internal/modules/cjs/helpers.js:88:18)
    at Object.<anonymous> (/Users/robertotomas/Public/Github/learning-chain/node_modules/ts-worker/dist/register.js:4:1)
    at Module._compile (internal/modules/cjs/loader.js:1063:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
    at Module.load (internal/modules/cjs/loader.js:928:32)
    at Function.Module._load (internal/modules/cjs/loader.js:769:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
Emitted 'error' event on process instance at:
    at emitUnhandledRejectionOrErr (internal/event_target.js:542:11)
    at MessagePort.[nodejs.internal.kHybridDispatch] (internal/event_target.js:357:9)
    at MessagePort.exports.emitMessage (internal/per_context/messageport.js:18:26) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [
    '/Users/robertotomas/Public/Github/learning-chain/node_modules/ts-worker/dist/register.js'
  ]
}

The directory structure I am working in is like: src/blockchain/

so, the worker is in the same directory as the utilities library where it is being referenced.

I have the worker:

get-block-at-difficulty.worker.ts

import { parentPort, workerData } from 'worker_threads'

import { getBlockAtDifficulty } from './utilities'

const block = workerData.args[0]
const difficulty = workerData.args[1]
const index = workerData.args[2]
const step = workerData.args[3]

parentPort!.postMessage(getBlockAtDifficulty(block, difficulty, index, step))

and it is relying on utilities.ts where it is also being called. see this excerpt:

utilities.ts

export function detect(hash: string, difficulty: number) {
  let i, b
  for (i = 0, b = hash.length; i < b; i++) {
    if (hash[i] !== '0') {
      break;
    }
  }
  return i === difficulty;
}

export function getBlockAtDifficulty(block: Partial<Block>, difficulty: number, index = 0, step = 1) {
  let result: Block
  let nonce = index
  do {
    result = new Block({ ...block, nonce: String(nonce) })
    nonce += step
  } while (!detect(Hash.encode(String(result)), difficulty))
  return result
}

export interface MultiServiceThreadpoolResolution { [threadpool: string]: any }

export class MultiService {
  private static resolver = new Subject<MultiServiceThreadpoolResolution>()
  static resolver$: Observable<MultiServiceThreadpoolResolution>
  static initialize() {
    MultiService.resolver$ = MultiService.resolver.asObservable()
  }
  static resolve(pr: Promise<any>, threadpool: string) {
    pr
      .then(v => MultiService.resolver.next({ [threadpool]: v }))
      .catch(e => console.error(e))
  }
}
MultiService.initialize()

/**
 * spawns threads to resolve hash at difficulty, publishing result in 
 * MultiService
 * @param block Block to resolve hash of
 * @param difficulty Difficulty of hash to resolve
 * @returns uuid of multiservice to subscribe to
 * usage:
 * const multiService = new MultiService()
 * const task = getBlockAtDifficultyMultiThreaded(myBlock, someDifficulty)
 * multiService.resolve$
 *   .pipe(first(resolution => resolution.hasOwnProperty(task)))
 *   .subscribe(resolution => onSuccess(resolution[task]))
 */
export function getBlockAtDifficultyMultiThreaded(block: Partial<Block>, difficulty: number): UUID {
  const uuid = uuidV4() // our task identifier
  const workers: Array<Worker> = []
  const threads = os.cpus()
  threads.forEach((_, i) => {
    const args = [block, difficulty, i, threads]
    const worker: Worker = TSWorker('get-block-at-difficulty.worker.ts', {
      workerData: { args }
    });

    workers.push(worker)
    worker.on('message', (result: Block) => {
      MultiService.resolve(new Promise(res => res(result)), uuid)
      workers.forEach(w => w.terminate())
    })
  })
  return uuid
}

I have a jest test for this:

utilties.spec.ts

describe('getBlockAtDifficultyMultithreaded', () => {
  it('should produce a hash multithreaded', done => {
    const chain: Array<Block> = []
    const data = ['Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.']

    chain.push(Block.factoryGenesisBlock())

    const task = getBlockAtDifficultyMultiThreaded(factoryNextBlock({ data }, chain), 8)
    MultiService.resolver$.pipe(first(resolution => resolution.hasOwnProperty(task))).subscribe(resolution => {
      chain.push(resolution[task])

      console.log(Hash.encode(String(chain[1])))

      expect(difficulty(Hash.encode(String(chain[1])))).toEqual(8)
      done()
    })
  })
})

I thought to try specifying the absolute path:

    const worker: Worker = TSWorker([__dirname, 'get-block-at-difficulty.worker.ts'].join('/'), {
      workerData: { args }
    });

but this produces basically the same error:

Error: Cannot find module '/usr/local/lib/node_modules/jest/node_modules/jest-runtime/build/Users/robertotomas/Public/Github/learning-chain/src/blockchain/get-block-at-difficulty.worker.ts'
robbiemu commented 3 years ago

modifying ts-worker like this allows the later solution to work (or equivalently, with "path"):

function getWorkerFilePath(workerFilename) {
    var callerFilePath = stack[stack.length - 2].getFileName();
    var res = callerFilePath.slice(0, callerFilePath.lastIndexOf('/'));
    return workerFilename.startsWith('/')
        ? workerFilename
        : res.concat('/' + workerFilename);
}

suggestion: if the current behavior really is valuable, consider allowing workerFilename to be a string or an array of strings. If it is an array of strings, it can process them with path.join.

I'm almost ready with that, and maybe I will find there is a solution for this already, but it gives me the error

Error [ERR_UNHANDLED_ERROR]: Unhandled error. ({
  diagnosticText: "src/blockchain/utilities.ts(117,95): error TS2304: Cannot find name 'UUID'.\n",
  diagnosticCodes: [ 2304 ]
})

UUID is defined globally in global.d.ts: type UUID = number | string

robbiemu commented 3 years ago

Requested support from ts-node for this issue: https://github.com/TypeStrong/ts-node/discussions/1260