-
Notifications
You must be signed in to change notification settings - Fork 125
/
firehose.go
306 lines (280 loc) · 7.78 KB
/
firehose.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
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"log/slog"
"net/http"
"net/url"
"os"
"strings"
comatproto "github.com/bluesky-social/indigo/api/atproto"
"github.com/bluesky-social/indigo/atproto/data"
"github.com/bluesky-social/indigo/atproto/syntax"
"github.com/bluesky-social/indigo/events"
"github.com/bluesky-social/indigo/events/schedulers/parallel"
lexutil "github.com/bluesky-social/indigo/lex/util"
"github.com/bluesky-social/indigo/repo"
"github.com/bluesky-social/indigo/repomgr"
"github.com/carlmjohnson/versioninfo"
"github.com/gorilla/websocket"
"github.com/urfave/cli/v2"
)
var cmdFirehose = &cli.Command{
Name: "firehose",
Usage: "stream repo and identity events",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "relay-host",
Usage: "method, hostname, and port of Relay instance (websocket)",
Value: "wss://bsky.network",
EnvVars: []string{"ATP_RELAY_HOST"},
},
&cli.IntFlag{
Name: "cursor",
Usage: "cursor to consume at",
},
&cli.StringSliceFlag{
Name: "collection",
Aliases: []string{"c"},
Usage: "filter to specific record types (NSID)",
},
&cli.BoolFlag{
Name: "account-events",
Usage: "only print account and identity events",
},
&cli.BoolFlag{
Name: "ops",
Aliases: []string{"records"},
Usage: "instead of printing entire events, print individual record ops",
},
},
Action: runFirehose,
}
type GoatFirehoseConsumer struct {
// for pretty-printing events to stdout
EventLogger *slog.Logger
OpsMode bool
AccountsOnly bool
// filter to specified collections
CollectionFilter []string
}
func runFirehose(cctx *cli.Context) error {
ctx := context.Background()
slog.SetDefault(slog.New(slog.NewJSONHandler(os.Stderr, nil)))
gfc := GoatFirehoseConsumer{
EventLogger: slog.New(slog.NewJSONHandler(os.Stdout, nil)),
OpsMode: cctx.Bool("ops"),
AccountsOnly: cctx.Bool("account-events"),
CollectionFilter: cctx.StringSlice("collection"),
}
relayHost := cctx.String("relay-host")
cursor := cctx.Int("cursor")
dialer := websocket.DefaultDialer
u, err := url.Parse(relayHost)
if err != nil {
return fmt.Errorf("invalid relayHost URI: %w", err)
}
u.Path = "xrpc/com.atproto.sync.subscribeRepos"
if cursor != 0 {
u.RawQuery = fmt.Sprintf("cursor=%d", cursor)
}
con, _, err := dialer.Dial(u.String(), http.Header{
"User-Agent": []string{fmt.Sprintf("goat/%s", versioninfo.Short())},
})
if err != nil {
return fmt.Errorf("subscribing to firehose failed (dialing): %w", err)
}
rsc := &events.RepoStreamCallbacks{
RepoCommit: func(evt *comatproto.SyncSubscribeRepos_Commit) error {
slog.Debug("commit event", "did", evt.Repo, "seq", evt.Seq)
if !gfc.AccountsOnly && !gfc.OpsMode {
return gfc.handleCommitEvent(ctx, evt)
} else if !gfc.AccountsOnly && gfc.OpsMode {
return gfc.handleCommitEventOps(ctx, evt)
}
return nil
},
RepoIdentity: func(evt *comatproto.SyncSubscribeRepos_Identity) error {
slog.Debug("identity event", "did", evt.Did, "seq", evt.Seq)
if !gfc.OpsMode {
return gfc.handleIdentityEvent(ctx, evt)
}
return nil
},
RepoAccount: func(evt *comatproto.SyncSubscribeRepos_Account) error {
slog.Debug("account event", "did", evt.Did, "seq", evt.Seq)
if !gfc.OpsMode {
return gfc.handleAccountEvent(ctx, evt)
}
return nil
},
}
scheduler := parallel.NewScheduler(
1,
100,
relayHost,
rsc.EventHandler,
)
slog.Info("starting firehose consumer", "relayHost", relayHost)
return events.HandleRepoStream(ctx, con, scheduler, nil)
}
// TODO: move this to a "ParsePath" helper in syntax package?
func splitRepoPath(path string) (syntax.NSID, syntax.RecordKey, error) {
parts := strings.SplitN(path, "/", 3)
if len(parts) != 2 {
return "", "", fmt.Errorf("invalid record path: %s", path)
}
collection, err := syntax.ParseNSID(parts[0])
if err != nil {
return "", "", err
}
rkey, err := syntax.ParseRecordKey(parts[1])
if err != nil {
return "", "", err
}
return collection, rkey, nil
}
func (gfc *GoatFirehoseConsumer) handleIdentityEvent(ctx context.Context, evt *comatproto.SyncSubscribeRepos_Identity) error {
out := make(map[string]interface{})
out["type"] = "identity"
out["payload"] = evt
b, err := json.Marshal(out)
if err != nil {
return err
}
fmt.Println(string(b))
return nil
}
func (gfc *GoatFirehoseConsumer) handleAccountEvent(ctx context.Context, evt *comatproto.SyncSubscribeRepos_Account) error {
out := make(map[string]interface{})
out["type"] = "account"
out["payload"] = evt
b, err := json.Marshal(out)
if err != nil {
return err
}
fmt.Println(string(b))
return nil
}
// this is the simple version, when not in "records" mode: print the event as JSON, but don't include blocks
func (gfc *GoatFirehoseConsumer) handleCommitEvent(ctx context.Context, evt *comatproto.SyncSubscribeRepos_Commit) error {
// apply collections filter
if len(gfc.CollectionFilter) > 0 {
keep := false
for _, op := range evt.Ops {
parts := strings.SplitN(op.Path, "/", 3)
if len(parts) != 2 {
slog.Error("invalid record path", "path", op.Path)
return nil
}
collection := parts[0]
for _, c := range gfc.CollectionFilter {
if c == collection {
keep = true
break
}
}
if keep == true {
break
}
}
if !keep {
return nil
}
}
evt.Blocks = nil
out := make(map[string]interface{})
out["type"] = "commit"
out["payload"] = evt
b, err := json.Marshal(out)
if err != nil {
return err
}
fmt.Println(string(b))
return nil
}
func (gfc *GoatFirehoseConsumer) handleCommitEventOps(ctx context.Context, evt *comatproto.SyncSubscribeRepos_Commit) error {
logger := slog.With("event", "commit", "did", evt.Repo, "rev", evt.Rev, "seq", evt.Seq)
if evt.TooBig {
logger.Warn("skipping tooBig events for now")
return nil
}
rr, err := repo.ReadRepoFromCar(ctx, bytes.NewReader(evt.Blocks))
if err != nil {
logger.Error("failed to read repo from car", "err", err)
return nil
}
for _, op := range evt.Ops {
collection, rkey, err := splitRepoPath(op.Path)
if err != nil {
logger.Error("invalid path in repo op", "eventKind", op.Action, "path", op.Path)
return nil
}
logger = logger.With("eventKind", op.Action, "collection", collection, "rkey", rkey)
if len(gfc.CollectionFilter) > 0 {
keep := false
for _, c := range gfc.CollectionFilter {
if collection.String() == c {
keep = true
break
}
}
if keep == false {
continue
}
}
out := make(map[string]interface{})
out["seq"] = evt.Seq
out["rev"] = evt.Rev
out["time"] = evt.Time
out["collection"] = collection
out["rkey"] = rkey
ek := repomgr.EventKind(op.Action)
switch ek {
case repomgr.EvtKindCreateRecord, repomgr.EvtKindUpdateRecord:
// read the record bytes from blocks, and verify CID
rc, recCBOR, err := rr.GetRecordBytes(ctx, op.Path)
if err != nil {
logger.Error("reading record from event blocks (CAR)", "err", err)
break
}
if op.Cid == nil || lexutil.LexLink(rc) != *op.Cid {
logger.Error("mismatch between commit op CID and record block", "recordCID", rc, "opCID", op.Cid)
break
}
switch ek {
case repomgr.EvtKindCreateRecord:
out["action"] = "create"
case repomgr.EvtKindUpdateRecord:
out["action"] = "update"
default:
logger.Error("impossible event kind", "kind", ek)
break
}
d, err := data.UnmarshalCBOR(*recCBOR)
if err != nil {
slog.Warn("failed to parse record CBOR")
continue
}
out["cid"] = op.Cid.String()
out["record"] = d
b, err := json.Marshal(out)
if err != nil {
return err
}
fmt.Println(string(b))
case repomgr.EvtKindDeleteRecord:
out["action"] = "delete"
b, err := json.Marshal(out)
if err != nil {
return err
}
fmt.Println(string(b))
default:
logger.Error("unexpected record op kind")
}
}
return nil
}