Add memorelay module

This commit is contained in:
Alex Gleason 2023-12-27 22:49:35 -06:00
parent 84a083bc7c
commit 5398042156
No known key found for this signature in database
GPG Key ID: 7211D1F99744FBB7
2 changed files with 42 additions and 3 deletions

27
src/db/memorelay.ts Normal file
View File

@ -0,0 +1,27 @@
import { Debug, type Event, type Filter, LRUCache } from '@/deps.ts';
import { getFilterId, type GetFiltersOpts, isMicrofilter } from '@/filter.ts';
const debug = Debug('ditto:memorelay');
const events = new LRUCache<string, Event>({ max: 1000 });
/** Get events from memory. */
function getFilters<K extends number>(filters: Filter<K>[], opts: GetFiltersOpts = {}): Promise<Event<K>[]> {
if (opts.signal?.aborted) return Promise.resolve([]);
if (!filters.length) return Promise.resolve([]);
debug('REQ', JSON.stringify(filters));
const results: Event<K>[] = [];
for (const filter of filters) {
if (isMicrofilter(filter)) {
const event = events.get(getFilterId(filter));
if (event) {
results.push(event as Event<K>);
}
}
}
return Promise.resolve(results);
}
export { getFilters };

View File

@ -1,7 +1,7 @@
import { Conf } from '@/config.ts';
import { type Event, type Filter, matchFilters, stringifyStable } from '@/deps.ts';
import type { EventData } from '@/types.ts';
import { type Event, type Filter, matchFilters, stringifyStable, z } from '@/deps.ts';
import { nostrIdSchema } from '@/schemas/nostr.ts';
import { type EventData } from '@/types.ts';
/** Additional properties that may be added by Ditto to events. */
type Relation = 'author' | 'author_stats' | 'event_stats';
@ -70,11 +70,23 @@ function eventToMicroFilter(event: Event): MicroFilter {
}
}
/** Microfilter schema. */
const microFilterSchema = z.union([
z.object({ ids: z.tuple([nostrIdSchema]) }).strict(),
z.object({ kinds: z.tuple([z.literal(0)]), authors: z.tuple([nostrIdSchema]) }).strict(),
]);
/** Checks whether the filter is a microfilter. */
function isMicrofilter(filter: Filter): filter is MicroFilter {
return microFilterSchema.safeParse(filter).success;
}
export {
type DittoFilter,
eventToMicroFilter,
getFilterId,
type GetFiltersOpts,
isMicrofilter,
matchDittoFilters,
type MicroFilter,
type Relation,