viniciusestevam / ts-worker Goto Github PK
View Code? Open in Web Editor NEW:construction_worker: A simple shorthand to use Node worker_threads with Typescript.
:construction_worker: A simple shorthand to use Node worker_threads with Typescript.
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:
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:
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:
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'
"devDependencies": {
"@types/node": "^13.7.1",
"@types/callsite": "^1.0.30",
"ts-node": "3.3.0",
"typescript": "3.7.5",
"callsite": "^1.0.0"
},
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.