@ceramicnetwork/core
Version:
Typescript implementation of the Ceramic protocol
54 lines • 2.32 kB
JavaScript
import { Observable, interval } from 'rxjs';
import { concatMap } from 'rxjs/operators';
import { MsgType } from './pubsub-message.js';
import { version } from '../version.js';
export class PubsubKeepalive extends Observable {
constructor(pubsub, ipfs, maxPubsubPublishInterval, maxIntervalWithoutKeepalive) {
super((subscriber) => {
pubsub.subscribe(subscriber);
const pubsubKeepaliveInterval = interval(Math.min(this.maxPubsubPublishInterval / 2, this.maxIntervalWithoutKeepalive / 2))
.pipe(concatMap(async () => {
if (!this._ipfsVersion) {
this._ipfsVersion = await ipfs.version().then((_) => _.version);
}
return this._ipfsVersion;
}))
.subscribe((ipfsVersion) => {
this.publishPubsubKeepaliveIfNeeded(ipfsVersion);
});
return () => {
pubsubKeepaliveInterval.unsubscribe();
};
});
this.pubsub = pubsub;
this.ipfs = ipfs;
this.maxPubsubPublishInterval = maxPubsubPublishInterval;
this.maxIntervalWithoutKeepalive = maxIntervalWithoutKeepalive;
this.lastPublishedMessageDate = Date.now() - this.maxPubsubPublishInterval;
this.lastPublishedKeepAliveMessageDate = 0;
this._ipfsVersion = undefined;
}
next(message) {
const now = Date.now();
this.lastPublishedMessageDate = now;
if (message.typ === MsgType.KEEPALIVE)
this.lastPublishedKeepAliveMessageDate = now;
return this.pubsub.next(message);
}
publishPubsubKeepaliveIfNeeded(ipfsVersion) {
const now = Date.now();
const needToPublishKeepaliveOnceADay = now - this.lastPublishedKeepAliveMessageDate > this.maxIntervalWithoutKeepalive;
const needToPublishKeepaliveInactivity = now - this.lastPublishedMessageDate >= this.maxPubsubPublishInterval / 2;
if (!needToPublishKeepaliveInactivity && !needToPublishKeepaliveOnceADay) {
return;
}
const message = {
typ: MsgType.KEEPALIVE,
ts: now,
ver: version,
ipfsVer: ipfsVersion,
};
this.next(message);
}
}
//# sourceMappingURL=pubsub-keepalive.js.map