flotilla/src/app/requests.ts

65 lines
1.9 KiB
TypeScript
Raw Normal View History

2025-01-02 18:04:28 +00:00
import {get} from "svelte/store"
2025-01-02 23:08:16 +00:00
import {partition, assoc, now} from "@welshman/lib"
import {MESSAGE, THREAD, COMMENT} from "@welshman/util"
2024-12-17 00:14:51 +00:00
import type {Subscription} from "@welshman/net"
2024-12-11 00:38:22 +00:00
import type {AppSyncOpts} from "@welshman/app"
2025-01-02 23:08:16 +00:00
import {subscribe, load, repository, pull, hasNegentropy} from "@welshman/app"
2025-01-02 18:04:28 +00:00
import {userRoomsByUrl, getUrlsForEvent} from "@app/state"
2024-12-11 00:38:22 +00:00
// Utils
export const pullConservatively = ({relays, filters}: AppSyncOpts) => {
2025-01-02 18:04:28 +00:00
const $getUrlsForEvent = get(getUrlsForEvent)
2024-12-11 00:38:22 +00:00
const [smart, dumb] = partition(hasNegentropy, relays)
const promises = [pull({relays: smart, filters})]
2025-01-02 18:04:28 +00:00
const allEvents = repository.query(filters, {shouldSort: false})
2024-12-11 00:38:22 +00:00
// Since pulling from relays without negentropy is expensive, limit how many
// duplicates we repeatedly download
2024-12-12 00:59:16 +00:00
for (const url of dumb) {
2025-01-02 18:04:28 +00:00
const events = allEvents.filter(e => $getUrlsForEvent(e.id).includes(url))
2024-12-11 00:38:22 +00:00
if (events.length > 100) {
filters = filters.map(assoc("since", events[10]!.created_at))
}
2024-12-12 00:59:16 +00:00
promises.push(pull({relays: [url], filters}))
2024-12-11 00:38:22 +00:00
}
return Promise.all(promises)
}
// Application requests
export const listenForNotifications = () => {
2024-12-17 00:14:51 +00:00
const subs: Subscription[] = []
2024-12-11 00:38:22 +00:00
for (const [url, rooms] of userRoomsByUrl.get()) {
2025-01-02 23:08:16 +00:00
load({
2024-12-11 00:38:22 +00:00
relays: [url],
filters: [
2025-01-02 23:08:16 +00:00
{kinds: [THREAD], limit: 1},
{kinds: [COMMENT], "#K": [String(THREAD)], limit: 1},
...Array.from(rooms).map(room => ({kinds: [MESSAGE], "#h": [room], limit: 1})),
2024-12-11 00:38:22 +00:00
],
})
2024-12-17 00:14:51 +00:00
subs.push(
subscribe({
2024-12-11 00:38:22 +00:00
relays: [url],
filters: [
{kinds: [THREAD], since: now()},
{kinds: [COMMENT], "#K": [String(THREAD)], since: now()},
2025-01-03 00:58:04 +00:00
...Array.from(rooms).map(room => ({kinds: [MESSAGE], "#h": [room], since: now()})),
2024-12-11 00:38:22 +00:00
],
}),
)
}
return () => {
2024-12-17 00:14:51 +00:00
for (const sub of subs) {
sub.close()
2024-12-11 00:38:22 +00:00
}
}
}