forked from nkuntz1934/matrix-workers
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRoomJoinWorkflow.ts
More file actions
296 lines (259 loc) · 9.4 KB
/
RoomJoinWorkflow.ts
File metadata and controls
296 lines (259 loc) · 9.4 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
// Room Join Workflow - Durable execution for reliable room joins
//
// This workflow handles room joins with:
// - Automatic retry on failures
// - Federation handshake (make_join → send_join) with backoff
// - Batched member notifications
// - Step persistence for resume on failure
import { WorkflowEntrypoint, WorkflowEvent, WorkflowStep } from 'cloudflare:workers';
import type { Env } from '../types';
import { generateEventId } from '../utils/ids';
import {
storeEvent,
updateMembership,
getRoomMembers,
getStateEvent,
getRoomEvents,
getMembership,
} from '../services/database';
// Parameters passed when triggering the workflow
export interface JoinParams {
roomId: string;
userId: string;
displayName?: string;
avatarUrl?: string;
isRemote: boolean;
remoteServer?: string;
reason?: string;
}
// Result returned when workflow completes
export interface JoinResult {
eventId: string;
roomId: string;
success: boolean;
error?: string;
}
// Serializable event data for workflow steps
// Using any for content to avoid TypeScript serialization issues with Cloudflare Workflows
interface SerializableEvent {
event_id: string;
room_id: string;
sender: string;
type: string;
state_key?: string;
content: any;
origin_server_ts: number;
depth: number;
auth_events: string[];
prev_events: string[];
}
export class RoomJoinWorkflow extends WorkflowEntrypoint<Env, JoinParams> {
async run(event: WorkflowEvent<JoinParams>, step: WorkflowStep): Promise<JoinResult> {
const { roomId, userId, isRemote, remoteServer, displayName, avatarUrl, reason } = event.payload;
console.log('[RoomJoinWorkflow] Starting join', { roomId, userId, isRemote, remoteServer });
try {
// Step 1: For remote joins, get join template from remote server
let remoteEventTemplate: { room_version: string; event: any } | null = null;
if (isRemote && remoteServer) {
remoteEventTemplate = await step.do('make-join', {
retries: {
limit: 3,
delay: 5000, // 5 seconds in milliseconds
backoff: 'exponential',
},
timeout: 30000, // 30 seconds in milliseconds
}, async () => {
return await this.makeJoinRequest(remoteServer, roomId, userId);
}) as { room_version: string; event: any } | null;
}
// Step 2: Create and sign the join event
const joinEventData = await step.do('create-event', async () => {
return await this.createJoinEvent({
roomId,
userId,
displayName,
avatarUrl,
reason,
remoteEventTemplate,
});
}) as SerializableEvent;
// Step 3: For remote joins, send signed event to remote server
if (isRemote && remoteServer && joinEventData) {
await step.do('send-join', {
retries: {
limit: 3,
delay: 5000,
backoff: 'exponential',
},
timeout: 30000,
}, async () => {
return await this.sendJoinRequest(remoteServer, roomId, joinEventData);
});
}
// Step 4: Persist event and membership locally
await step.do('persist', async () => {
await storeEvent(this.env.DB, joinEventData);
await updateMembership(this.env.DB, roomId, userId, 'join', joinEventData.event_id);
});
// Step 5: Get room members for notification
const members = await step.do('get-members', async () => {
const memberList = await getRoomMembers(this.env.DB, roomId);
// Exclude the joining user from notifications
return memberList.filter(m => m.userId !== userId).map(m => ({ userId: m.userId }));
}) as Array<{ userId: string }>;
// Step 6: Notify members in batches of 50
const BATCH_SIZE = 50;
for (let i = 0; i < members.length; i += BATCH_SIZE) {
const batch = members.slice(i, i + BATCH_SIZE);
await step.do(`notify-batch-${i}`, async () => {
await this.notifyMemberBatch(batch, joinEventData);
});
}
console.log('[RoomJoinWorkflow] Join completed successfully', { roomId, userId, eventId: joinEventData.event_id });
return {
eventId: joinEventData.event_id,
roomId,
success: true,
};
} catch (error) {
console.error('[RoomJoinWorkflow] Join failed', { roomId, userId, error });
return {
eventId: '',
roomId,
success: false,
error: error instanceof Error ? error.message : 'Unknown error',
};
}
}
// Make a make_join request to a remote server
private async makeJoinRequest(
remoteServer: string,
roomId: string,
userId: string
): Promise<{ room_version: string; event: any }> {
console.log('[RoomJoinWorkflow] Making make_join request', { remoteServer, roomId, userId });
const url = `https://${remoteServer}/_matrix/federation/v1/make_join/${encodeURIComponent(roomId)}/${encodeURIComponent(userId)}`;
const response = await fetch(url, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
});
if (!response.ok) {
const error = await response.text();
throw new Error(`make_join failed: ${response.status} ${error}`);
}
const result = await response.json() as { room_version: string; event: any };
return result;
}
// Create a join event (either from remote template or local state)
private async createJoinEvent(params: {
roomId: string;
userId: string;
displayName?: string;
avatarUrl?: string;
reason?: string;
remoteEventTemplate?: { room_version: string; event: any } | null;
}): Promise<SerializableEvent> {
const { roomId, userId, displayName, avatarUrl, reason, remoteEventTemplate } = params;
let authEvents: string[] = [];
let prevEvents: string[] = [];
let depth = 1;
if (remoteEventTemplate?.event) {
// Use template from remote server
authEvents = remoteEventTemplate.event.auth_events || [];
prevEvents = remoteEventTemplate.event.prev_events || [];
depth = remoteEventTemplate.event.depth || 1;
} else {
// Get local room state
const createEvent = await getStateEvent(this.env.DB, roomId, 'm.room.create');
const joinRulesEvent = await getStateEvent(this.env.DB, roomId, 'm.room.join_rules');
const powerLevelsEvent = await getStateEvent(this.env.DB, roomId, 'm.room.power_levels');
const currentMembership = await getMembership(this.env.DB, roomId, userId);
if (createEvent) authEvents.push(createEvent.event_id);
if (joinRulesEvent) authEvents.push(joinRulesEvent.event_id);
if (powerLevelsEvent) authEvents.push(powerLevelsEvent.event_id);
if (currentMembership) authEvents.push(currentMembership.eventId);
const { events: latestEvents } = await getRoomEvents(this.env.DB, roomId, undefined, 1);
prevEvents = latestEvents.map(e => e.event_id);
depth = (latestEvents[0]?.depth ?? 0) + 1;
}
const eventId = await generateEventId(this.env.SERVER_NAME);
const memberContent: any = {
membership: 'join',
};
if (displayName) {
memberContent.displayname = displayName;
}
if (avatarUrl) {
memberContent.avatar_url = avatarUrl;
}
if (reason) {
memberContent.reason = reason;
}
const event: SerializableEvent = {
event_id: eventId,
room_id: roomId,
sender: userId,
type: 'm.room.member',
state_key: userId,
content: memberContent,
origin_server_ts: Date.now(),
depth,
auth_events: authEvents,
prev_events: prevEvents,
};
return event;
}
// Send a send_join request to a remote server
private async sendJoinRequest(
remoteServer: string,
roomId: string,
joinEvent: SerializableEvent
): Promise<any> {
console.log('[RoomJoinWorkflow] Sending send_join request', { remoteServer, roomId, eventId: joinEvent.event_id });
const url = `https://${remoteServer}/_matrix/federation/v1/send_join/${encodeURIComponent(roomId)}/${encodeURIComponent(joinEvent.event_id)}`;
const response = await fetch(url, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(joinEvent),
});
if (!response.ok) {
const error = await response.text();
throw new Error(`send_join failed: ${response.status} ${error}`);
}
const result = await response.json();
return result;
}
// Notify a batch of members about the join
private async notifyMemberBatch(
members: Array<{ userId: string }>,
joinEvent: SerializableEvent
): Promise<void> {
const promises = members.map(async (member) => {
try {
const syncDO = this.env.SYNC;
const doId = syncDO.idFromName(member.userId);
const stub = syncDO.get(doId);
await stub.fetch(new Request('http://internal/notify', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
roomId: joinEvent.room_id,
eventId: joinEvent.event_id,
eventType: joinEvent.type,
}),
}));
} catch (error) {
console.error('[RoomJoinWorkflow] Failed to notify member', {
userId: member.userId,
error: error instanceof Error ? error.message : 'Unknown error',
});
// Don't throw - continue notifying other members
}
});
await Promise.all(promises);
}
}