tapped 0.3.1

Rust wrapper for the tap ATProto utility
Documentation
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
//! Type definitions for tap events and API responses.

use serde::{Deserialize, Serialize};
use serde_json::value::RawValue;

use tungstenite::protocol::frame::Utf8Bytes;

use crate::Error;

/// Action performed on a record.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
#[non_exhaustive]
pub enum RecordAction {
    Create,
    Update,
    Delete,
}

/// Account status.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
#[non_exhaustive]
pub enum AccountStatus {
    Active,
    Takendown,
    Suspended,
    Deactivated,
    Deleted,
}

/// Repository sync state.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
#[non_exhaustive]
pub enum RepoState {
    Pending,
    Desynchronized,
    Resyncing,
    Active,
    Takendown,
    Suspended,
    Deactivated,
    Error,
}

/// A record event from the tap stream.
pub struct RecordEvent {
    /// Unique event ID for acknowledgment.
    pub id: u64,
    /// True if from live firehose, false if from backfill/resync.
    pub live: bool,
    /// DID of the repository.
    pub did: String,
    /// Repository revision (TID format).
    pub rev: String,
    /// Collection NSID (e.g., "app.bsky.feed.post").
    pub collection: String,
    /// Record key (usually TID format).
    pub rkey: String,
    /// Action performed on the record.
    pub action: RecordAction,
    /// CID of the record (None on delete).
    pub cid: Option<String>,
    // Inner record JSON pointing into the outer JSON
    json: Option<Utf8Bytes>,
    record_offset: usize,
    record_len: usize,
}

impl RecordEvent {
    /// Get the record's content as a reference to a JSON string
    pub fn record_as_str(&self) -> Option<&str> {
        self.json
            .as_ref()
            .map(|j| &j.as_str()[self.record_offset..self.record_offset + self.record_len])
    }

    /// Parse the record's content to a compatible struct
    pub fn deserialize_as<T>(&self) -> Result<T, Error>
    where
        for<'de> T: Deserialize<'de>,
    {
        self.record_as_str()
            .map_or(Err(Error::NoRecordPresent), |s| {
                serde_json::from_str(s).map_err(Into::into)
            })
    }
}

/// An identity event from the tap stream.
#[derive(Debug, Clone)]
pub struct IdentityEvent {
    /// Unique event ID for acknowledgment.
    pub id: u64,
    /// DID of the account.
    pub did: String,
    /// Current handle.
    pub handle: String,
    /// Whether the account is active.
    pub is_active: bool,
    /// Account status.
    pub status: AccountStatus,
}

/// An event from the tap stream.
#[non_exhaustive]
pub enum Event {
    /// A record create/update/delete event.
    Record(RecordEvent),
    /// An identity (handle/status) change event.
    Identity(IdentityEvent),
}

impl Event {
    /// Get the event ID.
    pub fn id(&self) -> u64 {
        match self {
            Event::Record(e) => e.id,
            Event::Identity(e) => e.id,
        }
    }

    /// Get the DID associated with this event.
    pub fn did(&self) -> &str {
        match self {
            Event::Record(e) => &e.did,
            Event::Identity(e) => &e.did,
        }
    }
}

/// Information about a tracked repository.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RepoInfo {
    /// DID of the repository.
    pub did: String,
    /// Current handle (may be empty).
    pub handle: String,
    /// Sync state.
    pub state: RepoState,
    /// Current revision (TID format, empty if not synced).
    pub rev: String,
    /// Error message if in error state.
    pub error: String,
    /// Number of failed retry attempts.
    pub retries: u32,
    /// Total number of tracked records.
    pub records: u64,
}

/// Cursor positions.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Cursors {
    /// Firehose sequence number (None if not consuming).
    pub firehose: Option<i64>,
    /// List repos enumeration cursor (None if not enumerating).
    pub list_repos: Option<String>,
}

