@waku/sdk
Version:
A unified SDK for easy creation and management of js-waku nodes.
82 lines • 2.74 kB
JavaScript
import { LightPushCore } from "@waku/core";
import { ProtocolError, Protocols } from "@waku/interfaces";
import { Logger } from "@waku/utils";
import { RetryManager } from "./retry_manager.js";
const log = new Logger("sdk:light-push");
const DEFAULT_MAX_ATTEMPTS = 3;
const DEFAULT_SEND_OPTIONS = {
autoRetry: true,
retryIntervalMs: 1000,
maxAttempts: DEFAULT_MAX_ATTEMPTS,
numPeersToUse: 1
};
export class LightPush {
config;
retryManager;
peerManager;
protocol;
constructor(params) {
this.config = {
...DEFAULT_SEND_OPTIONS,
...(params.options || {})
};
this.peerManager = params.peerManager;
this.protocol = new LightPushCore(params.libp2p);
this.retryManager = new RetryManager({
peerManager: params.peerManager,
retryIntervalMs: this.config.retryIntervalMs
});
}
get multicodec() {
return this.protocol.multicodec;
}
start() {
this.retryManager.start();
}
stop() {
this.retryManager.stop();
}
async send(encoder, message, options = {}) {
options = {
...this.config,
...options
};
const { pubsubTopic } = encoder;
log.info("send: attempting to send a message to pubsubTopic:", pubsubTopic);
const peerIds = await this.peerManager.getPeers({
protocol: Protocols.LightPush,
pubsubTopic: encoder.pubsubTopic
});
const coreResults = peerIds?.length > 0
? await Promise.all(peerIds.map((peerId) => this.protocol.send(encoder, message, peerId).catch((_e) => ({
success: null,
failure: {
error: ProtocolError.GENERIC_FAIL
}
}))))
: [];
const results = coreResults.length
? {
successes: coreResults
.filter((v) => v.success)
.map((v) => v.success),
failures: coreResults
.filter((v) => v.failure)
.map((v) => v.failure)
}
: {
successes: [],
failures: [
{
error: ProtocolError.NO_PEER_AVAILABLE
}
]
};
if (options.autoRetry && results.successes.length === 0) {
const sendCallback = (peerId) => this.protocol.send(encoder, message, peerId);
this.retryManager.push(sendCallback.bind(this), options.maxAttempts || DEFAULT_MAX_ATTEMPTS, encoder.routingInfo);
}
return results;
}
}
//# sourceMappingURL=light_push.js.map