Scratch space for learning atproto app development

Replace the db resolver cache with an in-memory cache

Changed files
+4 -72
src
-7
src/db/migrations.ts
···
migrations['001'] = {
async up(db: Kysely<unknown>) {
await db.schema
-
.createTable('did_cache')
-
.addColumn('did', 'varchar', (col) => col.primaryKey())
-
.addColumn('doc', 'varchar', (col) => col.notNull())
-
.addColumn('updatedAt', 'varchar', (col) => col.notNull())
-
.execute()
-
await db.schema
.createTable('status')
.addColumn('authorDid', 'varchar', (col) => col.primaryKey())
.addColumn('status', 'varchar', (col) => col.notNull())
···
await db.schema.dropTable('auth_state').execute()
await db.schema.dropTable('auth_session').execute()
await db.schema.dropTable('status').execute()
-
await db.schema.dropTable('did_cache').execute()
},
}
-7
src/db/schema.ts
···
export type DatabaseSchema = {
-
did_cache: DidCache
status: Status
auth_session: AuthSession
auth_state: AuthState
-
}
-
-
export type DidCache = {
-
did: string
-
doc: string
-
updatedAt: string
}
export type Status = {
+3 -57
src/ident/resolver.ts
···
-
import { IdResolver, DidDocument, CacheResult } from '@atproto/identity'
-
import type { Database } from '#/db'
+
import { IdResolver, MemoryCache } from '@atproto/identity'
const HOUR = 60e3 * 60
const DAY = HOUR * 24
-
export function createResolver(db: Database) {
+
export function createResolver() {
const resolver = new IdResolver({
-
didCache: {
-
async cacheDid(did: string, doc: DidDocument): Promise<void> {
-
await db
-
.insertInto('did_cache')
-
.values({
-
did,
-
doc: JSON.stringify(doc),
-
updatedAt: new Date().toISOString(),
-
})
-
.onConflict((oc) =>
-
oc.column('did').doUpdateSet({
-
doc: JSON.stringify(doc),
-
updatedAt: new Date().toISOString(),
-
})
-
)
-
.execute()
-
},
-
-
async checkCache(did: string): Promise<CacheResult | null> {
-
const row = await db
-
.selectFrom('did_cache')
-
.selectAll()
-
.where('did', '=', did)
-
.executeTakeFirst()
-
if (!row) return null
-
const now = Date.now()
-
const updatedAt = +new Date(row.updatedAt)
-
return {
-
did,
-
doc: JSON.parse(row.doc),
-
updatedAt,
-
stale: now > updatedAt + HOUR,
-
expired: now > updatedAt + DAY,
-
}
-
},
-
-
async refreshCache(
-
did: string,
-
getDoc: () => Promise<DidDocument | null>
-
): Promise<void> {
-
const doc = await getDoc()
-
if (doc) {
-
await this.cacheDid(did, doc)
-
}
-
},
-
-
async clearEntry(did: string): Promise<void> {
-
await db.deleteFrom('did_cache').where('did', '=', did).execute()
-
},
-
-
async clear(): Promise<void> {
-
await db.deleteFrom('did_cache').execute()
-
},
-
},
+
didCache: new MemoryCache(HOUR, DAY),
})
return {
+1 -1
src/server.ts
···
await migrateToLatest(db)
const ingester = new Ingester(db)
const oauthClient = await createClient(db)
-
const resolver = await createResolver(db)
+
const resolver = createResolver()
ingester.start()
const ctx = {
db,