/// A DID document.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DidDocument {
    /// The DID itself.
    pub id: String,
    /// Also known as (ATProto handles, etc.).
    #[serde(default, rename = "alsoKnownAs")]
    pub also_known_as: Vec<String>,
    /// Verification methods (signing keys).
    #[serde(default, rename = "verificationMethod")]
    pub verification_method: Vec<VerificationMethod>,
    /// Services (PDS endpoint, etc.).
    #[serde(default)]
    pub service: Vec<Service>,
    /// Additional fields not explicitly modelled.
    #[serde(flatten)]
    pub extra: serde_json::Value,
}

/// A verification method in a DID document.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VerificationMethod {
    /// Method ID.
    pub id: String,
    /// Method type.
    #[serde(rename = "type")]
    pub type_: String,
    /// Controller DID.
    pub controller: String,
    /// Public key in multibase format.
    #[serde(rename = "publicKeyMultibase")]
    pub public_key_multibase: Option<String>,
}

/// A service in a DID document.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Service {
    /// Service ID.
    pub id: String,
    /// Service type.
    #[serde(rename = "type")]
    pub type_: String,
    /// Service endpoint URL.
    #[serde(rename = "serviceEndpoint")]
    pub service_endpoint: String,
}

// Internal deserialisation structures for parsing tap's JSON format

#[derive(Deserialize)]
#[serde(bound(deserialize = "'de: 'a"))]
pub(crate) struct RawEvent<'a> {
    pub id: u64,
    #[serde(rename = "type")]
    pub type_: String,
    pub identity: Option<RawIdentityEvent>,
    pub record: Option<RawRecordEvent<'a>>,
}

#[derive(Deserialize)]
#[serde(bound(deserialize = "'de: 'a"))]
pub(crate) struct RawRecordEvent<'a> {
    pub live: bool,
    pub did: String,
    pub rev: String,
    pub collection: String,
    pub rkey: String,
    pub action: RecordAction,
    pub cid: Option<String>,
    pub record: Option<&'a RawValue>,
}

#[derive(Deserialize, Clone)]
pub(crate) struct RawIdentityEvent {
    pub did: String,
    pub handle: String,
    #[serde(rename = "is_active")]
    pub is_active: bool,
    pub status: AccountStatus,
}

impl RawEvent<'_> {
    /// Convert to the public Event type.
    pub fn into_event(self, json: Utf8Bytes) -> Option<Event> {
        match self.type_.as_str() {
            "record" => {
                let r = self.record?;
                let (json, record_offset, record_len) = if let Some(rv) = r.record.as_ref() {
                    let json_str = json.as_str();
                    let rv_str = rv.get();
                    let offset = rv_str.as_ptr() as usize - json_str.as_ptr() as usize;
                    (Some(json), offset, rv_str.len())
                } else {
                    (None, 0, 0)
                };
                Some(Event::Record(RecordEvent {
                    id: self.id,
                    live: r.live,
                    did: r.did,
                    rev: r.rev,
                    collection: r.collection,
                    rkey: r.rkey,
                    action: r.action,
                    cid: r.cid,
                    json,
                    record_offset,
                    record_len,
                }))
            }
            "identity" => {
                let i = self.identity?;
                Some(Event::Identity(IdentityEvent {
                    id: self.id,
                    did: i.did,
                    handle: i.handle,
                    is_active: i.is_active,
                    status: i.status,
                }))
            }
            _ => None,
        }
    }
}

// Response types for stats endpoints

#[derive(Deserialize)]
pub(crate) struct RepoCountResponse {
    pub repo_count: u64,
}

#[derive(Deserialize)]
pub(crate) struct RecordCountResponse {
    pub record_count: u64,
}

#[derive(Deserialize)]
pub(crate) struct OutboxBufferResponse {
    pub outbox_buffer: u64,
}

#[derive(Deserialize)]
pub(crate) struct ResyncBufferResponse {
    pub resync_buffer: u64,
}

