-
Notifications
You must be signed in to change notification settings - Fork 4
/
stats.js
104 lines (98 loc) · 3.15 KB
/
stats.js
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
import CONFIG from '../../../conf.js'
import migrations from './migrations/index.js'
import { pgInit } from '../../../pg.js'
let pg
self.onmessage = async ({ data }) => {
if (data === 'getactions') {
try {
pg = await pgInit(CONFIG.plugs.builtin.stats.db, migrations)
} catch (e) {
console.error(e)
self.close()
}
self.postMessage([
'connect',
'disconnect',
'sub',
'unsub',
'eose',
'notice',
'error',
])
return
}
const { msgId, action, conn, data: dat } = data
try {
switch (action) {
case 'connect':
self.postMessage({ msgId, accept: true })
await pg`INSERT INTO conns (id, headers) VALUES
(${conn.id}, ${conn.headers})`
break
case 'disconnect':
await pg`UPDATE conns SET closed_at = NOW() AT TIME ZONE 'UTC' WHERE id = ${conn.id}`
break
case 'sub':
self.postMessage({ msgId, accept: true })
await pg.begin((pg) => {
const lines = []
lines.push(pg`INSERT INTO subs (conn_id, nostr_sub_id)
VALUES (${conn.id}, ${dat.subId})`)
for (
const {
ids = [],
authors = [],
kinds = [],
since,
until,
limit,
...tags
} of dat.filters
) {
lines.push(pg`INSERT INTO filters (sub_id, since, until, lmt)
VALUES (currval('subs_id_seq'), ${since}, ${until}, ${limit})`)
for (const id of ids) {
lines.push(pg`INSERT INTO event_ids (filter_id, event_id)
VALUES (currval('filters_id_seq'), ${id})`)
}
for (const author of authors) {
lines.push(pg`INSERT INTO authors (filter_id, author)
VALUES (currval('filters_id_seq'), ${author})`)
}
for (const kind of kinds) {
lines.push(pg`INSERT INTO kinds (filter_id, kind)
VALUES (currval('filters_id_seq'), ${kind})`)
}
for (const [tag, values] of Object.entries(tags)) {
lines.push(pg`INSERT INTO tags (filter_id, tag)
VALUES (currval('filters_id_seq'), ${tag})`)
for (const value of values) {
lines.push(pg`INSERT INTO vals (tag_id, val)
VALUES (currval('tags_id_seq'), ${value})`)
}
}
}
return lines
})
break
case 'unsub':
await pg`UPDATE subs SET closed_at = NOW() AT TIME ZONE 'UTC'
WHERE conn_id = ${conn.id} AND nostr_sub_id = ${dat.subId}`
break
case 'eose':
await pg`UPDATE subs SET eose_at = NOW() AT TIME ZONE 'UTC', eose_count = ${dat.count}
WHERE conn_id = ${conn.id} AND nostr_sub_id = ${dat.subId}`
break
case 'notice':
await pg`INSERT INTO notices (conn_id, msg)
VALUES (${conn.id}, ${dat.notice})`
break
case 'error':
await pg`INSERT INTO errors (conn_id, error)
VALUES (${conn.id}, ${dat.error})`
break
}
} catch (e) {
console.error(e)
}
}