this repo has no description
1#!/usr/bin/env python3 2 3import asyncio 4from datetime import datetime, timezone 5from io import BytesIO 6import json 7import os 8import sqlite3 9import sys 10 11from atproto import CAR 12import redis 13import dag_cbor 14import websockets 15 16app_bsky_allowlist = set([ 17 'app.bsky.actor.profile', 18 'app.bsky.feed.generator', 19 'app.bsky.feed.like', 20 'app.bsky.feed.post', 21 'app.bsky.feed.repost', 22 'app.bsky.feed.threadgate', 23 'app.bsky.graph.block', 24 'app.bsky.graph.follow', 25 'app.bsky.graph.list', 26 'app.bsky.graph.listblock', 27 'app.bsky.graph.listitem', 28 'app.bsky.labeler.service', 29 'chat.bsky.actor.declaration', 30 'app.bsky.graph.starterpack', 31]) 32 33async def bsky_activity(): 34 relay_url = 'ws://localhost:6008/subscribe' 35 36 sys.stdout.write(f'opening websocket connection to {relay_url}\n') 37 sys.stdout.flush() 38 39 async with websockets.connect(relay_url, ping_timeout=60) as firehose: 40 while True: 41 payload = BytesIO(await firehose.recv()) 42 43 yield json.load(payload) 44 45async def main(): 46 redis_cnx = redis.Redis() 47 redis_pipe = redis_cnx.pipeline() 48 49 if os.path.exists('/opt/muninsky/users.db'): 50 db_fname = '/opt/muninsky/users.db' 51 else: 52 db_fname = 'users.db' 53 54 db_cnx = sqlite3.connect(db_fname) 55 with db_cnx: 56 db_cnx.executescript(""" 57 PRAGMA journal_mode = WAL; 58 PRAGMA synchronous = off; 59 CREATE TABLE IF NOT EXISTS users (did TEXT, ts TIMESTAMP); 60 CREATE UNIQUE INDEX IF NOT EXISTS did_idx on users(did); 61 CREATE INDEX IF NOT EXISTS ts_idx on users(ts); 62 """) 63 64 sys.stdout.write('starting up\n') 65 sys.stdout.flush() 66 67 op_count = 0 68 async for payload in bsky_activity(): 69 if payload['opType'] != 'c': 70 continue 71 72 collection = payload['collection'] 73 if collection not in app_bsky_allowlist: 74 continue 75 76 repo_did = payload['did'] 77 repo_update_time = datetime.now(timezone.utc) 78 db_cnx.execute( 79 'insert into users values (:did, :ts) on conflict (did) do update set ts = :ts', 80 {'did': repo_did, 'ts': repo_update_time.timestamp()} 81 ) 82 83 redis_pipe \ 84 .incr(collection) \ 85 .incr('dev.edavis.muninsky.ops') 86 87 op_count += 1 88 if op_count % 500 == 0: 89 now = datetime.now(timezone.utc) 90 payload_seq = payload['seq'] 91 payload_lag = now - repo_update_time 92 93 sys.stdout.write(f'seq: {payload_seq}, lag: {payload_lag.total_seconds()}\n') 94 redis_pipe.set('dev.edavis.muninsky.seq', payload_seq) 95 redis_pipe.execute() 96 db_cnx.commit() 97 sys.stdout.flush() 98 99if __name__ == '__main__': 100 asyncio.run(main())