Something went wrong. Try again.
Atproto cohost clone/tribute
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453/** * Tap event consumer */
import { AppBskyGraphBlock } from "@atcute/bluesky";import { is } from "@atcute/lexicons";import type { BaseSchema } from "@atcute/lexicons/validations";import { TapClient, type TapIdentityEvent, type TapRecordCreateEvent, type TapRecordDeleteEvent, type TapRecordEvent, type TapRecordUpdateEvent,} from "@atcute/tap";import type { Kysely } from "kysely";import WebSocket from "ws";import * as types from "~/lexicon";import type { DB } from "../db/schema.js";import { removePostFromReadModel } from "../services/post.js";
// helpersfunction getUri(event: TapRecordEvent): string { return `at://${event.did}/${event.collection}/${event.rkey}`;}
function blobCid(value: unknown): string | null { if (!value || typeof value !== "object") return null; const ref = (value as Record<string, unknown>).ref as | Record<string, unknown> | undefined; if (typeof ref?.$link === "string") return ref.$link; return null;}
export class TapConsumer { private tap: TapClient | null; private running = false; private db: Kysely<DB>;
constructor(db: Kysely<DB>) { this.db = db; this.running = true; this.tap = null; }
// start/stop async start() { console.log("Starting tap consumer..."); this.tap = new TapClient({ url: process.env.TAP_URL ?? "http://localhost:2480", });
while (this.running) { try { await this.consume(); } catch (err) { console.error("Tap consumer failed, restarting in 5s:", err); }
if (!this.running) break; await new Promise((resolve) => setTimeout(resolve, 5000)); } }
private async consume() { const tap = this.tap; if (!tap) return; for await (const { event, ack } of tap.subscribe({ ws: { WebSocket }, })) { if (!this.running) return;
try { if (event.type === "identity") await this.handleIdentity(event); else if (event.type === "record" && event.action === "delete") await this.handleDeletion(event); else if (event.type === "record") await this.handleUpdate(event); } catch (err) { // Leave the event unacked so tap redelivers it (at-least-once) // instead of dropping a record on a transient failure. console.error( `Error handling event ${event.type}, leaving unacked:`, err, ); continue; }
try { await ack(); } catch (err) { console.error(`Error acking event ${event.type}:`, err); } } }
async stop() { console.log("Stopping tap consumer..."); this.running = false; }
// handle events async handleIdentity(event: TapIdentityEvent) { await this.db .insertInto("users") .values({ did: event.did, handle: event.handle }) .onConflict((oc) => oc.column("did").doUpdateSet({ handle: event.handle }), ) .execute(); }
async handleDeletion(event: TapRecordDeleteEvent) { const uri = getUri(event); if (event.collection === types.ids.PubNyaPostingPost) await removePostFromReadModel(this.db, uri); else if (event.collection === types.ids.PubNyaPostingBox) await this.db.deleteFrom("boxes").where("uri", "=", uri).execute(); else if (event.collection === types.ids.PubNyaPostingBoxFollow) await this.db.deleteFrom("box_follows").where("uri", "=", uri).execute(); else if (event.collection === types.ids.PubNyaPostingTagFollow) await this.db.deleteFrom("tag_follows").where("uri", "=", uri).execute(); else if (event.collection === "app.bsky.graph.block") await this.db.deleteFrom("blocks").where("uri", "=", uri).execute(); else if (event.collection === types.ids.PubNyaPostingLike) { await this.db.deleteFrom("likes").where("uri", "=", uri).execute(); await this.db .deleteFrom("notifications") .where("uri", "=", uri) .execute(); } else if (event.collection === types.ids.PubNyaPostingRepost) { await this.db.deleteFrom("reposts").where("uri", "=", uri).execute(); await this.db .deleteFrom("notifications") .where("uri", "=", uri) .execute(); } }
async handleUpdate(event: TapRecordCreateEvent | TapRecordUpdateEvent) { if (!event.record) { console.log(`Record ${getUri(event)} is empty`); return; }
if (event.collection === types.ids.PubNyaPostingPost) await this.handlePost(event); else if (event.collection === types.ids.PubNyaPostingProfile) await this.handlePostingProfile(event); else if (event.collection === types.ids.AppBskyActorProfile) await this.handleBskyProfile(event); else if (event.collection === types.ids.PubNyaPostingBox) await this.handleBox(event); else if (event.collection === types.ids.PubNyaPostingLike) await this.handleLike(event); else if (event.collection === types.ids.PubNyaPostingRepost) await this.handleRepost(event); else if (event.collection === "app.bsky.graph.block") await this.handleBlock(event); else if (event.collection === types.ids.PubNyaPostingBoxFollow) await this.handleBoxFollow(event); else if (event.collection === types.ids.PubNyaPostingTagFollow) await this.handleTagFollow(event); else if (event.collection === types.ids.PubNyaPostingReport) await this.handleReport(event); }
async handlePost(event: TapRecordCreateEvent | TapRecordUpdateEvent) { const record = event.record; if (!is(types.PubNyaPostingPost.mainSchema, record)) { console.log(`Post ${getUri(event)} validation failed`); return; }
const uri = getUri(event);
await this.db .insertInto("posts") .values({ uri, cid: event.cid, did: event.did, content: record.content, box: record.box ?? null, visibility: record.visibility ?? "public", tags: JSON.stringify(record.tags ?? []), cw_tags: JSON.stringify(record.cwTags ?? []), reply_parent_uri: record.reply?.parent?.uri ?? null, reply_root_uri: record.reply?.root?.uri ?? null, }) .onConflict((oc) => oc.column("uri").doUpdateSet({ content: record.content, box: record.box ?? null, visibility: record.visibility ?? "public", tags: JSON.stringify(record.tags ?? []), cw_tags: JSON.stringify(record.cwTags ?? []), }), ) .execute();
if (event.action === "create" && record.reply?.parent?.uri) { const parentDid = record.reply.parent.uri.split("/")[2]; if (parentDid && parentDid !== event.did) { await this.createNotification(uri, event.did, parentDid, "reply", uri); } } }
async handlePostingProfile( event: TapRecordCreateEvent | TapRecordUpdateEvent, ) { const record = event.record as Record<string, unknown>; const bio = typeof record.bio === "string" ? record.bio : null; const avatar = blobCid(record.avatar); const banner = blobCid(record.banner);
await this.db .insertInto("users") .values({ did: event.did, handle: event.did, bio, avatar, banner }) .onConflict((oc) => oc.column("did").doUpdateSet({ bio, avatar, banner })) .execute(); }
async handleBskyProfile(event: TapRecordCreateEvent | TapRecordUpdateEvent) { const record = event.record as Record<string, unknown>; const bio = typeof record.description === "string" ? record.description : null; const avatar = blobCid(record.avatar); const banner = blobCid(record.banner);
// Stored as the fallback; the posting profile overrides it at read time. await this.db .insertInto("users") .values({ did: event.did, handle: event.did, bsky_bio: bio, bsky_avatar: avatar, bsky_banner: banner, }) .onConflict((oc) => oc.column("did").doUpdateSet({ bsky_bio: bio, bsky_avatar: avatar, bsky_banner: banner, }), ) .execute(); }
async handleBox(event: TapRecordCreateEvent | TapRecordUpdateEvent) { const record = event.record; if (!is(types.PubNyaPostingBox.mainSchema, record)) { console.log(`Box ${getUri(event)} validation failed`); return; }
const uri = getUri(event); const icon = blobCid(record.icon); const active = record.active ?? true;
await this.db .insertInto("boxes") .values({ uri, owner_did: event.did, name: record.name ?? "", icon, active, }) .onConflict((oc) => oc.column("uri").doUpdateSet({ name: record.name, icon, active }), ) .execute(); }
async handleLike(event: TapRecordCreateEvent | TapRecordUpdateEvent) { const record = event.record; if (!is(types.PubNyaPostingLike.mainSchema, record)) { console.log(`Like ${getUri(event)} validation failed`); return; } await this.recordReaction(event, record.subject.uri, "likes", "like"); }
async handleRepost(event: TapRecordCreateEvent | TapRecordUpdateEvent) { const record = event.record; if (!is(types.PubNyaPostingRepost.mainSchema, record)) { console.log(`Repost ${getUri(event)} validation failed`); return; } await this.recordReaction(event, record.subject.uri, "reposts", "repost"); }
/** * Inserts a like/repost row and, on a fresh create, notifies the post * author (unless they reacted to their own post). */ private async recordReaction( event: TapRecordCreateEvent | TapRecordUpdateEvent, postUri: string, table: "likes" | "reposts", type: "like" | "repost", ) { const uri = getUri(event);
await this.ensureUserExists(event.did); await this.db .insertInto(table) .values({ uri, user_did: event.did, post_uri: postUri }) .onConflict((oc) => oc.column("uri").doNothing()) .execute();
if (event.action !== "create") return; const post = await this.db .selectFrom("posts") .select("did") .where("uri", "=", postUri) .executeTakeFirst(); if (post && post.did !== event.did) { await this.createNotification(uri, event.did, post.did, type, postUri); } }
async ensureUserExists(did: string) { await this.db .insertInto("users") .values({ did, handle: did }) .onConflict((oc) => oc.column("did").doNothing()) .execute(); }
async handleBlock(event: TapRecordCreateEvent | TapRecordUpdateEvent) { if (!is(AppBskyGraphBlock.mainSchema as BaseSchema, event.record)) { console.log(`Block ${getUri(event)} validation failed`); return; }
const record = event.record as AppBskyGraphBlock.Main; const uri = getUri(event);
// Ensure both user and blocked user exist await this.ensureUserExists(event.did); await this.ensureUserExists(record.subject);
await this.db .insertInto("blocks") .values({ uri, user_did: event.did, blocked_did: record.subject }) .onConflict((oc) => oc.column("uri").doNothing()) .execute(); }
async handleBoxFollow(event: TapRecordCreateEvent | TapRecordUpdateEvent) { const record = event.record; if (!is(types.PubNyaPostingBoxFollow.mainSchema, record)) { console.log(`BoxFollow ${getUri(event)} validation failed`); return; }
const uri = getUri(event);
// Ensure both follower and box owner exist await this.ensureUserExists(event.did); await this.ensureUserExists(record.actor);
await this.db .insertInto("box_follows") .values({ uri, user_did: event.did, box_owner_did: record.actor, box_name: record.box, }) .onConflict((oc) => oc.column("uri").doNothing()) .execute();
if (event.action === "create" && event.did !== record.actor) { const noteType = record.box === "all" ? "follow" : "boxFollow"; await this.createNotification(uri, event.did, record.actor, noteType); } }
async handleTagFollow(event: TapRecordCreateEvent | TapRecordUpdateEvent) { const record = event.record; if (!is(types.PubNyaPostingTagFollow.mainSchema, record)) { console.log(`TagFollow ${getUri(event)} validation failed`); return; }
const uri = getUri(event);
await this.db .insertInto("tag_follows") .values({ uri, user_did: event.did, tag: record.tag }) .onConflict((oc) => oc.column("uri").doNothing()) .execute(); }
async handleReport(event: TapRecordCreateEvent | TapRecordUpdateEvent) { const record = event.record; if (!is(types.PubNyaPostingReport.mainSchema, record)) { console.log(`Report ${getUri(event)} validation failed`); return; }
if (event.action !== "create") return;
const subjectUri = record.subject.uri; const subjectCid = record.subject.cid ?? null; const subjectType = subjectUri.startsWith("at://") && subjectUri.split("/").length >= 4 ? "post" : "user";
await this.ensureUserExists(event.did); await this.db .insertInto("reports") .values({ reported_by: event.did, subject_uri: subjectUri, subject_cid: subjectCid, subject_type: subjectType, reason_type: record.reasonType ?? "com.atproto.moderation.defs#reasonOther", reason: record.reason ?? null, }) .execute(); }
async createNotification( uri: string, actorDid: string, recipientDid: string, type: "like" | "reply" | "repost" | "follow" | "boxFollow", postUri?: string, ) { await this.ensureUserExists(actorDid); await this.ensureUserExists(recipientDid); await this.db .insertInto("notifications") .values({ uri, type, actor_did: actorDid, recipient_did: recipientDid, post_uri: postUri ?? null, }) .onConflict((oc) => oc.column("uri").doNothing()) .execute(); }}