flotilla/src/app/core/sync.ts

485 lines
12 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"
2025-10-28 18:29:59 +00:00
import {partition, call, sortBy, assoc, chunk, sleep, identity, WEEK, ago} from "@welshman/lib"
2025-10-06 18:23:19 +00:00
import {
getListTags,
getRelayTagValues,
WRAP,
2025-10-28 18:29:59 +00:00
MESSAGE,
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,
} from "@welshman/util"
2025-10-06 18:23:19 +00:00
import type {Filter, TrustedEvent} from "@welshman/util"
import {request, load, pull} from "@welshman/net"
2025-10-06 18:23:19 +00:00
import {
pubkey,
loadRelay,
userFollows,
userRelaySelections,
userInboxRelaySelections,
loadRelaySelections,
loadInboxRelaySelections,
loadBlossomServers,
loadFollows,
loadMutes,
loadProfile,
repository,
shouldUnwrap,
2025-10-06 18:23:19 +00:00
hasNegentropy,
2025-10-28 18:29:59 +00:00
relaysByUrl,
2025-10-06 18:23:19 +00:00
} from "@welshman/app"
import {
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,
loadGroupSelections,
userSpaceUrls,
2025-10-28 18:29:59 +00:00
userGroupSelections,
bootstrapPubkeys,
2025-10-06 18:23:19 +00:00
decodeRelay,
2025-10-06 18:23:19 +00:00
getUrlsForEvent,
2025-10-28 18:29:59 +00:00
hasNip29,
getSpaceUrlsFromGroupSelections,
getSpaceRoomsFromGroupSelections,
makeCommentFilter,
2025-10-06 18:23:19 +00:00
} from "@app/core/state"
import {loadAlerts, loadAlertStatuses} from "@app/core/requests"
2025-10-06 18:23:19 +00:00
import {hasBlossomSupport} from "@app/core/commands"
// Utils
type PullOpts = {
relays: string[]
filters: Filter[]
signal: AbortSignal
}
2025-10-28 18:29:59 +00:00
const pullWithFallback = ({relays, filters, signal}: PullOpts) => {
2025-10-06 18:23:19 +00:00
const $getUrlsForEvent = get(getUrlsForEvent)
const [smart, dumb] = partition(hasNegentropy, relays)
const events = repository.query(filters, {shouldSort: false}).filter(isSignedEvent)
const promises: Promise<TrustedEvent[]>[] = [pull({relays: smart, filters, signal, events})]
// Since pulling from relays without negentropy is expensive, limit how many
// duplicates we repeatedly download
for (const url of dumb) {
const urlEvents = events.filter(e => $getUrlsForEvent(e.id).includes(url))
if (urlEvents.length >= 100) {
filters = filters.map(assoc("since", sortBy(e => -e.created_at, urlEvents)[10]!.created_at))
}
promises.push(load({relays: [url], filters, signal}))
}
return Promise.all(promises)
}
2025-10-28 18:29:59 +00:00
const pullAndListen = ({relays, filters, signal}: PullOpts) => {
2025-10-28 21:53:44 +00:00
pullWithFallback({
relays,
signal,
filters: filters.map(f => ({limit: 100, ...f})),
})
request({
relays,
signal,
filters: filters.map(assoc("limit", 0)),
})
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({
relays: [url],
signal: controller.signal,
filters: [
{
kinds: [RELAY_ADD_MEMBER, RELAY_REMOVE_MEMBER, ROOM_CREATE_PERMISSION],
"#p": [$pubkey],
},
],
})
}
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({
relays: [url],
signal: controller.signal,
filters: [
{
kinds: [ROOM_ADD_MEMBER, ROOM_REMOVE_MEMBER],
"#p": [$pubkey],
2025-10-30 22:33:34 +00:00
"#h": [h],
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>()
const unsubscribeGroupSelections = userGroupSelections.subscribe($l => {
const $pubkey = pubkey.get()
2025-10-06 18:23:19 +00:00
if ($pubkey) {
2025-10-28 18:29:59 +00:00
const keys = new Set<string>()
for (const url of getSpaceUrlsFromGroupSelections($l)) {
if (!unsubscribersByKey.has(url)) {
unsubscribersByKey.set(url, syncUserSpaceMembership(url))
}
keys.add(url)
2025-10-30 22:33:34 +00:00
for (const h of getSpaceRoomsFromGroupSelections(url, $l)) {
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
}
})
const unsubscribeSelections = userRelaySelections.subscribe($l => {
const $pubkey = pubkey.get()
if ($pubkey) {
loadAlerts($pubkey)
loadAlertStatuses($pubkey)
loadBlossomServers($pubkey)
loadFollows($pubkey)
loadGroupSelections($pubkey)
2025-10-06 18:23:19 +00:00
loadMutes($pubkey)
loadProfile($pubkey)
loadSettings($pubkey)
}
})
const unsubscribeFollows = userFollows.subscribe(async $l => {
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(
pubkeys.map(async pk => {
await loadRelaySelections(pk)
await loadGroupSelections(pk)
await loadProfile(pk)
await loadFollows(pk)
await loadMutes(pk)
}),
)
}
})
const unsubscribePubkey = pubkey.subscribe($pubkey => {
if ($pubkey) {
loadRelaySelections($pubkey)
2025-10-06 18:23:19 +00:00
}
})
return () => {
2025-10-28 18:29:59 +00:00
unsubscribersByKey.forEach(call)
unsubscribeGroupSelections()
2025-10-06 18:23:19 +00:00
unsubscribeSelections()
unsubscribeFollows()
2025-10-28 18:29:59 +00:00
unsubscribePubkey()
2025-10-06 18:23:19 +00:00
}
}
2025-10-28 18:29:59 +00:00
// Spaces
2025-10-06 18:23:19 +00:00
2025-10-28 18:29:59 +00:00
const syncSpace = (url: string) => {
2025-10-06 18:23:19 +00:00
const controller = new AbortController()
2025-10-06 18:23:19 +00:00
2025-10-28 18:29:59 +00:00
pullAndListen({
2025-10-06 18:23:19 +00:00
relays: [url],
signal: controller.signal,
2025-10-28 18:29:59 +00:00
filters: [
{kinds: [RELAY_MEMBERS]},
2025-10-30 21:59:39 +00:00
{kinds: [ROOM_META, ROOM_DELETE]},
2025-11-03 19:10:16 +00:00
{kinds: [ROOM_ADMINS, ROOM_MEMBERS]},
2025-10-28 18:29:59 +00:00
{kinds: [RELAY_ADD_MEMBER, RELAY_REMOVE_MEMBER]},
2025-10-28 22:46:25 +00:00
...MESSAGE_KINDS.map(kind => ({kinds: [kind]})),
2025-10-28 18:29:59 +00:00
makeCommentFilter(CONTENT_KINDS),
],
2025-10-06 18:23:19 +00:00
})
return () => controller.abort()
}
2025-10-28 18:29:59 +00:00
const syncSpaces = () => {
const membershipUnsubscribersByUrl = new Map<string, Unsubscriber>()
2025-10-06 18:23:19 +00:00
const unsubscribeSpaceUrls = userSpaceUrls.subscribe(urls => {
2025-10-06 18:23:19 +00:00
// stop syncing removed spaces
2025-10-28 18:29:59 +00:00
for (const [url, unsubscribe] of membershipUnsubscribersByUrl.entries()) {
2025-10-06 18:23:19 +00:00
if (!urls.includes(url)) {
2025-10-28 18:29:59 +00:00
membershipUnsubscribersByUrl.delete(url)
2025-10-06 18:23:19 +00:00
unsubscribe()
}
}
2025-10-06 18:23:19 +00:00
// Start syncing newly added spaces
for (const url of urls) {
2025-10-28 18:29:59 +00:00
if (!membershipUnsubscribersByUrl.has(url)) {
membershipUnsubscribersByUrl.set(url, syncSpace(url))
2025-10-06 18:23:19 +00:00
}
}
2025-10-06 18:23:19 +00:00
})
2025-10-28 18:29:59 +00:00
const pageUnsubscribersByUrl = new Map<string, Unsubscriber>()
// Sync the space the user is currently visiting
const unsubscribePage = page.subscribe($page => {
if ($page.params.relay) {
const url = decodeRelay($page.params.relay)
// Don't subscribe twice if the user is a member
if (!pageUnsubscribersByUrl.has(url) && !get(userSpaceUrls).includes(url)) {
pageUnsubscribersByUrl.set(url, syncSpace(url))
}
// Clean up old subscriptions
for (const [oldUrl, unsubscribe] of pageUnsubscribersByUrl.entries()) {
if (url !== oldUrl) {
pageUnsubscribersByUrl.delete(oldUrl)
unsubscribe()
}
}
} else {
Array.from(pageUnsubscribersByUrl.values()).forEach(call)
}
})
2025-10-06 18:23:19 +00:00
return () => {
2025-10-28 18:29:59 +00:00
Array.from(membershipUnsubscribersByUrl.values()).forEach(call)
Array.from(pageUnsubscribersByUrl.values()).forEach(call)
unsubscribeSpaceUrls()
2025-10-28 18:29:59 +00:00
unsubscribePage()
2025-10-06 18:23:19 +00:00
}
}
2025-10-28 18:29:59 +00:00
// Chat
2025-10-06 18:23:19 +00:00
2025-11-03 19:10:16 +00:00
const syncRoom = (url: string, h: string) => {
2025-10-28 18:29:59 +00:00
const controller = new AbortController()
pullAndListen({
2025-10-06 18:23:19 +00:00
relays: [url],
signal: controller.signal,
filters: [
2025-10-30 22:33:34 +00:00
{kinds: [ROOM_ADMINS, ROOM_MEMBERS], "#d": [h]},
{kinds: [ROOM_ADD_MEMBER, ROOM_REMOVE_MEMBER], "#h": [h]},
{kinds: [MESSAGE], "#h": [h]},
2025-10-06 18:23:19 +00:00
],
})
return () => controller.abort()
}
2025-10-28 18:29:59 +00:00
const syncRooms = () => {
const unsubscribersByKey = new Map<string, Unsubscriber>()
2025-10-06 18:23:19 +00:00
2025-10-28 18:29:59 +00:00
const unsubscribeSpaceUrls = derived([userGroupSelections, relaysByUrl], identity).subscribe(
([$l, $relaysByUrl]) => {
const keys = new Set<string>()
const newUnsubscribersByKey = new Map<string, Unsubscriber>()
2025-10-06 18:23:19 +00:00
2025-10-28 18:29:59 +00:00
// Add new subscriptions, depending on whether nip 29 is supported
for (const url of getRelayTagValues(getListTags($l))) {
if (hasNip29($relaysByUrl.get(url))) {
2025-10-30 22:33:34 +00:00
for (const h of getSpaceRoomsFromGroupSelections(url, $l)) {
const key = `${url}'${h}`
2025-10-28 18:29:59 +00:00
2025-10-30 19:06:53 +00:00
if (!unsubscribersByKey.has(key)) {
2025-11-03 19:10:16 +00:00
newUnsubscribersByKey.set(key, syncRoom(url, h))
2025-10-28 18:29:59 +00:00
}
2025-10-30 19:06:53 +00:00
keys.add(key)
2025-10-28 18:29:59 +00:00
}
}
2025-10-06 18:23:19 +00:00
}
2025-10-28 18:29:59 +00:00
// Stop syncing removed selections
for (const [key, unsubscribe] of unsubscribersByKey.entries()) {
if (!keys.has(key)) {
unsubscribersByKey.delete(key)
2025-10-06 18:23:19 +00:00
unsubscribe()
}
}
2025-10-28 18:29:59 +00:00
// Start syncing newly added spaces
for (const [key, unsubscriber] of newUnsubscribersByKey.entries()) {
unsubscribersByKey.set(key, unsubscriber)
}
},
)
2025-10-06 18:23:19 +00:00
return () => {
2025-10-28 18:29:59 +00:00
Array.from(unsubscribersByKey.values()).forEach(call)
unsubscribeSpaceUrls()
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()
// Load historical data
2025-10-28 18:29:59 +00:00
pullWithFallback({
2025-10-06 18:23:19 +00:00
relays: [url],
signal: controller.signal,
filters: [{kinds: [WRAP], "#p": [pubkey], until: ago(WEEK, 2)}],
})
// Load new events
request({
relays: [url],
signal: controller.signal,
filters: [{kinds: [WRAP], "#p": [pubkey], since: ago(WEEK, 2)}],
})
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()
}
// If we have a pubkey, refresh our user's relay selections then sync our subscriptions
if ($pubkey && $shouldUnwrap) {
2025-10-06 18:23:19 +00:00
loadRelaySelections($pubkey)
.then(() => loadInboxRelaySelections($pubkey))
.then($l => subscribeAll($pubkey, getRelayTagValues(getListTags($l))))
}
currentPubkey = $pubkey
},
)
// When user inbox relays change, update synchronization
const unsubscribeSelections = userInboxRelaySelections.subscribe($userInboxRelaySelections => {
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) {
subscribeAll($pubkey, getRelayTagValues(getListTags($userInboxRelaySelections)))
2025-10-06 18:23:19 +00:00
}
})
return () => {
unsubscribeAll()
unsubscribePubkey()
unsubscribeSelections()
}
}
2025-10-06 18:23:19 +00:00
// Merge all synchronization functions
2025-10-06 18:23:19 +00:00
export const syncApplicationData = () => {
2025-10-28 18:29:59 +00:00
const unsubscribers = [syncRelays(), syncUserData(), syncSpaces(), syncRooms(), syncDMs()]
2025-10-06 18:23:19 +00:00
return () => unsubscribers.forEach(call)
}