Repository navigation
Expand file tree
/
Copy pathdb.py
More file actions
291 lines (236 loc) · 13.7 KB
/
Copy pathdb.py
File metadata and controls
291 lines (236 loc) · 13.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
"""Postgres storage for server snapshots and the message log (replacing Xenon and Quark), and the
Discord member records (replacing Airtable's Discord table)."""
import json
import pathlib
import asyncpg
SCHEMA_PATH = pathlib.Path(__file__).with_name("schema.sql")
RETENTION_DAYS = 30
async def _init_connection(conn):
# Hand jsonb columns to and from Python as dicts/lists rather than strings
await conn.set_type_codec("jsonb", encoder=json.dumps, decoder=json.loads, schema="pg_catalog")
async def create_pool(dsn):
# A slow database should fail a query rather than leave event handlers waiting on it
return await asyncpg.create_pool(dsn, min_size=1, max_size=5, init=_init_connection, command_timeout=10)
async def apply_schema(pool):
async with pool.acquire() as conn:
await conn.execute(SCHEMA_PATH.read_text())
# ── Server snapshots ──────────────────────────────────────────────────────────
async def save_snapshot(pool, guild_id, data):
return await pool.fetchval(
"INSERT INTO server_snapshots (guild_id, data) VALUES ($1, $2) RETURNING id",
guild_id, data,
)
async def latest_snapshot_time(pool, guild_id):
"""When the newest snapshot was taken, without pulling its (large) data."""
return await pool.fetchval("SELECT max(taken_at) FROM server_snapshots WHERE guild_id = $1", guild_id)
async def latest_snapshot(pool, guild_id):
return await pool.fetchrow(
"SELECT id, guild_id, taken_at, data FROM server_snapshots WHERE guild_id = $1 ORDER BY taken_at DESC LIMIT 1",
guild_id,
)
# ── Message log ───────────────────────────────────────────────────────────────
async def log_message(pool, *, message_id, guild_id, channel_id, author_id, content, attachments, created_at,
author_bot=False, deleted_at=None):
"""Stores a message; a message already stored is left alone, except that a deletion is kept.
`deleted_at` is set for a message deleted before its log write landed, so whichever write
comes second, the row ends up marked deleted. Returns whether it inserted a row or marked one
deleted."""
result = await pool.execute(
"""
INSERT INTO message_log (message_id, guild_id, channel_id, author_id, content, attachments, created_at,
author_bot, deleted_at)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
ON CONFLICT (message_id) DO UPDATE SET deleted_at = coalesce(message_log.deleted_at, EXCLUDED.deleted_at)
WHERE message_log.deleted_at IS NULL AND EXCLUDED.deleted_at IS NOT NULL
""",
message_id, guild_id, channel_id, author_id, content, attachments, created_at, author_bot, deleted_at,
)
# The command tag ("INSERT 0 1") says whether a row was inserted or marked deleted
return result.endswith(" 1")
async def log_edit(pool, message_id, content, edited_at, message=None):
"""Records the old content and stores the new. Returns the content before the edit, or None if
the message isn't logged or its text didn't change (e.g. Discord adding a link embed).
`edited_at` is None when Discord updated the message without an edit (e.g. a link unfurl).
Edit events can be handled out of order, so one older than the stored edit is dropped.
`message` holds the log_message fields other than content (guild_id, channel_id, author_id,
attachments, created_at, and optionally author_bot). With it, an edit that arrives before its message was logged stores
the message with the edited content; log_message then leaves that row alone."""
async with pool.acquire() as conn:
async with conn.transaction():
if message is not None:
inserted = await conn.fetchval(
"""
INSERT INTO message_log (message_id, guild_id, channel_id, author_id, content, attachments, created_at,
edited_at, author_bot)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
ON CONFLICT (message_id) DO NOTHING
RETURNING message_id
""",
message_id, message["guild_id"], message["channel_id"], message["author_id"],
content, message["attachments"], message["created_at"], edited_at,
message.get("author_bot", False),
)
if inserted is not None:
return None
row = await conn.fetchrow(
"SELECT content, edited_at FROM message_log WHERE message_id = $1 FOR UPDATE", message_id
)
if row is None or row["content"] == content:
return None
if edited_at is not None and row["edited_at"] is not None and edited_at <= row["edited_at"]:
return None
# A text change always carries an edit time; now() only guards the NOT NULL column
await conn.execute(
"INSERT INTO message_edits (message_id, content_before, edited_at) VALUES ($1, $2, coalesce($3, now()))",
message_id, row["content"], edited_at,
)
await conn.execute(
"UPDATE message_log SET content = $2, edited_at = coalesce($3, now()) WHERE message_id = $1",
message_id, content, edited_at,
)
return row["content"]
async def log_delete(pool, message_ids, deleted_at):
"""Marks messages deleted and returns the rows that were logged, for posting to a log channel."""
return await pool.fetch(
"""
UPDATE message_log SET deleted_at = $2
WHERE message_id = ANY($1::bigint[]) AND deleted_at IS NULL
RETURNING message_id, guild_id, channel_id, author_id, content, attachments, created_at, author_bot
""",
list(message_ids), deleted_at,
)
async def get_message(pool, message_id):
return await pool.fetchrow("SELECT * FROM message_log WHERE message_id = $1", message_id)
async def get_edits(pool, message_id):
return await pool.fetch(
"SELECT content_before, edited_at FROM message_edits WHERE message_id = $1 ORDER BY edited_at, id",
message_id,
)
async def record_log_post(pool, post_id, channel_id, oldest_sent_at):
"""Remembers a log channel post and when the oldest message it quotes was sent."""
await pool.execute(
"INSERT INTO log_posts (post_id, channel_id, oldest_sent_at) VALUES ($1, $2, $3) ON CONFLICT DO NOTHING",
post_id, channel_id, oldest_sent_at,
)
async def expired_log_posts(pool, cutoff):
"""Log channel posts quoting a message sent before cutoff, oldest first."""
return await pool.fetch(
"SELECT post_id, channel_id FROM log_posts WHERE oldest_sent_at < $1 ORDER BY oldest_sent_at", cutoff,
)
async def forget_log_post(pool, post_id):
await pool.execute("DELETE FROM log_posts WHERE post_id = $1", post_id)
# ── Discord members ───────────────────────────────────────────────────────────
# The flags set_flag may set; the column name is put into the SQL, so it must come from this list
MEMBER_FLAGS = ("onboarding_notification", "discord_reaction")
async def saved_roles(pool, member_id):
"""The (role_ids, role_names) last saved for a member, or None if there's no record of them."""
row = await pool.fetchrow("SELECT role_ids, role_names FROM discord_members WHERE id = $1", member_id)
return (row["role_ids"], row["role_names"]) if row else None
async def save_member(pool, *, member_id, username, nick, global_name, joined_at, role_ids, role_names,
onboarding_notification=False):
"""Creates or updates a member's record, clearing left_at. onboarding_notification only ever
turns the flag on."""
await pool.execute(
"""
INSERT INTO discord_members (id, username, nick, global_name, joined_at, role_ids, role_names, onboarding_notification)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
ON CONFLICT (id) DO UPDATE SET
username = EXCLUDED.username, nick = EXCLUDED.nick, global_name = EXCLUDED.global_name,
joined_at = EXCLUDED.joined_at, role_ids = EXCLUDED.role_ids, role_names = EXCLUDED.role_names,
left_at = NULL,
onboarding_notification = discord_members.onboarding_notification OR EXCLUDED.onboarding_notification
""",
member_id, username, nick, global_name, joined_at, list(role_ids), list(role_names), onboarding_notification,
)
async def mark_left(pool, member_id, username, left_at, role_ids, role_names):
"""Records a leave and the roles held at that moment, so they can be given back on rejoin."""
await pool.execute(
"""
INSERT INTO discord_members (id, username, left_at, role_ids, role_names) VALUES ($1, $2, $3, $4, $5)
ON CONFLICT (id) DO UPDATE SET left_at = EXCLUDED.left_at,
-- A member who rejoins and leaves again before their record is synced keeps the roles saved before
role_ids = CASE WHEN discord_members.left_at IS NULL THEN EXCLUDED.role_ids ELSE discord_members.role_ids END,
role_names = CASE WHEN discord_members.left_at IS NULL THEN EXCLUDED.role_names ELSE discord_members.role_names END
""",
member_id, username, left_at, list(role_ids), list(role_names),
)
async def set_flag(pool, flag, member_ids):
"""Turns one of MEMBER_FLAGS on for the given members. Returns how many records were updated."""
if flag not in MEMBER_FLAGS:
raise ValueError(f"Not a member flag: {flag!r}")
result = await pool.execute(
f"UPDATE discord_members SET {flag} = true WHERE id = ANY($1::bigint[])", list(member_ids)
)
return int(result.split()[-1])
async def linked_member_ids(pool):
"""IDs of the members CiviCRM has linked."""
rows = await pool.fetch("SELECT id FROM discord_members WHERE civicrm_linked_at IS NOT NULL")
return {row["id"] for row in rows}
async def mark_linked(pool, member_id, username):
await pool.execute(
"""
INSERT INTO discord_members (id, username, civicrm_linked_at) VALUES ($1, $2, now())
ON CONFLICT (id) DO UPDATE SET civicrm_linked_at = now()
""",
member_id, username,
)
async def discord_member_stats(pool):
"""Aggregate counts of the member records for the onboarding dashboard; never anything about
one person. A record without joined_at (e.g. a leave seen before any join) counts only in
records and skipped_no_join_date."""
current = "joined_at IS NOT NULL AND left_at IS NULL"
async with pool.acquire() as conn:
# One snapshot, so the series and totals agree
async with conn.transaction(isolation="repeatable_read", readonly=True):
joins = await conn.fetch(
"""
SELECT to_char(joined_at AT TIME ZONE 'UTC', 'YYYY-MM') AS month, count(*) AS n
FROM discord_members WHERE joined_at IS NOT NULL GROUP BY 1 ORDER BY 1
"""
)
lefts = await conn.fetch(
"""
SELECT to_char(left_at AT TIME ZONE 'UTC', 'YYYY-MM') AS month, count(*) AS n
FROM discord_members WHERE joined_at IS NOT NULL AND left_at IS NOT NULL GROUP BY 1 ORDER BY 1
"""
)
totals = await conn.fetchrow(
f"""
SELECT count(*) AS records,
count(*) FILTER (WHERE joined_at IS NULL) AS skipped_no_join_date,
count(*) FILTER (WHERE {current}) AS members_net,
count(*) FILTER (WHERE {current} AND onboarding_notification) AS onboarding_notification,
count(*) FILTER (WHERE {current} AND onboarding_notification AND discord_reaction)
AS discord_reaction
FROM discord_members
"""
)
roles = await conn.fetch(
f"""
SELECT role_id, count(DISTINCT id) AS n
FROM discord_members, unnest(role_ids) AS role_id WHERE {current} GROUP BY 1 ORDER BY 1
"""
)
return {
"new_members": {r["month"]: r["n"] for r in joins},
"left": {r["month"]: r["n"] for r in lefts},
"totals": {k: totals[k] for k in ("members_net", "onboarding_notification", "discord_reaction")},
"roles": {str(r["role_id"]): r["n"] for r in roles},
"records": totals["records"],
"skipped_no_join_date": totals["skipped_no_join_date"],
}
# ── Retention ─────────────────────────────────────────────────────────────────
# A day's expired messages and their cascaded edits can take far longer than the pool's 10s default
PRUNE_TIMEOUT = 600
async def prune(pool, days=RETENTION_DAYS):
"""Deletes snapshots and messages older than `days`. Returns (snapshots, messages) removed."""
snapshots = await pool.execute(
"DELETE FROM server_snapshots WHERE taken_at < now() - make_interval(days => $1)", days,
timeout=PRUNE_TIMEOUT,
)
messages = await pool.execute(
"DELETE FROM message_log WHERE created_at < now() - make_interval(days => $1)", days,
timeout=PRUNE_TIMEOUT,
)
# execute() returns the command tag, e.g. "DELETE 3"
return int(snapshots.split()[-1]), int(messages.split()[-1])