Code Monkey home page Code Monkey logo

ts-worker's Introduction

Hi there ☺️

My name is Vinícius Estevam, I'm a Software Engineer at @Pagar.me.

Love to have fun when programming, creating side projects all the time validating concepts or just dumb ideas. My main goal is to empower people and build a better world sharing knowledge with tech communities.

Studying Rust 🦀

📫 Reach me

Twitter Badge Medium Badge Linkedin Badge Gmail Badge

ts-worker's People

Contributors

viniciusestevam avatar

Stargazers

 avatar  avatar  avatar

Watchers

 avatar

Forkers

robbiemu

ts-worker's Issues

cannot find module in jest

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/

  • utilities.ts
  • utilities.spec.ts
  • get-block-at-difficulty.worker.ts

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'

dep should change can work

"devDependencies": {
"@types/node": "^13.7.1",
"@types/callsite": "^1.0.30",
"ts-node": "3.3.0",
"typescript": "3.7.5",
"callsite": "^1.0.0"
},

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.