Skip to content

Commit

Permalink
Merge branch 'feat/exported-name-not-classname'
Browse files Browse the repository at this point in the history
  • Loading branch information
Julusian committed Jun 8, 2020
2 parents 5355f3e + f0c0e3f commit 879efa3
Show file tree
Hide file tree
Showing 9 changed files with 77 additions and 72 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ import { threadedClass} from 'threadedclass'
import { Professor } from './professor'

async function getStory() {
let mrSmith = await threadedClass<Professor>('./professor.js', Professor, ['maths', 'greek'])
let mrSmith = await threadedClass<Professor>('./professor.js', 'Professor', Professor, ['maths', 'greek'])
let story = await mrSmith.talkAboutAncientGreece() // still takes a loong time, but now runs in a separate thread
return story
}
Expand Down
2 changes: 1 addition & 1 deletion examples/nodejs/own-class.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ async function runExample () {
let originalHouse = new House(['north', 'west'], ['entrance','kitchen', 'bedroom'])

// Create threaded instance of the class House:
let threadedHouse = await threadedClass<House, typeof House>(HOUSE_PATH, House, [['north', 'west'], ['entrance','kitchen', 'bedroom']])
let threadedHouse = await threadedClass<House, typeof House>(HOUSE_PATH, 'House', House, [['north', 'west'], ['entrance','kitchen', 'bedroom']])

// Print number of rooms:
console.log(originalHouse.getRooms()) // ['entrance','kitchen', 'bedroom']
Expand Down
18 changes: 9 additions & 9 deletions src/__tests__/restarting.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ describe('restarts', () => {
expect(ThreadedClassManager.getThreadCount()).toEqual(0)
})
test('restart instance', async () => {
let threaded = await threadedClass<TestClass, typeof TestClass>(TESTCLASS_PATH, TestClass, [])
let threaded = await threadedClass<TestClass, typeof TestClass>(TESTCLASS_PATH, 'TestClass', [])
let onClosed = jest.fn(() => {
// oh dear, the process was closed
})
Expand All @@ -47,9 +47,9 @@ describe('restarts', () => {

})
test('restart instance with multiple', async () => {
let threaded0 = await threadedClass<TestClass, typeof TestClass>(TESTCLASS_PATH, TestClass, [], { threadUsage: 0.1 })
let threaded1 = await threadedClass<TestClass, typeof TestClass>(TESTCLASS_PATH, TestClass, [], { threadUsage: 0.1 })
let threaded2 = await threadedClass<TestClass, typeof TestClass>(TESTCLASS_PATH, TestClass, [], { threadUsage: 0.1 })
let threaded0 = await threadedClass<TestClass, typeof TestClass>(TESTCLASS_PATH, 'TestClass', [], { threadUsage: 0.1 })
let threaded1 = await threadedClass<TestClass, typeof TestClass>(TESTCLASS_PATH, 'TestClass', [], { threadUsage: 0.1 })
let threaded2 = await threadedClass<TestClass, typeof TestClass>(TESTCLASS_PATH, 'TestClass', [], { threadUsage: 0.1 })
let onClosed0 = jest.fn()
let onClosed1 = jest.fn()
let onClosed2 = jest.fn()
Expand Down Expand Up @@ -94,7 +94,7 @@ describe('restarts', () => {
test('force restart', async () => {
expect(ThreadedClassManager.getThreadCount()).toEqual(0)

let thread0 = await threadedClass<House, typeof House>(HOUSE_PATH, House, [['south0'], []])
let thread0 = await threadedClass<House, typeof House>(HOUSE_PATH, 'House', [['south0'], []])
let onClosed = jest.fn()
ThreadedClassManager.onEvent(thread0, 'thread_closed', onClosed)

Expand All @@ -121,7 +121,7 @@ describe('restarts', () => {
test('child process crash', async () => {
expect(ThreadedClassManager.getThreadCount()).toEqual(0)

let thread0 = await threadedClass<TestClass, typeof TestClass>(TESTCLASS_PATH, TestClass, [])
let thread0 = await threadedClass<TestClass, typeof TestClass>(TESTCLASS_PATH, 'TestClass', [])
let onClosed = jest.fn()
ThreadedClassManager.onEvent(thread0, 'thread_closed', onClosed)

Expand All @@ -145,11 +145,11 @@ describe('restarts', () => {
test('automatic restart', async () => {
expect(ThreadedClassManager.getThreadCount()).toEqual(0)

let thread0 = await threadedClass<House, typeof House>(HOUSE_PATH, House, [['south0'], []],{
let thread0 = await threadedClass<House, typeof House>(HOUSE_PATH, 'House', [['south0'], []],{
autoRestart: true,
threadUsage: 0.5
})
let thread1 = await threadedClass<TestClass, typeof TestClass>(TESTCLASS_PATH, TestClass, [],{
let thread1 = await threadedClass<TestClass, typeof TestClass>(TESTCLASS_PATH, 'TestClass', [],{
autoRestart: true,
threadUsage: 0.5
})
Expand Down Expand Up @@ -210,7 +210,7 @@ describe('restarts', () => {
test('orphan monitoring', async () => {
expect(ThreadedClassManager.getThreadCount()).toEqual(0)

let thread1 = await threadedClass<TestClass, typeof TestClass>(TESTCLASS_PATH, TestClass, [],{
let thread1 = await threadedClass<TestClass, typeof TestClass>(TESTCLASS_PATH, 'TestClass', [],{
autoRestart: true,
threadUsage: 0.5,
freezeLimit: 200
Expand Down
79 changes: 44 additions & 35 deletions src/__tests__/test.spec.ts

Large diffs are not rendered by default.

20 changes: 7 additions & 13 deletions src/internalApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,7 @@ export interface MessageSent {
export interface MessageInitConstr {
cmd: MessageType.INIT
modulePath: string
className: string
classFunction?: Function // only used in single-thread mode
exportName: string
args: Array<ArgDefinition>
config: ThreadedClassConfig
}
Expand Down Expand Up @@ -279,35 +278,29 @@ export abstract class Worker {
f = function() {
${bodyString}
;
return ${msg.className}
return ${msg.exportName}
}
`
// tslint:disable-next-line:no-eval
let moduleClass = eval(fcn)()
f = f
if (!moduleClass) {
throw Error(`${msg.className} not found in ${msg.modulePath}`)
throw Error(`${msg.exportName} not found in ${msg.modulePath}`)
}
return moduleClass
})
} else {
pModuleClass = Promise.resolve(require(msg.modulePath))
.then((module) => {
return module[msg.className]
return module[msg.exportName]
})
}

pModuleClass
.then((moduleClass) => {
if (m.classFunction) {
// In single thread mode.
// When classFunction is provided, use that instead of the imported js file.
return m.classFunction
} else {
return moduleClass
if (!moduleClass) {
return Promise.reject('Failed to find class')
}
})
.then((moduleClass) => {

const handle: InstanceHandle = {
id: msg.instanceId,
Expand Down Expand Up @@ -379,6 +372,7 @@ export abstract class Worker {
}
})
this.reply(handle, msg, props)
return
})
.catch((e: any) => {
console.log('INIT error', e)
Expand Down
12 changes: 4 additions & 8 deletions src/manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,8 +120,7 @@ export interface ChildInstance {
readonly freezeLimit?: number
readonly onMessageCallback: (instance: ChildInstance, message: MessageFromChild) => void
readonly pathToModule: string
readonly className: string
readonly classFunction: Function // used in single-threaded mode
readonly exportName: string
readonly constructorArgs: any[]
readonly config: ThreadedClassConfig
initialized: boolean
Expand Down Expand Up @@ -188,8 +187,7 @@ export class ThreadedClassManagerClassInternal extends EventEmitter {
child: Child,
proxy: ThreadedClass<any>,
pathToModule: string,
className: string,
classFunction: Function,
exportName: string,
constructorArgs: any[],
onMessage: (instance: ChildInstance, message: MessageFromChild) => void
): ChildInstance {
Expand All @@ -202,8 +200,7 @@ export class ThreadedClassManagerClassInternal extends EventEmitter {
freezeLimit: config.freezeLimit,
onMessageCallback: onMessage,
pathToModule: pathToModule,
className: className,
classFunction: classFunction,
exportName: exportName,
constructorArgs: constructorArgs,
initialized: false,
config: config
Expand Down Expand Up @@ -414,8 +411,7 @@ export class ThreadedClassManagerClassInternal extends EventEmitter {
let msg: MessageInitConstr = {
cmd: MessageType.INIT,
modulePath: instance.pathToModule,
className: instance.className,
classFunction: (config.disableMultithreading ? instance.classFunction : undefined),
exportName: instance.exportName,
args: encodedArgs,
config: config
}
Expand Down
9 changes: 4 additions & 5 deletions src/threadedClass.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,16 +30,16 @@ type CtorArgs<CtorT extends new (...args: any) => any> = CtorT extends new (...a
/**
* Returns an asynchronous version of the provided class
* @param orgModule Path to imported module (this is what is in the require('XX') function, or import {class} from 'XX'} )
* @param orgClass The class to be threaded
* @param orgExport Name of export in module
* @param constructorArgs An array of arguments to be fed into the class constructor
*/
export function threadedClass<T, TCtor extends new (...args: any) => T> (
orgModule: string,
orgClass: TCtor,
orgExport: string,
constructorArgs: CtorArgs<TCtor>,
config: ThreadedClassConfig = {}
): Promise<ThreadedClass<T>> {
let orgClassName: string = orgClass.name
let exportName: string = orgExport

if (isBrowser()) {
if (!config.pathToWorker) {
Expand Down Expand Up @@ -184,8 +184,7 @@ export function threadedClass<T, TCtor extends new (...args: any) => T> (
child,
proxy,
pathToModule,
orgClassName,
orgClass,
exportName,
constructorArgs,
onMessage
)
Expand Down
4 changes: 4 additions & 0 deletions test-lib/rename.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const testClass_1 = require("./testClass");
exports.AlmostTestClass = testClass_1.TestClass;
3 changes: 3 additions & 0 deletions test-lib/rename.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { TestClass as AlmostTestClass } from './testClass'

export { AlmostTestClass }

0 comments on commit 879efa3

Please sign in to comment.