memorelay: insertEvent

This commit is contained in:
Alex Gleason 2023-12-27 23:22:24 -06:00
parent 5398042156
commit acffdd7fb8
No known key found for this signature in database
GPG Key ID: 7211D1F99744FBB7
2 changed files with 30 additions and 6 deletions

View File

@ -1,8 +1,13 @@
import { Debug, type Event, type Filter, LRUCache } from '@/deps.ts';
import { getFilterId, type GetFiltersOpts, isMicrofilter } from '@/filter.ts';
import { getFilterId, type GetFiltersOpts, getMicroFilters, isMicrofilter } from '@/filter.ts';
const debug = Debug('ditto:memorelay');
const events = new LRUCache<string, Event>({ max: 1000 });
const events = new LRUCache<string, Event>({
max: 1000,
maxEntrySize: 1000,
sizeCalculation: (event) => JSON.stringify(event).length,
});
/** Get events from memory. */
function getFilters<K extends number>(filters: Filter<K>[], opts: GetFiltersOpts = {}): Promise<Event<K>[]> {
@ -24,4 +29,15 @@ function getFilters<K extends number>(filters: Filter<K>[], opts: GetFiltersOpts
return Promise.resolve(results);
}
export { getFilters };
/** Insert an event into memory. */
function insertEvent(event: Event): void {
for (const microfilter of getMicroFilters(event)) {
const filterId = getFilterId(microfilter);
const existing = events.get(filterId);
if (!existing || event.created_at > existing.created_at) {
events.set(filterId, event);
}
}
}
export { getFilters, insertEvent };

View File

@ -63,11 +63,18 @@ function getFilterId(filter: MicroFilter): string {
/** Get a microfilter from a Nostr event. */
function eventToMicroFilter(event: Event): MicroFilter {
const [microfilter] = getMicroFilters(event);
return microfilter;
}
/** Get all the microfilters for an event, in order of priority. */
function getMicroFilters(event: Event): MicroFilter[] {
const microfilters: MicroFilter[] = [];
if (event.kind === 0) {
return { kinds: [0], authors: [event.pubkey] };
} else {
return { ids: [event.id] };
microfilters.push({ kinds: [0], authors: [event.pubkey] });
}
microfilters.push({ ids: [event.id] });
return microfilters;
}
/** Microfilter schema. */
@ -86,6 +93,7 @@ export {
eventToMicroFilter,
getFilterId,
type GetFiltersOpts,
getMicroFilters,
isMicrofilter,
matchDittoFilters,
type MicroFilter,