forked from nkuntz1934/matrix-workers
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsliding-sync.ts
More file actions
2105 lines (1841 loc) · 77.8 KB
/
sliding-sync.ts
File metadata and controls
2105 lines (1841 loc) · 77.8 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
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
// Sliding Sync API (MSC3575 & MSC4186)
// Implements both the original sliding sync and simplified sliding sync
import { Hono, type Context } from 'hono';
import type { AppEnv } from '../types';
import { Errors } from '../utils/errors';
import { requireAuth } from '../middleware/auth';
import { getTypingForRooms } from './typing';
import { getReceiptsForRooms } from './receipts';
import { countNotificationsWithRules } from '../services/push-rule-evaluator';
// Room cache helper available for future optimizations
// import { getRoomMetadata, invalidateRoomCache, type RoomMetadata } from '../services/room-cache';
const app = new Hono<AppEnv>();
// Types for sliding sync
interface SlidingSyncRequest {
// Connection tracking
conn_id?: string;
pos?: string;
txn_id?: string;
timeout?: number;
// MSC3575 style
delta_token?: string;
// Room lists
lists?: Record<string, SyncListConfig>;
// Direct room subscriptions
room_subscriptions?: Record<string, RoomSubscription>;
unsubscribe_rooms?: string[];
// Extensions
extensions?: ExtensionsRequest;
}
interface SyncListConfig {
ranges?: [number, number][]; // MSC3575
range?: [number, number]; // MSC4186
sort?: string[];
required_state?: [string, string][];
timeline_limit?: number;
filters?: SlidingRoomFilter;
bump_event_types?: string[];
}
interface RoomSubscription {
required_state?: [string, string][];
timeline_limit?: number;
include_old_rooms?: {
timeline_limit?: number;
required_state?: [string, string][];
};
}
interface SlidingRoomFilter {
is_dm?: boolean;
spaces?: string[];
is_encrypted?: boolean;
is_invite?: boolean;
is_tombstoned?: boolean;
room_types?: string[];
not_room_types?: string[];
room_name_like?: string;
tags?: string[];
not_tags?: string[];
}
interface ExtensionsRequest {
to_device?: {
enabled?: boolean;
since?: string;
limit?: number;
};
e2ee?: {
enabled?: boolean;
};
account_data?: {
enabled?: boolean;
lists?: string[];
rooms?: string[];
};
typing?: {
enabled?: boolean;
lists?: string[];
rooms?: string[];
};
receipts?: {
enabled?: boolean;
lists?: string[];
rooms?: string[];
};
presence?: {
enabled?: boolean;
};
}
interface SlidingSyncResponse {
pos: string;
txn_id?: string;
lists: Record<string, SyncListResult>;
rooms: Record<string, RoomResult>;
extensions: ExtensionsResponse;
delta_token?: string;
}
interface SyncListResult {
count: number;
ops?: RoomListOperation[];
}
interface RoomListOperation {
op: 'SYNC' | 'DELETE' | 'INSERT' | 'INVALIDATE';
range?: [number, number];
index?: number;
room_ids?: string[];
room_id?: string;
}
interface RoomResult {
name?: string;
avatar?: string;
topic?: string;
canonical_alias?: string;
heroes?: StrippedHero[];
initial?: boolean;
required_state?: any[];
timeline?: any[];
prev_batch?: string;
limited?: boolean;
joined_count?: number;
invited_count?: number;
notification_count?: number;
highlight_count?: number;
num_live?: number;
timestamp?: number;
bump_stamp?: number;
is_dm?: boolean;
invite_state?: any[];
knock_state?: any[];
membership?: string; // MSC4186: explicit membership status ('join', 'invite', 'knock', 'leave', 'ban')
}
interface StrippedHero {
user_id: string;
displayname?: string;
avatar_url?: string;
}
interface ExtensionsResponse {
to_device?: {
next_batch: string;
events: any[];
};
e2ee?: {
device_lists?: {
changed: string[];
left: string[];
};
device_one_time_keys_count?: Record<string, number>;
device_unused_fallback_key_types?: string[];
};
account_data?: {
global?: any[];
rooms?: Record<string, any[]>;
};
typing?: {
rooms?: Record<string, { type: string; content: { user_ids: string[] } }>;
};
receipts?: {
rooms?: Record<string, any>;
};
presence?: {
events?: any[];
};
}
// Connection state stored in Durable Object (previously KV, migrated to avoid rate limits)
interface ConnectionState {
userId: string;
pos: number; // Actual stream_ordering from database
lastAccess: number;
roomStates: Record<string, {
lastStreamOrdering: number; // Last stream_ordering sent for this room
sentState: boolean;
}>;
listStates: Record<string, {
roomIds: string[];
count: number;
}>;
// Track last-sent notification counts to detect changes even without new timeline events
roomNotificationCounts?: Record<string, number>;
// Track last-sent m.fully_read event IDs to detect when user marks as read
roomFullyReadMarkers?: Record<string, string>;
// Track if initial sync has been completed to prevent ephemeral spam on reconnects
initialSyncComplete?: boolean;
// Track rooms we've sent as "read" (notification_count = 0) to avoid resending
roomSentAsRead?: Record<string, boolean>;
}
// Helper to get the current maximum stream ordering from the database
async function getCurrentStreamPosition(db: D1Database): Promise<number> {
const result = await db.prepare(
`SELECT MAX(stream_ordering) as max_pos FROM events`
).first<{ max_pos: number | null }>();
return result?.max_pos ?? 0;
}
// Helper to get or create connection state using Durable Object (not KV - avoids rate limits)
async function getConnectionState(
syncDO: DurableObjectNamespace,
userId: string,
connId: string
): Promise<ConnectionState | null> {
// Use userId as the DO ID so each user has their own DO instance
const doId = syncDO.idFromName(userId);
const stub = syncDO.get(doId);
try {
const response = await stub.fetch(
new URL(`http://internal/sliding-sync/state?conn_id=${encodeURIComponent(connId)}`),
{ method: 'GET' }
);
if (!response.ok) {
// DO returned error (400 for bad params, 500 for internal error)
// Throw so caller knows DO is unavailable vs state not found
const errorText = await response.text().catch(() => 'unknown error');
throw new Error(`DO fetch failed: ${response.status} - ${errorText}`);
}
// 200 with null body means state not found (this is expected for new connections)
// 200 with state object means found
const data = await response.json();
return data as ConnectionState | null;
} catch (error) {
// Log but rethrow - caller should handle DO unavailability
console.error('[sliding-sync] Failed to get connection state from DO:', error);
throw error;
}
}
async function saveConnectionState(
syncDO: DurableObjectNamespace,
userId: string,
connId: string,
state: ConnectionState
): Promise<void> {
// Use userId as the DO ID so each user has their own DO instance
const doId = syncDO.idFromName(userId);
const stub = syncDO.get(doId);
try {
const response = await stub.fetch(
new URL(`http://internal/sliding-sync/state?conn_id=${encodeURIComponent(connId)}`),
{
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(state),
}
);
if (!response.ok) {
const errorText = await response.text();
throw new Error(`DO save failed: ${response.status} - ${errorText}`);
}
} catch (error) {
// Log but don't throw - state can be rebuilt on next sync
console.error('[sliding-sync] Failed to save connection state to DO:', error);
}
}
// Get rooms for a user with optional filtering
// OPTIMIZED: Uses consolidated query with subqueries to avoid N+1 problem
async function getUserRooms(
db: D1Database,
userId: string,
filters?: SlidingRoomFilter,
sort?: string[]
): Promise<{ roomId: string; membership: string; lastActivity: number; name?: string; isDm: boolean }[]> {
// Consolidated query with subqueries for room name and member count
// This eliminates N+1 queries by fetching all data in a single query
let query = `
SELECT
rm.room_id,
rm.membership,
COALESCE(
(SELECT MAX(origin_server_ts) FROM events WHERE room_id = rm.room_id),
r.created_at
) as last_activity,
-- Subquery for room name (JSON_EXTRACT is SQLite function)
(SELECT JSON_EXTRACT(e.content, '$.name')
FROM room_state rs
JOIN events e ON rs.event_id = e.event_id
WHERE rs.room_id = rm.room_id AND rs.event_type = 'm.room.name'
LIMIT 1
) as room_name,
-- Subquery for member count (for DM detection)
(SELECT COUNT(*)
FROM room_memberships rm2
WHERE rm2.room_id = rm.room_id AND rm2.membership = 'join'
) as member_count
FROM room_memberships rm
JOIN rooms r ON rm.room_id = r.room_id
WHERE rm.user_id = ?
`;
const params: any[] = [userId];
// Apply filters
if (filters?.is_invite) {
query += ` AND rm.membership = 'invite'`;
} else if (filters?.is_tombstoned) {
// Check for tombstone state
query += ` AND EXISTS (SELECT 1 FROM room_state rs JOIN events e ON rs.event_id = e.event_id WHERE rs.room_id = rm.room_id AND rs.event_type = 'm.room.tombstone')`;
} else {
// By default, only return rooms the user has joined or been invited to
query += ` AND rm.membership IN ('join', 'invite')`;
}
// Default sort: by recency
const sortBy = sort || ['by_recency'];
if (sortBy.includes('by_recency')) {
query += ` ORDER BY last_activity DESC`;
} else if (sortBy.includes('by_name')) {
query += ` ORDER BY COALESCE(room_name, rm.room_id) ASC`;
} else {
query += ` ORDER BY last_activity DESC`;
}
const result = await db.prepare(query).bind(...params).all();
const rooms: { roomId: string; membership: string; lastActivity: number; name?: string; isDm: boolean }[] = [];
for (const row of result.results as any[]) {
const name = row.room_name as string | null | undefined;
const memberCount = row.member_count as number;
// A DM is typically a room with 2 members and no explicit name
const isDm = memberCount <= 2 && !name;
// Apply filters in memory (already have all data)
if (filters?.room_name_like && name) {
if (!name.toLowerCase().includes(filters.room_name_like.toLowerCase())) {
continue;
}
}
if (filters?.is_dm !== undefined) {
if (filters.is_dm && !isDm) continue;
if (!filters.is_dm && isDm) continue;
}
rooms.push({
roomId: row.room_id,
membership: row.membership,
lastActivity: row.last_activity,
name: name || undefined,
isDm,
});
}
return rooms;
}
// Get room data for response
// OPTIMIZED: Uses DB.batch() to fetch all room metadata in a single network call
async function getRoomData(
db: D1Database,
roomId: string,
userId: string,
config: {
requiredState?: [string, string][];
timelineLimit?: number;
initial?: boolean;
sinceStreamOrdering?: number; // Only return events after this stream position
}
): Promise<RoomResult & { maxStreamOrdering?: number }> {
const result: RoomResult & { maxStreamOrdering?: number } = {
membership: 'join', // MSC4186: explicitly indicate this is a joined room
};
// OPTIMIZATION: Batch all metadata queries into a single network call
// This reduces 8+ sequential queries to 1 batched call
const [
roomResult,
nameResult,
avatarResult,
topicResult,
aliasResult,
joinedCountResult,
invitedCountResult,
heroesResult,
] = await db.batch([
// 1. Room info
db.prepare(`SELECT room_id, created_at FROM rooms WHERE room_id = ?`).bind(roomId),
// 2. Room name
db.prepare(`
SELECT e.content FROM room_state rs
JOIN events e ON rs.event_id = e.event_id
WHERE rs.room_id = ? AND rs.event_type = 'm.room.name'
`).bind(roomId),
// 3. Room avatar
db.prepare(`
SELECT e.content FROM room_state rs
JOIN events e ON rs.event_id = e.event_id
WHERE rs.room_id = ? AND rs.event_type = 'm.room.avatar'
`).bind(roomId),
// 4. Room topic
db.prepare(`
SELECT e.content FROM room_state rs
JOIN events e ON rs.event_id = e.event_id
WHERE rs.room_id = ? AND rs.event_type = 'm.room.topic'
`).bind(roomId),
// 5. Canonical alias
db.prepare(`
SELECT e.content FROM room_state rs
JOIN events e ON rs.event_id = e.event_id
WHERE rs.room_id = ? AND rs.event_type = 'm.room.canonical_alias'
`).bind(roomId),
// 6. Joined member count
db.prepare(`SELECT COUNT(*) as count FROM room_memberships WHERE room_id = ? AND membership = 'join'`).bind(roomId),
// 7. Invited member count
db.prepare(`SELECT COUNT(*) as count FROM room_memberships WHERE room_id = ? AND membership = 'invite'`).bind(roomId),
// 8. Heroes (other members for display)
db.prepare(`
SELECT user_id, display_name, avatar_url
FROM room_memberships
WHERE room_id = ? AND membership = 'join' AND user_id != ?
LIMIT 5
`).bind(roomId, userId),
]);
// Check if room exists
const room = roomResult.results[0] as { room_id: string; created_at: number } | undefined;
if (!room) {
return result;
}
// Process batched results
result.initial = config.initial;
// Member counts
const joinedCount = (joinedCountResult.results[0] as { count: number } | undefined)?.count || 0;
const invitedCount = (invitedCountResult.results[0] as { count: number } | undefined)?.count || 0;
result.joined_count = joinedCount;
result.invited_count = invitedCount;
result.is_dm = joinedCount <= 2;
// Room name
const nameEvent = nameResult.results[0] as { content: string } | undefined;
if (nameEvent) {
try {
result.name = JSON.parse(nameEvent.content).name;
} catch { /* ignore */ }
}
// Room avatar
const avatarEvent = avatarResult.results[0] as { content: string } | undefined;
if (avatarEvent) {
try {
result.avatar = JSON.parse(avatarEvent.content).url;
} catch { /* ignore */ }
}
// Room topic
const topicEvent = topicResult.results[0] as { content: string } | undefined;
if (topicEvent) {
try {
result.topic = JSON.parse(topicEvent.content).topic;
} catch { /* ignore */ }
}
// Canonical alias
const aliasEvent = aliasResult.results[0] as { content: string } | undefined;
if (aliasEvent) {
try {
result.canonical_alias = JSON.parse(aliasEvent.content).alias;
} catch { /* ignore */ }
}
// Heroes (only used when room has no name)
if (!result.name) {
result.heroes = (heroesResult.results as any[]).map(h => ({
user_id: h.user_id,
displayname: h.display_name,
avatar_url: h.avatar_url,
}));
}
// Get required state
if (config.requiredState && config.requiredState.length > 0) {
result.required_state = [];
for (const [eventType, stateKey] of config.requiredState) {
let stateQuery = `
SELECT e.event_id, e.event_type, e.state_key, e.content, e.sender, e.origin_server_ts, e.unsigned
FROM room_state rs
JOIN events e ON rs.event_id = e.event_id
WHERE rs.room_id = ?
`;
const stateParams: any[] = [roomId];
if (eventType !== '*') {
stateQuery += ` AND rs.event_type = ?`;
stateParams.push(eventType);
}
if (stateKey !== '*' && stateKey !== '') {
stateQuery += ` AND rs.state_key = ?`;
// Handle $ME placeholder - replace with actual user ID
const resolvedStateKey = stateKey === '$ME' ? userId : stateKey;
stateParams.push(resolvedStateKey);
} else if (stateKey === '') {
stateQuery += ` AND rs.state_key = ''`;
}
const stateEvents = await db.prepare(stateQuery).bind(...stateParams).all();
for (const event of stateEvents.results as any[]) {
try {
result.required_state.push({
type: event.event_type,
state_key: event.state_key,
content: JSON.parse(event.content),
sender: event.sender,
origin_server_ts: event.origin_server_ts,
event_id: event.event_id,
unsigned: event.unsigned ? JSON.parse(event.unsigned) : undefined,
});
} catch { /* ignore parse errors */ }
}
}
}
// Get timeline
if (config.timelineLimit && config.timelineLimit > 0) {
let timelineQuery: string;
let timelineParams: (string | number)[];
const isIncremental = config.sinceStreamOrdering !== undefined && config.sinceStreamOrdering > 0;
// For incremental sync (sinceStreamOrdering provided), only get new events
// For initial sync, get the last N events
// Fetch one extra event to determine if there are more events than the limit
const fetchLimit = config.timelineLimit + 1;
if (isIncremental) {
// Incremental: get events since the last sync position
timelineQuery = `
SELECT event_id, event_type, state_key, content, sender, origin_server_ts, unsigned, depth, stream_ordering
FROM events
WHERE room_id = ? AND stream_ordering > ?
ORDER BY stream_ordering ASC
LIMIT ?
`;
timelineParams = [roomId, config.sinceStreamOrdering!, fetchLimit];
} else {
// Initial: get the most recent events
timelineQuery = `
SELECT event_id, event_type, state_key, content, sender, origin_server_ts, unsigned, depth, stream_ordering
FROM events
WHERE room_id = ?
ORDER BY stream_ordering DESC
LIMIT ?
`;
timelineParams = [roomId, fetchLimit];
}
const timelineEvents = await db.prepare(timelineQuery).bind(...timelineParams).all();
// Check if there are more events than the limit
const hasMoreEvents = timelineEvents.results.length > config.timelineLimit;
// Only use up to timelineLimit events
const eventsToUse = timelineEvents.results.slice(0, config.timelineLimit) as any[];
// For initial sync, reverse to get chronological order
const eventsToProcess = isIncremental ? eventsToUse : eventsToUse.reverse();
result.timeline = eventsToProcess.map(event => {
try {
return {
type: event.event_type,
event_id: event.event_id,
sender: event.sender,
origin_server_ts: event.origin_server_ts,
content: JSON.parse(event.content),
state_key: event.state_key || undefined,
unsigned: event.unsigned ? JSON.parse(event.unsigned) : undefined,
};
} catch {
return {
type: event.event_type,
event_id: event.event_id,
sender: event.sender,
origin_server_ts: event.origin_server_ts,
content: {},
state_key: event.state_key || undefined,
};
}
});
// Track the max stream_ordering we're sending
if (eventsToProcess.length > 0) {
const maxEvent = eventsToProcess[eventsToProcess.length - 1];
result.maxStreamOrdering = maxEvent.stream_ordering;
}
// Set num_live for incremental syncs (tells client how many new events)
if (isIncremental) {
result.num_live = result.timeline.length;
}
// Get prev_batch for pagination (only useful for initial sync really)
if (eventsToProcess.length > 0) {
const oldestEvent = eventsToProcess[0];
result.prev_batch = `s${oldestEvent.stream_ordering || oldestEvent.depth}`;
}
// limited: true means there are more events than what was returned
// For incremental syncs: only true if there are actually more new events
// For initial syncs: true if there are more historical events
result.limited = hasMoreEvents;
}
// Get notification and highlight counts using push rule evaluation
const counts = await countNotificationsWithRules(db, userId, roomId);
result.notification_count = counts.notification_count;
result.highlight_count = counts.highlight_count;
// Get last activity timestamp
const lastEvent = await db.prepare(`
SELECT MAX(origin_server_ts) as ts FROM events WHERE room_id = ?
`).bind(roomId).first<{ ts: number }>();
if (lastEvent?.ts) {
result.bump_stamp = lastEvent.ts;
result.timestamp = lastEvent.ts;
}
return result;
}
// Get stripped invite state for invited rooms
// Per Matrix spec, invited rooms only see limited "stripped state"
async function getInviteRoomData(
db: D1Database,
roomId: string,
userId: string
): Promise<RoomResult> {
const result: RoomResult = {
initial: true,
membership: 'invite', // MSC4186: explicitly indicate this is an invited room
};
// Get stripped state events for invited users
// These are the key events that help the user understand what they're invited to
const strippedStateTypes = [
'm.room.create',
'm.room.name',
'm.room.avatar',
'm.room.topic',
'm.room.canonical_alias',
'm.room.encryption',
'm.room.member', // Only for inviter and invitee
];
const inviteState: any[] = [];
for (const eventType of strippedStateTypes) {
let query = `
SELECT e.event_type, e.state_key, e.content, e.sender
FROM room_state rs
JOIN events e ON rs.event_id = e.event_id
WHERE rs.room_id = ? AND rs.event_type = ?
`;
const params: any[] = [roomId, eventType];
// For member events, only include the invitee's own membership
if (eventType === 'm.room.member') {
query += ` AND rs.state_key = ?`;
params.push(userId);
}
const events = await db.prepare(query).bind(...params).all();
for (const event of events.results as any[]) {
try {
inviteState.push({
type: event.event_type,
state_key: event.state_key,
content: JSON.parse(event.content),
sender: event.sender,
});
} catch { /* ignore parse errors */ }
}
}
result.invite_state = inviteState;
// Extract name from state if available
const nameEvent = inviteState.find(e => e.type === 'm.room.name');
if (nameEvent?.content?.name) {
result.name = nameEvent.content.name;
}
// Extract avatar from state if available
const avatarEvent = inviteState.find(e => e.type === 'm.room.avatar');
if (avatarEvent?.content?.url) {
result.avatar = avatarEvent.content.url;
}
// Get member counts
const joinedCount = await db.prepare(`
SELECT COUNT(*) as count FROM room_memberships WHERE room_id = ? AND membership = 'join'
`).bind(roomId).first<{ count: number }>();
const invitedCount = await db.prepare(`
SELECT COUNT(*) as count FROM room_memberships WHERE room_id = ? AND membership = 'invite'
`).bind(roomId).first<{ count: number }>();
result.joined_count = joinedCount?.count || 0;
result.invited_count = invitedCount?.count || 0;
return result;
}
// MSC3575 Sliding Sync endpoint
app.post('/_matrix/client/unstable/org.matrix.msc3575/sync', requireAuth(), async (c) => {
const userId = c.get('userId');
const db = c.env.DB;
const syncDO = c.env.SYNC; // Use Durable Object for connection state (not KV - avoids rate limits)
const cache = c.env.CACHE; // KV for presence lookups (read-only, no rate limit issues)
let body: SlidingSyncRequest;
try {
body = await c.req.json();
} catch {
return Errors.badJson().toResponse();
}
const connId = body.conn_id || 'default';
// Note: timeout is parsed but not used yet (for future long-polling support)
const _ = Math.min(body.timeout || 0, 30000); void _;
// Get current stream position from database
const currentStreamPos = await getCurrentStreamPosition(db);
// Get or create connection state
let connectionState: ConnectionState | null;
try {
connectionState = await getConnectionState(syncDO, userId, connId);
} catch (error) {
// DO unavailable - return error so client knows to retry
console.error('[sliding-sync MSC3575] DO unavailable:', error);
return c.json({
errcode: 'M_UNKNOWN',
error: 'Sync service temporarily unavailable',
}, 503);
}
// IMPORTANT: pos can be in query string OR body - check both
const queryPos = c.req.query('pos');
const posToken = queryPos || body.pos;
const sincePos = posToken ? parseInt(posToken) : 0;
// Note: isInitialSync is computed but not currently used (for future diagnostics)
void (!posToken || !connectionState);
// If client sends a pos but we don't have connection state, check if the pos
// is a valid stream position (could be from before a deployment or KV expiry)
if (posToken && !connectionState) {
if (sincePos <= currentStreamPos) {
// Valid position, create fresh connection state treating it as a reconnect
console.log('[sliding-sync MSC3575] Reconnecting with valid pos', sincePos, 'current:', currentStreamPos);
connectionState = {
userId,
pos: sincePos,
lastAccess: Date.now(),
roomStates: {},
listStates: {},
};
} else {
// Position is in the future - invalid
return c.json({
errcode: 'M_UNKNOWN_POS',
error: 'Unknown position token',
}, 400);
}
}
if (!connectionState) {
connectionState = {
userId,
pos: 0,
lastAccess: Date.now(),
roomStates: {},
listStates: {},
};
}
connectionState.pos = currentStreamPos;
connectionState.lastAccess = Date.now();
const response: SlidingSyncResponse = {
pos: String(currentStreamPos),
lists: {},
rooms: {},
extensions: {},
};
if (body.txn_id) {
response.txn_id = body.txn_id;
}
// Process lists
if (body.lists) {
for (const [listKey, listConfig] of Object.entries(body.lists)) {
const rooms = await getUserRooms(db, userId, listConfig.filters, listConfig.sort);
// Determine range to return
let startIndex = 0;
let endIndex = rooms.length - 1;
// MSC3575 uses ranges array
if (listConfig.ranges && listConfig.ranges.length > 0) {
startIndex = listConfig.ranges[0][0];
endIndex = Math.min(listConfig.ranges[0][1], rooms.length - 1);
}
// MSC4186 uses single range
else if (listConfig.range) {
startIndex = listConfig.range[0];
endIndex = Math.min(listConfig.range[1], rooms.length - 1);
}
const roomsInRange = rooms.slice(startIndex, endIndex + 1);
const roomIds = roomsInRange.map(r => r.roomId);
// Check if the list has changed since last sync
const previousListState = connectionState.listStates[listKey];
const listChanged = !previousListState ||
previousListState.count !== rooms.length ||
JSON.stringify(previousListState.roomIds) !== JSON.stringify(roomIds);
// Only include ops if the list changed (or it's an initial sync)
if (listChanged) {
response.lists[listKey] = {
count: rooms.length,
ops: [{
op: 'SYNC',
range: [startIndex, endIndex],
room_ids: roomIds,
}],
};
} else {
// List unchanged - just report count with no ops
response.lists[listKey] = {
count: rooms.length,
};
}
// Get room data for rooms in range
for (const roomInfo of roomsInRange) {
const roomState = connectionState.roomStates[roomInfo.roomId];
const isInitialRoom = !roomState?.sentState;
const roomSincePos = isInitialRoom ? 0 : (roomState?.lastStreamOrdering || 0);
// Handle invited rooms differently - they get invite_state not timeline
// Always include invited room data (small payload) so client doesn't lose invites on reconnect
if (roomInfo.membership === 'invite') {
const roomData = await getInviteRoomData(db, roomInfo.roomId, userId);
response.rooms[roomInfo.roomId] = roomData;
connectionState.roomStates[roomInfo.roomId] = {
sentState: true,
lastStreamOrdering: roomSincePos,
};
continue;
}
// For joined rooms, get full room data
const roomData = await getRoomData(db, roomInfo.roomId, userId, {
requiredState: listConfig.required_state,
timelineLimit: listConfig.timeline_limit || 10,
initial: isInitialRoom,
sinceStreamOrdering: isInitialRoom ? undefined : roomSincePos,
});
// Check if notification count changed (for marking rooms as read)
const hasPrevCount = roomInfo.roomId in (connectionState.roomNotificationCounts || {});
const prevNotificationCount = connectionState.roomNotificationCounts?.[roomInfo.roomId] ?? 0;
const currentNotificationCount = roomData.notification_count ?? 0;
const notificationCountChanged = hasPrevCount && currentNotificationCount !== prevNotificationCount;
// Check if m.fully_read marker changed
const fullyReadResult = await db.prepare(`
SELECT content FROM account_data
WHERE user_id = ? AND room_id = ? AND event_type = 'm.fully_read'
`).bind(userId, roomInfo.roomId).first<{ content: string }>();
let currentFullyRead = '';
if (fullyReadResult) {
try {
currentFullyRead = JSON.parse(fullyReadResult.content).event_id || '';
} catch { /* ignore */ }
}
const prevFullyRead = connectionState.roomFullyReadMarkers?.[roomInfo.roomId] ?? '';
const fullyReadChanged = currentFullyRead !== prevFullyRead && currentFullyRead !== '';
// Track if this is the first time we're sending this room as "read" (notification_count = 0)
// This ensures Element X receives the room with 0 unread count at least once
const firstTimeRead = currentNotificationCount === 0
&& !connectionState.roomSentAsRead?.[roomInfo.roomId];
// Include room if it's initial, has new events, notification count changed, fully_read changed, OR first time read
if (isInitialRoom || (roomData.timeline && roomData.timeline.length > 0) || notificationCountChanged || fullyReadChanged || firstTimeRead) {
response.rooms[roomInfo.roomId] = roomData;
// Update tracked state
connectionState.roomNotificationCounts = connectionState.roomNotificationCounts || {};
connectionState.roomNotificationCounts[roomInfo.roomId] = currentNotificationCount;
connectionState.roomFullyReadMarkers = connectionState.roomFullyReadMarkers || {};
connectionState.roomFullyReadMarkers[roomInfo.roomId] = currentFullyRead;
// Track room read status - set when read, clear when unread
connectionState.roomSentAsRead = connectionState.roomSentAsRead || {};
if (currentNotificationCount === 0) {
connectionState.roomSentAsRead[roomInfo.roomId] = true;
} else {
// Clear flag when there are unread messages so room will be included again when read
delete connectionState.roomSentAsRead[roomInfo.roomId];
}
}
// Mark as sent with stream ordering tracking
const newStreamOrdering = roomData.maxStreamOrdering || roomSincePos;
connectionState.roomStates[roomInfo.roomId] = {
sentState: true,
lastStreamOrdering: newStreamOrdering,
};
}
// Save list state
connectionState.listStates[listKey] = {
roomIds,
count: rooms.length,
};
}
}
// Process room subscriptions
if (body.room_subscriptions) {
for (const [roomId, subscription] of Object.entries(body.room_subscriptions)) {
// Check if user has access to this room
const membershipResult = await db.prepare(`
SELECT membership FROM room_memberships WHERE room_id = ? AND user_id = ?
`).bind(roomId, userId).first<{ membership: string }>();
if (!membershipResult) {
continue; // Skip rooms user isn't in
}
const roomState = connectionState.roomStates[roomId];
const isInitialRoom = !roomState?.sentState;
const roomSincePos = isInitialRoom ? 0 : (roomState?.lastStreamOrdering || 0);
// Handle invited rooms differently - they get invite_state not timeline
// Always include invited room data (small payload) so client doesn't lose invites on reconnect
if (membershipResult.membership === 'invite') {
const roomData = await getInviteRoomData(db, roomId, userId);
response.rooms[roomId] = roomData;
connectionState.roomStates[roomId] = {
sentState: true,
lastStreamOrdering: roomSincePos,
};
continue;
}
// For joined rooms, get full room data
const roomData = await getRoomData(db, roomId, userId, {
requiredState: subscription.required_state,
timelineLimit: subscription.timeline_limit || 10,
initial: isInitialRoom,
sinceStreamOrdering: isInitialRoom ? undefined : roomSincePos,
});
// Check if notification count changed (for marking rooms as read)
const hasPrevCount = roomId in (connectionState.roomNotificationCounts || {});
const prevNotificationCount = connectionState.roomNotificationCounts?.[roomId] ?? 0;
const currentNotificationCount = roomData.notification_count ?? 0;
const notificationCountChanged = hasPrevCount && currentNotificationCount !== prevNotificationCount;
// Check if m.fully_read marker changed
const fullyReadResult = await db.prepare(`
SELECT content FROM account_data
WHERE user_id = ? AND room_id = ? AND event_type = 'm.fully_read'
`).bind(userId, roomId).first<{ content: string }>();
let currentFullyRead = '';
if (fullyReadResult) {
try {
currentFullyRead = JSON.parse(fullyReadResult.content).event_id || '';
} catch { /* ignore */ }