@panyam/tsutils
Version:
Some basic TS utils for personal use
85 lines • 2.46 kB
JavaScript
import { assert } from "../types";
export class Actor {
processMessage(msg) {
assert(msg.target == this, "Cannot handle messages whose target is not this.");
if (msg.isReply) {
const reply = msg;
assert(reply.responseTo.spawnedFrom != null, "Cannot spawn a reply for a send that itself was not spawned from another send");
this.processReply(reply);
}
else {
this.processSend(msg);
}
}
processSend(send) {
}
processReply(_reply) {
}
}
export class Message {
constructor(name, source, target) {
this.uuid = Message.counter++;
this.sourceData = null;
this.payload = null;
assert(source != null, "Source cannot be null");
assert(target != null, "Target cannot be null");
this.name = name;
this.source = source;
this.target = target;
}
}
Message.counter = 0;
class ForwardableBase extends Message {
constructor() {
super(...arguments);
this._spawnedFrom = null;
}
get spawnedFrom() {
return this._spawnedFrom;
}
setSpawnedFrom(msg) {
this._spawnedFrom = msg;
if (msg == null)
this._rootMessage = this;
else
this._rootMessage = msg.rootMessage;
}
get rootMessage() {
return this._rootMessage;
}
}
export class Reply extends ForwardableBase {
constructor(responseTo, error) {
super(responseTo.name, responseTo.target, responseTo.source);
this.isReply = true;
assert(responseTo.reply == null, "Send's reply has already been set");
this.responseTo = responseTo;
this.error = error || null;
this.isError = this.error != null;
responseTo.reply = this;
}
spawn(responseTo, error) {
const child = new Reply(responseTo, error);
child.setSpawnedFrom(this);
return child;
}
}
export class Send extends ForwardableBase {
constructor() {
super(...arguments);
this.isReply = false;
this.children = [];
this.reply = null;
this.cancelledAt = null;
}
spawn(nextTarget) {
const child = new Send(this.name, this.target, nextTarget);
child.setSpawnedFrom(this);
this.children.push(child);
return child;
}
spawnReply(error) {
return new Reply(this, error);
}
}
//# sourceMappingURL=actors.js.map