summaryrefslogtreecommitdiff
path: root/src/locking.rs
blob: 12e9ac09c043cf10aaf82bd044776fc56a125855 (plain) (blame)
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
use anyhow::Result;
use bytes::Bytes;
use log::*;
use serde::{Deserialize, Serialize};

use crate::Consul;

#[derive(Serialize, Deserialize, Debug)]
pub struct ConsulSessionRequest {
    #[serde(rename = "Name")]
    pub name: String,

    #[serde(rename = "Node")]
    pub node: Option<String>,

    #[serde(rename = "LockDelay")]
    pub lock_delay: Option<String>,

    #[serde(rename = "TTL")]
    pub ttl: Option<String>,

    #[serde(rename = "Behavior")]
    pub behavior: Option<String>,
}

#[derive(Serialize, Deserialize, Debug)]
pub struct ConsulSessionResponse {
    #[serde(rename = "ID")]
    pub id: String,
}

impl Consul {
    pub async fn create_session(&self, req: &ConsulSessionRequest) -> Result<String> {
        debug!("create_session {:?}", req);

        let url = format!("{}/v1/session/create", self.url);
        let http = self.client.put(&url).json(req).send().await?;
        let resp: ConsulSessionResponse = http.json().await?;
        Ok(resp.id)
    }

    pub async fn acquire(&self, key: &str, bytes: Bytes, session: &str) -> Result<bool> {
        debug!("acquire {}", key);

        let url = format!(
            "{}/v1/kv/{}{}?acquire={}",
            self.url, self.kv_prefix, key, session
        );
        let http = self.client.put(&url).body(bytes).send().await?;
        let resp: bool = http.json().await?;
        Ok(resp)
    }

    pub async fn release(&self, key: &str, bytes: Bytes, session: &str) -> Result<()> {
        debug!("release {}", key);

        let url = format!(
            "{}/v1/kv/{}{}?release={}",
            self.url, self.kv_prefix, key, session
        );
        let http = self.client.put(&url).body(bytes).send().await?;
        http.error_for_status()?;
        Ok(())
    }
}