#[derive(Deserialize)]
pub(crate) struct ApiError {
    pub message: String,
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    /// Helper macro for testing enum variant deserialisation.
    macro_rules! assert_deserialize {
        ($type:ty, $($json:literal => $variant:expr),+ $(,)?) => {
            $(
                assert_eq!(
                    serde_json::from_str::<$type>($json).unwrap(),
                    $variant
                );
            )+
        };
    }

    #[test]
    fn record_action_deserialize() {
        assert_deserialize!(RecordAction,
            r#""create""# => RecordAction::Create,
            r#""update""# => RecordAction::Update,
            r#""delete""# => RecordAction::Delete,
        );
    }

    #[test]
    fn account_status_deserialize() {
        assert_deserialize!(AccountStatus,
            r#""active""# => AccountStatus::Active,
            r#""takendown""# => AccountStatus::Takendown,
            r#""suspended""# => AccountStatus::Suspended,
            r#""deactivated""# => AccountStatus::Deactivated,
            r#""deleted""# => AccountStatus::Deleted,
        );
    }

    #[test]
    fn repo_state_deserialize() {
        assert_deserialize!(RepoState,
            r#""pending""# => RepoState::Pending,
            r#""active""# => RepoState::Active,
            r#""error""# => RepoState::Error,
        );
    }

    #[test]
    fn repo_info_deserialize() {
        let json = json!({
            "did": "did:plc:abc123",
            "handle": "test.bsky.social",
            "state": "active",
            "rev": "3abc123",
            "error": "",
            "retries": 0,
            "records": 42
        });

        let info: RepoInfo = serde_json::from_value(json).unwrap();
        assert_eq!(info.did, "did:plc:abc123");
        assert_eq!(info.handle, "test.bsky.social");
        assert_eq!(info.state, RepoState::Active);
        assert_eq!(info.records, 42);
    }

    #[test]
    fn cursors_deserialize() {
        let json = json!({
            "firehose": 12345678,
            "list_repos": "some-cursor"
        });

        let cursors: Cursors = serde_json::from_value(json).unwrap();
        assert_eq!(cursors.firehose, Some(12345678));
        assert_eq!(cursors.list_repos, Some("some-cursor".to_string()));
    }

    #[test]
    fn cursors_deserialize_nulls() {
        let json = json!({
            "firehose": null,
            "list_repos": null
        });

        let cursors: Cursors = serde_json::from_value(json).unwrap();
        assert_eq!(cursors.firehose, None);
        assert_eq!(cursors.list_repos, None);
    }

    #[test]
    fn did_document_deserialize() {
        let json = json!({
            "id": "did:plc:example1234567890abc",
            "alsoKnownAs": ["at://alice.test"],
            "verificationMethod": [{
                "id": "did:plc:example1234567890abc#atproto",
                "type": "Multikey",
                "controller": "did:plc:example1234567890abc",
                "publicKeyMultibase": "zDnaekeGCpVsdvDCrGNa9t3bXYUs45MHX1hLwqvaKLtPU9m7X"
            }],
            "service": [{
                "id": "#atproto_pds",
                "type": "AtprotoPersonalDataServer",
                "serviceEndpoint": "https://pds.example.com"
            }]
        });

        let doc: DidDocument = serde_json::from_value(json).unwrap();
        assert_eq!(doc.id, "did:plc:example1234567890abc");
        assert_eq!(doc.also_known_as, vec!["at://alice.test"]);
        assert_eq!(doc.verification_method.len(), 1);
        assert_eq!(doc.verification_method[0].type_, "Multikey");
        assert_eq!(doc.service.len(), 1);
        assert_eq!(doc.service[0].type_, "AtprotoPersonalDataServer");
    }

