Skip to main content

git_lfs_api/
locks.rs

1//! Locking API: create, list, verify, and delete file locks.
2//!
3//! See `docs/api/locking.md` for the wire-protocol contract.
4
5use serde::{Deserialize, Serialize};
6
7use crate::client::{Client, decode};
8use crate::error::ApiError;
9use crate::models::{Lock, Ref};
10
11// ---- create ---------------------------------------------------------------
12
13/// POST `/locks` body.
14#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
15pub struct CreateLockRequest {
16    pub path: String,
17    #[serde(default, skip_serializing_if = "Option::is_none")]
18    pub r#ref: Option<Ref>,
19}
20
21impl CreateLockRequest {
22    pub fn new(path: impl Into<String>) -> Self {
23        Self {
24            path: path.into(),
25            r#ref: None,
26        }
27    }
28
29    pub fn with_ref(mut self, r: Ref) -> Self {
30        self.r#ref = Some(r);
31        self
32    }
33}
34
35#[derive(Debug, Deserialize)]
36struct LockEnvelope {
37    lock: Lock,
38}
39
40/// Flexible POST `/locks` response decoder. The reference test server
41/// returns `{"message": "lock already created"}` at HTTP 200 for the
42/// "path is already locked" case (no `lock` field, no 409 status), so a
43/// strict envelope deserialize would blow up with a missing-field
44/// error. We accept `lock` and `message` independently and let
45/// [`Client::create_lock`] interpret which arrived.
46#[derive(Debug, Deserialize)]
47struct CreateLockResponse {
48    #[serde(default)]
49    lock: Option<Lock>,
50    #[serde(default)]
51    message: Option<String>,
52}
53
54/// Errors specific to [`Client::create_lock`].
55///
56/// Wraps [`ApiError`] but adds a typed `Conflict` for the in-band
57/// "already locked" case. `existing` is `Some` for servers that return
58/// HTTP 409 with the conflicting lock attached; `None` for servers that
59/// only ship a message.
60#[derive(Debug, thiserror::Error)]
61pub enum CreateLockError {
62    #[error("lock conflict: {message}")]
63    Conflict {
64        existing: Option<Lock>,
65        message: String,
66    },
67
68    #[error(transparent)]
69    Api(#[from] ApiError),
70}
71
72// ---- list -----------------------------------------------------------------
73
74/// Filter for `GET /locks`. All fields are optional; absent ones are not
75/// sent on the wire.
76#[derive(Debug, Default, Clone, Serialize)]
77pub struct ListLocksFilter {
78    #[serde(skip_serializing_if = "Option::is_none")]
79    pub path: Option<String>,
80    #[serde(skip_serializing_if = "Option::is_none")]
81    pub id: Option<String>,
82    #[serde(skip_serializing_if = "Option::is_none")]
83    pub cursor: Option<String>,
84    #[serde(skip_serializing_if = "Option::is_none")]
85    pub limit: Option<u32>,
86    #[serde(skip_serializing_if = "Option::is_none")]
87    pub refspec: Option<String>,
88}
89
90#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
91pub struct LockList {
92    /// Go LFS servers serialize an empty result as `"locks": null`
93    /// rather than `"locks": []`; treat null as the empty list.
94    #[serde(default, deserialize_with = "deserialize_null_as_default")]
95    pub locks: Vec<Lock>,
96    /// Opaque cursor; pass back as `cursor` in the next request to continue.
97    #[serde(default, skip_serializing_if = "Option::is_none")]
98    pub next_cursor: Option<String>,
99}
100
101// ---- verify ---------------------------------------------------------------
102
103#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq, Eq)]
104pub struct VerifyLocksRequest {
105    #[serde(default, skip_serializing_if = "Option::is_none")]
106    pub r#ref: Option<Ref>,
107    #[serde(default, skip_serializing_if = "Option::is_none")]
108    pub cursor: Option<String>,
109    #[serde(default, skip_serializing_if = "Option::is_none")]
110    pub limit: Option<u32>,
111}
112
113#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
114pub struct VerifyLocksResponse {
115    /// Locks owned by the authenticated user. Servers may serialize an
116    /// empty list as `null`; `deserialize_null_as_default` normalizes
117    /// that to `Vec::new()`.
118    #[serde(default, deserialize_with = "deserialize_null_as_default")]
119    pub ours: Vec<Lock>,
120    /// Locks owned by other users. Same null-handling as `ours`.
121    #[serde(default, deserialize_with = "deserialize_null_as_default")]
122    pub theirs: Vec<Lock>,
123    #[serde(default, skip_serializing_if = "Option::is_none")]
124    pub next_cursor: Option<String>,
125}
126
127// ---- delete ---------------------------------------------------------------
128
129#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq, Eq)]
130pub struct DeleteLockRequest {
131    /// True to delete a lock owned by another user. Server enforces auth.
132    #[serde(default, skip_serializing_if = "is_false")]
133    pub force: bool,
134    #[serde(default, skip_serializing_if = "Option::is_none")]
135    pub r#ref: Option<Ref>,
136}
137
138fn is_false(b: &bool) -> bool {
139    !*b
140}
141
142/// Treat a JSON `null` as `T::default()`. Go's `encoding/json` serializes
143/// a `nil` slice as `null` rather than `[]`, and the LFS reference server
144/// (and lfstest-gitserver) inherits that — so a request that legitimately
145/// returns "no locks" looks like `{"ours": null}`. Without this, our
146/// `Vec<Lock>` deserialize bombs on the null.
147fn deserialize_null_as_default<'de, D, T>(d: D) -> Result<T, D::Error>
148where
149    D: serde::Deserializer<'de>,
150    T: Default + serde::Deserialize<'de>,
151{
152    let opt = Option::<T>::deserialize(d)?;
153    Ok(opt.unwrap_or_default())
154}
155
156// ---- client ---------------------------------------------------------------
157
158impl Client {
159    /// POST `/locks` to create a new lock.
160    ///
161    /// Body decoding is flexible to accommodate both spec'd 409 → existing
162    /// lock responses and the reference test server's "200 with `message`
163    /// but no `lock`" in-band-conflict pattern.
164    pub async fn create_lock(&self, req: &CreateLockRequest) -> Result<Lock, CreateLockError> {
165        let url = self.url("locks").map_err(CreateLockError::Api)?;
166        // Serialize once so the closure (which may run twice — once
167        // with current auth, once after a 401 → fill) doesn't re-encode
168        // the body each time.
169        let body_bytes = serde_json::to_vec(req)
170            .map_err(|e| CreateLockError::Api(ApiError::Decode(e.to_string())))?;
171        let resp = self
172            .send_with_auth_retry_response(|| {
173                self.request(reqwest::Method::POST, url.clone())
174                    .header(reqwest::header::CONTENT_TYPE, crate::client::LFS_MEDIA_TYPE)
175                    .body(body_bytes.clone())
176            })
177            .await
178            .map_err(CreateLockError::Api)?;
179
180        let status = resp.status();
181        let bytes = resp
182            .bytes()
183            .await
184            .map_err(|e| CreateLockError::Api(ApiError::Transport(e)))?;
185
186        // 409 = standard conflict, with the existing lock spelled out in
187        // the body. Decode flexibly: server may or may not include a
188        // `message` alongside the lock.
189        if status.as_u16() == 409 {
190            let parsed: CreateLockResponse = serde_json::from_slice(&bytes)
191                .map_err(|e| CreateLockError::Api(ApiError::Decode(e.to_string())))?;
192            return Err(CreateLockError::Conflict {
193                existing: parsed.lock,
194                message: parsed.message.unwrap_or_else(|| "lock conflict".into()),
195            });
196        }
197
198        // Other non-success statuses fall through as plain ApiError::Status.
199        if !status.is_success() {
200            let body: Option<crate::error::ServerError> = serde_json::from_slice(&bytes).ok();
201            return Err(CreateLockError::Api(ApiError::Status {
202                status: status.as_u16(),
203                lfs_authenticate: None,
204                body,
205            }));
206        }
207
208        // 2xx — could be {lock: ...} success or {message: ...}
209        // in-band conflict.
210        let parsed: CreateLockResponse = serde_json::from_slice(&bytes)
211            .map_err(|e| CreateLockError::Api(ApiError::Decode(e.to_string())))?;
212        if let Some(lock) = parsed.lock {
213            return Ok(lock);
214        }
215        if let Some(message) = parsed.message {
216            return Err(CreateLockError::Conflict {
217                existing: None,
218                message,
219            });
220        }
221        Err(CreateLockError::Api(ApiError::Decode(
222            "create-lock response had neither lock nor message".into(),
223        )))
224    }
225
226    /// GET `/locks` with optional filters.
227    pub async fn list_locks(&self, filter: &ListLocksFilter) -> Result<LockList, ApiError> {
228        self.get_json("locks", filter).await
229    }
230
231    /// POST `/locks/verify` to list locks partitioned into ours/theirs.
232    ///
233    /// Per the spec, servers that don't implement locking can return 404
234    /// here; that surfaces as `ApiError::Status { status: 404, .. }`. The
235    /// caller (typically push) should treat that as "no locks to verify"
236    /// rather than a hard failure — see `is_not_found()`.
237    pub async fn verify_locks(
238        &self,
239        req: &VerifyLocksRequest,
240    ) -> Result<VerifyLocksResponse, ApiError> {
241        self.post_json("locks/verify", req).await
242    }
243
244    /// POST `/locks/{id}/unlock` to delete a lock.
245    pub async fn delete_lock(&self, id: &str, req: &DeleteLockRequest) -> Result<Lock, ApiError> {
246        // Percent-encode the id to keep nested path segments safe.
247        let encoded = url_path_segment(id);
248        let path = format!("locks/{encoded}/unlock");
249        let url = self.url(&path)?;
250        let body_bytes = serde_json::to_vec(req).map_err(|e| ApiError::Decode(e.to_string()))?;
251        let resp = self
252            .send_with_auth_retry_response(|| {
253                self.request(reqwest::Method::POST, url.clone())
254                    .header(reqwest::header::CONTENT_TYPE, crate::client::LFS_MEDIA_TYPE)
255                    .body(body_bytes.clone())
256            })
257            .await?;
258        let env: LockEnvelope = decode(resp).await?;
259        Ok(env.lock)
260    }
261}
262
263/// Minimal percent-encoder for one URL path segment. Encodes anything that
264/// isn't an unreserved character per RFC 3986.
265fn url_path_segment(s: &str) -> String {
266    let mut out = String::with_capacity(s.len());
267    for b in s.bytes() {
268        let unreserved = b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~');
269        if unreserved {
270            out.push(b as char);
271        } else {
272            out.push_str(&format!("%{b:02X}"));
273        }
274    }
275    out
276}
277
278#[cfg(test)]
279mod tests {
280    use super::*;
281
282    #[test]
283    fn list_filter_omits_none_fields() {
284        // serde_json round-trip keeps only the fields we actually want on
285        // the wire — same omission rule reqwest applies when building the
286        // query string.
287        let f = ListLocksFilter {
288            path: Some("a.bin".into()),
289            ..Default::default()
290        };
291        let v = serde_json::to_value(&f).unwrap();
292        assert_eq!(v["path"], "a.bin");
293        assert!(v.get("id").is_none());
294        assert!(v.get("cursor").is_none());
295        assert!(v.get("limit").is_none());
296        assert!(v.get("refspec").is_none());
297    }
298
299    #[test]
300    fn delete_request_omits_force_when_false() {
301        let r = DeleteLockRequest::default();
302        let v = serde_json::to_value(&r).unwrap();
303        assert!(v.get("force").is_none());
304    }
305
306    #[test]
307    fn delete_request_includes_force_when_true() {
308        let r = DeleteLockRequest {
309            force: true,
310            ..Default::default()
311        };
312        assert_eq!(serde_json::to_value(&r).unwrap()["force"], true);
313    }
314
315    #[test]
316    fn parses_create_lock_envelope() {
317        let body = r#"{
318            "lock": {
319                "id": "some-uuid", "path": "foo/bar.zip",
320                "locked_at": "2016-05-17T15:49:06+00:00",
321                "owner": { "name": "Jane Doe" }
322            }
323        }"#;
324        let env: LockEnvelope = serde_json::from_str(body).unwrap();
325        assert_eq!(env.lock.path, "foo/bar.zip");
326        assert_eq!(env.lock.owner.unwrap().name, "Jane Doe");
327    }
328
329    #[test]
330    fn parses_create_lock_response_with_lock() {
331        let body = r#"{
332            "lock": { "id": "x", "path": "foo", "locked_at": "2016-01-01T00:00:00Z" }
333        }"#;
334        let parsed: CreateLockResponse = serde_json::from_str(body).unwrap();
335        assert!(parsed.lock.is_some());
336        assert_eq!(parsed.lock.unwrap().id, "x");
337        assert!(parsed.message.is_none());
338    }
339
340    #[test]
341    fn parses_create_lock_response_message_only() {
342        // Reference test server's "already locked" response shape.
343        let body = r#"{"message":"lock already created"}"#;
344        let parsed: CreateLockResponse = serde_json::from_str(body).unwrap();
345        assert!(parsed.lock.is_none());
346        assert_eq!(parsed.message.as_deref(), Some("lock already created"));
347    }
348
349    #[test]
350    fn url_path_segment_encodes_special() {
351        assert_eq!(url_path_segment("abc-123_xyz.~"), "abc-123_xyz.~");
352        assert_eq!(url_path_segment("a/b"), "a%2Fb");
353        assert_eq!(url_path_segment("hello world"), "hello%20world");
354    }
355}