Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import {Worker, TransferListItem, MessagePort, parentPort} from 'worker_threads';
interface MessagePair<T extends any, U extends any> {
//THESE SHOULD BE PRIVATE
//only present in the interface as a contract BETWEEN APPLICABLE (parameterised) parties
//not ALL PUBLIC PARTIES
//as they should use the IMPLEMENTATION'S EXPOSED METHODS
message :(value :T) => void;
postMessage :(
value :U extends MessagePair<infer V, this> ? V : never,
transferList ?:TransferListItem[]
) => void;
}
type Message<T> = T extends {message :(value :infer U) => void} ? U : never;
//bob accepts strings from steve
class Bob implements MessagePair<string[], Steve> {
message = (strings :string[]) => {
console.log(strings.join(' '));
};
postMessage :(
steves :Message<Steve>,
ports ?:TransferListItem[]
) => void;
constructor(port :Worker) {
//with the contract satisfied, this is safe
this.postMessage = (...args :[any, any]) => { port.postMessage(...args) };
port.on('message', this.message);
}
//PUBLIC
tellSteveThisPlease(some :number, numbers :number) {
if (some > numbers)
throw new Error('I don\t trust like that');
this.postMessage([some, numbers);
}
}
//steve accepts numbers from bob
class Steve implements MessagePair<number[], Bob> {
message = (strings :number[]) => {
this.postMessage(['yo', 'thanks']);
};
postMessage :(
bobs :Message<Bob>,
ports ?:TransferListItem[]
) => void;
constructor(port :MessagePort) {
//with the contract satisfied, this is safe
this.postMessage = (...args :[any, any]) => { port.postMessage(...args) };
port.on('message', this.message);
}
}
//you shouldn't be able to send messages to steve/bob YOURSELF
//they should be PRIVATE and you should have to ASK steve/bob to do so on your behalf
//(if that's your IMPLEMENTATION)
//parent
(new Bob(new Worker(''))).tellSteveThisPlease(1, 2);
//worker
new Steve(parentPort!);
@Hashbrown777

This comment has been minimized.

Copy link
Owner Author

@Hashbrown777 Hashbrown777 commented May 20, 2021

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment