atproto-client 0.11.0

HTTP client for AT Protocol services with OAuth and identity integration
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
//! AT Protocol repository operations.
//!
//! Client functions for com.atproto.repo XRPC methods including
//! record CRUD operations with DPoP authentication support.
//! - **`create_record()`**: Create a new record in a repository
//! - **`put_record()`**: Update or create a record with a specific key
//! - **`delete_record()`**: Delete a record from a repository
//!
//! ## Request/Response Types
//!
//! - **`CreateRecordRequest`**: Parameters for creating new records
//! - **`PutRecordRequest`**: Parameters for updating/creating records with specific keys
//! - **`DeleteRecordRequest`**: Parameters for deleting records
//! - **`GetRecordResponse`**: Response containing record data or error
//! - **`ListRecordsResponse`**: Paginated list of records with cursor support
//! - **`CreateRecordResponse`**: Response with created record URI and CID
//! - **`PutRecordResponse`**: Response with updated record URI and CID
//! - **`DeleteRecordResponse`**: Response with commit information or error
//!
//! ## Authentication
//!
//! All operations require DPoP authentication using the `DPoPAuth` struct containing
//! OAuth access tokens and private keys for proof generation.

use std::collections::HashMap;

use anyhow::Result;
use bytes::Bytes;
use serde::{Deserialize, Serialize, de::DeserializeOwned};

use crate::{
    client::{DPoPAuth, get_bytes, get_dpop_json, get_json, post_dpop_json},
    errors::SimpleError,
    url::URLBuilder,
};

/// Response from getting a record from an AT Protocol repository.
#[cfg_attr(debug_assertions, derive(Debug))]
#[derive(Deserialize, Clone)]
#[serde(untagged)]
pub enum GetRecordResponse {
    /// Successfully retrieved record
    Record {
        /// AT-URI identifying the record
        uri: String,
        /// Content identifier (CID) of the record
        cid: String,
        /// The record content as JSON
        value: serde_json::Value,

        /// Additional fields not part of the standard response
        #[serde(flatten)]
        extra: HashMap<String, serde_json::Value>,
    },
    /// Error response from the server
    Error(SimpleError),
}

/// Retrieves a blob from an AT Protocol repository by DID and CID.
///
/// # Arguments
///
/// * `http_client` - HTTP client for making requests
/// * `base_url` - Base URL of the AT Protocol server
/// * `did` - Repository identifier (DID) containing the blob
/// * `cid` - Content identifier (CID) of the blob to retrieve
///
/// # Returns
///
/// The blob data as bytes
pub async fn get_blob(
    http_client: &reqwest::Client,
    base_url: &str,
    did: &str,
    cid: &str,
) -> Result<Bytes> {
    let mut url_builder = URLBuilder::new(base_url);
    url_builder.path("/xrpc/com.atproto.sync.getBlob");

    url_builder.param("did", did);
    url_builder.param("cid", cid);

    let url = url_builder.build();

    get_bytes(http_client, &url).await
}

/// Retrieves a record from an AT Protocol repository.
///
/// # Arguments
///
/// * `http_client` - HTTP client for making requests
/// * `dpop_auth` - DPoP authentication credentials
/// * `base_url` - Base URL of the AT Protocol server
/// * `repo` - Repository identifier (DID)
/// * `collection` - Collection NSID
/// * `rkey` - Record key
/// * `cid` - Optional specific version CID to retrieve
///
/// # Returns
///
/// The record data or an error response
pub async fn get_record(
    http_client: &reqwest::Client,
    dpop_auth: Option<&DPoPAuth>,
    base_url: &str,
    repo: &str,
    collection: &str,
    rkey: &str,
    cid: Option<&str>,
) -> Result<GetRecordResponse> {
    let mut url_builder = URLBuilder::new(base_url);
    url_builder.path("/xrpc/com.atproto.repo.getRecord");

    url_builder.param("repo", repo);
    url_builder.param("collection", collection);
    url_builder.param("rkey", rkey);

    if let Some(cid) = cid {
        url_builder.param("cid", cid);
    }

    let url = url_builder.build();

    if let Some(dpop_auth) = dpop_auth {
        get_dpop_json(http_client, dpop_auth, &url)
            .await
            .and_then(|value| serde_json::from_value(value).map_err(|err| err.into()))
    } else {
        get_json(http_client, &url)
            .await
            .and_then(|value| serde_json::from_value(value).map_err(|err| err.into()))
    }
}

/// A single record in a list records response.
#[cfg_attr(debug_assertions, derive(Debug))]
#[derive(Deserialize, Clone)]
pub struct ListRecord<T> {
    /// AT-URI of the record
    pub uri: String,
    /// Content identifier (CID) of the record
    pub cid: String,
    /// The record content
    pub value: T,
}

/// Response from listing records in an AT Protocol repository.
#[cfg_attr(debug_assertions, derive(Debug))]
#[derive(Deserialize, Clone)]
pub struct ListRecordsResponse<T> {
    /// Pagination cursor for retrieving more records
    pub cursor: Option<String>,
    /// List of records in the collection
    pub records: Vec<ListRecord<T>>,
}

