-
Notifications
You must be signed in to change notification settings - Fork 479
/
Copy pathserver.ts
2195 lines (1957 loc) · 81.2 KB
/
server.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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
CastAddMessage,
CastId,
CastRemoveMessage,
ContactInfoResponse,
DbStats,
FidsResponse,
getServer,
HubError,
HubEvent,
HubEventType,
HubInfoResponse,
HubServiceServer,
HubServiceService,
LinkAddMessage,
LinkCompactStateMessage,
LinkRemoveMessage,
Message,
MessagesResponse,
Metadata,
ReactionAddMessage,
ReactionRemoveMessage,
Server as GrpcServer,
ServerCredentials,
ServiceError,
status,
StorageLimitsResponse,
SyncIds,
SyncStatus,
SyncStatusResponse,
TrieNodeMetadataResponse,
TrieNodeSnapshotResponse,
UserDataAddMessage,
VerificationAddAddressMessage,
VerificationRemoveMessage,
ValidationResponse,
UserNameProof,
UsernameProofsResponse,
OnChainEventResponse,
SignerOnChainEvent,
OnChainEvent,
HubResult,
HubAsyncResult,
ServerWritableStream,
SubscribeRequest,
StreamSyncRequest,
StreamSyncResponse,
HubInfoRequest,
Empty,
SyncStatusRequest,
TrieNodePrefix,
StreamFetchRequest,
StreamFetchResponse,
StreamError,
OnChainEventRequest,
FidRequest,
getFarcasterTime,
MessageBundle,
SubmitBulkMessagesResponse,
BulkMessageResponse,
MessageError,
} from "@farcaster/hub-nodejs";
import { err, ok, Result, ResultAsync } from "neverthrow";
import { APP_NICKNAME, APP_VERSION, HubInterface } from "../hubble.js";
import { GossipNode } from "../network/p2p/gossipNode.js";
import { NodeMetadata } from "../network/sync/merkleTrie.js";
import SyncEngine from "../network/sync/syncEngine.js";
import Engine from "../storage/engine/index.js";
import { MessagesPage } from "../storage/stores/types.js";
import { logger } from "../utils/logger.js";
import { addressInfoFromParts, extractIPAddress, getPublicIp } from "../utils/p2p.js";
import { RateLimiterMemory } from "rate-limiter-flexible";
import {
BufferedStreamWriter,
STREAM_MESSAGE_BUFFER_SIZE,
SLOW_CLIENT_GRACE_PERIOD_MS,
} from "./bufferedStreamWriter.js";
import { blake3Truncate160, sleep } from "../utils/crypto.js";
import { jumpConsistentHash } from "../utils/jumpConsistentHash.js";
import { SUBMIT_MESSAGE_RATE_LIMIT, rateLimitByIp } from "../utils/rateLimits.js";
import { statsd } from "../utils/statsd.js";
import { SyncId } from "../network/sync/syncId.js";
import { AddressInfo } from "net";
import * as net from "node:net";
import axios from "axios";
import { fidFromEvent } from "../storage/stores/storeEventHandler.js";
import { rustErrorToHubError } from "../rustfunctions.js";
import { handleUnaryCall, sendUnaryData, ServerDuplexStream, ServerUnaryCall } from "@grpc/grpc-js";
import { MAX_BUNDLE_SIZE } from "../network/p2p/bundleCreator.js";
const HUBEVENTS_READER_TIMEOUT = 1 * 60 * 60 * 1000; // 1 hour
const STREAM_METHODS_TIMEOUT = 8 * 1000; // 2 seconds
export const DEFAULT_SUBSCRIBE_PERIP_LIMIT = 4; // Max 4 subscriptions per IP
export const DEFAULT_SUBSCRIBE_GLOBAL_LIMIT = 4096; // Max 4096 subscriptions globally
const MAX_EVENT_STREAM_SHARDS = 10;
export const DEFAULT_SERVER_INTERNET_ADDRESS_IPV4 = "0.0.0.0";
export const MAX_VALUES_RETURNED_PER_SYNC_ID_REQUEST = 1024; // getAllSyncIdsByPrefix returns a max of 1024 sync ids in one response. This value is mirrored in [addon/src/trie/trie_node.rs], make sure to change it in both places.
export type RpcUsers = Map<string, string[]>;
const log = logger.child({ component: "gRPCServer" });
// Check if the user is authenticated via the metadata
export const authenticateUser = (metadata: Metadata, rpcUsers: RpcUsers): HubResult<boolean> => {
// If there is no auth user/pass, we don't need to authenticate
if (rpcUsers.size === 0) {
return ok(true);
}
if (metadata.get("authorization")) {
const authHeader = metadata.get("authorization")[0] as string;
if (!authHeader) {
return err(new HubError("unauthenticated", "Authorization header is empty"));
}
const encodedCredentials = authHeader.replace("Basic ", "");
const decodedCredentials = Buffer.from(encodedCredentials, "base64").toString("utf-8");
const [username, password] = decodedCredentials.split(":");
if (!username || !password) {
return err(new HubError("unauthenticated", `Invalid username: ${username}`));
}
// See if username and password match one of rpcUsers
const allowedPasswords = rpcUsers.get(username);
if (!allowedPasswords) {
return err(new HubError("unauthenticated", `Invalid username: ${username}`));
}
if (!allowedPasswords.includes(password)) {
return err(new HubError("unauthenticated", `Invalid password for user: ${username}`));
}
return ok(true);
}
return err(new HubError("unauthenticated", "No authorization header"));
};
async function retryAsyncOperation<T>(
operation: () => HubAsyncResult<T>,
retries = 3,
delayMs = 1000,
): HubAsyncResult<T> {
const attempt = async (remainingRetries: number, delayMs: number): HubAsyncResult<T> => {
const result = await operation();
if (result.isErr()) {
if (remainingRetries > 0) {
await sleep(delayMs);
return attempt(remainingRetries - 1, delayMs * 2);
}
return err(result.error);
}
return ok(result.value);
};
return attempt(retries, delayMs);
}
export async function checkPort(ip: string, port: number): HubAsyncResult<void> {
if (ip === "") {
return err(new HubError("bad_request.invalid_param", "Invalid ip address"));
}
if (port === 0) {
return err(new HubError("bad_request.invalid_param", "Invalid port"));
}
return ResultAsync.fromPromise(
new Promise<void>((resolve, reject) => {
const socket = new net.Socket();
const socketTimeoutMs = 2000; // 2 seconds
socket.setTimeout(socketTimeoutMs);
socket
.once("connect", () => {
socket.destroy();
resolve();
})
.once("error", (err) => {
socket.destroy();
reject(err);
})
.once("timeout", () => {
socket.destroy();
reject(new HubError("unavailable.network_failure", `Timeout connecting to ${ip}:${port}`));
})
.connect(port, ip);
}),
(error) => {
return new HubError("unavailable.network_failure", `Failed to connect to ${ip}:${port}: ${error}`);
},
).match(
async (okResult: void): HubAsyncResult<void> => ok(okResult),
async (errorResult: HubError): HubAsyncResult<void> => err(errorResult),
);
}
export const checkPortAndPublicAddress = async (
localIP: string,
port: number,
remoteIP?: string,
): HubAsyncResult<void> => {
const retryCount = 3;
const localDelayMs = 50;
const localResult: Result<void, Error> = await retryAsyncOperation<void>(
() => checkPort(localIP, port),
retryCount,
localDelayMs, // local ping does not need high timeout
);
if (localResult.isErr()) {
return err(
new HubError("unavailable.network_failure", `Failed to connect to ${localIP}:${port}: ${localResult.error}`),
);
}
let publicIP: string = remoteIP ?? "";
if (publicIP === "") {
const publicIPResponse = await getPublicIp("json");
if (publicIPResponse.isErr()) {
return err(publicIPResponse.error);
}
publicIP = publicIPResponse.value;
}
return await retryAsyncOperation<void>(() => checkPort(publicIP, port), retryCount);
};
export const toServiceError = (err: HubError): ServiceError => {
// hack: After rust migration, requests that propagate to RocksDB may yield string errors that don't have an errCode.
// Since the rustErrorToHubError function is not called in these cases, we attempt conversion here.
const hubErr: HubError = err.errCode ? err : rustErrorToHubError(err);
let grpcCode: number;
if (err.errCode === "unauthenticated") {
grpcCode = status.UNAUTHENTICATED;
} else if (err.errCode === "unauthorized") {
grpcCode = status.PERMISSION_DENIED;
} else if (
err.errCode === "bad_request" ||
err.errCode === "bad_request.parse_failure" ||
err.errCode === "bad_request.validation_failure" ||
err.errCode === "bad_request.invalid_param" ||
err.errCode === "bad_request.conflict" ||
err.errCode === "bad_request.duplicate" ||
err.errCode === "bad_request.prunable"
) {
grpcCode = status.INVALID_ARGUMENT;
} else if (err.errCode === "not_found") {
grpcCode = status.NOT_FOUND;
} else if (
err.errCode === "unavailable" ||
err.errCode === "unavailable.network_failure" ||
err.errCode === "unavailable.storage_failure"
) {
grpcCode = status.UNAVAILABLE;
} else {
grpcCode = status.UNKNOWN;
}
const metadata = new Metadata();
metadata.set("errCode", hubErr.errCode);
return Object.assign(hubErr, {
code: grpcCode,
details: hubErr.message,
metadata,
});
};
const messagesPageToResponse = ({ messages, nextPageToken }: MessagesPage<Message>) => {
return MessagesResponse.create({
messages,
nextPageToken: nextPageToken ?? new Uint8Array(),
});
};
export const getRPCUsersFromAuthString = (rpcAuth?: string): Map<string, string[]> => {
if (!rpcAuth) {
return new Map();
}
// Split up the auth string by commas
const rpcAuthUsers = rpcAuth?.split(",") ?? [];
// Create a map of username to all the passwords for that user
const rpcUsers = new Map();
rpcAuthUsers.forEach((rpcAuthUser) => {
const [username, password] = rpcAuthUser.split(":");
if (username && password) {
const passwords = rpcUsers.get(username) ?? [];
passwords.push(password);
rpcUsers.set(username, passwords);
}
});
return rpcUsers;
};
/**
* Limit the number of simultaneous connections to the RPC server by
* a single IP address.
*/
class IpConnectionLimiter {
private perIpLimit: number;
private globalLimit: number;
private ipConnections: Map<string, number>;
private totalConnections: number;
constructor(perIpLimit: number, globalLimit: number) {
this.ipConnections = new Map();
this.perIpLimit = perIpLimit;
this.globalLimit = globalLimit;
this.totalConnections = 0;
}
public addConnection(peerString: string): Result<boolean, Error> {
// Get the IP part of the address
const ip = extractIPAddress(peerString) ?? "unknown";
const connections = this.ipConnections.get(ip) ?? 0;
if (ip !== "127.0.0.1" && ip !== "::1" && connections >= this.perIpLimit) {
return err(new Error(`Too many connections from this IP: ${ip}`));
}
if (this.totalConnections >= this.globalLimit) {
return err(new Error("Too many connections to this server"));
}
this.ipConnections.set(ip, connections + 1);
this.totalConnections += 1;
return ok(true);
}
public removeConnection(peerString: string) {
// Get the IP part of the address
const ip = extractIPAddress(peerString) ?? "unknown";
const connections = this.ipConnections.get(ip) ?? 0;
if (connections > 0) {
this.ipConnections.set(ip, connections - 1);
this.totalConnections -= 1;
}
}
clear() {
this.ipConnections.clear();
this.totalConnections = 0;
}
}
export function destroyStream<T, R>(stream: ServerWritableStream<T, R> | ServerDuplexStream<T, R>, error: Error) {
stream.emit("error", error);
stream.end();
}
export const toTrieNodeMetadataResponse = (metadata?: NodeMetadata): TrieNodeMetadataResponse => {
const childrenTrie = [];
if (!metadata) {
return TrieNodeMetadataResponse.create({});
}
if (metadata.children) {
for (const [, child] of metadata.children) {
childrenTrie.push(
TrieNodeMetadataResponse.create({
prefix: child.prefix,
numMessages: child.numMessages,
hash: child.hash,
children: [],
}),
);
}
}
const metadataResponse = TrieNodeMetadataResponse.create({
prefix: metadata.prefix,
numMessages: metadata.numMessages,
hash: metadata.hash,
children: childrenTrie,
});
return metadataResponse;
};
export default class Server {
private hub: HubInterface | undefined;
private engine: Engine | undefined;
private syncEngine: SyncEngine | undefined;
private gossipNode: GossipNode | undefined;
private grpcServer: GrpcServer;
private listenIp: string;
private port: number;
private impl: HubServiceServer;
private incomingConnections = 0;
private rpcUsers: RpcUsers;
private submitMessageRateLimiter: RateLimiterMemory;
private subscribeIpLimiter: IpConnectionLimiter;
constructor(
hub?: HubInterface,
engine?: Engine,
syncEngine?: SyncEngine,
gossipNode?: GossipNode,
rpcAuth?: string,
rpcRateLimit?: number,
rpcSubscribePerIpLimit?: number,
) {
this.hub = hub;
this.engine = engine;
this.syncEngine = syncEngine;
this.gossipNode = gossipNode;
this.grpcServer = getServer();
this.listenIp = "";
this.port = 0;
this.rpcUsers = getRPCUsersFromAuthString(rpcAuth);
if (this.rpcUsers.size > 0) {
log.info({ num_users: this.rpcUsers.size }, "RPC auth enabled");
}
this.impl = this.makeImpl();
this.grpcServer.addService(HubServiceService, this.impl);
// Submit message are rate limited by default to 20k per minute
const rateLimitPerMinute = SUBMIT_MESSAGE_RATE_LIMIT;
if (rpcRateLimit !== undefined && rpcRateLimit >= 0) {
rateLimitPerMinute.points = rpcRateLimit;
}
log.info({ rpcRateLimit }, "RPC rate limit enabled");
this.submitMessageRateLimiter = new RateLimiterMemory(rateLimitPerMinute);
this.subscribeIpLimiter = new IpConnectionLimiter(
rpcSubscribePerIpLimit ?? DEFAULT_SUBSCRIBE_PERIP_LIMIT,
DEFAULT_SUBSCRIBE_GLOBAL_LIMIT,
);
}
async start(ip = DEFAULT_SERVER_INTERNET_ADDRESS_IPV4, port = 0): Promise<number> {
return new Promise((resolve, reject) => {
this.grpcServer.bindAsync(`${ip}:${port}`, ServerCredentials.createInsecure(), (err, port) => {
if (err) {
logger.error({ component: "gRPC Server", err }, "Failed to start gRPC Server. Is the port already in use?");
reject(err);
} else {
this.grpcServer.start();
this.listenIp = ip;
this.port = port;
logger.info({ component: "gRPC Server", address: this.address }, "Starting gRPC Server");
resolve(port);
}
});
});
}
async stop(force = false): Promise<void> {
return new Promise((resolve, reject) => {
if (force) {
this.grpcServer.forceShutdown();
log.info("gRPC server force shutdown succeeded");
resolve();
} else {
this.grpcServer.tryShutdown((err) => {
if (err) {
log.error(`gRPC server shutdown failed: ${err}`);
reject(err);
} else {
log.info("gRPC server shutdown succeeded");
resolve();
}
});
}
});
}
get address(): HubResult<AddressInfo> {
const addr = addressInfoFromParts(this.listenIp, this.port);
return addr;
}
get auth() {
return this.rpcUsers;
}
get listenPort() {
return this.port;
}
public hasInboundConnections() {
return this.incomingConnections > 0;
}
public clearRateLimiters() {
this.subscribeIpLimiter.clear();
}
public async getInfo(request: HubInfoRequest) {
const info = HubInfoResponse.create({
version: APP_VERSION,
isSyncing: !!this.syncEngine?.isSyncing(),
nickname: APP_NICKNAME,
rootHash: (await this.syncEngine?.trie.rootHash()) ?? "",
peerId: Result.fromThrowable(
() => this.hub?.identity ?? "",
(e) => e,
)().unwrapOr(""),
hubOperatorFid: this.hub?.hubOperatorFid ?? 0,
});
if (request.dbStats && this.syncEngine) {
const stats = await this.syncEngine.getDbStats();
info.dbStats = DbStats.create({
approxSize: stats?.approxSize,
numMessages: stats?.numItems,
numFidEvents: stats?.numFids,
numFnameEvents: stats?.numFnames,
});
}
return info;
}
public getInfoRPC(call: ServerUnaryCall<HubInfoRequest, HubInfoResponse>, callback: sendUnaryData<HubInfoResponse>) {
(async () => {
const peer = Result.fromThrowable(() => call.getPeer())().unwrapOr("unknown");
log.debug({ method: "getInfo", req: call?.request || { dbStats: false } }, `RPC call from ${peer}`);
statsd().increment("rpc.open_request_count", { method: "getInfo" });
const info = await this.getInfo(call?.request || { dbStats: false });
statsd().decrement("rpc.open_request_count", { method: "getInfo" });
callback(null, info);
})();
}
public async stopSync() {
const result = await this.syncEngine?.stopSync();
if (!result) {
return err(new HubError("bad_request", "Stop sync timed out"));
} else {
return ok(
SyncStatusResponse.create({
isSyncing: this.syncEngine?.isSyncing() || false,
engineStarted: this.syncEngine?.isStarted() || false,
syncStatus: [],
}),
);
}
}
public stopSyncRPC(call: ServerUnaryCall<Empty, SyncStatusResponse>, callback: sendUnaryData<SyncStatusResponse>) {
(async () => {
const peer = Result.fromThrowable(() => call.getPeer())().unwrapOr("unknown");
log.debug({ method: "stopSync", req: call.request }, `RPC call from ${peer}`);
statsd().increment("rpc.open_request_count", { method: "stopSync" });
const result = await this.stopSync();
statsd().decrement("rpc.open_request_count", { method: "stopSync" });
if (result.isErr()) {
callback(toServiceError(result.error));
} else {
callback(null, result.value);
}
})();
}
public async forceSync(request: SyncStatusRequest) {
const peerId = request.peerId;
if (!peerId || peerId.length === 0) {
return err(new HubError("bad_request", "peerId is required"));
}
const result = await this.syncEngine?.forceSyncWithPeer(peerId);
if (!result || result.isErr()) {
return err(result?.error || new HubError("bad_request", "sync engine not available"));
} else {
const status = result.value;
const response = SyncStatusResponse.create({
isSyncing: this.syncEngine?.isSyncing() || false,
engineStarted: this.syncEngine?.isStarted() || false,
syncStatus: [
SyncStatus.create({
peerId,
inSync: status.inSync,
shouldSync: status.shouldSync,
lastBadSync: status.lastBadSync,
ourMessages: status.ourSnapshot.numMessages,
theirMessages: status.theirSnapshot.numMessages,
score: status.score,
}),
],
});
return ok(response);
}
}
public forceSyncRPC(
call: ServerUnaryCall<SyncStatusRequest, SyncStatusResponse>,
callback: sendUnaryData<SyncStatusResponse>,
) {
(async () => {
const peer = Result.fromThrowable(() => call.getPeer())().unwrapOr("unknown");
log.debug({ method: "forceSync", req: call.request }, `RPC call from ${peer}`);
statsd().increment("rpc.open_request_count", { method: "forceSync" });
const result = await this.forceSync(call.request);
statsd().decrement("rpc.open_request_count", { method: "forceSync" });
if (result.isErr()) {
callback(toServiceError(result.error));
} else {
callback(null, result.value);
}
})();
}
public getCurrentPeers() {
const currentHubPeerContacts = this.syncEngine?.getCurrentHubPeerContacts();
if (!currentHubPeerContacts) {
return ContactInfoResponse.create({ contacts: [] });
}
const contactInfoArray = Array.from(currentHubPeerContacts).map((peerContact) => peerContact[1]);
return ContactInfoResponse.create({ contacts: contactInfoArray });
}
public getCurrentPeersRPC(
call: ServerUnaryCall<Empty, ContactInfoResponse>,
callback: sendUnaryData<ContactInfoResponse>,
) {
(async () => {
const peer = Result.fromThrowable(() => call.getPeer())().unwrapOr("unknown");
log.debug({ method: "getCurrentPeers", req: call.request }, `RPC call from ${peer}`);
statsd().increment("rpc.open_request_count", { method: "getCurrentPeers" });
const result = this.getCurrentPeers();
statsd().decrement("rpc.open_request_count", { method: "getCurrentPeers" });
callback(null, result);
})();
}
public async getSyncStatus(peerId: string | undefined) {
if (!this.gossipNode || !this.syncEngine || !this.hub) {
return err(new HubError("bad_request", "Hub isn't initialized"));
}
let peersToCheck: string[];
if (peerId && peerId.length > 0) {
peersToCheck = [peerId];
} else {
// If no peerId is specified, check upto 20 peers
peersToCheck = (await this.gossipNode.allPeerIds()).slice(0, 20);
}
const response = SyncStatusResponse.create({
isSyncing: false,
syncStatus: [],
engineStarted: this.syncEngine.isStarted(),
});
await Promise.all(
peersToCheck.map(async (peerId) => {
const statusResult = await this.syncEngine?.getSyncStatusForPeer(peerId, this.hub as HubInterface);
if (statusResult?.isOk()) {
const status = statusResult.value;
response.isSyncing = status.isSyncing;
response.syncStatus.push(
SyncStatus.create({
peerId,
inSync: status.inSync,
shouldSync: status.shouldSync,
lastBadSync: status.lastBadSync,
ourMessages: status.ourSnapshot.numMessages,
theirMessages: status.theirSnapshot.numMessages,
score: status.score,
}),
);
}
}),
);
return ok(response);
}
public getSyncStatusRPC(
call: ServerUnaryCall<SyncStatusRequest, SyncStatusResponse>,
callback: sendUnaryData<SyncStatusResponse>,
) {
(async () => {
const peer = Result.fromThrowable(() => call.getPeer())().unwrapOr("unknown");
log.debug({ method: "getSyncStatus", req: call.request }, `RPC call from ${peer}`);
statsd().increment("rpc.open_request_count", { method: "getSyncStatus" });
const peerId = call.request.peerId;
const result = await this.getSyncStatus(peerId);
statsd().decrement("rpc.open_request_count", { method: "getSyncStatus" });
if (result.isErr()) {
callback(toServiceError(result.error));
} else {
callback(null, result.value);
}
})();
}
public async getAllSyncIdsByPrefix(request: TrieNodePrefix) {
const syncIdsResponse = await this.syncEngine?.getAllSyncIdsByPrefix(request.prefix);
return ok(SyncIds.create({ syncIds: syncIdsResponse ?? [] }));
}
public getAllSyncIdsByPrefixRPC(call: ServerUnaryCall<TrieNodePrefix, SyncIds>, callback: sendUnaryData<SyncIds>) {
const peer = Result.fromThrowable(() => call.getPeer())().unwrapOr("unknown");
log.debug({ method: "getAllSyncIdsByPrefix", req: call.request }, `RPC call from ${peer}`);
statsd().increment("rpc.open_request_count", { method: "getAllSyncIdsByPrefix" });
(async () => {
const result = await this.getAllSyncIdsByPrefix(call.request);
statsd().decrement("rpc.open_request_count", { method: "getAllSyncIdsByPrefix" });
if (result.isErr()) {
callback(toServiceError(result.error));
} else {
callback(null, result.value);
}
})();
}
public async getAllMessagesBySyncIds(request: SyncIds) {
if (request.syncIds.length > MAX_VALUES_RETURNED_PER_SYNC_ID_REQUEST) {
return err(new HubError("bad_request.validation_failure", "Too many sync ids provided"));
}
const syncIds = request.syncIds.map((syncId) => SyncId.fromBytes(syncId));
const messagesResult = await this.syncEngine?.getAllMessagesBySyncIds(syncIds);
if (messagesResult?.isErr()) {
return err(messagesResult.error);
} else if (messagesResult?.isOk()) {
let messages = messagesResult.value;
// Check the messages for corruption. If a message is blank, that means it was present
// in our sync trie, but the DB couldn't find it. So remove it from the sync Trie.
const corruptedSyncIds = this.syncEngine?.findCorruptedSyncIDs(messages, syncIds);
if ((corruptedSyncIds?.length ?? 0) > 0) {
log.warn(
{ num: corruptedSyncIds?.length },
"Found corrupted messages while serving API, rebuilding some syncIDs",
);
// Don't wait for this to finish, just return the messages we have.
this.syncEngine?.revokeSyncIds(corruptedSyncIds ?? []);
messages = messages.filter((message) => message.data !== undefined && message.hash.length > 0);
}
const response = MessagesResponse.create({ messages });
return ok(response);
} else {
return err(new HubError("unavailable", "no messages available"));
}
}
public async getAllMessagesBySyncIdsRPC(
call: ServerUnaryCall<SyncIds, MessagesResponse>,
callback: sendUnaryData<MessagesResponse>,
) {
const peer = Result.fromThrowable(() => call.getPeer())().unwrapOr("unknown");
log.debug({ method: "getAllMessagesBySyncIds", req: call.request }, `RPC call from ${peer}`);
statsd().increment("rpc.open_request_count", { method: "getAllMessagesBySyncIds" });
const result = await this.getAllMessagesBySyncIds(call.request);
statsd().decrement("rpc.open_request_count", { method: "getAllMessagesBySyncIds" });
if (result.isErr()) {
callback(toServiceError(result.error));
} else {
callback(null, result.value);
}
}
public async getSyncMetadataByPrefix(request: TrieNodePrefix) {
const metadata = await this.syncEngine?.getTrieNodeMetadata(request.prefix);
return ok(toTrieNodeMetadataResponse(metadata));
}
public getSyncMetadataByPrefixRPC(
call: ServerUnaryCall<TrieNodePrefix, TrieNodeMetadataResponse>,
callback: sendUnaryData<TrieNodeMetadataResponse>,
) {
const peer = Result.fromThrowable(() => call.getPeer())().unwrapOr("unknown");
log.debug({ method: "getSyncMetadataByPrefix", req: call.request }, `RPC call from ${peer}`);
statsd().increment("rpc.open_request_count", { method: "getSyncMetadataByPrefix" });
(async () => {
const result = await this.getSyncMetadataByPrefix(call.request);
statsd().decrement("rpc.open_request_count", { method: "getSyncMetadataByPrefix" });
if (result.isErr()) {
callback(toServiceError(result.error));
} else {
callback(null, result.value);
}
})();
}
public async getSyncSnapshotByPrefix(request: TrieNodePrefix) {
const rootHash = (await this.syncEngine?.trie.rootHash()) ?? "";
const snapshot = await this.syncEngine?.getSnapshotByPrefix(request.prefix);
if (snapshot?.isErr()) {
return err(snapshot.error);
} else if (snapshot?.isOk()) {
const snapshotResponse = TrieNodeSnapshotResponse.create({
prefix: snapshot.value.prefix,
numMessages: snapshot.value.numMessages,
rootHash,
excludedHashes: snapshot.value.excludedHashes,
});
return ok(snapshotResponse);
} else {
return err(new HubError("unavailable", "no snapshot available"));
}
}
public getSyncSnapshotByPrefixRPC(
call: ServerUnaryCall<TrieNodePrefix, TrieNodeSnapshotResponse>,
callback: sendUnaryData<TrieNodeSnapshotResponse>,
) {
const peer = Result.fromThrowable(() => call.getPeer())().unwrapOr("unknown");
log.debug({ method: "getSyncSnapshotByPrefix", req: call.request }, `RPC call from ${peer}`);
statsd().increment("rpc.open_request_count", { method: "getSyncSnapshotByPrefix" });
// If someone is asking for our sync snapshot, that means we're getting incoming
// connections
this.incomingConnections += 1;
statsd().increment("rpc.get_sync_snapshot");
(async () => {
const result = await this.getSyncSnapshotByPrefix(call.request);
statsd().decrement("rpc.open_request_count", { method: "getSyncSnapshotByPrefix" });
if (result.isErr()) {
callback(toServiceError(result.error));
} else {
callback(null, result.value);
}
})();
}
public async getOnChainSignersByFid(request: FidRequest) {
const { fid, pageSize, pageToken, reverse } = request;
return (
(await this.engine?.getOnChainSignersByFid(fid, {
pageSize,
pageToken,
reverse,
})) || err(new HubError("bad_request", "sync engine not available"))
);
}
public async getOnChainSignersByFidRPC(
call: ServerUnaryCall<FidRequest, OnChainEventResponse>,
callback: sendUnaryData<OnChainEventResponse>,
) {
const peer = Result.fromThrowable(() => call.getPeer())().unwrapOr("unknown");
log.debug({ method: "getOnChainSignersByFid", req: call.request }, `RPC call from ${peer}`);
statsd().increment("rpc.open_request_count", { method: "getOnChainSignersByFid" });
const signersResult = await this.getOnChainSignersByFid(call.request);
statsd().decrement("rpc.open_request_count", { method: "getOnChainSignersByFid" });
signersResult?.match(
(page: OnChainEventResponse) => {
callback(null, page);
},
(err: HubError) => {
callback(toServiceError(err));
},
);
}
public async getOnChainEvents(request: OnChainEventRequest) {
return (
(await this.engine?.getOnChainEvents(request.eventType, request.fid)) ||
err(new HubError("bad_request", "sync engine not available"))
);
}
public getOnChainEventsRPC(
call: ServerUnaryCall<OnChainEventRequest, OnChainEventResponse>,
callback: sendUnaryData<OnChainEventResponse>,
) {
const peer = Result.fromThrowable(() => call.getPeer())().unwrapOr("unknown");
log.debug({ method: "getOnChainEvents", req: call.request }, `RPC call from ${peer}`);
statsd().increment("rpc.open_request_count", { method: "getOnChainEvents" });
(async () => {
const result = await this.getOnChainEvents(call.request);
statsd().decrement("rpc.open_request_count", { method: "getOnChainEvents" });
if (result.isErr()) {
callback(toServiceError(result.error));
} else {
callback(null, result.value);
}
})();
}
getImpl(): HubServiceServer {
return this.impl;
}
makeImpl(): HubServiceServer {
return {
getInfo: async (call, callback) => this.getInfoRPC(call, callback),
getCurrentPeers: async (call, callback) => this.getCurrentPeersRPC(call, callback),
stopSync: async (call, callback) => this.stopSyncRPC(call, callback),
forceSync: async (call, callback) => this.forceSyncRPC(call, callback),
getSyncStatus: async (call, callback) => this.getSyncStatusRPC(call, callback),
getAllSyncIdsByPrefix: async (call, callback) => this.getAllSyncIdsByPrefixRPC(call, callback),
getAllMessagesBySyncIds: async (call, callback) => this.getAllMessagesBySyncIdsRPC(call, callback),
getSyncMetadataByPrefix: async (call, callback) => this.getSyncMetadataByPrefixRPC(call, callback),
getSyncSnapshotByPrefix: async (call, callback) => this.getSyncSnapshotByPrefixRPC(call, callback),
getOnChainSignersByFid: async (call, callback) => this.getOnChainSignersByFidRPC(call, callback),
getOnChainEvents: async (call, callback) => this.getOnChainEventsRPC(call, callback),
submitMessage: async (call, callback) => {
// Identify peer that is calling, if available. This is used for rate limiting.
const peer = Result.fromThrowable(
() => call.getPeer(),
(e) => e,
)().unwrapOr("unavailable");
statsd().increment("rpc.open_request_count", { method: "submitMessage" });
const rateLimitResult = await rateLimitByIp(peer, this.submitMessageRateLimiter);
if (rateLimitResult.isErr()) {
logger.warn({ peer }, "submitMessage rate limited");
callback(toServiceError(new HubError("unavailable", "API rate limit exceeded")));
return;
}
// Authentication
const authResult = authenticateUser(call.metadata, this.rpcUsers);
if (authResult.isErr()) {
logger.warn({ errMsg: authResult.error.message }, "gRPC submitMessage failed");
callback(
toServiceError(new HubError("unauthenticated", `gRPC authentication failed: ${authResult.error.message}`)),
);
return;
}
const message = call.request;
const result = await this.hub?.submitMessage(message, "rpc");
statsd().decrement("rpc.open_request_count", { method: "submitMessage" });
result?.match(
() => {
callback(null, message);
},
(err: HubError) => {
callback(toServiceError(err));
},
);
},
submitBulkMessages: async (call, callback) => {
// Identify peer that is calling, if available. This is used for rate limiting.
const peer = Result.fromThrowable(
() => call.getPeer(),
(e) => e,
)().unwrapOr("unavailable");
statsd().increment("rpc.open_request_count", { method: "submitBulkMessages" });
// Check for rate limits
const rateLimitResult = await rateLimitByIp(peer, this.submitMessageRateLimiter);
if (rateLimitResult.isErr()) {
logger.warn({ peer }, "submitBulkMessages rate limited");
callback(toServiceError(new HubError("unavailable", "API rate limit exceeded")));
return;
}
// Authentication
const authResult = authenticateUser(call.metadata, this.rpcUsers);
if (authResult.isErr()) {
logger.warn({ errMsg: authResult.error.message }, "gRPC submitBulkMessages failed");
callback(
toServiceError(new HubError("unauthenticated", `gRPC authentication failed: ${authResult.error.message}`)),
);
return;
}
if (call.request.messages.length > MAX_BUNDLE_SIZE) {
logger.warn({ total: call.request.messages.length }, "gRPC submitBulkMessages received too many messages");