import { Func, Inbox, Lifecycle, spawn, loop, STOP } from 'anneal' import { Event as NEvent } from 'nostr-tools' import { compareEvents, getReplaceableCoordinateFromEvent, isReplaceableEvent } from '@/lib/event' export type EventCacheActor = { cache: Inbox lookup: Func lookupMany: Func lookupReplaceable: Func lc: Lifecycle } export function createEventCacheActor(): EventCacheActor { const events = new Map() const replaceables = new Map() const cache = new Inbox(0) const lookup = new Func() const lookupMany = new Func() const lookupReplaceable = new Func() const lc = new Lifecycle() spawn(lc, async () => { await loop( lc.on(() => STOP), cache.on((event) => { events.set(event.id, event) if (isReplaceableEvent(event.kind)) { const coord = getReplaceableCoordinateFromEvent(event) const existing = replaceables.get(coord) if (!existing || compareEvents(event, existing) > 0) { replaceables.set(coord, event) } } }), lookup.on(({ req: id, reply }) => { reply(events.get(id)) }), lookupMany.on(({ req: ids, reply }) => { reply(ids.map((id) => events.get(id))) }), lookupReplaceable.on(({ req: coord, reply }) => { reply(replaceables.get(coord)) }) ) }) return { cache, lookup, lookupMany, lookupReplaceable, lc } }