-
Notifications
You must be signed in to change notification settings - Fork 88
/
indexing.go
604 lines (525 loc) · 16.3 KB
/
indexing.go
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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
package search
import (
"bytes"
"context"
_ "embed"
"encoding/json"
"fmt"
"io"
"log/slog"
"os"
"strings"
"time"
appbsky "github.com/bluesky-social/indigo/api/bsky"
"github.com/bluesky-social/indigo/atproto/identity"
"github.com/bluesky-social/indigo/atproto/syntax"
"github.com/bluesky-social/indigo/backfill"
"github.com/bluesky-social/indigo/xrpc"
"github.com/ipfs/go-cid"
"github.com/labstack/echo/v4"
"go.opentelemetry.io/otel/attribute"
"golang.org/x/time/rate"
gorm "gorm.io/gorm"
es "github.com/opensearch-project/opensearch-go/v2"
esapi "github.com/opensearch-project/opensearch-go/v2/opensearchapi"
)
type Indexer struct {
escli *es.Client
postIndex string
profileIndex string
db *gorm.DB
relayhost string
relayXRPC *xrpc.Client
dir identity.Directory
echo *echo.Echo
logger *slog.Logger
bfs *backfill.Gormstore
bf *backfill.Backfiller
enableRepoDiscovery bool
indexLimiter *rate.Limiter
profileQueue chan *ProfileIndexJob
postQueue chan *PostIndexJob
pagerankQueue chan *PagerankIndexJob
}
type IndexerConfig struct {
RelayHost string
ProfileIndex string
PostIndex string
Logger *slog.Logger
RelaySyncRateLimit int
IndexMaxConcurrency int
DiscoverRepos bool
IndexingRateLimit int
}
type ProfileIndexJob struct {
ident *identity.Identity
record *appbsky.ActorProfile
rcid cid.Cid
}
type PostIndexJob struct {
did syntax.DID
record *appbsky.FeedPost
rcid cid.Cid
rkey string
}
type PagerankIndexJob struct {
did syntax.DID
rank float64
}
func NewIndexer(db *gorm.DB, escli *es.Client, dir identity.Directory, config IndexerConfig) (*Indexer, error) {
logger := config.Logger
if logger == nil {
logger = slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
Level: slog.LevelInfo,
}))
}
logger = logger.With("component", "indexer")
logger.Info("running database migrations")
db.AutoMigrate(&LastSeq{})
db.AutoMigrate(&backfill.GormDBJob{})
relayWS := config.RelayHost
if !strings.HasPrefix(relayWS, "ws") {
return nil, fmt.Errorf("specified bgs host must include 'ws://' or 'wss://'")
}
relayHTTP := strings.Replace(relayWS, "ws", "http", 1)
relayXRPC := &xrpc.Client{
Host: relayHTTP,
}
limiter := rate.NewLimiter(rate.Limit(config.IndexingRateLimit), 10_000)
idx := &Indexer{
escli: escli,
profileIndex: config.ProfileIndex,
postIndex: config.PostIndex,
db: db,
relayhost: config.RelayHost,
relayXRPC: relayXRPC,
dir: dir,
logger: logger,
enableRepoDiscovery: config.DiscoverRepos,
indexLimiter: limiter,
profileQueue: make(chan *ProfileIndexJob, 1000),
postQueue: make(chan *PostIndexJob, 1000),
pagerankQueue: make(chan *PagerankIndexJob, 1000),
}
bfstore := backfill.NewGormstore(db)
opts := backfill.DefaultBackfillOptions()
if config.RelaySyncRateLimit > 0 {
opts.SyncRequestsPerSecond = config.RelaySyncRateLimit
opts.ParallelBackfills = 2 * config.RelaySyncRateLimit
} else {
opts.SyncRequestsPerSecond = 8
}
opts.CheckoutPath = fmt.Sprintf("%s/xrpc/com.atproto.sync.getRepo", relayHTTP)
if config.IndexMaxConcurrency > 0 {
opts.ParallelRecordCreates = config.IndexMaxConcurrency
} else {
opts.ParallelRecordCreates = 20
}
opts.NSIDFilter = "app.bsky."
bf := backfill.NewBackfiller(
"search",
bfstore,
idx.handleCreateOrUpdate,
idx.handleCreateOrUpdate,
idx.handleDelete,
opts,
)
idx.bfs = bfstore
idx.bf = bf
return idx, nil
}
//go:embed post_schema.json
var palomarPostSchemaJSON string
//go:embed profile_schema.json
var palomarProfileSchemaJSON string
func (idx *Indexer) EnsureIndices(ctx context.Context) error {
indices := []struct {
Name string
SchemaJSON string
}{
{Name: idx.postIndex, SchemaJSON: palomarPostSchemaJSON},
{Name: idx.profileIndex, SchemaJSON: palomarProfileSchemaJSON},
}
for _, index := range indices {
resp, err := idx.escli.Indices.Exists([]string{index.Name})
if err != nil {
return err
}
defer resp.Body.Close()
io.ReadAll(resp.Body)
if resp.IsError() && resp.StatusCode != 404 {
return fmt.Errorf("failed to check index existence")
}
if resp.StatusCode == 404 {
idx.logger.Warn("creating opensearch index", "index", index.Name)
if len(index.SchemaJSON) < 2 {
return fmt.Errorf("empty schema file (go:embed failed)")
}
buf := strings.NewReader(index.SchemaJSON)
resp, err := idx.escli.Indices.Create(
index.Name,
idx.escli.Indices.Create.WithBody(buf))
if err != nil {
return err
}
defer resp.Body.Close()
io.ReadAll(resp.Body)
if resp.IsError() {
return fmt.Errorf("failed to create index")
}
}
}
return nil
}
func (idx *Indexer) runPostIndexer(ctx context.Context) {
ctx, span := tracer.Start(ctx, "runPostIndexer")
defer span.End()
// Batch up to 1000 posts at a time, or every 5 seconds
tick := time.NewTicker(5 * time.Second)
defer tick.Stop()
var posts []*PostIndexJob
for {
select {
case <-ctx.Done():
return
case <-tick.C:
if len(posts) > 0 {
err := idx.indexLimiter.WaitN(ctx, len(posts))
if err != nil {
idx.logger.Error("failed to wait for rate limiter", "err", err)
continue
}
err = idx.indexPosts(ctx, posts)
if err != nil {
idx.logger.Error("failed to index posts", "err", err)
}
posts = posts[:0]
}
case job := <-idx.postQueue:
posts = append(posts, job)
if len(posts) >= 1000 {
err := idx.indexLimiter.WaitN(ctx, len(posts))
if err != nil {
idx.logger.Error("failed to wait for rate limiter", "err", err)
continue
}
err = idx.indexPosts(ctx, posts)
if err != nil {
idx.logger.Error("failed to index posts", "err", err)
}
posts = posts[:0]
}
}
}
}
func (idx *Indexer) runProfileIndexer(ctx context.Context) {
ctx, span := tracer.Start(ctx, "runProfileIndexer")
defer span.End()
// Batch up to 1000 profiles at a time, or every 5 seconds
tick := time.NewTicker(5 * time.Second)
defer tick.Stop()
var profiles []*ProfileIndexJob
for {
select {
case <-ctx.Done():
return
case <-tick.C:
if len(profiles) > 0 {
err := idx.indexLimiter.WaitN(ctx, len(profiles))
if err != nil {
idx.logger.Error("failed to wait for rate limiter", "err", err)
continue
}
err = idx.indexProfiles(ctx, profiles)
if err != nil {
idx.logger.Error("failed to index profiles", "err", err)
}
profiles = profiles[:0]
}
case job := <-idx.profileQueue:
profiles = append(profiles, job)
if len(profiles) >= 1000 {
err := idx.indexLimiter.WaitN(ctx, len(profiles))
if err != nil {
idx.logger.Error("failed to wait for rate limiter", "err", err)
continue
}
err = idx.indexProfiles(ctx, profiles)
if err != nil {
idx.logger.Error("failed to index profiles", "err", err)
}
profiles = profiles[:0]
}
}
}
}
func (idx *Indexer) runPagerankIndexer(ctx context.Context) {
ctx, span := tracer.Start(ctx, "runPagerankIndexer")
defer span.End()
// Batch up to 1000 pageranks at a time, or every 5 seconds
tick := time.NewTicker(5 * time.Second)
defer tick.Stop()
var pageranks []*PagerankIndexJob
for {
select {
case <-ctx.Done():
return
case <-tick.C:
if len(pageranks) > 0 {
err := idx.indexLimiter.WaitN(ctx, len(pageranks))
if err != nil {
idx.logger.Error("failed to wait for rate limiter", "err", err)
continue
}
err = idx.indexPageranks(ctx, pageranks)
if err != nil {
idx.logger.Error("failed to index pageranks", "err", err)
}
pageranks = pageranks[:0]
}
case job := <-idx.pagerankQueue:
pageranks = append(pageranks, job)
if len(pageranks) >= 1000 {
err := idx.indexLimiter.WaitN(ctx, len(pageranks))
if err != nil {
idx.logger.Error("failed to wait for rate limiter", "err", err)
continue
}
err = idx.indexPageranks(ctx, pageranks)
if err != nil {
idx.logger.Error("failed to index pageranks", "err", err)
}
pageranks = pageranks[:0]
}
}
}
}
func (idx *Indexer) deletePost(ctx context.Context, did syntax.DID, recordPath string) error {
ctx, span := tracer.Start(ctx, "deletePost")
defer span.End()
span.SetAttributes(attribute.String("repo", did.String()), attribute.String("path", recordPath))
logger := idx.logger.With("repo", did, "path", recordPath, "op", "deletePost")
parts := strings.SplitN(recordPath, "/", 3)
if len(parts) < 2 {
logger.Warn("skipping post record with malformed path")
return nil
}
rkey, err := syntax.ParseTID(parts[1])
if err != nil {
logger.Warn("skipping post record with non-TID rkey")
return nil
}
docID := fmt.Sprintf("%s_%s", did.String(), rkey)
logger.Info("deleting post from index", "docID", docID)
req := esapi.DeleteRequest{
Index: idx.postIndex,
DocumentID: docID,
Refresh: "true",
}
err = idx.indexLimiter.Wait(ctx)
if err != nil {
logger.Warn("failed to wait for rate limiter", "err", err)
return err
}
res, err := req.Do(ctx, idx.escli)
if err != nil {
return fmt.Errorf("failed to delete post: %w", err)
}
defer res.Body.Close()
body, err := io.ReadAll(res.Body)
if err != nil {
return fmt.Errorf("failed to read indexing response: %w", err)
}
if res.IsError() {
logger.Warn("opensearch indexing error", "status_code", res.StatusCode, "response", res, "body", string(body))
return fmt.Errorf("indexing error, code=%d", res.StatusCode)
}
return nil
}
func (idx *Indexer) indexPosts(ctx context.Context, jobs []*PostIndexJob) error {
ctx, span := tracer.Start(ctx, "indexPosts")
defer span.End()
span.SetAttributes(attribute.Int("num_posts", len(jobs)))
log := idx.logger.With("op", "indexPosts")
start := time.Now()
var buf bytes.Buffer
for i := range jobs {
job := jobs[i]
doc := TransformPost(job.record, job.did, job.rkey, job.rcid.String())
docBytes, err := json.Marshal(doc)
if err != nil {
log.Warn("failed to marshal post", "err", err)
return err
}
indexScript := []byte(fmt.Sprintf(`{"index":{"_id":"%s"}}%s`, doc.DocId(), "\n"))
docBytes = append(docBytes, "\n"...)
buf.Grow(len(indexScript) + len(docBytes))
buf.Write(indexScript)
buf.Write(docBytes)
}
log.Info("indexing posts", "num_posts", len(jobs))
res, err := idx.escli.Bulk(bytes.NewReader(buf.Bytes()), idx.escli.Bulk.WithIndex(idx.postIndex))
if err != nil {
log.Warn("failed to send bulk indexing request", "err", err)
return fmt.Errorf("failed to send bulk indexing request: %w", err)
}
defer res.Body.Close()
if res.IsError() {
body, err := io.ReadAll(res.Body)
if err != nil {
log.Warn("failed to read bulk indexing response", "err", err)
return fmt.Errorf("failed to read bulk indexing response: %w", err)
}
log.Warn("opensearch bulk indexing error", "status_code", res.StatusCode, "response", res, "body", string(body))
return fmt.Errorf("bulk indexing error, code=%d", res.StatusCode)
}
log.Info("indexed posts", "num_posts", len(jobs), "duration", time.Since(start))
return nil
}
func (idx *Indexer) indexProfiles(ctx context.Context, jobs []*ProfileIndexJob) error {
ctx, span := tracer.Start(ctx, "indexProfiles")
defer span.End()
span.SetAttributes(attribute.Int("num_profiles", len(jobs)))
log := idx.logger.With("op", "indexProfiles")
start := time.Now()
var buf bytes.Buffer
for i := range jobs {
job := jobs[i]
doc := TransformProfile(job.record, job.ident, job.rcid.String())
docBytes, err := json.Marshal(doc)
if err != nil {
log.Warn("failed to marshal profile", "err", err)
return err
}
indexScript := []byte(fmt.Sprintf(`{"index":{"_id":"%s"}}%s`, job.ident.DID.String(), "\n"))
docBytes = append(docBytes, "\n"...)
buf.Grow(len(indexScript) + len(docBytes))
buf.Write(indexScript)
buf.Write(docBytes)
}
log.Info("indexing profiles", "num_profiles", len(jobs))
res, err := idx.escli.Bulk(bytes.NewReader(buf.Bytes()), idx.escli.Bulk.WithIndex(idx.profileIndex))
if err != nil {
log.Warn("failed to send bulk indexing request", "err", err)
return fmt.Errorf("failed to send bulk indexing request: %w", err)
}
defer res.Body.Close()
if res.IsError() {
body, err := io.ReadAll(res.Body)
if err != nil {
log.Warn("failed to read bulk indexing response", "err", err)
return fmt.Errorf("failed to read bulk indexing response: %w", err)
}
log.Warn("opensearch bulk indexing error", "status_code", res.StatusCode, "response", res, "body", string(body))
return fmt.Errorf("bulk indexing error, code=%d", res.StatusCode)
}
log.Info("indexed profiles", "num_profiles", len(jobs), "duration", time.Since(start))
return nil
}
// updateProfilePagranks uses the OpenSearch bulk API to update the pageranks for the given DIDs
func (idx *Indexer) indexPageranks(ctx context.Context, pageranks []*PagerankIndexJob) error {
ctx, span := tracer.Start(ctx, "indexPageranks")
defer span.End()
span.SetAttributes(attribute.Int("num_profiles", len(pageranks)))
log := idx.logger.With("op", "indexPageranks")
log.Info("updating profile pageranks")
var buf bytes.Buffer
for _, pr := range pageranks {
updateScript := map[string]any{
"script": map[string]any{
"source": "ctx._source.pagerank = params.pagerank",
"lang": "painless",
"params": map[string]any{
"pagerank": pr.rank,
},
},
}
updateScriptJSON, err := json.Marshal(updateScript)
if err != nil {
log.Warn("failed to marshal update script", "err", err)
return err
}
updateMetaJSON := []byte(fmt.Sprintf(`{"update":{"_id":"%s"}}%s`, pr.did.String(), "\n"))
updateScriptJSON = append(updateScriptJSON, "\n"...)
buf.Grow(len(updateMetaJSON) + len(updateScriptJSON))
buf.Write(updateMetaJSON)
buf.Write(updateScriptJSON)
}
res, err := idx.escli.Bulk(bytes.NewReader(buf.Bytes()), idx.escli.Bulk.WithIndex(idx.profileIndex))
if err != nil {
log.Warn("failed to send bulk indexing request", "err", err)
return fmt.Errorf("failed to send bulk indexing request: %w", err)
}
defer res.Body.Close()
if res.IsError() {
body, err := io.ReadAll(res.Body)
if err != nil {
log.Warn("failed to read bulk indexing response", "err", err)
return fmt.Errorf("failed to read bulk indexing response: %w", err)
}
log.Warn("opensearch bulk indexing error", "status_code", res.StatusCode, "response", res, "body", string(body))
return fmt.Errorf("bulk indexing error, code=%d", res.StatusCode)
}
return nil
}
func (idx *Indexer) updateUserHandle(ctx context.Context, did syntax.DID, handle string) error {
ctx, span := tracer.Start(ctx, "updateUserHandle")
defer span.End()
span.SetAttributes(attribute.String("repo", did.String()), attribute.String("event.handle", handle))
log := idx.logger.With("repo", did.String(), "op", "updateUserHandle", "handle_from_event", handle)
err := idx.dir.Purge(ctx, did.AtIdentifier())
if err != nil {
log.Warn("failed to purge DID from directory", "err", err)
return err
}
ident, err := idx.dir.LookupDID(ctx, did)
if err != nil {
log.Warn("failed to lookup DID in directory", "err", err)
return err
}
if ident == nil {
log.Warn("got nil identity from directory")
return fmt.Errorf("got nil identity from directory")
}
log.Info("updating user handle", "handle_from_dir", ident.Handle)
span.SetAttributes(attribute.String("dir.handle", ident.Handle.String()))
b, err := json.Marshal(map[string]any{
"script": map[string]any{
"source": "ctx._source.handle = params.handle",
"lang": "painless",
"params": map[string]any{
"handle": ident.Handle,
},
},
})
if err != nil {
log.Warn("failed to marshal update script", "err", err)
return err
}
req := esapi.UpdateRequest{
Index: idx.profileIndex,
DocumentID: did.String(),
Body: bytes.NewReader(b),
}
err = idx.indexLimiter.Wait(ctx)
if err != nil {
log.Warn("failed to wait for rate limiter", "err", err)
return err
}
res, err := req.Do(ctx, idx.escli)
if err != nil {
log.Warn("failed to send indexing request", "err", err)
return fmt.Errorf("failed to send indexing request: %w", err)
}
defer res.Body.Close()
body, err := io.ReadAll(res.Body)
if err != nil {
log.Warn("failed to read indexing response", "err", err)
return fmt.Errorf("failed to read indexing response: %w", err)
}
if res.IsError() {
log.Warn("opensearch indexing error", "status_code", res.StatusCode, "response", res, "body", string(body))
return fmt.Errorf("indexing error, code=%d", res.StatusCode)
}
return nil
}