Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

#47 persistent context #48

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
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
14 changes: 14 additions & 0 deletions __tests__/persistent-ctx.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { job, stop, start } from '../src/job'

beforeAll(async () => await start())
afterAll(async () => await stop())

describe('Persistent ctx testing', () => {
it('should return persistent ctx after save', async () => {
await job(() => {}, {persistentCtx: {test: true}})
const persistentCtx = await job(() => {
return persistentCtx
})
expect(persistentCtx).toEqual({test: true})
})
})
1 change: 1 addition & 0 deletions src/interfaces.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
export interface Config<T = {}, U = {}> {
ctx?: T
data?: U
persistentCtx?: any
}

export interface Task {
Expand Down
5 changes: 4 additions & 1 deletion src/worker-pool.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,15 +94,18 @@ class WorkerPool {
// @ts-ignore
const dataSerialized = v8.serialize(config.data)
const dataStr = JSON.stringify(dataSerialized)
const persistentCtxStr = JSON.stringify(config.persistentCtx || {})
const workerStr = `
async function __executor__() {
async function __executor__(persistentCtx) {
const v8 = require('v8')
${variables}
const dataParsed = JSON.parse('${dataStr}')
const dataBuffer = Buffer.from(dataParsed.data)
const dataDeserialized = v8.deserialize(dataBuffer)
return await (${handler.toString()})(dataDeserialized)
}

__executor__.persistentCtx = JSON.parse('${persistentCtxStr}')
`

// @ts-ignore
Expand Down
5 changes: 4 additions & 1 deletion src/worker.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
const { parentPort } = require('worker_threads')

let persistentCtx = {}

parentPort.on('message', async worker => {
const response = {
error: null,
Expand All @@ -9,7 +11,8 @@ parentPort.on('message', async worker => {
try {
eval(worker)
// __executor__ is defined in worker
response.data = await __executor__()
Object.assign(persistentCtx, __executor__.persistentCtx)
response.data = await __executor__(persistentCtx)
parentPort.postMessage(response)
} catch (err) {
response.data = null
Expand Down