/// Parameters for listing records from a repository collection.
#[derive(Default)]
pub struct ListRecordsParams {
    /// Maximum number of records to return
    pub limit: Option<u32>,
    /// Pagination cursor from previous request
    pub cursor: Option<String>,
    /// Whether to return records in reverse chronological order
    pub reverse: Option<bool>,
}

impl ListRecordsParams {
    /// Creates new list records parameters with default values.
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the maximum number of records to return.
    pub fn limit(mut self, limit: u32) -> Self {
        self.limit = Some(limit);
        self
    }

    /// Sets the pagination cursor.
    pub fn cursor(mut self, cursor: String) -> Self {
        self.cursor = Some(cursor);
        self
    }

    /// Sets reverse chronological ordering.
    pub fn reverse(mut self, reverse: bool) -> Self {
        self.reverse = Some(reverse);
        self
    }
}

/// Lists records from an AT Protocol repository collection.
///
/// # Arguments
///
/// * `http_client` - HTTP client for making requests
/// * `dpop_auth` - DPoP authentication credentials
/// * `base_url` - Base URL of the AT Protocol server
/// * `repo` - Repository identifier (DID)
/// * `collection` - Collection NSID to list from
/// * `params` - Optional parameters for listing (limit, cursor, reverse)
///
/// # Returns
///
/// A paginated list of records from the collection
pub async fn list_records<T: DeserializeOwned>(
    http_client: &reqwest::Client,
    dpop_auth: Option<&DPoPAuth>,
    base_url: &str,
    repo: String,
    collection: String,
    params: ListRecordsParams,
) -> Result<ListRecordsResponse<T>> {
    let mut url_builder = URLBuilder::new(base_url);
    url_builder.path("/xrpc/com.atproto.repo.listRecords");

    // Add query parameters
    url_builder.param("repo", &repo);
    url_builder.param("collection", &collection);

    if let Some(limit) = params.limit {
        url_builder.param("limit", &limit.to_string());
    }

    if let Some(cursor) = params.cursor {
        url_builder.param("cursor", &cursor);
    }

    if let Some(reverse) = params.reverse {
        url_builder.param("reverse", &reverse.to_string());
    }

    let url = url_builder.build();

    if let Some(dpop_auth) = dpop_auth {
        get_dpop_json(http_client, dpop_auth, &url)
            .await
            .and_then(|value| serde_json::from_value(value).map_err(|err| err.into()))
    } else {
        get_json(http_client, &url)
            .await
            .and_then(|value| serde_json::from_value(value).map_err(|err| err.into()))
    }
}

/// Request to create a new record in an AT Protocol repository.
#[cfg_attr(debug_assertions, derive(Debug))]
#[derive(Serialize, Deserialize, Clone)]
#[serde(bound = "T: Serialize + DeserializeOwned")]
pub struct CreateRecordRequest<T: DeserializeOwned> {
    /// Repository identifier (DID)
    pub repo: String,
    /// Collection NSID (e.g., "app.bsky.feed.post")
    pub collection: String,

    /// Optional record key; if None, server will generate one
    #[serde(skip_serializing_if = "Option::is_none", default, rename = "rkey")]
    pub record_key: Option<String>,

    /// Whether to validate the record against its schema
    pub validate: bool,

    /// The record content to create
    pub record: T,

    /// Optional commit CID to swap (for atomic updates)
    #[serde(
        skip_serializing_if = "Option::is_none",
        default,
        rename = "swapCommit"
    )]
    pub swap_commit: Option<String>,
}

/// Response from creating a record in an AT Protocol repository.
#[cfg_attr(debug_assertions, derive(Debug))]
#[derive(Deserialize, Clone)]
#[serde(untagged)]
pub enum CreateRecordResponse {
    /// Successfully created record reference
    StrongRef {
        /// AT-URI of the created record
        uri: String,
        /// Content identifier (CID) of the created record
        cid: String,

        /// Additional fields not part of the standard response
        #[serde(flatten)]
        extra: HashMap<String, serde_json::Value>,
    },
    /// Error response from the server
    Error(SimpleError),
}

/// Creates a new record in an AT Protocol repository.
///
/// # Arguments
///
/// * `http_client` - HTTP client for making requests
/// * `dpop_auth` - DPoP authentication credentials
/// * `base_url` - Base URL of the AT Protocol server
/// * `record` - Record creation request with content and metadata
///
/// # Returns
///
/// The created record reference or an error response
pub async fn create_record<T: DeserializeOwned + Serialize>(
    http_client: &reqwest::Client,
    dpop_auth: &DPoPAuth,
    base_url: &str,
    record: CreateRecordRequest<T>,
) -> Result<CreateRecordResponse> {
    let mut url_builder = URLBuilder::new(base_url);
    url_builder.path("/xrpc/com.atproto.repo.createRecord");
    let url = url_builder.build();

    let value = serde_json::to_value(record)?;

    post_dpop_json(http_client, dpop_auth, &url, value)
        .await
        .and_then(|value| serde_json::from_value(value).map_err(|err| err.into()))
}

