flotilla/src/app/core/sync.ts

453 lines
11 KiB
TypeScript
Raw Normal View History

2025-10-06 18:23:19 +00:00
import {page} from "$app/stores"
import type {Unsubscriber} from "svelte/store"
import {derived, get} from "svelte/store"
2026-03-25 21:36:48 +00:00
import {last, call, ifLet, assoc, chunk, sleep, identity, WEEK, ago} from "@welshman/lib"
2025-10-06 18:23:19 +00:00
import {
getListTags,
getRelayTagValues,
WRAP,
2025-10-06 18:23:19 +00:00
ROOM_META,
2025-10-24 20:36:59 +00:00
ROOM_DELETE,
ROOM_ADMINS,
ROOM_MEMBERS,
ROOM_ADD_MEMBER,
ROOM_REMOVE_MEMBER,
2025-10-24 20:36:59 +00:00
ROOM_CREATE_PERMISSION,
RELAY_MEMBERS,
2025-10-28 18:29:59 +00:00
RELAY_ADD_MEMBER,
RELAY_REMOVE_MEMBER,
2025-10-06 18:23:19 +00:00
isSignedEvent,
2025-11-04 23:36:20 +00:00
unionFilters,
2026-03-25 21:36:48 +00:00
getTagValue,
2025-10-06 18:23:19 +00:00
} from "@welshman/util"
2026-03-25 21:36:48 +00:00
import type {Filter, TrustedEvent} from "@welshman/util"
2026-02-26 22:29:13 +00:00
import {request, requestOne, Difference, DifferenceEvent} from "@welshman/net"
2025-10-06 18:23:19 +00:00
import {
pubkey,
loadRelay,
2025-11-20 23:54:06 +00:00
userFollowList,
2025-11-20 23:12:16 +00:00
userRelayList,
userMessagingRelayList,
loadRelayList,
loadMessagingRelayList,
2025-11-20 23:54:06 +00:00
loadBlossomServerList,
2026-01-16 21:10:48 +00:00
loadBlockedRelayList,
2025-11-20 23:54:06 +00:00
loadFollowList,
loadMuteList,
2025-10-06 18:23:19 +00:00
loadProfile,
repository,
shouldUnwrap,
2025-10-06 18:23:19 +00:00
hasNegentropy,
2025-10-06 18:23:19 +00:00
} from "@welshman/app"
import {
2025-11-11 00:19:50 +00:00
REACTION_KINDS,
2025-10-28 22:46:25 +00:00
MESSAGE_KINDS,
2025-10-28 18:29:59 +00:00
CONTENT_KINDS,
2025-10-06 18:23:19 +00:00
INDEXER_RELAYS,
loadSettings,
2025-11-20 23:12:16 +00:00
loadGroupList,
userSpaceUrls,
2025-11-20 23:12:16 +00:00
userGroupList,
bootstrapPubkeys,
2025-10-06 18:23:19 +00:00
decodeRelay,
2025-11-20 23:12:16 +00:00
getSpaceUrlsFromGroupList,
getSpaceRoomsFromGroupList,
2025-10-28 18:29:59 +00:00
makeCommentFilter,
2026-02-18 01:15:00 +00:00
loadFeedsForPubkey,
2025-10-06 18:23:19 +00:00
} from "@app/core/state"
2025-10-06 18:23:19 +00:00
import {hasBlossomSupport} from "@app/core/commands"
import {LIVEKIT_PARTICIPANTS} from "@app/voice"
2025-10-06 18:23:19 +00:00
// Utils
type SyncOpts = {
url: string
2025-10-06 18:23:19 +00:00
signal: AbortSignal
filters: Filter[]
2026-03-25 21:36:48 +00:00
onEvent?: (event: TrustedEvent) => void
2025-10-06 18:23:19 +00:00
}
2026-03-25 21:36:48 +00:00
const pullOneWithFallback = async (
url: string,
filter: Filter,
signal: AbortSignal,
onEvent?: (event: TrustedEvent) => void,
) => {
2026-02-26 22:29:13 +00:00
const cachedEvents = repository.query([filter]).filter(isSignedEvent)
const since = last(cachedEvents.slice(10))?.created_at || 0
2026-03-25 21:36:48 +00:00
if (onEvent) {
for (const event of cachedEvents) {
onEvent(event)
}
}
2026-02-26 22:29:13 +00:00
const shouldFallback =
!hasNegentropy(url) ||
(await new Promise(resolve => {
const diff = new Difference({relay: url, filter, events: cachedEvents, signal})
diff.on(DifferenceEvent.Error, () => {
resolve(true)
})
diff.on(DifferenceEvent.Close, () => {
for (const ids of chunk(100, Array.from(diff.need))) {
2026-03-25 21:36:48 +00:00
requestOne({relay: url, signal, autoClose: true, filters: [{ids}], onEvent})
2026-02-26 22:29:13 +00:00
}
resolve(false)
})
}))
if (shouldFallback && !signal.aborted) {
2026-03-25 21:36:48 +00:00
request({relays: [url], signal, autoClose: true, filters: [{since, ...filter}], onEvent})
2026-02-26 22:29:13 +00:00
}
}
2026-03-25 21:36:48 +00:00
export const pullWithFallback = async ({url, signal, filters, onEvent}: SyncOpts) => {
2026-02-26 22:29:13 +00:00
await loadRelay(url)
if (signal.aborted) return
for (const filter of filters) {
2026-03-25 21:36:48 +00:00
pullOneWithFallback(url, filter, signal, onEvent)
2025-10-06 18:23:19 +00:00
}
}
2026-03-25 21:36:48 +00:00
const listen = ({url, signal, filters, onEvent}: SyncOpts) => {
const relays = [url]
2025-10-28 21:53:44 +00:00
2026-03-25 21:36:48 +00:00
request({relays, signal, filters: unionFilters(filters.map(assoc("limit", 0))), onEvent})
}
2026-03-25 21:36:48 +00:00
const pullAndListen = (options: SyncOpts) => {
pullWithFallback(options)
listen(options)
2025-10-28 18:29:59 +00:00
}
2025-10-06 18:23:19 +00:00
// Relays
2025-10-06 18:23:19 +00:00
const syncRelays = () => {
for (const url of INDEXER_RELAYS) {
loadRelay(url)
}
const unsubscribePage = page.subscribe($page => {
if ($page.params.relay) {
2025-10-06 18:23:19 +00:00
const url = decodeRelay($page.params.relay)
loadRelay(url)
hasBlossomSupport(url)
2025-10-06 18:23:19 +00:00
}
})
const unsubscribeSpaceUrls = userSpaceUrls.subscribe(urls => {
for (const url of urls) {
2025-10-06 18:23:19 +00:00
loadRelay(url)
}
})
return () => {
unsubscribePage()
unsubscribeSpaceUrls()
2025-10-06 18:23:19 +00:00
}
}
2025-10-06 18:23:19 +00:00
// User data
2025-10-28 18:29:59 +00:00
const syncUserSpaceMembership = (url: string) => {
const $pubkey = pubkey.get()
const controller = new AbortController()
if ($pubkey) {
pullAndListen({
url,
2025-10-28 18:29:59 +00:00
signal: controller.signal,
filters: [
2025-12-01 18:56:37 +00:00
{kinds: [RELAY_ADD_MEMBER], "#p": [$pubkey], limit: 1},
{kinds: [RELAY_REMOVE_MEMBER], "#p": [$pubkey], limit: 1},
{kinds: [ROOM_CREATE_PERMISSION], "#p": [$pubkey], limit: 1},
2025-10-28 18:29:59 +00:00
],
})
}
return () => controller.abort()
}
2025-10-30 22:33:34 +00:00
const syncUserRoomMembership = (url: string, h: string) => {
2025-10-28 18:29:59 +00:00
const $pubkey = pubkey.get()
const controller = new AbortController()
if ($pubkey) {
pullAndListen({
url,
2025-10-28 18:29:59 +00:00
signal: controller.signal,
filters: [
2025-12-01 18:56:37 +00:00
{kinds: [ROOM_ADD_MEMBER], "#p": [$pubkey], "#h": [h], limit: 1},
{kinds: [ROOM_REMOVE_MEMBER], "#p": [$pubkey], "#h": [h], limit: 1},
2025-10-28 18:29:59 +00:00
],
})
}
return () => controller.abort()
}
2025-10-06 18:23:19 +00:00
const syncUserData = () => {
2025-10-28 18:29:59 +00:00
const unsubscribersByKey = new Map<string, Unsubscriber>()
2025-12-01 18:56:37 +00:00
const unsubscribeGroupList = userGroupList.subscribe($userGroupList => {
if ($userGroupList) {
2025-10-28 18:29:59 +00:00
const keys = new Set<string>()
2025-12-01 18:56:37 +00:00
for (const url of getSpaceUrlsFromGroupList($userGroupList)) {
2025-10-28 18:29:59 +00:00
if (!unsubscribersByKey.has(url)) {
unsubscribersByKey.set(url, syncUserSpaceMembership(url))
}
keys.add(url)
2025-12-01 18:56:37 +00:00
for (const h of getSpaceRoomsFromGroupList(url, $userGroupList)) {
2025-10-30 22:33:34 +00:00
const key = `${url}'${h}`
2025-10-28 18:29:59 +00:00
if (!unsubscribersByKey.has(key)) {
2025-10-30 22:33:34 +00:00
unsubscribersByKey.set(key, syncUserRoomMembership(url, h))
2025-10-28 18:29:59 +00:00
}
keys.add(key)
}
}
for (const [key, unsubscribe] of unsubscribersByKey.entries()) {
if (!keys.has(key)) {
unsubscribersByKey.delete(key)
unsubscribe()
}
}
2025-10-06 18:23:19 +00:00
}
})
2025-12-01 18:56:37 +00:00
const unsubscribeRelayList = userRelayList.subscribe($userRelayList => {
if ($userRelayList) {
loadBlossomServerList($userRelayList.event.pubkey)
2026-01-16 21:10:48 +00:00
loadBlockedRelayList($userRelayList.event.pubkey)
2025-12-01 18:56:37 +00:00
loadFollowList($userRelayList.event.pubkey)
loadGroupList($userRelayList.event.pubkey)
loadMuteList($userRelayList.event.pubkey)
loadProfile($userRelayList.event.pubkey)
loadSettings($userRelayList.event.pubkey)
2026-02-18 01:15:00 +00:00
loadFeedsForPubkey($userRelayList.event.pubkey)
2025-10-06 18:23:19 +00:00
}
})
2025-12-01 18:56:37 +00:00
const unsubscribeFollows = userFollowList.subscribe(async $userFollowList => {
for (const pubkeys of chunk(10, get(bootstrapPubkeys))) {
2025-10-06 18:23:19 +00:00
// This isn't urgent, avoid clogging other stuff up
await sleep(1000)
2025-10-28 18:29:59 +00:00
await Promise.all(
2026-01-16 21:10:48 +00:00
pubkeys.flatMap(pk => [
loadRelayList(pk),
loadGroupList(pk),
loadProfile(pk),
loadFollowList(pk),
loadMuteList(pk),
]),
2025-10-28 18:29:59 +00:00
)
}
})
2025-10-06 18:23:19 +00:00
return () => {
2025-10-28 18:29:59 +00:00
unsubscribersByKey.forEach(call)
2025-11-20 23:12:16 +00:00
unsubscribeGroupList()
2025-12-01 18:56:37 +00:00
unsubscribeRelayList()
2025-10-06 18:23:19 +00:00
unsubscribeFollows()
}
}
2025-10-28 18:29:59 +00:00
// Spaces
2025-10-06 18:23:19 +00:00
2026-02-26 22:29:13 +00:00
const syncSpace = (url: string, rooms: string[]) => {
2026-03-25 21:36:48 +00:00
const since = ago(WEEK)
const seen = new Set<string>()
2025-10-06 18:23:19 +00:00
const controller = new AbortController()
2025-10-06 18:23:19 +00:00
2026-03-25 21:36:48 +00:00
const pullRoomContent = (room: string) => {
if (!seen.has(room)) {
seen.add(room)
pullAndListen({
url,
signal: controller.signal,
filters: [
{kinds: MESSAGE_KINDS, since, "#h": [room]},
makeCommentFilter(CONTENT_KINDS, {since, "#h": [room]}),
],
})
}
}
for (const room of rooms) {
pullRoomContent(room)
}
const relayKinds = [RELAY_MEMBERS, RELAY_ADD_MEMBER, RELAY_REMOVE_MEMBER]
const roomMetaKinds = [ROOM_META, ROOM_ADMINS, ROOM_MEMBERS, LIVEKIT_PARTICIPANTS]
const roomMemberKinds = [ROOM_DELETE, ROOM_ADD_MEMBER, ROOM_REMOVE_MEMBER]
pullAndListen({
url,
signal: controller.signal,
2026-03-25 21:36:48 +00:00
filters: [
{kinds: relayKinds},
{kinds: roomMetaKinds},
{kinds: roomMemberKinds},
{kinds: MESSAGE_KINDS, since},
makeCommentFilter(CONTENT_KINDS, {since}),
],
onEvent: event => {
if (event.kind === ROOM_META) {
ifLet(getTagValue("d", event.tags), pullRoomContent)
}
},
})
2026-03-25 21:36:48 +00:00
listen({
url,
signal: controller.signal,
2026-03-25 21:36:48 +00:00
filters: [{kinds: REACTION_KINDS}],
})
2025-10-06 18:23:19 +00:00
return () => controller.abort()
}
2025-10-28 18:29:59 +00:00
const syncSpaces = () => {
2026-02-26 22:29:13 +00:00
const store = derived([userGroupList, page], identity)
2025-12-01 18:56:37 +00:00
const unsubscribersByUrl = new Map<string, Unsubscriber>()
2026-02-26 22:29:13 +00:00
const roomsByUrl = new Map<string, string>()
const unsubscribe = store.subscribe(([$userGroupList, $page]) => {
const urls = new Set(getSpaceUrlsFromGroupList($userGroupList))
2025-12-01 18:56:37 +00:00
if ($page.params.relay) {
2026-02-26 22:29:13 +00:00
urls.add(decodeRelay($page.params.relay))
2025-12-01 18:56:37 +00:00
}
2025-10-06 18:23:19 +00:00
2026-02-26 22:29:13 +00:00
// Stop syncing removed spaces
2025-12-01 18:56:37 +00:00
for (const [url, unsubscribe] of unsubscribersByUrl.entries()) {
2026-02-26 22:29:13 +00:00
if (!urls.has(url)) {
2025-12-01 18:56:37 +00:00
unsubscribersByUrl.delete(url)
2026-02-26 22:29:13 +00:00
roomsByUrl.delete(url)
2025-10-06 18:23:19 +00:00
unsubscribe()
}
}
2025-10-06 18:23:19 +00:00
2026-02-26 22:29:13 +00:00
// Start or restart syncing for each space
2025-10-06 18:23:19 +00:00
for (const url of urls) {
2026-02-26 22:29:13 +00:00
const rooms = getSpaceRoomsFromGroupList(url, $userGroupList)
const roomsKey = rooms.join(",")
if (unsubscribersByUrl.has(url) && roomsByUrl.get(url) === roomsKey) continue
// Tear down existing sync if rooms changed
unsubscribersByUrl.get(url)?.()
roomsByUrl.set(url, roomsKey)
unsubscribersByUrl.set(url, syncSpace(url, rooms))
2025-10-06 18:23:19 +00:00
}
2025-10-06 18:23:19 +00:00
})
2025-12-01 18:56:37 +00:00
return () => {
for (const unsubscriber of unsubscribersByUrl.values()) {
unsubscriber()
2025-10-28 18:29:59 +00:00
}
2025-12-01 18:56:37 +00:00
unsubscribe()
2025-10-06 18:23:19 +00:00
}
}
2025-10-06 18:23:19 +00:00
// DMs
2025-10-06 18:23:19 +00:00
const syncDMRelay = (url: string, pubkey: string) => {
const controller = new AbortController()
pullAndListen({
url,
2025-10-06 18:23:19 +00:00
signal: controller.signal,
filters: [{kinds: [WRAP], "#p": [pubkey]}],
2025-10-06 18:23:19 +00:00
})
return () => controller.abort()
}
const syncDMs = () => {
const unsubscribersByUrl = new Map<string, Unsubscriber>()
let currentPubkey: string | undefined
const unsubscribeAll = () => {
for (const [url, unsubscribe] of unsubscribersByUrl.entries()) {
unsubscribersByUrl.delete(url)
unsubscribe()
}
}
const subscribeAll = (pubkey: string, urls: string[]) => {
// Start syncing newly added relays
for (const url of urls) {
if (!unsubscribersByUrl.has(url)) {
unsubscribersByUrl.set(url, syncDMRelay(url, pubkey))
}
}
// Stop syncing removed spaces
for (const [url, unsubscribe] of unsubscribersByUrl.entries()) {
if (!urls.includes(url)) {
unsubscribersByUrl.delete(url)
unsubscribe()
}
}
}
// When pubkey changes, re-sync
const unsubscribePubkey = derived([pubkey, shouldUnwrap], identity).subscribe(
([$pubkey, $shouldUnwrap]) => {
2025-10-06 18:23:19 +00:00
if ($pubkey !== currentPubkey) {
unsubscribeAll()
}
2025-11-20 23:12:16 +00:00
// If we have a pubkey, refresh our user's relay list then sync our subscriptions
if ($pubkey && $shouldUnwrap) {
2025-11-20 23:12:16 +00:00
loadRelayList($pubkey)
.then(() => loadMessagingRelayList($pubkey))
2025-10-06 18:23:19 +00:00
.then($l => subscribeAll($pubkey, getRelayTagValues(getListTags($l))))
}
currentPubkey = $pubkey
},
)
2025-11-20 23:12:16 +00:00
// When user messaging relays change, update synchronization
const unsubscribeList = userMessagingRelayList.subscribe($userMessagingRelayList => {
2025-10-06 18:23:19 +00:00
const $pubkey = pubkey.get()
const $shouldUnwrap = shouldUnwrap.get()
2025-10-06 18:23:19 +00:00
if ($pubkey && $shouldUnwrap) {
2025-11-20 23:12:16 +00:00
subscribeAll($pubkey, getRelayTagValues(getListTags($userMessagingRelayList)))
2025-10-06 18:23:19 +00:00
}
})
return () => {
unsubscribeAll()
unsubscribePubkey()
2025-11-20 23:12:16 +00:00
unsubscribeList()
2025-10-06 18:23:19 +00:00
}
}
2025-10-06 18:23:19 +00:00
// Merge all synchronization functions
2025-10-06 18:23:19 +00:00
export const syncApplicationData = () => {
2025-11-11 00:19:50 +00:00
const unsubscribers = [syncRelays(), syncUserData(), syncSpaces(), syncDMs()]
2025-10-06 18:23:19 +00:00
return () => unsubscribers.forEach(call)
}