-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathfederation.service.ts
More file actions
393 lines (349 loc) · 9.68 KB
/
federation.service.ts
File metadata and controls
393 lines (349 loc) · 9.68 KB
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
import type { EventBase } from '@rocket.chat/federation-core';
import type { BaseEDU } from '@rocket.chat/federation-core';
import { createLogger } from '@rocket.chat/federation-core';
import {
EventID,
Pdu,
PersistentEventBase,
PersistentEventFactory,
extractDomainFromId,
} from '@rocket.chat/federation-room';
import { singleton } from 'tsyringe';
import {
FederationEndpoints,
type MakeJoinResponse,
type SendJoinResponse,
type SendTransactionResponse,
type Transaction,
type Version,
} from '../specs/federation-api';
import { ConfigService } from './config.service';
import { FederationRequestService } from './federation-request.service';
import { StateService } from './state.service';
@singleton()
export class FederationService {
private readonly logger = createLogger('FederationService');
constructor(
private readonly configService: ConfigService,
private readonly requestService: FederationRequestService,
private readonly stateService: StateService,
) {}
/**
* Get a make_join template for a room and user
*/
async makeJoin(
domain: string,
roomId: string,
userId: string,
version?: string,
): Promise<MakeJoinResponse> {
try {
const uri = FederationEndpoints.makeJoin(roomId, userId);
const queryParams: Record<string, string | string[]> = {};
if (version) {
queryParams.ver = version;
} else {
queryParams.ver = PersistentEventFactory.supportedRoomVersions;
}
return await this.requestService.get<MakeJoinResponse>(
domain,
uri,
queryParams,
);
} catch (error: any) {
this.logger.error({ msg: 'makeJoin failed', err: error });
throw error;
}
}
/**
* Send a join event to a remote server
*/
async sendJoin(
joinEvent: PersistentEventBase,
omitMembers = false,
): Promise<SendJoinResponse> {
try {
const event = joinEvent.event;
const uri = FederationEndpoints.sendJoinV2(
joinEvent.roomId,
joinEvent.eventId,
);
const queryParams = omitMembers ? { omit_members: 'true' } : undefined;
const residentServer = joinEvent.roomId.split(':').pop();
if (!residentServer) {
this.logger.debug({ msg: 'invalid room_id', event: joinEvent.event });
throw new Error(
`invalid room_id ${joinEvent.roomId}, no server_name part`,
);
}
return await this.requestService.put<SendJoinResponse>(
residentServer,
uri,
event,
queryParams,
);
} catch (error: any) {
this.logger.error({ msg: 'sendJoin failed', err: error });
throw error;
}
}
async makeLeave(
domain: string,
roomId: string,
userId: string,
): Promise<{ event: Pdu; room_version: string }> {
try {
const uri = FederationEndpoints.makeLeave(roomId, userId);
return await this.requestService.get<{
event: Pdu;
room_version: string;
}>(domain, uri);
} catch (error: any) {
this.logger.error({ msg: 'makeLeave failed', err: error });
throw error;
}
}
async sendLeave(leaveEvent: PersistentEventBase): Promise<void> {
try {
const uri = FederationEndpoints.sendLeave(
leaveEvent.roomId,
leaveEvent.eventId,
);
const residentServer = leaveEvent.roomId.split(':').pop();
if (!residentServer) {
this.logger.debug({ msg: 'invalid room_id', event: leaveEvent.event });
throw new Error(
`invalid room_id ${leaveEvent.roomId}, no server_name part`,
);
}
await this.requestService.put<void>(
residentServer,
uri,
leaveEvent.event,
);
} catch (error: any) {
this.logger.error({ msg: 'sendLeave failed', err: error });
throw error;
}
}
/**
* Send a transaction to a remote server
*/
async sendTransaction(
domain: string,
transaction: Transaction,
): Promise<SendTransactionResponse> {
try {
const txnId = Date.now().toString();
const uri = FederationEndpoints.sendTransaction(txnId);
return await this.requestService.put<SendTransactionResponse>(
domain,
uri,
transaction,
);
} catch (error: any) {
this.logger.error({ msg: 'sendTransaction failed', err: error });
throw error;
}
}
/**
* Send an event to a remote server
*/
async sendEvent<T extends Pdu>(
domain: string,
event: T,
): Promise<SendTransactionResponse> {
try {
const transaction: Transaction = {
origin: this.configService.serverName,
origin_server_ts: Date.now(),
pdus: [event],
};
return await this.sendTransaction(domain, transaction);
} catch (error: any) {
this.logger.error({ msg: 'sendEvent failed', err: error });
throw error;
}
}
/**
* Get events from a remote server
*/
async getEvent(domain: string, eventId: string): Promise<Pdu> {
try {
const uri = FederationEndpoints.getEvent(eventId);
return await this.requestService.get<Pdu>(domain, uri);
} catch (error: any) {
this.logger.error({ msg: 'getEvent failed', err: error });
throw error;
}
}
/**
* Get events from a remote server
*/
async getMissingEvents(
domain: string,
roomId: string,
earliestEvents: EventID[],
latestEvents: EventID[],
limit = 10,
minDepth = 0,
): Promise<{ events: Pdu[] }> {
try {
const uri = FederationEndpoints.getMissingEvents(roomId);
return await this.requestService.post<{ events: Pdu[] }>(domain, uri, {
earliest_events: earliestEvents,
latest_events: latestEvents,
limit,
min_depth: minDepth,
});
} catch (error: any) {
this.logger.error({ msg: 'getEvent failed', err: error });
throw error;
}
}
/**
* Get state for a room from remote server
*/
async getState(
domain: string,
roomId: string,
eventId: string,
): Promise<EventBase> {
try {
const uri = FederationEndpoints.getState(roomId);
const queryParams = { event_id: eventId };
return await this.requestService.get<EventBase>(domain, uri, queryParams);
} catch (error: any) {
this.logger.error({ msg: 'getState failed', err: error });
throw error;
}
}
/**
* Get state IDs for a room from remote server
*/
async getStateIds(domain: string, roomId: string): Promise<EventBase[]> {
try {
const uri = FederationEndpoints.getStateIds(roomId);
return await this.requestService.get<EventBase[]>(domain, uri);
} catch (error: any) {
this.logger.error({ msg: 'getStateIds failed', err: error });
throw error;
}
}
/**
* Get server version information
*/
async getVersion(domain: string): Promise<Version> {
try {
return await this.requestService.get<Version>(
domain,
FederationEndpoints.version,
);
} catch (error: any) {
this.logger.error({ msg: 'getVersion failed', err: error });
throw error;
}
}
// invite user from another homeserver to our homeserver
async inviteUser(inviteEvent: PersistentEventBase, roomVersion: string) {
const uri = FederationEndpoints.inviteV2(
inviteEvent.roomId,
inviteEvent.eventId,
);
if (!inviteEvent.stateKey) {
this.logger.debug({ msg: 'invalid state_key', event: inviteEvent.event });
throw new Error(
'failed to send invite request, invite has invalid state_key',
);
}
const residentServer = inviteEvent.stateKey.split(':').pop();
if (!residentServer) {
throw new Error(
`invalid state_key ${inviteEvent.stateKey}, no domain found, failed to send invite`,
);
}
return await this.requestService.put<any>(residentServer, uri, {
event: inviteEvent.event,
room_version: roomVersion,
invite_room_state: await this.stateService.getStrippedRoomState(
inviteEvent.roomId,
),
});
}
async sendEventToAllServersInRoom(event: PersistentEventBase) {
const servers = await this.stateService.getServerSetInRoom(event.roomId);
if (event.stateKey) {
const server = extractDomainFromId(event.stateKey);
// TODO: fgetser
if (!servers.has(server)) {
servers.add(server);
}
}
for (const server of servers) {
if (server === event.origin) {
this.logger.info(
`Skipping transaction to event origin: ${event.origin}`,
);
continue;
}
if (server === this.configService.serverName) {
this.logger.info(`Skipping transaction to local server: ${server}`);
continue;
}
// TODO: signing should happen here over local persisting
// should be handled in transaction queue implementation
await this.stateService.signEvent(event);
const txn: Transaction = {
origin: this.configService.serverName,
origin_server_ts: Date.now(),
pdus: [event.event],
edus: [],
};
this.logger.info({
transaction: txn,
msg: `Sending event ${event.eventId} to server: ${server}`,
});
try {
await this.sendTransaction(server, txn);
} catch (error) {
this.logger.error({
msg: `Failed to send event ${event.eventId} to server: ${server}`,
err: error,
});
}
}
}
async sendEDUToServers(edus: BaseEDU[], servers: string[]): Promise<void> {
// Process servers sequentially to avoid concurrent transactions per Matrix spec
for (const server of servers) {
if (server === this.configService.serverName) {
this.logger.info(`Skipping EDU to local server: ${server}`);
continue;
}
// Respect Matrix spec transaction limits: max 100 EDUs per transaction
const maxEDUsPerTransaction = 100;
const batches = [];
for (let i = 0; i < edus.length; i += maxEDUsPerTransaction) {
batches.push(edus.slice(i, i + maxEDUsPerTransaction));
}
for (const batch of batches) {
const txn: Transaction = {
origin: this.configService.serverName,
origin_server_ts: Date.now(),
pdus: [],
edus: batch,
};
this.logger.info(`Sending ${batch.length} EDUs to server: ${server}`);
try {
await this.sendTransaction(server, txn);
} catch (error) {
this.logger.error({
msg: `Failed to send EDUs to server: ${server}`,
err: error,
});
// Continue with next batch/server even if one fails
}
}
}
}
}