/// Request to update an existing record in an AT Protocol repository.
#[cfg_attr(debug_assertions, derive(Debug))]
#[derive(Serialize, Deserialize, Clone)]
#[serde(bound = "T: Serialize + DeserializeOwned")]
pub struct PutRecordRequest<T: DeserializeOwned> {
    /// Repository identifier (DID)
    pub repo: String,
    /// Collection NSID (e.g., "app.bsky.feed.post")
    pub collection: String,

    /// Record key to update
    #[serde(rename = "rkey")]
    pub record_key: String,

    /// Whether to validate the record against its schema
    pub validate: bool,

    /// The new record content
    pub record: T,

    /// Optional commit CID to swap (for atomic updates)
    #[serde(
        skip_serializing_if = "Option::is_none",
        default,
        rename = "swapCommit"
    )]
    pub swap_commit: Option<String>,

    /// Optional record CID to swap (for conditional updates)
    #[serde(
        skip_serializing_if = "Option::is_none",
        default,
        rename = "swapRecord"
    )]
    pub swap_record: Option<String>,
}

/// Response from updating a record in an AT Protocol repository.
#[cfg_attr(debug_assertions, derive(Debug))]
#[derive(Serialize, Deserialize, Clone)]
#[serde(untagged)]
pub enum PutRecordResponse {
    /// Successfully updated record reference
    StrongRef {
        /// AT-URI of the updated record
        uri: String,
        /// Content identifier (CID) of the updated record
        cid: String,

        /// Additional fields not part of the standard response
        #[serde(flatten)]
        extra: HashMap<String, serde_json::Value>,
    },
    /// Error response from the server
    Error(SimpleError),
}

/// Updates an existing record in an AT Protocol repository.
///
/// # Arguments
///
/// * `http_client` - HTTP client for making requests
/// * `dpop_auth` - DPoP authentication credentials
/// * `base_url` - Base URL of the AT Protocol server
/// * `record` - Record update request with new content and metadata
///
/// # Returns
///
/// The updated record reference or an error response
pub async fn put_record<T: DeserializeOwned + Serialize>(
    http_client: &reqwest::Client,
    dpop_auth: &DPoPAuth,
    base_url: &str,
    record: PutRecordRequest<T>,
) -> Result<PutRecordResponse> {
    let mut url_builder = URLBuilder::new(base_url);
    url_builder.path("/xrpc/com.atproto.repo.putRecord");
    let url = url_builder.build();

    let value = serde_json::to_value(record)?;

    post_dpop_json(http_client, dpop_auth, &url, value)
        .await
        .and_then(|value| serde_json::from_value(value).map_err(|err| err.into()))
}

/// Request to delete a record from an AT Protocol repository.
#[cfg_attr(debug_assertions, derive(Debug))]
#[derive(Serialize, Deserialize, Clone)]
pub struct DeleteRecordRequest {
    /// Repository identifier (DID)
    pub repo: String,
    /// Collection NSID (e.g., "app.bsky.feed.post")
    pub collection: String,

    /// Record key to delete
    #[serde(rename = "rkey")]
    pub record_key: String,

    /// Optional commit CID to swap (for atomic updates)
    #[serde(
        skip_serializing_if = "Option::is_none",
        default,
        rename = "swapCommit"
    )]
    pub swap_commit: Option<String>,

    /// Optional record CID to swap (for atomic updates)
    #[serde(
        skip_serializing_if = "Option::is_none",
        default,
        rename = "swapRecord"
    )]
    pub swap_record: Option<String>,
}

/// Response from deleting a record in an AT Protocol repository.
#[cfg_attr(debug_assertions, derive(Debug))]
#[derive(Deserialize, Clone)]
#[serde(untagged)]
pub enum DeleteRecordResponse {
    /// Successfully deleted record with commit information
    Commit {
        /// Commit information as a map of fields
        #[serde(flatten)]
        commit: HashMap<String, serde_json::Value>,
    },

    /// Error response from the server
    Error(SimpleError),
}

/// Deletes a record from an AT Protocol repository.
///
/// # Arguments
///
/// * `http_client` - HTTP client for making requests
/// * `dpop_auth` - DPoP authentication credentials
/// * `base_url` - Base URL of the AT Protocol server
/// * `record` - Record deletion request with repository, collection, and key
///
/// # Returns
///
/// The deletion response with commit information or an error
pub async fn delete_record(
    http_client: &reqwest::Client,
    dpop_auth: &DPoPAuth,
    base_url: &str,
    record: DeleteRecordRequest,
) -> Result<DeleteRecordResponse> {
    let mut url_builder = URLBuilder::new(base_url);
    url_builder.path("/xrpc/com.atproto.repo.deleteRecord");
    let url = url_builder.build();

    let value = serde_json::to_value(record)?;

    post_dpop_json(http_client, dpop_auth, &url, value)
        .await
        .and_then(|value| serde_json::from_value(value).map_err(|err| err.into()))
}