-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathcheck-online.ts
238 lines (183 loc) · 6.14 KB
/
check-online.ts
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
import { simpleFetchHandler, XRPC, XRPCError } from '@atcute/client';
import * as v from '@badrap/valita';
import { differenceInDays } from 'date-fns/differenceInDays';
import { DEFAULT_HEADERS, MAX_FAILURE_DAYS } from '../src/constants';
import { serializedState, type LabelerInfo, type PDSInfo, type SerializedState } from '../src/state';
import { PromiseQueue } from '../src/utils/pqueue';
const now = Date.now();
const env = v.object({ STATE_FILE: v.string() }).parse(process.env, { mode: 'passthrough' });
let state: SerializedState | undefined;
// Read existing state file
{
let json: unknown;
try {
json = await Bun.file(env.STATE_FILE).json();
} catch {}
if (json !== undefined) {
state = serializedState.parse(json);
}
}
// Some schema validations
const pdsDescribeServerResponse = v.object({
availableUserDomains: v.array(v.string()),
did: v.string(),
contact: v.object({ email: v.string().optional() }).optional(),
inviteCodeRequired: v.boolean().optional(),
links: v.object({ privacyPolicy: v.string().optional(), termsOfService: v.string().optional() }).optional(),
phoneVerificationRequired: v.boolean().optional(),
});
const labelerQueryLabelsResponse = v.object({
cursor: v.string().optional(),
labels: v.array(
v.object({
src: v.string(),
uri: v.string(),
val: v.string(),
cts: v.string(),
cid: v.string().optional(),
exp: v.string().optional(),
neg: v.boolean().optional(),
sig: v.object({ $bytes: v.string() }).optional(),
ver: v.number().optional(),
}),
),
});
const offHealthResponse = v.object({
version: v.string(),
});
// Global states
const pdses = new Map<string, PDSInfo>(state ? Object.entries(state.pdses) : []);
const labelers = new Map<string, LabelerInfo>(state ? Object.entries(state.labelers) : []);
const queue = new PromiseQueue();
// Connect to PDSes
console.log(`crawling known pdses`);
await Promise.all(
Array.from(pdses, ([href, obj]) => {
return queue.add(async () => {
const host = new URL(href).host;
const rpc = new XRPC({ handler: simpleFetchHandler({ service: href }) });
const start = performance.now();
const signal = AbortSignal.timeout(15_000);
const meta = await rpc
.get('com.atproto.server.describeServer', { signal, headers: DEFAULT_HEADERS })
.then(({ data: rawData }) => {
const data = pdsDescribeServerResponse.parse(rawData, { mode: 'passthrough' });
if (data.did !== `did:web:${host}`) {
throw new Error(`did mismatch`);
}
return data;
})
.catch(() => null);
const end = performance.now();
if (meta === null) {
const errorAt = obj.errorAt;
if (errorAt === undefined) {
obj.errorAt = now;
} else if (differenceInDays(now, errorAt) > MAX_FAILURE_DAYS) {
// It's been days without a response, stop tracking.
pdses.delete(href);
return;
}
console.log(` ${host}: fail (took ${end - start})`);
return { host, info: obj };
}
const version = await getVersion(rpc, obj.version);
obj.version = version;
obj.inviteCodeRequired = meta.inviteCodeRequired;
obj.errorAt = undefined;
console.log(` ${host}: pass (took ${end - start})`);
return { host, info: obj };
});
}),
).then((results) => results.filter((r) => r !== undefined));
// Connect to labelers
console.log(`crawling known labelers`);
await Promise.all(
Array.from(labelers, async ([href, obj]) => {
return queue.add(async () => {
const host = new URL(href).host;
const rpc = new XRPC({ handler: simpleFetchHandler({ service: href }) });
const start = performance.now();
const signal = AbortSignal.timeout(15_000);
const meta = await rpc
.get('com.atproto.label.queryLabels', {
signal: signal,
headers: DEFAULT_HEADERS,
params: { uriPatterns: ['*'], limit: 1 },
})
.then(({ data: rawData }) => labelerQueryLabelsResponse.parse(rawData, { mode: 'passthrough' }))
.catch(() => null);
const end = performance.now();
if (meta === null) {
const errorAt = obj.errorAt;
if (errorAt === undefined) {
obj.errorAt = now;
} else if (differenceInDays(now, errorAt) > MAX_FAILURE_DAYS) {
// It's been days without a response, stop tracking.
labelers.delete(href);
return;
}
console.log(` ${host}: fail (took ${end - start})`);
return { host, info: obj };
}
const version = await getVersion(rpc, obj.version);
obj.version = version;
obj.errorAt = undefined;
console.log(` ${host}: pass (took ${end - start})`);
return { host, info: obj };
});
}),
).then((results) => results.filter((r) => r !== undefined));
// Persist the state
{
const serialized: SerializedState = {
firehose: {
cursor: state?.firehose.cursor,
didWebs: state?.firehose.didWebs || {},
},
plc: {
cursor: state?.plc.cursor,
},
pdses: Object.fromEntries(Array.from(pdses)),
labelers: Object.fromEntries(Array.from(labelers)),
};
// Properly sort the JSON state for clarity
const isPlainObject = (o: any): boolean => {
if (typeof o !== 'object' || o === null) {
return false;
}
const proto = Object.getPrototypeOf(o);
return (proto === null || proto === Object.prototype) && Object.isExtensible(o);
};
const replacer = (_key: string, value: any): any => {
if (isPlainObject(value)) {
const keys = Object.keys(value).sort();
const obj: any = {};
for (let i = 0, ilen = keys.length; i < ilen; i++) {
const key = keys[i];
obj[key] = value[key];
}
return obj;
}
return value;
};
await Bun.write(env.STATE_FILE, JSON.stringify(serialized, replacer, '\t'));
}
async function getVersion(rpc: XRPC, prev: string | null | undefined) {
// skip if the response previously returned null (not official distrib)
if (prev === null) {
return null;
}
try {
// @ts-expect-error: undocumented endpoint
const { data: rawData } = await rpc.get('_health', { headers: DEFAULT_HEADERS });
const { version } = offHealthResponse.parse(rawData, { mode: 'passthrough' });
return /^[0-9a-f]{40}$/.test(version) ? `git-${version.slice(0, 7)}` : version;
} catch (err) {
if (err instanceof XRPCError && (err.status === 404 || err.status === 501)) {
// Not implemented.
return null;
}
}
return undefined;
}