ditto/src/pipeline.ts

192 lines
5.9 KiB
TypeScript
Raw Normal View History

2023-09-03 23:49:45 +00:00
import { Conf } from '@/config.ts';
import * as eventsDB from '@/db/events.ts';
2023-12-28 05:35:42 +00:00
import { memorelay } from '@/db/memorelay.ts';
2023-08-17 21:47:22 +00:00
import { addRelays } from '@/db/relays.ts';
import { deleteAttachedMedia } from '@/db/unattached-media.ts';
2023-08-17 21:47:22 +00:00
import { findUser } from '@/db/users.ts';
2023-12-28 05:35:42 +00:00
import { Debug, type Event } from '@/deps.ts';
2023-08-26 18:40:10 +00:00
import { isEphemeralKind } from '@/kinds.ts';
import * as mixer from '@/mixer.ts';
import { publish } from '@/pool.ts';
2023-08-18 00:32:05 +00:00
import { isLocallyFollowed } from '@/queries.ts';
import { reqmeister } from '@/reqmeister.ts';
2023-12-10 17:10:11 +00:00
import { updateStats } from '@/stats.ts';
2023-08-24 04:25:38 +00:00
import { Sub } from '@/subs.ts';
import { getTagSet } from '@/tags.ts';
2023-12-28 05:35:42 +00:00
import { type EventData } from '@/types.ts';
2023-09-05 22:10:20 +00:00
import { eventAge, isRelay, nostrDate, Time } from '@/utils.ts';
import { TrendsWorker } from '@/workers/trends.ts';
2023-12-03 22:55:34 +00:00
import { verifySignatureWorker } from '@/workers/verify.ts';
2023-08-17 21:47:22 +00:00
const debug = Debug('ditto:pipeline');
2023-08-17 21:47:22 +00:00
/**
* Common pipeline function to process (and maybe store) events.
* It is idempotent, so it can be called multiple times for the same event.
*/
async function handleEvent(event: Event): Promise<void> {
2023-12-03 22:55:34 +00:00
if (!(await verifySignatureWorker(event))) return;
2023-12-21 20:56:21 +00:00
const wanted = reqmeister.isWanted(event);
if (encounterEvent(event)) return;
debug(`Event<${event.kind}> ${event.id}`);
2023-08-24 22:00:08 +00:00
const data = await getEventData(event);
await Promise.all([
2023-12-21 20:56:21 +00:00
storeEvent(event, data, { force: wanted }),
processDeletions(event),
trackRelays(event),
trackHashtags(event),
fetchRelatedEvents(event, data),
processMedia(event, data),
2023-08-24 22:00:08 +00:00
streamOut(event, data),
broadcast(event, data),
]);
}
2023-08-17 21:47:22 +00:00
/** Encounter the event, and return whether it has already been encountered. */
2023-12-21 20:56:21 +00:00
function encounterEvent(event: Event): boolean {
2023-12-28 05:35:42 +00:00
const preexisting = memorelay.hasEvent(event);
memorelay.insertEvent(event);
2023-12-21 20:56:21 +00:00
reqmeister.encounter(event);
2023-12-28 05:35:42 +00:00
return preexisting;
}
2023-08-24 22:00:08 +00:00
/** Preload data that will be useful to several tasks. */
async function getEventData({ pubkey }: Event): Promise<EventData> {
const user = await findUser({ pubkey });
return { user };
}
2023-09-03 23:49:45 +00:00
/** Check if the pubkey is the `DITTO_NSEC` pubkey. */
const isAdminEvent = ({ pubkey }: Event): boolean => pubkey === Conf.pubkey;
2023-12-21 20:56:21 +00:00
interface StoreEventOpts {
force?: boolean;
}
/** Maybe store the event, if eligible. */
2023-12-21 20:56:21 +00:00
async function storeEvent(event: Event, data: EventData, opts: StoreEventOpts = {}): Promise<void> {
2023-08-26 18:40:10 +00:00
if (isEphemeralKind(event.kind)) return;
2023-12-21 20:56:21 +00:00
const { force = false } = opts;
2023-12-21 20:56:21 +00:00
if (force || data.user || isAdminEvent(event) || await isLocallyFollowed(event.pubkey)) {
const [deletion] = await mixer.getFilters(
[{ kinds: [5], authors: [event.pubkey], '#e': [event.id], limit: 1 }],
2023-12-22 16:38:48 +00:00
{ limit: 1, signal: AbortSignal.timeout(Time.seconds(1)) },
);
if (deletion) {
return Promise.reject(new RelayError('blocked', 'event was deleted'));
} else {
2023-12-10 17:10:11 +00:00
await Promise.all([
2023-12-28 02:19:59 +00:00
eventsDB.insertEvent(event, data).catch(debug),
updateStats(event).catch(debug),
2023-12-10 17:10:11 +00:00
]);
}
} else {
return Promise.reject(new RelayError('blocked', 'only registered users can post'));
2023-08-17 21:47:22 +00:00
}
}
/** Query to-be-deleted events, ensure their pubkey matches, then delete them from the database. */
async function processDeletions(event: Event): Promise<void> {
if (event.kind === 5) {
const ids = getTagSet(event.tags, 'e');
const events = await eventsDB.getFilters([{ ids: [...ids] }]);
const deleteIds = events
.filter(({ pubkey, id }) => pubkey === event.pubkey && ids.has(id))
.map((event) => event.id);
await eventsDB.deleteFilters([{ ids: deleteIds }]);
}
}
2023-08-17 21:47:22 +00:00
/** Track whenever a hashtag is used, for processing trending tags. */
async function trackHashtags(event: Event): Promise<void> {
2023-08-17 21:47:22 +00:00
const date = nostrDate(event.created_at);
const tags = event.tags
.filter((tag) => tag[0] === 't')
.map((tag) => tag[1])
.slice(0, 5);
if (!tags.length) return;
try {
2023-12-28 04:27:05 +00:00
debug('tracking tags:', JSON.stringify(tags));
await TrendsWorker.addTagUsages(event.pubkey, tags, date);
2023-08-17 21:47:22 +00:00
} catch (_e) {
// do nothing
}
}
/** Tracks known relays in the database. */
function trackRelays(event: Event) {
const relays = new Set<`wss://${string}`>();
event.tags.forEach((tag) => {
if (['p', 'e', 'a'].includes(tag[0]) && isRelay(tag[2])) {
relays.add(tag[2]);
}
if (event.kind === 10002 && tag[0] === 'r' && isRelay(tag[1])) {
relays.add(tag[1]);
}
});
return addRelays([...relays]);
}
/** Queue related events to fetch. */
function fetchRelatedEvents(event: Event, data: EventData) {
2023-12-21 20:56:21 +00:00
if (!data.user) {
2023-12-22 01:10:42 +00:00
reqmeister.req({ kinds: [0], authors: [event.pubkey] }).catch(() => {});
2023-12-21 20:56:21 +00:00
}
for (const [name, id, relay] of event.tags) {
2023-12-28 05:35:42 +00:00
if (name === 'e' && !memorelay.hasEventById(id)) {
2023-12-22 01:10:42 +00:00
reqmeister.req({ ids: [id] }, [relay]).catch(() => {});
2023-12-21 20:56:21 +00:00
}
}
}
/** Delete unattached media entries that are attached to the event. */
function processMedia({ tags, pubkey }: Event, { user }: EventData) {
if (user) {
const urls = getTagSet(tags, 'media');
return deleteAttachedMedia(pubkey, [...urls]);
}
}
/** Determine if the event is being received in a timely manner. */
2023-09-05 22:10:20 +00:00
const isFresh = (event: Event): boolean => eventAge(event) < Time.seconds(10);
2023-08-24 04:25:38 +00:00
/** Distribute the event through active subscriptions. */
2023-08-24 22:00:08 +00:00
function streamOut(event: Event, data: EventData) {
if (!isFresh(event)) return;
for (const sub of Sub.matches(event, data)) {
sub.stream(event);
2023-08-24 04:25:38 +00:00
}
}
/**
* Publish the event to other relays.
* This should only be done in certain circumstances, like mentioning a user or publishing deletions.
*/
function broadcast(event: Event, data: EventData) {
if (!data.user || !isFresh(event)) return;
if (event.kind === 5) {
publish(event);
}
}
/** NIP-20 command line result. */
class RelayError extends Error {
constructor(prefix: 'duplicate' | 'pow' | 'blocked' | 'rate-limited' | 'invalid' | 'error', message: string) {
super(`${prefix}: ${message}`);
}
}
export { handleEvent, RelayError };