1use super::error::StateError;
6use super::row::Row;
7use super::store::Store;
8use crate::process::ProcessStamp;
9use crate::types::{Pid, ProcessStartTime};
10
11#[derive(Debug)]
12pub struct LockClaim<'a> {
13 pub instance: String,
14 pub operation: String,
15 token: String,
16 store: &'a Store,
17}
18
19impl Drop for LockClaim<'_> {
20 fn drop(&mut self) {
21 let _ = self.store.release_lock(self);
22 }
23}
24
25#[derive(Debug)]
26struct Holder {
27 operation: String,
28 pid: u32,
29 start: i64,
30 host: String,
31 acquired_at: i64,
32 token: String,
33}
34
35impl Store {
36 pub fn claim_lock(&self, instance: &str, operation: &str) -> Result<LockClaim<'_>, StateError> {
37 let me = ProcessStamp::current();
38 let host = Self::hostname();
39 let token = uuid::Uuid::new_v4().to_string();
40 for _ in 0..3 {
43 let claimed = self.execute(
44 "INSERT INTO op_locks
45 (instance, operation, holder_pid, holder_start_time, holder_host, acquired_at, claim_id)
46 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)
47 ON CONFLICT(instance) DO NOTHING",
48 &[
49 instance.into(), operation.into(), me.pid.into(), me.start_time.into(),
50 host.as_str().into(), Self::now().into(), token.as_str().into(),
51 ],
52 )?;
53 if claimed > 0 {
54 return Ok(LockClaim {
55 instance: instance.into(),
56 operation: operation.into(),
57 token,
58 store: self,
59 });
60 }
61 let Some(holder) = self.query_row(
62 "SELECT operation, holder_pid, holder_start_time, holder_host, acquired_at, claim_id
63 FROM op_locks WHERE instance = ?1",
64 &[instance.into()],
65 |row: &Row| Ok(Holder {
66 operation: row.get_string(0)?, pid: row.get_u32(1)?, start: row.get_i64(2)?,
67 host: row.get_string(3)?, acquired_at: row.get_i64(4)?, token: row.get_string(5)?,
68 }),
69 )? else { continue };
70 let stamp = ProcessStamp {
71 pid: Pid::from_os(holder.pid),
72 start_time: ProcessStartTime::from_os(holder.start as u64),
73 };
74 if holder.host != host || stamp.is_alive() {
75 return Err(StateError::LockHeld {
76 instance: instance.into(),
77 operation: holder.operation,
78 holder_pid: holder.pid,
79 acquired_at: holder.acquired_at,
80 });
81 }
82 let won = self.execute(
85 "UPDATE op_locks SET operation = ?2, holder_pid = ?3, holder_start_time = ?4,
86 holder_host = ?5, acquired_at = ?6, claim_id = ?7
87 WHERE instance = ?1 AND claim_id = ?8 AND holder_pid = ?9
88 AND holder_start_time = ?10 AND holder_host = ?11 AND acquired_at = ?12",
89 &[
90 instance.into(),
91 operation.into(),
92 me.pid.into(),
93 me.start_time.into(),
94 host.as_str().into(),
95 Self::now().into(),
96 token.as_str().into(),
97 holder.token.into(),
98 holder.pid.into(),
99 holder.start.into(),
100 holder.host.into(),
101 holder.acquired_at.into(),
102 ],
103 )?;
104 if won > 0 {
105 return Ok(LockClaim {
106 instance: instance.into(),
107 operation: operation.into(),
108 token,
109 store: self,
110 });
111 }
112 }
113 Err(StateError::LockHeld {
114 instance: instance.into(),
115 operation: operation.into(),
116 holder_pid: me.pid.get(),
117 acquired_at: Self::now(),
118 })
119 }
120
121 pub fn release_lock(&self, claim: &LockClaim<'_>) -> Result<(), StateError> {
122 self.execute(
123 "DELETE FROM op_locks WHERE instance = ?1 AND claim_id = ?2",
124 &[claim.instance.as_str().into(), claim.token.as_str().into()],
125 )?;
126 Ok(())
127 }
128
129 pub fn lock_holder_alive(&self, instance: &str) -> Result<bool, StateError> {
130 let host = Self::hostname();
131 let existing = self.query_row(
132 "SELECT holder_pid, holder_start_time, holder_host FROM op_locks WHERE instance = ?1",
133 &[instance.into()],
134 |row: &Row| Ok((row.get_u32(0)?, row.get_i64(1)?, row.get_string(2)?)),
135 )?;
136 Ok(existing.is_some_and(|(pid, start_time, holder_host)| {
137 holder_host != host
138 || ProcessStamp {
139 pid: Pid::from_os(pid),
140 start_time: ProcessStartTime::from_os(start_time as u64),
141 }
142 .is_alive()
143 }))
144 }
145}