forked from
tangled.org/core
Monorepo for Tangled
1package cache
2
3import (
4 "context"
5 "fmt"
6 "time"
7
8 "github.com/bluesky-social/indigo/atproto/syntax"
9 "github.com/redis/go-redis/v9"
10 "tangled.org/core/appview/db"
11)
12
13const (
14 PreferredHandleByDid = "preferred_handle:did:%s"
15 PreferredHandleByHandle = "preferred_handle:handle:%s"
16 PreferredHandleTTL = 24 * time.Hour
17)
18
19type Cache struct {
20 *redis.Client
21}
22
23func New(addr string) *Cache {
24 rdb := redis.NewClient(&redis.Options{
25 Addr: addr,
26 })
27 return &Cache{rdb}
28}
29
30func LookupPreferredHandle(ctx context.Context, rdb *Cache, e db.Execer, did string) string {
31 if rdb != nil {
32 if h, err := rdb.Get(ctx, fmt.Sprintf(PreferredHandleByDid, did)).Result(); err == nil {
33 return h
34 }
35 }
36
37 var handle string
38 if h, err := db.GetPreferredHandle(e, did); err == nil {
39 handle = string(h)
40 }
41
42 if rdb != nil {
43 pipe := rdb.Pipeline()
44 pipe.Set(ctx, fmt.Sprintf(PreferredHandleByDid, did), handle, PreferredHandleTTL)
45 if handle != "" {
46 pipe.Set(ctx, fmt.Sprintf(PreferredHandleByHandle, handle), did, PreferredHandleTTL)
47 }
48 pipe.Exec(ctx)
49 }
50
51 return handle
52}
53
54func LookupDidByPreferredHandle(ctx context.Context, rdb *Cache, e db.Execer, handle syntax.Handle) string {
55 handleStr := string(handle)
56 if rdb != nil {
57 if d, err := rdb.Get(ctx, fmt.Sprintf(PreferredHandleByHandle, handleStr)).Result(); err == nil {
58 return d
59 }
60 }
61
62 var did string
63 if d, err := db.GetDidByPreferredHandle(e, handle); err == nil {
64 did = string(d)
65 }
66
67 if rdb != nil {
68 pipe := rdb.Pipeline()
69 pipe.Set(ctx, fmt.Sprintf(PreferredHandleByHandle, handleStr), did, PreferredHandleTTL)
70 if did != "" {
71 pipe.Set(ctx, fmt.Sprintf(PreferredHandleByDid, did), handleStr, PreferredHandleTTL)
72 }
73 pipe.Exec(ctx)
74 }
75
76 return did
77}