flotilla/src/app/requests.ts

62 lines
1.7 KiB
TypeScript
Raw Normal View History

import {partition, assoc, now, ago, MONTH} from "@welshman/lib"
import {MESSAGE, DELETE, 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"
import {subscribe, repository, pull, hasNegentropy} from "@welshman/app"
import {userRoomsByUrl, getEventsForUrl} from "@app/state"
2024-12-11 00:38:22 +00:00
// Utils
export const pullConservatively = ({relays, filters}: AppSyncOpts) => {
const [smart, dumb] = partition(hasNegentropy, relays)
const promises = [pull({relays: smart, filters})]
// 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) {
2024-12-16 18:30:42 +00:00
const events = getEventsForUrl(repository, url, filters)
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()) {
pullConservatively({
2024-12-11 00:38:22 +00:00
relays: [url],
filters: [
{kinds: [THREAD, DELETE], since: ago(MONTH)},
{kinds: [COMMENT], "#K": [String(THREAD)], since: ago(MONTH)},
...Array.from(rooms).map(room => ({kinds: [MESSAGE], "#h": [room], since: ago(MONTH)})),
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()},
{kinds: [MESSAGE], "#h": Array.from(rooms), 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
}
}
}