UNPKG

@ceramicnetwork/core

Version:

Typescript implementation of the Ceramic protocol

55 lines 2.02 kB
import { buildQueryMessage, MsgType } from './pubsub-message.js'; import { Observable, Subject, Subscription, empty, pipe, } from 'rxjs'; import { filter, map, takeUntil, tap } from 'rxjs/operators'; import { OutstandingQueries, Query } from './outstanding-queries.js'; export const MAX_RESPONSE_INTERVAL = 300; function betweenTimeout(betweenMs) { const stop = new Subject(); let trigger = undefined; return pipe(tap(() => { if (trigger) clearTimeout(trigger); trigger = setTimeout(() => { stop.next(true); }, betweenMs); }), takeUntil(stop)); } export class MessageBus extends Observable { constructor(pubsub, peerSyncDisabled) { super((subscriber) => { this.feed$.subscribe(subscriber); }); this.pubsub = pubsub; this.peerSyncDisabled = peerSyncDisabled; this.outstandingQueries = new OutstandingQueries(); this.feed$ = new Subject(); this.pubsubSubscription = this.pubsub.subscribe(this.feed$); } get closed() { return this.feed$.isStopped; } next(message) { if (this.closed) { return Subscription.EMPTY; } else { return this.pubsub.next(message); } } queryNetwork(streamId) { if (this.peerSyncDisabled) { return empty(); } const queryMessage = buildQueryMessage(streamId); this.next(queryMessage); const timeNow = Date.now(); const query = new Query(timeNow, streamId, queryMessage.id); this.outstandingQueries.add(queryMessage.id, query); return this.pipe(filter((message) => message.typ === MsgType.RESPONSE && message.id === queryMessage.id), map((message) => message.tips.get(streamId.toString())), filter((tip) => !!tip), betweenTimeout(MAX_RESPONSE_INTERVAL)); } unsubscribe() { this.pubsubSubscription.unsubscribe(); this.feed$.complete(); } } //# sourceMappingURL=message-bus.js.map