-
Notifications
You must be signed in to change notification settings - Fork 43
/
Copy pathlight_push.ts
181 lines (154 loc) · 4.38 KB
/
light_push.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
import type { Peer, PeerId } from "@libp2p/interface";
import {
ConnectionManager,
getHealthManager,
LightPushCodec,
LightPushCore
} from "@waku/core";
import {
type CoreProtocolResult,
Failure,
type IEncoder,
ILightPush,
type IMessage,
type ISenderOptions,
type Libp2p,
type ProtocolCreateOptions,
ProtocolError,
SDKProtocolResult
} from "@waku/interfaces";
import { ensurePubsubTopicIsConfigured, Logger } from "@waku/utils";
import { DEFAULT_NUM_PEERS_TO_USE } from "../base_protocol.js";
const log = new Logger("sdk:light-push");
const DEFAULT_MAX_ATTEMPTS = 3;
const DEFAULT_SEND_OPTIONS: ISenderOptions = {
autoRetry: false,
maxAttempts: DEFAULT_MAX_ATTEMPTS
};
type RetryCallback = (peer: Peer) => Promise<CoreProtocolResult>;
export class LightPush implements ILightPush {
private numPeersToUse: number = DEFAULT_NUM_PEERS_TO_USE;
public readonly protocol: LightPushCore;
public constructor(
connectionManager: ConnectionManager,
private libp2p: Libp2p,
options?: ProtocolCreateOptions
) {
this.numPeersToUse = options?.numPeersToUse ?? DEFAULT_NUM_PEERS_TO_USE;
this.protocol = new LightPushCore(
connectionManager.configuredPubsubTopics,
libp2p
);
}
public async send(
encoder: IEncoder,
message: IMessage,
options: ISenderOptions = DEFAULT_SEND_OPTIONS
): Promise<SDKProtocolResult> {
const successes: PeerId[] = [];
const failures: Failure[] = [];
const { pubsubTopic } = encoder;
try {
ensurePubsubTopicIsConfigured(pubsubTopic, this.protocol.pubsubTopics);
} catch (error) {
log.error("Failed to send waku light push: pubsub topic not configured");
return {
successes,
failures: [
{
error: ProtocolError.TOPIC_NOT_CONFIGURED
}
]
};
}
const peers = await this.getConnectedPeers();
if (peers.length === 0) {
return {
successes,
failures: [
{
error: ProtocolError.NO_PEER_AVAILABLE
}
]
};
}
const results = await Promise.allSettled(
peers.map((peer) => this.protocol.send(encoder, message, peer))
);
for (const result of results) {
if (result.status !== "fulfilled") {
log.error("Failed unexpectedly while sending:", result.reason);
failures.push({ error: ProtocolError.GENERIC_FAIL });
continue;
}
const { failure, success } = result.value;
if (success) {
successes.push(success);
continue;
}
if (failure) {
failures.push(failure);
if (options?.autoRetry) {
void this.attemptRetries(
(peer: Peer) => this.protocol.send(encoder, message, peer),
options.maxAttempts
);
}
}
}
getHealthManager().updateProtocolHealth(
this.protocol.multicodec,
successes.length
);
return {
successes,
failures
};
}
private async attemptRetries(
fn: RetryCallback,
maxAttempts?: number
): Promise<void> {
maxAttempts = maxAttempts || DEFAULT_MAX_ATTEMPTS;
const connectedPeers = await this.getConnectedPeers();
if (connectedPeers.length === 0) {
log.warn("Cannot retry with no connected peers.");
return;
}
for (let i = 0; i < maxAttempts; i++) {
const peer = connectedPeers[i % connectedPeers.length]; // always present as we checked for the length already
const response = await fn(peer);
if (response.success) {
return;
}
log.info(
`Attempted retry for peer:${peer.id} failed with:${response?.failure?.error}`
);
}
}
private async getConnectedPeers(): Promise<Peer[]> {
const peerIDs = this.libp2p.getPeers();
if (peerIDs.length === 0) {
return [];
}
const peers = await Promise.all(
peerIDs.map(async (id) => {
try {
return await this.libp2p.peerStore.get(id);
} catch (e) {
return null;
}
})
);
return peers
.filter((p) => !!p)
.filter((p) => (p as Peer).protocols.includes(LightPushCodec))
.slice(0, this.numPeersToUse) as Peer[];
}
}
export function wakuLightPush(
connectionManager: ConnectionManager,
init: Partial<ProtocolCreateOptions> = {}
): (libp2p: Libp2p) => ILightPush {
return (libp2p: Libp2p) => new LightPush(connectionManager, libp2p, init);
}