this repo has no description
1#!/usr/bin/env python3 2 3import asyncio 4from datetime import datetime, timezone 5import json 6import os 7import sqlite3 8import sys 9 10import redis 11import websockets 12 13app_bsky_allowlist = set([ 14 'app.bsky.actor.profile', 15 'app.bsky.feed.generator', 16 'app.bsky.feed.like', 17 'app.bsky.feed.post', 18 'app.bsky.feed.postgate', 19 'app.bsky.feed.repost', 20 'app.bsky.feed.threadgate', 21 'app.bsky.graph.block', 22 'app.bsky.graph.follow', 23 'app.bsky.graph.list', 24 'app.bsky.graph.listblock', 25 'app.bsky.graph.listitem', 26 'app.bsky.graph.starterpack', 27 'app.bsky.labeler.service', 28 'chat.bsky.actor.declaration', 29]) 30 31other_allowlist = set([ 32 'social.psky.feed.post', 33]) 34 35async def bsky_activity(): 36 relay_url = 'ws://localhost:6008/subscribe' 37 38 sys.stdout.write(f'opening websocket connection to {relay_url}\n') 39 sys.stdout.flush() 40 41 async with websockets.connect(relay_url, ping_timeout=60) as firehose: 42 while True: 43 yield json.loads(await firehose.recv()) 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 event in bsky_activity(): 69 if event['type'] != 'com': 70 continue 71 72 payload = event.get('commit') 73 if payload is None: 74 continue 75 76 if payload['type'] != 'c': 77 continue 78 79 collection = payload['collection'] 80 if collection not in app_bsky_allowlist | other_allowlist: 81 continue 82 83 repo_did = event['did'] 84 repo_update_time = datetime.now(timezone.utc) 85 db_cnx.execute( 86 'insert into users values (:did, :ts) on conflict (did) do update set ts = :ts', 87 {'did': repo_did, 'ts': repo_update_time.timestamp()} 88 ) 89 90 if collection == 'app.bsky.feed.post': 91 embed = payload['record'].get('embed') 92 if embed is not None and embed.get('$type', ''): 93 embed_type = embed['$type'] 94 redis_pipe.incr(f'app.bsky.feed.post:embed:{embed_type}') 95 96 redis_pipe \ 97 .incr(collection) \ 98 .incr('dev.edavis.muninsky.ops') 99 100 op_count += 1 101 if op_count % 500 == 0: 102 current_time_ms = datetime.now(timezone.utc).timestamp() 103 event_time_ms = event['time_us'] / 1_000_000 104 current_lag = current_time_ms - event_time_ms 105 sys.stdout.write(f'lag: {current_lag:.2f}\n') 106 redis_pipe.execute() 107 db_cnx.commit() 108 sys.stdout.flush() 109 110if __name__ == '__main__': 111 asyncio.run(main())