df_consul/
locking.rs

1//! Contains structures to interact with the locks/sessions API
2//!
3//! See <https://developer.hashicorp.com/consul/api-docs/session>
4//! for the full definition of the API.
5
6use anyhow::Result;
7use bytes::Bytes;
8use log::*;
9use serde::{Deserialize, Serialize};
10
11use crate::Consul;
12
13/// Session creation request as specified in
14/// <https://developer.hashicorp.com/consul/api-docs/session#create-session>
15#[derive(Serialize, Deserialize, Debug)]
16#[serde(rename_all = "PascalCase")]
17pub struct SessionRequest {
18    pub name: String,
19    pub node: Option<String>,
20    pub lock_delay: Option<String>,
21    #[serde(rename = "TTL")]
22    pub ttl: Option<String>,
23    pub behavior: Option<String>,
24}
25
26/// (for internal use, mostly)
27#[derive(Serialize, Deserialize, Debug)]
28pub struct SessionResponse {
29    #[serde(rename = "ID")]
30    pub id: String,
31}
32
33impl Consul {
34    pub async fn create_session(&self, req: &SessionRequest) -> Result<String> {
35        debug!("create_session {:?}", req);
36
37        let url = format!("{}/v1/session/create", self.url);
38        let http = self.client.put(&url).json(req).send().await?;
39        let resp: SessionResponse = http.json().await?;
40        Ok(resp.id)
41    }
42
43    pub async fn acquire(&self, key: &str, bytes: Bytes, session: &str) -> Result<bool> {
44        debug!("acquire {}", key);
45
46        let url = format!(
47            "{}/v1/kv/{}{}?acquire={}",
48            self.url, self.kv_prefix, key, session
49        );
50        let http = self.client.put(&url).body(bytes).send().await?;
51        let resp: bool = http.json().await?;
52        Ok(resp)
53    }
54
55    pub async fn release(&self, key: &str, bytes: Bytes, session: &str) -> Result<()> {
56        debug!("release {}", key);
57
58        let url = format!(
59            "{}/v1/kv/{}{}?release={}",
60            self.url, self.kv_prefix, key, session
61        );
62        let http = self.client.put(&url).body(bytes).send().await?;
63        http.error_for_status()?;
64        Ok(())
65    }
66}