Add memorelay module
This commit is contained in:
parent
84a083bc7c
commit
5398042156
|
@ -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 };
|
|
@ -1,7 +1,7 @@
|
||||||
import { Conf } from '@/config.ts';
|
import { Conf } from '@/config.ts';
|
||||||
import { type Event, type Filter, matchFilters, stringifyStable } from '@/deps.ts';
|
import { type Event, type Filter, matchFilters, stringifyStable, z } from '@/deps.ts';
|
||||||
|
import { nostrIdSchema } from '@/schemas/nostr.ts';
|
||||||
import type { EventData } from '@/types.ts';
|
import { type EventData } from '@/types.ts';
|
||||||
|
|
||||||
/** Additional properties that may be added by Ditto to events. */
|
/** Additional properties that may be added by Ditto to events. */
|
||||||
type Relation = 'author' | 'author_stats' | 'event_stats';
|
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 {
|
export {
|
||||||
type DittoFilter,
|
type DittoFilter,
|
||||||
eventToMicroFilter,
|
eventToMicroFilter,
|
||||||
getFilterId,
|
getFilterId,
|
||||||
type GetFiltersOpts,
|
type GetFiltersOpts,
|
||||||
|
isMicrofilter,
|
||||||
matchDittoFilters,
|
matchDittoFilters,
|
||||||
type MicroFilter,
|
type MicroFilter,
|
||||||
type Relation,
|
type Relation,
|
||||||
|
|
Loading…
Reference in New Issue