@x5e/gink
Version:
an eventually consistent database
70 lines • 2.74 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.Peer = void 0;
const utils_1 = require("./utils");
const builders_1 = require("./builders");
class Peer {
constructor(sendFunc, closeFunc = utils_1.noOp) {
this.sendFunc = sendFunc;
this.closeFunc = closeFunc;
const thisPeer = this;
this.ready = new Promise((resolve, reject) => {
thisPeer.callWhenReady = resolve;
thisPeer.callOnTimeout = reject;
});
setTimeout(() => {
thisPeer.callOnTimeout();
}, 1000);
}
close() {
const func = this.closeFunc;
func();
this.sendFunc = utils_1.noOp;
this.hasMap = undefined;
}
_receiveHasMap(hasMap) {
(0, utils_1.ensure)(!this.hasMap, "Already received a HasMap/Greeting from this Peer!");
this.hasMap = hasMap;
this.callWhenReady(this);
}
/**
* The Message proto contains an embedded one-of. Essentially this will wrap
* the bundle bytes payload in a wrapper by prefixing a few bytes to it.
* In theory the "Message" proto could be expanded with some extra metadata
* (e.g. send time) in the future.
* Note that the bundle is always passed around as bytes and then
* parsed as needed to avoid losing unknown fields.
* @param bundleBytes: the bytes corresponding to a bundle
* @returns a serialized "Message" proto
*/
static makeBundleMessage(bundleBytes) {
const message = new builders_1.SyncMessageBuilder();
message.setBundle(bundleBytes);
return message.serializeBinary();
}
/**
* Sends a bundle if we've received a greeting and our internal recordkeeping indicates
* that the peer could use this particular bundle (but ensures that we're not sending
* bundles that would cause gaps in the peer's chain.)
* @param bundleBytes The bundle to be sent.
* @param bundleInfo Metadata about the bundle.
*/
_sendIfNeeded(bundle) {
var _a;
if ((_a = this.hasMap) === null || _a === void 0 ? void 0 : _a.markAsHaving(bundle.info, true)) {
this.sendFunc(Peer.makeBundleMessage(bundle.bytes));
}
}
_sendAck(changeSetInfo) {
const ack = new builders_1.AckBuilder();
ack.setMedallion(changeSetInfo.medallion);
ack.setChainStart(changeSetInfo.chainStart);
ack.setTimestamp(changeSetInfo.timestamp);
const syncMessageBuilder = new builders_1.SyncMessageBuilder();
syncMessageBuilder.setAck(ack);
const bytes = syncMessageBuilder.serializeBinary();
this.sendFunc(bytes);
}
}
exports.Peer = Peer;
//# sourceMappingURL=Peer.js.map