-
Notifications
You must be signed in to change notification settings - Fork 41
/
dbClient.ts
373 lines (326 loc) · 8.84 KB
/
dbClient.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
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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
import {
Document,
Filter,
MongoClient,
ObjectId,
WithoutId,
SortDirection,
} from 'mongodb'
import dotenv from 'dotenv'
import { InvalidRequestError } from '@atproto/xrpc-server'
dotenv.config()
class dbSingleton {
private static instance: dbSingleton | null = null
client: MongoClient | null = null
constructor(connection_string: string) {
this.client = new MongoClient(connection_string)
this.init()
}
static getInstance(): dbSingleton {
if (dbSingleton.instance === null) {
dbSingleton.instance = new dbSingleton(
`${process.env.FEEDGEN_MONGODB_CONNECTION_STRING}`,
)
}
return dbSingleton.instance
}
async init() {
if (this.client === null) throw new Error('DB Cannot be null')
await this.client.connect()
}
async deleteManyURI(collection: string, uris: string[]) {
await this.client
?.db()
.collection(collection)
.deleteMany({ uri: { $in: uris } })
}
async deleteManyDID(collection: string, dids: string[]) {
await this.client
?.db()
.collection(collection)
.deleteMany({ did: { $in: dids } })
}
async replaceOneURI(collection: string, uri: string, data: any) {
if (!(typeof data._id === typeof '')) data._id = new ObjectId()
else {
data._id = new ObjectId(data._id)
}
try {
await this.client?.db().collection(collection).insertOne(data)
} catch (err) {
await this.client
?.db()
.collection(collection)
.replaceOne({ uri: uri }, data)
}
}
async replaceOneDID(collection: string, did: string, data: any) {
if (!(typeof data._id === typeof '')) data._id = new ObjectId()
else {
data._id = new ObjectId(data._id)
}
try {
await this.client?.db().collection(collection).insertOne(data)
} catch (err) {
await this.client
?.db()
.collection(collection)
.replaceOne({ did: did }, data)
}
}
async getPostBySortWeight(
collection: string,
limit = 50,
cursor: string | undefined = undefined,
) {
let start = 0
if (cursor !== undefined) {
start = Number.parseInt(cursor)
}
const posts = await this.client
?.db()
.collection(collection)
.find({})
.sort({ sort_weight: -1 })
.skip(start)
.limit(limit)
.toArray()
if (posts?.length !== undefined && posts.length > 0) return posts
else return []
}
async aggregatePostsByRepliesToCollection(
collection: string,
tag: string,
threshold: number,
out: string,
limit: number = 10000,
) {
const indexedAt = new Date().getTime()
await this.client
?.db()
.collection(collection)
.aggregate([
{ $match: { algoTags: tag, replyRoot: { $ne: null } } },
{
$group: {
_id: '$replyRoot',
count: { $sum: 1 },
},
},
{ $match: { count: { $gt: threshold } } },
{ $sort: { count: -1 } },
{ $limit: limit },
{ $addFields: { indexedAt: indexedAt } },
{ $merge: { into: out, on: '_id' } },
])
.toArray()
await this.client
?.db()
.collection(out)
.deleteMany({ indexedAt: { $ne: indexedAt } })
}
async getCollection(collection: string) {
const ret = await this.client
?.db()
.collection(collection)
.find({})
.toArray()
if (ret) return ret
else return []
}
async insertOrReplaceRecord(
query: Filter<Document>,
data: WithoutId<Document>,
collection: string,
) {
try {
await this.client?.db().collection(collection).insertOne(data)
} catch (err) {
await this.client?.db().collection(collection).replaceOne(query, data)
}
}
async updateSubStateCursor(service: string, cursor: number) {
await this.client
?.db()
.collection('sub_state')
.findOneAndReplace(
{ service: service },
{ service: service, cursor: cursor },
{ upsert: true },
)
}
async getSubStateCursor(service: string) {
const res = await this.client
?.db()
.collection('sub_state')
.findOne({ service: service })
if (res === null) return { service: service, cursor: 0 }
return res
}
async getLatestPostsForTag({
tag,
limit = 50,
cursor = undefined,
mediaOnly = false,
nsfwOnly = false,
excludeNSFW = false,
sortOrder = -1,
}: {
tag: string
limit?: number
cursor?: string | undefined
mediaOnly?: boolean
nsfwOnly?: boolean
excludeNSFW?: boolean
sortOrder?: SortDirection
}) {
let query: { indexedAt?: any; cid?: any; algoTags: string; $and?: any[] } =
{
algoTags: tag,
}
const conditions: any[] = []
if (mediaOnly) {
conditions.push({
$or: [
{ 'embed.images': { $ne: null } },
{ 'embed.video': { $ne: null } },
{ 'embed.media': { $ne: null } },
],
})
}
if (nsfwOnly) {
conditions.push({
labels: {
$in: ['porn', 'nudity', 'sexual', 'underwear'],
$ne: null,
},
})
}
if (excludeNSFW) {
conditions.push({
labels: {
$nin: ['porn', 'nudity', 'sexual', 'underwear'],
$ne: null,
},
})
}
if (cursor !== undefined) {
const [indexedAt, cid] = cursor.split('::')
if (!indexedAt || !cid) {
throw new InvalidRequestError('malformed cursor')
}
const timeStr = new Date(parseInt(indexedAt, 10)).getTime()
query['indexedAt'] = { $lte: timeStr }
query['cid'] = { $ne: cid }
}
if (conditions.length > 0) {
query.$and = conditions
}
const results = this.client
?.db()
.collection('post')
.find(query)
.sort({
earliestCreatedIndexedAt: sortOrder,
createdAt: sortOrder,
indexedAt: sortOrder,
cid: -1,
})
.limit(limit)
.toArray()
if (results === undefined) return []
else return results
}
async getTaggedPostsBetween(tag: string, start: number, end: number) {
const larger = start > end ? start : end
const smaller = start > end ? end : start
const results = this.client
?.db()
.collection('post')
.find({ indexedAt: { $lt: larger, $gt: smaller }, algoTags: tag })
.sort({ indexedAt: -1, cid: -1 })
.toArray()
if (results === undefined) return []
else return results
}
async getUnlabelledPostsWithMedia(limit = 100, lagTime = 5 * 60 * 1000) {
const results = this.client
?.db()
.collection('post')
.find({
$or: [
{ 'embed.images': { $ne: null } },
{ 'embed.video': { $ne: null } },
{ 'embed.media': { $ne: null } },
],
labels: null,
indexedAt: { $lt: new Date().getTime() - lagTime },
})
.sort({ indexedAt: -1, cid: -1 })
.limit(limit)
.toArray()
return results || []
}
async updateLabelsForURIs(postEntries: { uri: string; labels: string[] }[]) {
for (let i = 0; i < postEntries.length; i++) {
this.client
?.db()
.collection('post')
.findOneAndUpdate(
{ uri: { $eq: postEntries[i].uri } },
{ $set: { labels: postEntries[i].labels } },
)
}
}
async getRecentAuthorsForTag(tag: string, lastMs: number = 600000) {
const results = await this.client
?.db()
.collection('post')
.distinct('author', {
indexedAt: { $gt: new Date().getTime() - lastMs },
algoTags: tag,
})
if (results === undefined) return []
else return results
}
async getDistinctFromCollection(collection: string, field: string) {
const results = await this.client
?.db()
.collection(collection)
.distinct(field)
if (results === undefined) return []
else return results
}
async removeTagFromPostsForAuthor(tag: string, authors: string[]) {
const pullQuery: Record<string, any> = { algoTags: { $in: [tag] } }
await this.client
?.db()
.collection('post')
.updateMany({ author: { $in: authors } }, { $pull: pullQuery })
await this.deleteUntaggedPosts()
}
async removeTagFromOldPosts(tag: string, indexedAt: number) {
const pullQuery: Record<string, any> = { algoTags: { $in: [tag] } }
await this.client
?.db()
.collection('post')
.updateMany({ indexedAt: { $lt: indexedAt } }, { $pull: pullQuery })
await this.deleteUntaggedPosts()
}
async deleteUntaggedPosts() {
await this.client
?.db()
.collection('post')
.deleteMany({ algoTags: { $size: 0 } })
}
async getPostForURI(uri: string) {
const results = await this.client
?.db()
.collection('post')
.findOne({ uri: uri })
if (results === undefined) return null
return results
}
}
const dbClient = dbSingleton.getInstance()
export default dbClient