    #[test]
    fn did_document_with_extra_fields() {
        let json = json!({
            "id": "did:plc:test",
            "alsoKnownAs": [],
            "@context": ["https://www.w3.org/ns/did/v1"],
            "customField": "some value"
        });

        let doc: DidDocument = serde_json::from_value(json).unwrap();
        assert_eq!(doc.id, "did:plc:test");
        assert!(doc.extra.get("@context").is_some());
        assert!(doc.extra.get("customField").is_some());
    }

    #[test]
    fn raw_record_event_deserialize() {
        let json = json!({
            "id": 12345,
            "type": "record",
            "record": {
                "live": true,
                "did": "did:plc:abc123",
                "rev": "3abc",
                "collection": "app.bsky.feed.post",
                "rkey": "3def",
                "action": "create",
                "cid": "bafyreid...",
                "record": {
                    "$type": "app.bsky.feed.post",
                    "text": "Hello!"
                }
            }
        })
        .to_string();

        let json: Utf8Bytes = json.into();
        let raw: RawEvent = serde_json::from_str(json.as_str()).unwrap();
        assert_eq!(raw.id, 12345);
        assert_eq!(raw.type_, "record");

        let event = raw.into_event(json.clone()).unwrap();
        match event {
            Event::Record(r) => {
                assert_eq!(r.id, 12345);
                assert!(r.live);
                assert_eq!(r.did, "did:plc:abc123");
                assert_eq!(r.collection, "app.bsky.feed.post");
                assert_eq!(r.action, RecordAction::Create);
            }
            _ => panic!("Expected Record event"),
        }
    }

    #[test]
    fn raw_identity_event_deserialize() {
        let json: Utf8Bytes = json!({
            "id": 99999,
            "type": "identity",
            "identity": {
                "did": "did:plc:xyz789",
                "handle": "alice.bsky.social",
                "is_active": true,
                "status": "active"
            }
        })
        .to_string()
        .into();

        let raw: RawEvent = serde_json::from_str(json.as_str()).unwrap();
        let event = raw.into_event(json.clone()).unwrap();

        match event {
            Event::Identity(i) => {
                assert_eq!(i.id, 99999);
                assert_eq!(i.did, "did:plc:xyz789");
                assert_eq!(i.handle, "alice.bsky.social");
                assert!(i.is_active);
                assert_eq!(i.status, AccountStatus::Active);
            }
            _ => panic!("Expected Identity event"),
        }
    }

    #[test]
    fn raw_delete_event_no_record() {
        let json: Utf8Bytes = json!({
            "id": 55555,
            "type": "record",
            "record": {
                "live": false,
                "did": "did:plc:deleted",
                "rev": "3xyz",
                "collection": "app.bsky.feed.post",
                "rkey": "3abc",
                "action": "delete",
                "cid": null,
                "record": null
            }
        })
        .to_string()
        .into();

        let raw: RawEvent = serde_json::from_str(json.as_str()).unwrap();
        let event = raw.into_event(json.clone()).unwrap();

        match event {
            Event::Record(r) => {
                assert_eq!(r.action, RecordAction::Delete);
                assert!(r.cid.is_none());
                assert!(r.record_as_str().is_none());
            }
            _ => panic!("Expected Record event"),
        }
    }

    #[test]
    fn event_helper_methods() {
        let record_event = Event::Record(RecordEvent {
            id: 123,
            live: true,
            did: "did:plc:record".to_string(),
            rev: "abc".to_string(),
            collection: "test".to_string(),
            rkey: "key".to_string(),
            action: RecordAction::Create,
            cid: None,
            json: None,
            record_offset: 0,
            record_len: 0,
        });

        assert_eq!(record_event.id(), 123);
        assert_eq!(record_event.did(), "did:plc:record");

        let identity_event = Event::Identity(IdentityEvent {
            id: 456,
            did: "did:plc:identity".to_string(),
            handle: "test".to_string(),
            is_active: true,
            status: AccountStatus::Active,
        });

        assert_eq!(identity_event.id(), 456);
        assert_eq!(identity_event.did(), "did:plc:identity");
    }
}