Scratch space for learning atproto app development

Merge remote-tracking branch 'origin/add-sync-package' into main

+150 -18
package-lock.json
···
"@atproto/api": "^0.13.4",
"@atproto/common": "^0.4.1",
"@atproto/identity": "^0.4.0",
-
"@atproto/lexicon": "^0.4.1",
"@atproto/oauth-client-node": "^0.1.0",
-
"@atproto/repo": "^0.4.3",
"@atproto/syntax": "^0.3.0",
"@atproto/xrpc-server": "^0.6.3",
"better-sqlite3": "^11.1.2",
···
"undici": "^6.14.1"
}
},
"node_modules/@atproto-labs/handle-resolver": {
"version": "0.1.2",
"resolved": "https://registry.npmjs.org/@atproto-labs/handle-resolver/-/handle-resolver-0.1.2.tgz",
···
"tlds": "^1.234.0"
}
},
"node_modules/@atproto/common": {
"version": "0.4.1",
"resolved": "https://registry.npmjs.org/@atproto/common/-/common-0.4.1.tgz",
···
"lex": "dist/index.js"
}
},
-
"node_modules/@atproto/lexicon": {
"version": "0.4.1",
"resolved": "https://registry.npmjs.org/@atproto/lexicon/-/lexicon-0.4.1.tgz",
"integrity": "sha512-bzyr+/VHXLQWbumViX5L7h1NKQObfs8Z+XZJl43OUK8nYFUI4e/sW1IZKRNfw7Wvi5YVNK+J+yP3DWIBZhkCYA==",
"dependencies": {
"@atproto/common-web": "^0.3.0",
"@atproto/syntax": "^0.3.0",
···
}
},
"node_modules/@atproto/repo": {
-
"version": "0.4.3",
-
"resolved": "https://registry.npmjs.org/@atproto/repo/-/repo-0.4.3.tgz",
-
"integrity": "sha512-9w4TlyxExLfFL9BysvXq4vhIsYsnmGi0uelmxJjlRXBICgLpqjqQVqhS8OBqE25ZTYvgXUi7nNqpo2llCHhOvQ==",
"dependencies": {
"@atproto/common": "^0.4.1",
"@atproto/common-web": "^0.3.0",
···
"rate-limiter-flexible": "^2.4.1",
"uint8arrays": "3.0.0",
"ws": "^8.12.0",
"zod": "^3.23.8"
}
},
···
"node": ">=6"
}
},
"node_modules/events": {
"version": "3.3.0",
"resolved": "https://registry.npmjs.org/events/-/events-3.3.0.tgz",
···
"integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew=="
},
"node_modules/ipaddr.js": {
-
"version": "2.2.0",
-
"resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-2.2.0.tgz",
-
"integrity": "sha512-Ag3wB2o37wslZS19hZqorUnrnzSkpOVy+IiiDEiTqNubEYpYuHWIf6K4psgN2ZWKExS4xhVCrRVfb/wfW8fWJA==",
"engines": {
-
"node": ">= 10"
}
},
"node_modules/iron-session": {
···
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/package-json-from-dist": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/package-json-from-dist/-/package-json-from-dist-1.0.0.tgz",
···
"forwarded": "0.2.0",
"ipaddr.js": "1.9.1"
},
-
"engines": {
-
"node": ">= 0.10"
-
}
-
},
-
"node_modules/proxy-addr/node_modules/ipaddr.js": {
-
"version": "1.9.1",
-
"resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz",
-
"integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==",
"engines": {
"node": ">= 0.10"
}
···
"@atproto/api": "^0.13.4",
"@atproto/common": "^0.4.1",
"@atproto/identity": "^0.4.0",
+
"@atproto/lexicon": "0.4.1-rc.0",
"@atproto/oauth-client-node": "^0.1.0",
+
"@atproto/repo": "0.4.2-rc.0",
+
"@atproto/sync": "^0.1.0",
"@atproto/syntax": "^0.3.0",
"@atproto/xrpc-server": "^0.6.3",
"better-sqlite3": "^11.1.2",
···
"undici": "^6.14.1"
}
},
+
"node_modules/@atproto-labs/fetch-node/node_modules/ipaddr.js": {
+
"version": "2.2.0",
+
"resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-2.2.0.tgz",
+
"integrity": "sha512-Ag3wB2o37wslZS19hZqorUnrnzSkpOVy+IiiDEiTqNubEYpYuHWIf6K4psgN2ZWKExS4xhVCrRVfb/wfW8fWJA==",
+
"engines": {
+
"node": ">= 10"
+
}
+
},
"node_modules/@atproto-labs/handle-resolver": {
"version": "0.1.2",
"resolved": "https://registry.npmjs.org/@atproto-labs/handle-resolver/-/handle-resolver-0.1.2.tgz",
···
"tlds": "^1.234.0"
}
},
+
"node_modules/@atproto/api/node_modules/@atproto/lexicon": {
+
"version": "0.4.1",
+
"resolved": "https://registry.npmjs.org/@atproto/lexicon/-/lexicon-0.4.1.tgz",
+
"integrity": "sha512-bzyr+/VHXLQWbumViX5L7h1NKQObfs8Z+XZJl43OUK8nYFUI4e/sW1IZKRNfw7Wvi5YVNK+J+yP3DWIBZhkCYA==",
+
"dependencies": {
+
"@atproto/common-web": "^0.3.0",
+
"@atproto/syntax": "^0.3.0",
+
"iso-datestring-validator": "^2.2.2",
+
"multiformats": "^9.9.0",
+
"zod": "^3.23.8"
+
}
+
},
"node_modules/@atproto/common": {
"version": "0.4.1",
"resolved": "https://registry.npmjs.org/@atproto/common/-/common-0.4.1.tgz",
···
"lex": "dist/index.js"
}
},
+
"node_modules/@atproto/lex-cli/node_modules/@atproto/lexicon": {
"version": "0.4.1",
"resolved": "https://registry.npmjs.org/@atproto/lexicon/-/lexicon-0.4.1.tgz",
"integrity": "sha512-bzyr+/VHXLQWbumViX5L7h1NKQObfs8Z+XZJl43OUK8nYFUI4e/sW1IZKRNfw7Wvi5YVNK+J+yP3DWIBZhkCYA==",
+
"dev": true,
+
"dependencies": {
+
"@atproto/common-web": "^0.3.0",
+
"@atproto/syntax": "^0.3.0",
+
"iso-datestring-validator": "^2.2.2",
+
"multiformats": "^9.9.0",
+
"zod": "^3.23.8"
+
}
+
},
+
"node_modules/@atproto/lexicon": {
+
"version": "0.4.1-rc.0",
+
"resolved": "https://registry.npmjs.org/@atproto/lexicon/-/lexicon-0.4.1-rc.0.tgz",
+
"integrity": "sha512-CSYO8MWbxTXTLQMEJ1mTXD2pDxIXO2oCK/FVw9T/BeXLMcvwmeVgKAaytd1AGFkapX8IMAAtjBB3cnaltuHwbg==",
"dependencies": {
"@atproto/common-web": "^0.3.0",
"@atproto/syntax": "^0.3.0",
···
}
},
"node_modules/@atproto/repo": {
+
"version": "0.4.2-rc.0",
+
"resolved": "https://registry.npmjs.org/@atproto/repo/-/repo-0.4.2-rc.0.tgz",
+
"integrity": "sha512-y8zXAR23r6qlsTmbzXaBEHYjvlgeNlAKj9eJ6V17JtT+4FVdW246alhsgSsglJ2Uv/e24RC1r90yNJNRxqDzXw==",
+
"dependencies": {
+
"@atproto/common": "^0.4.1",
+
"@atproto/common-web": "^0.3.0",
+
"@atproto/crypto": "^0.4.0",
+
"@atproto/lexicon": "^0.4.1-rc.0",
+
"@ipld/car": "^3.2.3",
+
"@ipld/dag-cbor": "^7.0.0",
+
"multiformats": "^9.9.0",
+
"uint8arrays": "3.0.0",
+
"zod": "^3.23.8"
+
}
+
},
+
"node_modules/@atproto/sync": {
+
"version": "0.1.0",
+
"resolved": "https://registry.npmjs.org/@atproto/sync/-/sync-0.1.0.tgz",
+
"integrity": "sha512-2O1UPaeZfL0agitE9rp2mjYVezvZsao3DgJwWCSid1S0N7Y2pOdc7/fSLH/OHn96QhG7g0FGpWzTEcdekRuT0g==",
+
"dependencies": {
+
"@atproto/common": "^0.4.1",
+
"@atproto/identity": "^0.4.1",
+
"@atproto/lexicon": "^0.4.1",
+
"@atproto/repo": "^0.5.0",
+
"@atproto/syntax": "^0.3.0",
+
"@atproto/xrpc-server": "^0.6.3",
+
"multiformats": "^9.9.0",
+
"p-queue": "^6.6.2"
+
}
+
},
+
"node_modules/@atproto/sync/node_modules/@atproto/lexicon": {
+
"version": "0.4.1",
+
"resolved": "https://registry.npmjs.org/@atproto/lexicon/-/lexicon-0.4.1.tgz",
+
"integrity": "sha512-bzyr+/VHXLQWbumViX5L7h1NKQObfs8Z+XZJl43OUK8nYFUI4e/sW1IZKRNfw7Wvi5YVNK+J+yP3DWIBZhkCYA==",
+
"dependencies": {
+
"@atproto/common-web": "^0.3.0",
+
"@atproto/syntax": "^0.3.0",
+
"iso-datestring-validator": "^2.2.2",
+
"multiformats": "^9.9.0",
+
"zod": "^3.23.8"
+
}
+
},
+
"node_modules/@atproto/sync/node_modules/@atproto/repo": {
+
"version": "0.5.0",
+
"resolved": "https://registry.npmjs.org/@atproto/repo/-/repo-0.5.0.tgz",
+
"integrity": "sha512-kZbj4wW5eFrDjkSTS9z+6bT4OTr5K4GrqWukWbfdBJtZPXsRDm75AV0C9ItoHDTdbBXn65TK6kqaJTrf89osCg==",
"dependencies": {
"@atproto/common": "^0.4.1",
"@atproto/common-web": "^0.3.0",
···
"rate-limiter-flexible": "^2.4.1",
"uint8arrays": "3.0.0",
"ws": "^8.12.0",
+
"zod": "^3.23.8"
+
}
+
},
+
"node_modules/@atproto/xrpc-server/node_modules/@atproto/lexicon": {
+
"version": "0.4.1",
+
"resolved": "https://registry.npmjs.org/@atproto/lexicon/-/lexicon-0.4.1.tgz",
+
"integrity": "sha512-bzyr+/VHXLQWbumViX5L7h1NKQObfs8Z+XZJl43OUK8nYFUI4e/sW1IZKRNfw7Wvi5YVNK+J+yP3DWIBZhkCYA==",
+
"dependencies": {
+
"@atproto/common-web": "^0.3.0",
+
"@atproto/syntax": "^0.3.0",
+
"iso-datestring-validator": "^2.2.2",
+
"multiformats": "^9.9.0",
+
"zod": "^3.23.8"
+
}
+
},
+
"node_modules/@atproto/xrpc/node_modules/@atproto/lexicon": {
+
"version": "0.4.1",
+
"resolved": "https://registry.npmjs.org/@atproto/lexicon/-/lexicon-0.4.1.tgz",
+
"integrity": "sha512-bzyr+/VHXLQWbumViX5L7h1NKQObfs8Z+XZJl43OUK8nYFUI4e/sW1IZKRNfw7Wvi5YVNK+J+yP3DWIBZhkCYA==",
+
"dependencies": {
+
"@atproto/common-web": "^0.3.0",
+
"@atproto/syntax": "^0.3.0",
+
"iso-datestring-validator": "^2.2.2",
+
"multiformats": "^9.9.0",
"zod": "^3.23.8"
}
},
···
"node": ">=6"
}
},
+
"node_modules/eventemitter3": {
+
"version": "4.0.7",
+
"resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-4.0.7.tgz",
+
"integrity": "sha512-8guHBZCwKnFhYdHr2ysuRWErTwhoN2X8XELRlrRwpmfeY2jjuUN4taQMsULKUVo1K4DvZl+0pgfyoysHxvmvEw=="
+
},
"node_modules/events": {
"version": "3.3.0",
"resolved": "https://registry.npmjs.org/events/-/events-3.3.0.tgz",
···
"integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew=="
},
"node_modules/ipaddr.js": {
+
"version": "1.9.1",
+
"resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz",
+
"integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==",
"engines": {
+
"node": ">= 0.10"
}
},
"node_modules/iron-session": {
···
"url": "https://github.com/sponsors/sindresorhus"
}
},
+
"node_modules/p-finally": {
+
"version": "1.0.0",
+
"resolved": "https://registry.npmjs.org/p-finally/-/p-finally-1.0.0.tgz",
+
"integrity": "sha512-LICb2p9CB7FS+0eR1oqWnHhp0FljGLZCWBE9aix0Uye9W8LTQPwMTYVGWQWIw9RdQiDg4+epXQODwIYJtSJaow==",
+
"engines": {
+
"node": ">=4"
+
}
+
},
+
"node_modules/p-queue": {
+
"version": "6.6.2",
+
"resolved": "https://registry.npmjs.org/p-queue/-/p-queue-6.6.2.tgz",
+
"integrity": "sha512-RwFpb72c/BhQLEXIZ5K2e+AhgNVmIejGlTgiB9MzZ0e93GRvqZ7uSi0dvRF7/XIXDeNkra2fNHBxTyPDGySpjQ==",
+
"dependencies": {
+
"eventemitter3": "^4.0.4",
+
"p-timeout": "^3.2.0"
+
},
+
"engines": {
+
"node": ">=8"
+
},
+
"funding": {
+
"url": "https://github.com/sponsors/sindresorhus"
+
}
+
},
+
"node_modules/p-timeout": {
+
"version": "3.2.0",
+
"resolved": "https://registry.npmjs.org/p-timeout/-/p-timeout-3.2.0.tgz",
+
"integrity": "sha512-rhIwUycgwwKcP9yTOOFK/AKsAopjjCakVqLHePO3CC6Mir1Z99xT+R63jZxAT5lFZLa2inS5h+ZS2GvR99/FBg==",
+
"dependencies": {
+
"p-finally": "^1.0.0"
+
},
+
"engines": {
+
"node": ">=8"
+
}
+
},
"node_modules/package-json-from-dist": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/package-json-from-dist/-/package-json-from-dist-1.0.0.tgz",
···
"forwarded": "0.2.0",
"ipaddr.js": "1.9.1"
},
"engines": {
"node": ">= 0.10"
}
+3 -2
package.json
···
"@atproto/common": "^0.4.1",
"@atproto/api": "^0.13.4",
"@atproto/identity": "^0.4.0",
-
"@atproto/lexicon": "^0.4.1",
"@atproto/oauth-client-node": "^0.1.0",
-
"@atproto/repo": "^0.4.3",
"@atproto/syntax": "^0.3.0",
"@atproto/xrpc-server": "^0.6.3",
"better-sqlite3": "^11.1.2",
···
"@atproto/common": "^0.4.1",
"@atproto/api": "^0.13.4",
"@atproto/identity": "^0.4.0",
+
"@atproto/lexicon": "0.4.1-rc.0",
"@atproto/oauth-client-node": "^0.1.0",
+
"@atproto/repo": "0.4.2-rc.0",
+
"@atproto/sync": "^0.1.0",
"@atproto/syntax": "^0.3.0",
"@atproto/xrpc-server": "^0.6.3",
"better-sqlite3": "^11.1.2",
-194
src/firehose/firehose.ts
···
-
import type { RepoRecord } from '@atproto/lexicon'
-
import { cborToLexRecord, readCar } from '@atproto/repo'
-
import { AtUri } from '@atproto/syntax'
-
import { Subscription } from '@atproto/xrpc-server'
-
import type { CID } from 'multiformats/cid'
-
import {
-
type Account,
-
type Commit,
-
type Identity,
-
type RepoEvent,
-
isAccount,
-
isCommit,
-
isIdentity,
-
isValidRepoEvent,
-
} from './lexicons'
-
-
type Opts = {
-
service?: string
-
getCursor?: () => Promise<number | undefined>
-
setCursor?: (cursor: number) => Promise<void>
-
subscriptionReconnectDelay?: number
-
filterCollections?: string[]
-
excludeIdentity?: boolean
-
excludeAccount?: boolean
-
excludeCommit?: boolean
-
}
-
-
export class Firehose {
-
public sub: Subscription<RepoEvent>
-
private abortController: AbortController
-
-
constructor(public opts: Opts) {
-
this.abortController = new AbortController()
-
this.sub = new Subscription({
-
service: opts.service ?? 'https://bsky.network',
-
method: 'com.atproto.sync.subscribeRepos',
-
signal: this.abortController.signal,
-
getParams: async () => {
-
if (!opts.getCursor) return undefined
-
const cursor = await opts.getCursor()
-
return { cursor }
-
},
-
validate: (value: unknown) => {
-
try {
-
return isValidRepoEvent(value)
-
} catch (err) {
-
console.error('repo subscription skipped invalid message', err)
-
}
-
},
-
})
-
}
-
-
async *run(): AsyncGenerator<Event> {
-
try {
-
for await (const evt of this.sub) {
-
try {
-
if (isCommit(evt) && !this.opts.excludeCommit) {
-
const parsed = await parseCommit(evt)
-
for (const write of parsed) {
-
if (
-
!this.opts.filterCollections ||
-
this.opts.filterCollections.includes(write.uri.collection)
-
) {
-
yield write
-
}
-
}
-
} else if (isAccount(evt) && !this.opts.excludeAccount) {
-
const parsed = parseAccount(evt)
-
if (parsed) {
-
yield parsed
-
}
-
} else if (isIdentity(evt) && !this.opts.excludeIdentity) {
-
yield parseIdentity(evt)
-
}
-
} catch (err) {
-
console.error('repo subscription could not handle message', err)
-
}
-
if (this.opts.setCursor && typeof evt.seq === 'number') {
-
await this.opts.setCursor(evt.seq)
-
}
-
}
-
} catch (err) {
-
console.error('repo subscription errored', err)
-
setTimeout(() => this.run(), this.opts.subscriptionReconnectDelay ?? 3000)
-
}
-
}
-
-
destroy() {
-
this.abortController.abort()
-
}
-
}
-
-
export const parseCommit = async (evt: Commit): Promise<CommitEvt[]> => {
-
const car = await readCar(evt.blocks)
-
-
const evts: CommitEvt[] = []
-
-
for (const op of evt.ops) {
-
const uri = new AtUri(`at://${evt.repo}/${op.path}`)
-
-
const meta: CommitMeta = {
-
uri,
-
author: uri.host,
-
collection: uri.collection,
-
rkey: uri.rkey,
-
}
-
-
if (op.action === 'create' || op.action === 'update') {
-
if (!op.cid) continue
-
const recordBytes = car.blocks.get(op.cid)
-
if (!recordBytes) continue
-
const record = cborToLexRecord(recordBytes)
-
evts.push({
-
...meta,
-
event: op.action as 'create' | 'update',
-
cid: op.cid,
-
record,
-
})
-
}
-
-
if (op.action === 'delete') {
-
evts.push({
-
...meta,
-
event: 'delete',
-
})
-
}
-
}
-
-
return evts
-
}
-
-
export const parseIdentity = (evt: Identity): IdentityEvt => {
-
return {
-
event: 'identity',
-
did: evt.did,
-
handle: evt.handle,
-
}
-
}
-
-
export const parseAccount = (evt: Account): AccountEvt | undefined => {
-
if (evt.status && !isValidStatus(evt.status)) return
-
return {
-
event: 'account',
-
did: evt.did,
-
active: evt.active,
-
status: evt.status as AccountStatus,
-
}
-
}
-
-
const isValidStatus = (str: string): str is AccountStatus => {
-
return ['takendown', 'suspended', 'deleted', 'deactivated'].includes(str)
-
}
-
-
type Event = CommitEvt | IdentityEvt | AccountEvt
-
-
type CommitMeta = {
-
uri: AtUri
-
author: string
-
collection: string
-
rkey: string
-
}
-
-
type CommitEvt = Create | Update | Delete
-
-
type Create = CommitMeta & {
-
event: 'create'
-
record: RepoRecord
-
cid: CID
-
}
-
-
type Update = CommitMeta & {
-
event: 'update'
-
record: RepoRecord
-
cid: CID
-
}
-
-
type Delete = CommitMeta & {
-
event: 'delete'
-
}
-
-
type IdentityEvt = {
-
event: 'identity'
-
did: string
-
handle?: string
-
}
-
-
type AccountEvt = {
-
event: 'account'
-
did: string
-
active: boolean
-
status?: AccountStatus
-
}
-
-
type AccountStatus = 'takendown' | 'suspended' | 'deleted' | 'deactivated'
···
+19 -18
src/firehose/ingester.ts src/ingester.ts
···
import type { Database } from '#/db'
-
import { Firehose } from '#/firehose/firehose'
import * as Status from '#/lexicon/types/com/example/status'
-
export class Ingester {
-
firehose: Firehose | undefined
-
constructor(public db: Database) {}
-
-
async start() {
-
const firehose = new Firehose({})
-
-
for await (const evt of firehose.run()) {
// Watch for write events
if (evt.event === 'create' || evt.event === 'update') {
const record = evt.record
···
Status.validateRecord(record).success
) {
// Store the status in our SQLite
-
await this.db
.insertInto('status')
.values({
uri: evt.uri.toString(),
-
authorDid: evt.author,
status: record.status,
createdAt: record.createdAt,
indexedAt: new Date().toISOString(),
···
evt.collection === 'com.example.status'
) {
// Remove the status from our SQLite
-
await this.db.deleteFrom('status').where({ uri: evt.uri.toString() })
}
-
}
-
}
-
-
destroy() {
-
this.firehose?.destroy()
-
}
}
···
+
import pino from 'pino'
+
import { IdResolver } from '@atproto/identity'
+
import { Firehose } from '@atproto/sync'
import type { Database } from '#/db'
import * as Status from '#/lexicon/types/com/example/status'
+
export function createIngester(db: Database, idResolver: IdResolver) {
+
const logger = pino({ name: 'firehose ingestion' })
+
return new Firehose({
+
idResolver,
+
handleEvent: async (evt) => {
// Watch for write events
if (evt.event === 'create' || evt.event === 'update') {
const record = evt.record
···
Status.validateRecord(record).success
) {
// Store the status in our SQLite
+
await db
.insertInto('status')
.values({
uri: evt.uri.toString(),
+
authorDid: evt.did,
status: record.status,
createdAt: record.createdAt,
indexedAt: new Date().toISOString(),
···
evt.collection === 'com.example.status'
) {
// Remove the status from our SQLite
+
await db.deleteFrom('status').where({ uri: evt.uri.toString() })
}
+
},
+
onError: (err) => {
+
logger.error({ err }, 'error on firehose ingestion')
+
},
+
filterCollections: ['com.example.status'],
+
excludeIdentity: true,
+
excludeAccount: true,
+
})
}
-355
src/firehose/lexicons.ts
···
-
import type { IncomingMessage } from 'node:http'
-
-
import { type LexiconDoc, Lexicons } from '@atproto/lexicon'
-
import type { ErrorFrame, HandlerAuth } from '@atproto/xrpc-server'
-
import type { CID } from 'multiformats/cid'
-
-
// @NOTE: this file is an ugly copy job of codegen output. I'd like to clean this whole thing up
-
-
export function isObj(v: unknown): v is Record<string, unknown> {
-
return typeof v === 'object' && v !== null
-
}
-
-
export function hasProp<K extends PropertyKey>(data: object, prop: K): data is Record<K, unknown> {
-
return prop in data
-
}
-
-
export interface QueryParams {
-
/** The last known event seq number to backfill from. */
-
cursor?: number
-
}
-
-
export type RepoEvent =
-
| Commit
-
| Identity
-
| Account
-
| Handle
-
| Migrate
-
| Tombstone
-
| Info
-
| { $type: string; [k: string]: unknown }
-
export type HandlerError = ErrorFrame<'FutureCursor' | 'ConsumerTooSlow'>
-
export type HandlerOutput = HandlerError | RepoEvent
-
export type HandlerReqCtx<HA extends HandlerAuth = never> = {
-
auth: HA
-
params: QueryParams
-
req: IncomingMessage
-
signal: AbortSignal
-
}
-
export type Handler<HA extends HandlerAuth = never> = (ctx: HandlerReqCtx<HA>) => AsyncIterable<HandlerOutput>
-
-
/** Represents an update of repository state. Note that empty commits are allowed, which include no repo data changes, but an update to rev and signature. */
-
export interface Commit {
-
/** The stream sequence number of this message. */
-
seq: number
-
/** DEPRECATED -- unused */
-
rebase: boolean
-
/** Indicates that this commit contained too many ops, or data size was too large. Consumers will need to make a separate request to get missing data. */
-
tooBig: boolean
-
/** The repo this event comes from. */
-
repo: string
-
/** Repo commit object CID. */
-
commit: CID
-
/** DEPRECATED -- unused. WARNING -- nullable and optional; stick with optional to ensure golang interoperability. */
-
prev?: CID | null
-
/** The rev of the emitted commit. Note that this information is also in the commit object included in blocks, unless this is a tooBig event. */
-
rev: string
-
/** The rev of the last emitted commit from this repo (if any). */
-
since: string | null
-
/** CAR file containing relevant blocks, as a diff since the previous repo state. */
-
blocks: Uint8Array
-
ops: RepoOp[]
-
blobs: CID[]
-
/** Timestamp of when this message was originally broadcast. */
-
time: string
-
[k: string]: unknown
-
}
-
-
export function isCommit(v: unknown): v is Commit {
-
return isObj(v) && hasProp(v, '$type') && v.$type === 'com.atproto.sync.subscribeRepos#commit'
-
}
-
-
/** Represents a change to an account's identity. Could be an updated handle, signing key, or pds hosting endpoint. Serves as a prod to all downstream services to refresh their identity cache. */
-
export interface Identity {
-
seq: number
-
did: string
-
time: string
-
/** The current handle for the account, or 'handle.invalid' if validation fails. This field is optional, might have been validated or passed-through from an upstream source. Semantics and behaviors for PDS vs Relay may evolve in the future; see atproto specs for more details. */
-
handle?: string
-
[k: string]: unknown
-
}
-
-
export function isIdentity(v: unknown): v is Identity {
-
return isObj(v) && hasProp(v, '$type') && v.$type === 'com.atproto.sync.subscribeRepos#identity'
-
}
-
-
/** Represents a change to an account's status on a host (eg, PDS or Relay). The semantics of this event are that the status is at the host which emitted the event, not necessarily that at the currently active PDS. Eg, a Relay takedown would emit a takedown with active=false, even if the PDS is still active. */
-
export interface Account {
-
seq: number
-
did: string
-
time: string
-
/** Indicates that the account has a repository which can be fetched from the host that emitted this event. */
-
active: boolean
-
/** If active=false, this optional field indicates a reason for why the account is not active. */
-
status?: 'takendown' | 'suspended' | 'deleted' | 'deactivated' | (string & {})
-
[k: string]: unknown
-
}
-
-
export function isAccount(v: unknown): v is Account {
-
return isObj(v) && hasProp(v, '$type') && v.$type === 'com.atproto.sync.subscribeRepos#account'
-
}
-
-
/** DEPRECATED -- Use #identity event instead */
-
export interface Handle {
-
seq: number
-
did: string
-
handle: string
-
time: string
-
[k: string]: unknown
-
}
-
-
export function isHandle(v: unknown): v is Handle {
-
return isObj(v) && hasProp(v, '$type') && v.$type === 'com.atproto.sync.subscribeRepos#handle'
-
}
-
-
/** DEPRECATED -- Use #account event instead */
-
export interface Migrate {
-
seq: number
-
did: string
-
migrateTo: string | null
-
time: string
-
[k: string]: unknown
-
}
-
-
export function isMigrate(v: unknown): v is Migrate {
-
return isObj(v) && hasProp(v, '$type') && v.$type === 'com.atproto.sync.subscribeRepos#migrate'
-
}
-
-
/** DEPRECATED -- Use #account event instead */
-
export interface Tombstone {
-
seq: number
-
did: string
-
time: string
-
[k: string]: unknown
-
}
-
-
export function isTombstone(v: unknown): v is Tombstone {
-
return isObj(v) && hasProp(v, '$type') && v.$type === 'com.atproto.sync.subscribeRepos#tombstone'
-
}
-
-
export interface Info {
-
name: 'OutdatedCursor' | (string & {})
-
message?: string
-
[k: string]: unknown
-
}
-
-
export function isInfo(v: unknown): v is Info {
-
return isObj(v) && hasProp(v, '$type') && v.$type === 'com.atproto.sync.subscribeRepos#info'
-
}
-
-
/** A repo operation, ie a mutation of a single record. */
-
export interface RepoOp {
-
action: 'create' | 'update' | 'delete' | (string & {})
-
path: string
-
/** For creates and updates, the new record CID. For deletions, null. */
-
cid: CID | null
-
[k: string]: unknown
-
}
-
-
export function isRepoOp(v: unknown): v is RepoOp {
-
return isObj(v) && hasProp(v, '$type') && v.$type === 'com.atproto.sync.subscribeRepos#repoOp'
-
}
-
-
export const ComAtprotoSyncSubscribeRepos: LexiconDoc = {
-
lexicon: 1,
-
id: 'com.atproto.sync.subscribeRepos',
-
defs: {
-
main: {
-
type: 'subscription',
-
description: 'Subscribe to repo updates',
-
parameters: {
-
type: 'params',
-
properties: {
-
cursor: {
-
type: 'integer',
-
description: 'The last known event to backfill from.',
-
},
-
},
-
},
-
message: {
-
schema: {
-
type: 'union',
-
refs: [
-
'lex:com.atproto.sync.subscribeRepos#commit',
-
'lex:com.atproto.sync.subscribeRepos#handle',
-
'lex:com.atproto.sync.subscribeRepos#migrate',
-
'lex:com.atproto.sync.subscribeRepos#tombstone',
-
'lex:com.atproto.sync.subscribeRepos#info',
-
],
-
},
-
},
-
errors: [
-
{
-
name: 'FutureCursor',
-
},
-
{
-
name: 'ConsumerTooSlow',
-
},
-
],
-
},
-
commit: {
-
type: 'object',
-
required: ['seq', 'rebase', 'tooBig', 'repo', 'commit', 'rev', 'since', 'blocks', 'ops', 'blobs', 'time'],
-
nullable: ['prev', 'since'],
-
properties: {
-
seq: {
-
type: 'integer',
-
},
-
rebase: {
-
type: 'boolean',
-
},
-
tooBig: {
-
type: 'boolean',
-
},
-
repo: {
-
type: 'string',
-
format: 'did',
-
},
-
commit: {
-
type: 'cid-link',
-
},
-
prev: {
-
type: 'cid-link',
-
},
-
rev: {
-
type: 'string',
-
description: 'The rev of the emitted commit',
-
},
-
since: {
-
type: 'string',
-
description: 'The rev of the last emitted commit from this repo',
-
},
-
blocks: {
-
type: 'bytes',
-
description: 'CAR file containing relevant blocks',
-
maxLength: 1000000,
-
},
-
ops: {
-
type: 'array',
-
items: {
-
type: 'ref',
-
ref: 'lex:com.atproto.sync.subscribeRepos#repoOp',
-
},
-
maxLength: 200,
-
},
-
blobs: {
-
type: 'array',
-
items: {
-
type: 'cid-link',
-
},
-
},
-
time: {
-
type: 'string',
-
format: 'datetime',
-
},
-
},
-
},
-
handle: {
-
type: 'object',
-
required: ['seq', 'did', 'handle', 'time'],
-
properties: {
-
seq: {
-
type: 'integer',
-
},
-
did: {
-
type: 'string',
-
format: 'did',
-
},
-
handle: {
-
type: 'string',
-
format: 'handle',
-
},
-
time: {
-
type: 'string',
-
format: 'datetime',
-
},
-
},
-
},
-
migrate: {
-
type: 'object',
-
required: ['seq', 'did', 'migrateTo', 'time'],
-
nullable: ['migrateTo'],
-
properties: {
-
seq: {
-
type: 'integer',
-
},
-
did: {
-
type: 'string',
-
format: 'did',
-
},
-
migrateTo: {
-
type: 'string',
-
},
-
time: {
-
type: 'string',
-
format: 'datetime',
-
},
-
},
-
},
-
tombstone: {
-
type: 'object',
-
required: ['seq', 'did', 'time'],
-
properties: {
-
seq: {
-
type: 'integer',
-
},
-
did: {
-
type: 'string',
-
format: 'did',
-
},
-
time: {
-
type: 'string',
-
format: 'datetime',
-
},
-
},
-
},
-
info: {
-
type: 'object',
-
required: ['name'],
-
properties: {
-
name: {
-
type: 'string',
-
knownValues: ['OutdatedCursor'],
-
},
-
message: {
-
type: 'string',
-
},
-
},
-
},
-
repoOp: {
-
type: 'object',
-
description:
-
"A repo operation, ie a write of a single record. For creates and updates, cid is the record's CID as of this operation. For deletes, it's null.",
-
required: ['action', 'path', 'cid'],
-
nullable: ['cid'],
-
properties: {
-
action: {
-
type: 'string',
-
knownValues: ['create', 'update', 'delete'],
-
},
-
path: {
-
type: 'string',
-
},
-
cid: {
-
type: 'cid-link',
-
},
-
},
-
},
-
},
-
}
-
-
const lexicons = new Lexicons([ComAtprotoSyncSubscribeRepos])
-
-
export const isValidRepoEvent = (evt: unknown) => {
-
return lexicons.assertValidXrpcMessage<RepoEvent>('com.atproto.sync.subscribeRepos', evt)
-
}
···
+9 -6
src/firehose/resolver.ts src/id-resolver.ts
···
const HOUR = 60e3 * 60
const DAY = HOUR * 24
-
export interface Resolver {
resolveDidToHandle(did: string): Promise<string>
resolveDidsToHandles(dids: string[]): Promise<Record<string, string>>
}
-
export function createResolver() {
-
const resolver = new IdResolver({
-
didCache: new MemoryCache(HOUR, DAY),
-
})
-
return {
async resolveDidToHandle(did: string): Promise<string> {
const didDoc = await resolver.did.resolveAtprotoData(did)
···
const HOUR = 60e3 * 60
const DAY = HOUR * 24
+
+
export function createIdResolver() {
+
return new IdResolver({
+
didCache: new MemoryCache(HOUR, DAY),
+
})
+
}
+
+
export interface BidirectionalResolver {
resolveDidToHandle(did: string): Promise<string>
resolveDidsToHandles(dids: string[]): Promise<Record<string, string>>
}
+
export function createBidirectionalResolver(resolver: IdResolver) {
return {
async resolveDidToHandle(did: string): Promise<string> {
const didDoc = await resolver.did.resolveAtprotoData(did)
+10 -7
src/index.ts
···
import express, { type Express } from 'express'
import { pino } from 'pino'
import type { OAuthClient } from '@atproto/oauth-client-node'
import { createDb, migrateToLatest } from '#/db'
import { env } from '#/lib/env'
-
import { Ingester } from '#/firehose/ingester'
import { createRouter } from '#/routes'
import { createClient } from '#/auth/client'
-
import { createResolver, Resolver } from '#/firehose/resolver'
import type { Database } from '#/db'
// Application state passed to the router and elsewhere
export type AppContext = {
db: Database
-
ingester: Ingester
logger: pino.Logger
oauthClient: OAuthClient
-
resolver: Resolver
}
export class Server {
···
// Create the atproto utilities
const oauthClient = await createClient(db)
-
const ingester = new Ingester(db)
-
const resolver = createResolver()
const ctx = {
db,
ingester,
···
async close() {
this.ctx.logger.info('sigint received, shutting down')
-
this.ctx.ingester.destroy()
return new Promise<void>((resolve) => {
this.server.close(() => {
this.ctx.logger.info('server closed')
···
import express, { type Express } from 'express'
import { pino } from 'pino'
import type { OAuthClient } from '@atproto/oauth-client-node'
+
import { Firehose } from '@atproto/sync'
import { createDb, migrateToLatest } from '#/db'
import { env } from '#/lib/env'
+
import { createIngester } from '#/ingester'
import { createRouter } from '#/routes'
import { createClient } from '#/auth/client'
+
import { createBidirectionalResolver, createIdResolver, BidirectionalResolver } from '#/id-resolver'
import type { Database } from '#/db'
+
import { IdResolver, MemoryCache } from '@atproto/identity'
// Application state passed to the router and elsewhere
export type AppContext = {
db: Database
+
ingester: Firehose
logger: pino.Logger
oauthClient: OAuthClient
+
resolver: BidirectionalResolver
}
export class Server {
···
// Create the atproto utilities
const oauthClient = await createClient(db)
+
const baseIdResolver = createIdResolver()
+
const ingester = createIngester(db, baseIdResolver)
+
const resolver = createBidirectionalResolver(baseIdResolver)
const ctx = {
db,
ingester,
···
async close() {
this.ctx.logger.info('sigint received, shutting down')
+
await this.ctx.ingester.destroy()
return new Promise<void>((resolve) => {
this.server.close(() => {
this.ctx.logger.info('server closed')
+3 -1
src/routes.ts
···
import { OAuthResolverError } from '@atproto/oauth-client-node'
import { isValidHandle } from '@atproto/syntax'
import { TID } from '@atproto/common'
import express from 'express'
import { getIronSession } from 'iron-session'
import type { AppContext } from '#/index'
···
})
if (!session.did) return null
try {
-
return await ctx.oauthClient.restore(session.did)
} catch (err) {
ctx.logger.warn({ err }, 'oauth restore failed')
await session.destroy()
···
import { OAuthResolverError } from '@atproto/oauth-client-node'
import { isValidHandle } from '@atproto/syntax'
import { TID } from '@atproto/common'
+
import { Agent } from '@atproto/api'
import express from 'express'
import { getIronSession } from 'iron-session'
import type { AppContext } from '#/index'
···
})
if (!session.did) return null
try {
+
const oauthSession = await ctx.oauthClient.restore(session.did)
+
return oauthSession ? new Agent(oauthSession) : null
} catch (err) {
ctx.logger.warn({ err }, 'oauth restore failed')
await session.destroy()