sdx 1.13.0

Native Xet client library for Shardline's Xet frontend.
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
//! Revision/branch client (M5b, `docs/SDX_PLAN.md` ยง4.3): create, list, and
//! delete revisions against the M5a revision-registry endpoints.
//!
//! Exposes [`XetClient::list_revisions`], [`XetClient::create_revision`], and
//! [`XetClient::delete_revision`]. Creating a revision that already exists
//! returns [`SdxError::RevisionExists`]; deletion is idempotent.

use std::collections::HashSet;

use reqwest::Method;
use serde::Deserialize;
use shardline_xet_adapter::{XET_REVISION_ROUTE, XET_REVISIONS_ROUTE};

use crate::{
    client::XetClient,
    error::{SdxError, TransferError},
    tree::MetadataClient,
};

// Server names are <=512 UTF-8 bytes without controls. Quotes/backslashes
// expand at most 2x; timestamps are u64. This client requests default 1000-row
// pages, plus one bounded nextCursor and the outer JSON envelope.
const REVISION_RESPONSE_LIMIT: usize = 1152;
const REVISION_PAGE_RESPONSE_LIMIT: usize = 1_153_152;

/// A revision record (`{name,createdAt,updatedAt}`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Revision {
    /// Revision name.
    pub name: String,
    /// Creation time as Unix seconds.
    pub created_at: u64,
    /// Last update time as Unix seconds.
    pub updated_at: u64,
}

#[derive(Debug, Deserialize)]
#[cfg_attr(test, derive(serde::Serialize))]
#[serde(rename_all = "camelCase")]
struct RevisionJson {
    name: String,
    created_at: u64,
    updated_at: u64,
}

#[derive(Debug, Deserialize)]
#[cfg_attr(test, derive(serde::Serialize))]
#[serde(rename_all = "camelCase")]
struct RevisionsResponse {
    revisions: Vec<RevisionJson>,
    #[serde(default)]
    next_cursor: Option<String>,
}

#[derive(Debug, Deserialize)]
#[cfg_attr(test, derive(serde::Serialize))]
#[serde(rename_all = "camelCase")]
struct DeleteRevisionResponse {}

impl MetadataClient {
    /// Lists every revision of the repository by walking the keyset-cursor
    /// pages until the server reports no `nextCursor`.
    ///
    /// The server bounds each page (default limit 1000), so a repository with
    /// more revisions than one page would silently truncate without this loop
    /// (F-84).
    async fn list_revisions(&self) -> Result<Vec<Revision>, SdxError> {
        let retry = self.read_retry();
        let token = self.tokens.read_token().await?;
        let route = self.repo_route(XET_REVISIONS_ROUTE);
        let mut revisions = Vec::new();
        let mut cursor: Option<String> = None;
        let mut cursors = HashSet::new();
        loop {
            let query: Vec<(String, String)> = cursor
                .as_deref()
                .map(|c| vec![("cursor".to_owned(), c.to_owned())])
                .unwrap_or_default();
            let url = crate::tree::build_url(&self.api_base, &route, &query);
            let response: RevisionsResponse = self
                .send_json(
                    &retry,
                    token.token.clone(),
                    Method::GET,
                    url,
                    None,
                    ("list_revisions", REVISION_PAGE_RESPONSE_LIMIT),
                )
                .await?;
            revisions.extend(response.revisions.into_iter().map(|revision| Revision {
                name: revision.name,
                created_at: revision.created_at,
                updated_at: revision.updated_at,
            }));
            cursor = crate::tree::checked_next_cursor(
                "list_revisions",
                response.next_cursor,
                &mut cursors,
            )?;
            if cursor.is_none() {
                break;
            }
        }
        Ok(revisions)
    }

    async fn create_revision(&self, rev: &str) -> Result<Revision, SdxError> {
        let retry = self.write_retry();
        let token = self.tokens.write_token().await?;
        let route = self
            .repo_route_scope(XET_REVISION_ROUTE)
            .replace("{rev}", &crate::tree::encode_path_segment(rev));
        let url = crate::tree::build_url(&self.api_base, &route, crate::tree::no_query());
        match self
            .send_json::<RevisionJson>(
                &retry,
                token.token,
                Method::POST,
                url,
                None,
                ("create_revision", REVISION_RESPONSE_LIMIT),
            )
            .await
        {
            Ok(revision) => Ok(Revision {
                name: revision.name,
                created_at: revision.created_at,
                updated_at: revision.updated_at,
            }),
            Err(SdxError::Transfer(TransferError::HttpStatus { status: 409, .. })) => {
                Err(SdxError::RevisionExists(rev.to_owned()))
            }
            Err(error) => Err(error),
        }
    }

    async fn delete_revision(&self, rev: &str) -> Result<(), SdxError> {
        let retry = self.write_retry();
        let token = self.tokens.write_token().await?;
        let route = self
            .repo_route_scope(XET_REVISION_ROUTE)
            .replace("{rev}", &crate::tree::encode_path_segment(rev));
        let url = crate::tree::build_url(&self.api_base, &route, crate::tree::no_query());
        let _: DeleteRevisionResponse = self
            .send_json(
                &retry,
                token.token,
                Method::DELETE,
                url,
                None,
                ("delete_revision", REVISION_RESPONSE_LIMIT),
            )
            .await?;
        // Idempotent: the server returns 200 even when `deleted: false`.
        Ok(())
    }
}

impl XetClient {
    /// Lists all revisions of the client's repository.
    ///
    /// # Errors
    ///
    /// Returns [`SdxError`] when the request fails or the response is invalid.
    pub async fn list_revisions(&self) -> Result<Vec<Revision>, SdxError> {
        MetadataClient::from_download(self.download_inner())
            .list_revisions()
            .await
    }

    /// Creates a revision, returning its record.
    ///
    /// # Errors
    ///
    /// Returns [`SdxError::RevisionExists`] when the revision already exists,
    /// or another typed error on failure.
    pub async fn create_revision(&self, rev: &str) -> Result<Revision, SdxError> {
        MetadataClient::from_download(self.download_inner())
            .create_revision(rev)
            .await
    }

    /// Deletes a revision (and cascades its tree rows). Idempotent.
    ///
    /// # Errors
    ///
    /// Returns [`SdxError`] when the request fails.
    pub async fn delete_revision(&self, rev: &str) -> Result<(), SdxError> {
        MetadataClient::from_download(self.download_inner())
            .delete_revision(rev)
            .await
    }
}

#[cfg(test)]
mod tests {
    #[test]
    fn revision_response_envelopes_cover_maximum_names_and_default_page() {
        // Names permit quotes and backslashes (controls are rejected), both
        // serialized as two bytes. Cursor is the raw last revision name.
        let name = "\"\\".repeat(256);
        let record = super::RevisionJson {
            name: name.clone(),
            created_at: u64::MAX,
            updated_at: u64::MAX,
        };
        assert!(serde_json::to_vec(&record).unwrap().len() <= super::REVISION_RESPONSE_LIMIT);
        let delete = serde_json::json!({ "name": &name, "deleted": false });
        assert!(serde_json::to_vec(&delete).unwrap().len() <= super::REVISION_RESPONSE_LIMIT);
        #[derive(serde::Serialize)]
        #[serde(rename_all = "camelCase")]
        struct Page<'wire> {
            revisions: Vec<&'wire super::RevisionJson>,
            next_cursor: Option<&'wire str>,
        }
        let page = Page {
            revisions: vec![&record; 1000],
            next_cursor: Some(&name),
        };
        assert!(serde_json::to_vec(&page).unwrap().len() <= super::REVISION_PAGE_RESPONSE_LIMIT);
    }

    use serde_json::json;
    use wiremock::{
        Mock, MockServer, ResponseTemplate,
        matchers::{method, path, query_param},
    };

    use super::Revision;
    use crate::{Auth, RepositoryId, XetClientBuilder};

    const READ_TOKEN: &str = "read-token";

    async fn build_client(server: &MockServer) -> crate::XetClient {
        let auth = Auth::new(
            &server.uri(),
            RepositoryId {
                provider: "github".to_owned(),
                owner: "team".to_owned(),
                repo: "assets".to_owned(),
                revision: "main".to_owned(),
            },
        )
        .unwrap()
        .with_api_key("bootstrap".to_owned())
        .with_subject("user".to_owned());
        let port = server.uri().split(':').next_back().unwrap().to_owned();
        XetClientBuilder::new()
            .endpoint(format!("xet://127.0.0.1:{port}/github/team/assets/main"))
            .auth(auth)
            .build()
            .unwrap()
    }

    async fn mock_read_token(server: &MockServer) {
        Mock::given(method("GET"))
            .and(path("/api/github/team/assets/xet-read-token/main"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "casUrl": server.uri(),
                "exp": 4_000_000_000u64,
                "accessToken": READ_TOKEN,
            })))
            .mount(server)
            .await;
    }

    fn revision_json(name: &str) -> serde_json::Value {
        json!({"name": name, "createdAt": 1, "updatedAt": 2})
    }

    #[tokio::test]
    async fn pagination_rejects_empty_repeated_and_cyclic_cursors() {
        for returned_cursors in [vec![""], vec!["a", "a"], vec!["a", "b", "a"]] {
            let server = MockServer::start().await;
            mock_read_token(&server).await;
            for (index, next) in returned_cursors.iter().enumerate() {
                let expected = index.checked_sub(1).map(|i| returned_cursors[i].to_owned());
                Mock::given(method("GET"))
                    .and(path("/api/github/team/assets/revisions"))
                    .and(move |request: &wiremock::Request| {
                        request
                            .url
                            .query_pairs()
                            .find(|(key, _)| key == "cursor")
                            .map(|(_, value)| value.into_owned())
                            == expected
                    })
                    .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                        "revisions": [], "nextCursor": next
                    })))
                    .expect(1)
                    .mount(&server)
                    .await;
            }
            let client = build_client(&server).await;
            let result =
                tokio::time::timeout(std::time::Duration::from_secs(2), client.list_revisions())
                    .await
                    .expect("malformed pagination must terminate");
            assert!(
                matches!(result, Err(crate::SdxError::Metadata(_))),
                "{result:?}"
            );
            server.verify().await;
        }
    }

    #[tokio::test]
    async fn revisions_json_decode_preserves_context_without_retrying_parse_errors() {
        let server = MockServer::start().await;
        mock_read_token(&server).await;
        Mock::given(method("GET"))
            .and(path("/api/github/team/assets/revisions"))
            .respond_with(ResponseTemplate::new(200).set_body_string("{invalid"))
            .expect(1)
            .mount(&server)
            .await;
        let error = build_client(&server)
            .await
            .list_revisions()
            .await
            .unwrap_err();
        assert!(
            matches!(error, crate::SdxError::Metadata(message) if message.starts_with("list_revisions: "))
        );
    }

    #[tokio::test]
    async fn revisions_wrong_type_diagnostic_is_bounded_with_context_and_no_retry() {
        let server = MockServer::start().await;
        mock_read_token(&server).await;
        Mock::given(method("GET"))
            .and(path("/api/github/team/assets/revisions"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "revisions": [{"name": "main", "createdAt": "x".repeat(100_000), "updatedAt": 1}],
            })))
            .expect(1)
            .mount(&server)
            .await;
        let error = build_client(&server)
            .await
            .list_revisions()
            .await
            .unwrap_err();
        assert!(matches!(error, crate::SdxError::Metadata(message)
            if message.starts_with("list_revisions: ") && message.len() <= 8 * 1024 + "list_revisions: ".len()
                && message.contains("[truncated; at line 1 column ")));
    }

    #[tokio::test]
    async fn revision_mutations_preserve_path_segment_identity() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/api/github/team/assets/xet-write-token/main"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "casUrl": server.uri(), "exp": 4_000_000_000u64,
                "accessToken": "write-token",
            })))
            .mount(&server)
            .await;
        let client = build_client(&server).await;
        for revision in [
            "release candidate",
            "release+candidate",
            "release%candidate",
            "็‰ˆๆœฌ",
            "release/candidate",
        ] {
            for verb in ["POST", "DELETE"] {
                let expected = revision.to_owned();
                let response = if verb == "POST" {
                    revision_json(revision)
                } else {
                    json!({"deleted": true})
                };
                Mock::given(method(verb))
                    .and(move |request: &wiremock::Request| {
                        request
                            .url
                            .path()
                            .strip_prefix("/api/github/team/assets/revisions/")
                            .is_some_and(|segment| {
                                !segment.contains('/')
                                    && percent_encoding::percent_decode_str(segment)
                                        .decode_utf8()
                                        .is_ok_and(|decoded| decoded == expected)
                            })
                    })
                    .respond_with(ResponseTemplate::new(200).set_body_json(response))
                    .expect(1)
                    .mount(&server)
                    .await;
            }
            assert_eq!(
                client.create_revision(revision).await.unwrap().name,
                revision
            );
            client.delete_revision(revision).await.unwrap();
        }
        server.verify().await;
    }

    #[test]
    fn revision_is_comparable() {
        let a = Revision {
            name: "main".to_owned(),
            created_at: 1,
            updated_at: 2,
        };
        let b = a.clone();
        assert_eq!(a, b);
        assert_ne!(
            a,
            Revision {
                name: "other".to_owned(),
                ..a
            }
        );
    }

    /// A response with `nextCursor` set must be followed until the cursor is
    /// exhausted so a repository with more than one page of revisions (server
    /// default limit 1000) is never silently truncated (F-84).
    #[tokio::test]
    async fn list_revisions_follows_next_cursor_until_exhausted() {
        let server = MockServer::start().await;
        mock_read_token(&server).await;
        // Page 2 mounted first so first-match-wins handles it.
        Mock::given(method("GET"))
            .and(path("/api/github/team/assets/revisions"))
            .and(query_param("cursor", "two"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "revisions": [revision_json("three"), revision_json("four")],
                "nextCursor": null
            })))
            .mount(&server)
            .await;
        Mock::given(method("GET"))
            .and(path("/api/github/team/assets/revisions"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "revisions": [revision_json("one"), revision_json("two")],
                "nextCursor": "two"
            })))
            .mount(&server)
            .await;

        let client = build_client(&server).await;
        let revisions = client.list_revisions().await.unwrap();
        let names: Vec<&str> = revisions.iter().map(|r| r.name.as_str()).collect();
        assert_eq!(names, vec!["one", "two", "three", "four"]);
    }

    /// A single page with no cursor returns exactly the page contents.
    #[tokio::test]
    async fn list_revisions_single_page_without_cursor() {
        let server = MockServer::start().await;
        mock_read_token(&server).await;
        Mock::given(method("GET"))
            .and(path("/api/github/team/assets/revisions"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "revisions": [revision_json("main")],
                "nextCursor": null
            })))
            .mount(&server)
            .await;

        let client = build_client(&server).await;
        let revisions = client.list_revisions().await.unwrap();
        let names: Vec<&str> = revisions.iter().map(|r| r.name.as_str()).collect();
        assert_eq!(names, vec!["main"]);
    }
}