Skip to main content

stackdeck_mcp_writes/
store.rs

1use std::collections::HashMap;
2use std::fmt::Write as _;
3use std::sync::Mutex;
4
5use crate::error::{ErrorCode, WriteSafetyError};
6use crate::json::{JsonValue, MAX_SAFE_INTEGER};
7
8pub const DEFAULT_SPENT_KEY_RETENTION_MS: i64 = 604_800_000;
9
10pub const SQLITE_SCHEMA_SQL: &str = "CREATE TABLE IF NOT EXISTS mcp_write_receipts (
11  scope TEXT NOT NULL,
12  operation TEXT NOT NULL,
13  idempotency_key TEXT NOT NULL,
14  status TEXT NOT NULL CHECK (status IN ('in_progress', 'succeeded')),
15  claim_token TEXT,
16  input_hash TEXT NOT NULL,
17  receipt_json TEXT,
18  created_at_ms INTEGER NOT NULL,
19  completed_at_ms INTEGER,
20  lease_expires_at_ms INTEGER,
21  expires_at_ms INTEGER,
22  retain_until_ms INTEGER,
23  PRIMARY KEY (scope, operation, idempotency_key)
24);
25CREATE INDEX IF NOT EXISTS mcp_write_receipts_expires_at_idx ON mcp_write_receipts(expires_at_ms);";
26
27pub const POSTGRES_SCHEMA_SQL: &str = "CREATE TABLE IF NOT EXISTS mcp_write_receipts (
28  scope TEXT NOT NULL,
29  operation TEXT NOT NULL,
30  idempotency_key TEXT NOT NULL,
31  status TEXT NOT NULL CHECK (status IN ('in_progress', 'succeeded')),
32  claim_token TEXT,
33  input_hash TEXT NOT NULL,
34  receipt_json JSONB,
35  created_at_ms BIGINT NOT NULL,
36  completed_at_ms BIGINT,
37  lease_expires_at_ms BIGINT,
38  expires_at_ms BIGINT,
39  retain_until_ms BIGINT,
40  PRIMARY KEY (scope, operation, idempotency_key)
41);
42CREATE INDEX IF NOT EXISTS expiry_mcp_write_receipts ON mcp_write_receipts(expires_at_ms);";
43
44pub const REDIS_CLAIM_LUA: &str = concat!("local action = 'claim'\n", include_str!("redis.lua"));
45pub const REDIS_COMPLETE_LUA: &str = concat!("local action = 'complete'\n", include_str!("redis.lua"));
46pub const REDIS_RELEASE_LUA: &str = concat!("local action = 'release'\n", include_str!("redis.lua"));
47pub const REDIS_EXTEND_LEASE_LUA: &str = concat!("local action = 'extend'\n", include_str!("redis.lua"));
48
49pub fn build_redis_store_key(prefix: &str, scope: &str, operation: &str, idempotency_key: &str) -> String {
50    let mut output = prefix.to_owned();
51    for (index, value) in [scope, operation, idempotency_key].iter().enumerate() {
52        if index > 0 {
53            output.push(':');
54        }
55        for byte in value.bytes() {
56            if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~') {
57                output.push(char::from(byte));
58            } else {
59                write!(output, "%{byte:02X}").expect("write to String");
60            }
61        }
62    }
63    output
64}
65
66pub(crate) fn timestamp(value: i64) -> Result<i64, WriteSafetyError> {
67    if !(0..=MAX_SAFE_INTEGER).contains(&value) {
68        return Err(WriteSafetyError::new(ErrorCode::Validation, "Timestamp must be a non-negative safe integer."));
69    }
70    Ok(value)
71}
72
73pub(crate) fn duration(value: i64) -> Result<i64, WriteSafetyError> {
74    if !(1..=MAX_SAFE_INTEGER).contains(&value) {
75        return Err(WriteSafetyError::new(ErrorCode::Validation, "Duration must be a positive safe integer."));
76    }
77    Ok(value)
78}
79
80pub(crate) fn deadline(now: i64, value: i64) -> Result<i64, WriteSafetyError> {
81    timestamp(timestamp(now)? + duration(value)?)
82}
83
84pub(crate) fn retention(ttl: i64, retain: i64) -> Result<i64, WriteSafetyError> {
85    if duration(retain)? < duration(ttl)? {
86        return Err(WriteSafetyError::new(ErrorCode::Validation, "spent_key_retention_ms must be greater than or equal to ttl_ms."));
87    }
88    Ok(retain)
89}
90
91#[derive(Debug, Clone, PartialEq)]
92pub struct InProgressRecord {
93    pub claim_token: String,
94    pub input_hash: String,
95    pub created_at_ms: i64,
96    pub lease_expires_at_ms: i64,
97}
98
99#[derive(Debug, Clone, PartialEq)]
100pub struct SucceededRecord {
101    pub input_hash: String,
102    pub receipt: JsonValue,
103    pub created_at_ms: i64,
104    pub completed_at_ms: i64,
105    pub expires_at_ms: i64,
106    pub retain_until_ms: i64,
107    pub replay_unavailable: bool,
108}
109
110#[derive(Debug, Clone, PartialEq)]
111pub enum ClaimResult {
112    Claimed { took_over_expired_lease: bool },
113    InProgress { record: InProgressRecord, store_now_ms: i64 },
114    Existing { record: SucceededRecord, store_now_ms: i64 },
115}
116
117#[derive(Clone, Copy)]
118pub struct ClaimRequest<'a> {
119    pub scope: &'a str,
120    pub operation: &'a str,
121    pub idempotency_key: &'a str,
122    pub input_hash: &'a str,
123    pub claim_token: &'a str,
124    pub now_ms: i64,
125    pub lease_ms: i64,
126}
127
128#[derive(Clone)]
129pub struct CompleteRequest<'a> {
130    pub scope: &'a str,
131    pub operation: &'a str,
132    pub idempotency_key: &'a str,
133    pub claim_token: &'a str,
134    pub receipt: JsonValue,
135    pub now_ms: i64,
136    pub ttl_ms: i64,
137    pub spent_key_retention_ms: i64,
138    pub replay_unavailable: bool,
139}
140
141#[derive(Clone, Copy)]
142pub struct ReleaseRequest<'a> {
143    pub scope: &'a str,
144    pub operation: &'a str,
145    pub idempotency_key: &'a str,
146    pub claim_token: &'a str,
147}
148
149pub struct ExtendLeaseRequest<'a> {
150    pub owner: ReleaseRequest<'a>,
151    pub now_ms: i64,
152    pub lease_ms: i64,
153}
154
155pub trait WriteStore: Send + Sync {
156    fn claim(&self, req: ClaimRequest<'_>) -> Result<ClaimResult, WriteSafetyError>;
157    fn complete(&self, req: CompleteRequest<'_>) -> Result<bool, WriteSafetyError>;
158    fn release(&self, req: ReleaseRequest<'_>) -> Result<bool, WriteSafetyError>;
159    fn extend_lease(&self, req: ExtendLeaseRequest<'_>) -> Result<bool, WriteSafetyError>;
160}
161
162#[derive(Debug)]
163enum StoredEntry {
164    InProgress(InProgressRecord),
165    Succeeded { claim_token: String, record: SucceededRecord },
166}
167
168type Key = (String, String, String);
169type Records = HashMap<Key, StoredEntry>;
170
171fn key(scope: &str, operation: &str, id: &str) -> Key {
172    (scope.to_owned(), operation.to_owned(), id.to_owned())
173}
174
175#[derive(Default)]
176pub struct MemoryStore {
177    records: Mutex<Records>,
178}
179
180impl MemoryStore {
181    pub fn new() -> Self {
182        Self::default()
183    }
184
185    fn lock(&self) -> Result<std::sync::MutexGuard<'_, Records>, WriteSafetyError> {
186        self.records.lock().map_err(|_| WriteSafetyError::new(ErrorCode::StoreError, "Store lock poisoned."))
187    }
188
189    pub fn purge_expired(&self, before_ms: i64) -> Result<usize, WriteSafetyError> {
190        timestamp(before_ms)?;
191        let mut records = self.lock()?;
192        let before = records.len();
193        records.retain(|_, entry| !matches!(entry, StoredEntry::Succeeded { record, .. }
194            if !record.replay_unavailable && record.retain_until_ms <= before_ms));
195        Ok(before - records.len())
196    }
197}
198
199impl WriteStore for MemoryStore {
200    fn claim(&self, req: ClaimRequest<'_>) -> Result<ClaimResult, WriteSafetyError> {
201        let lease_expires_at_ms = deadline(req.now_ms, req.lease_ms)?;
202        let mut records = self.lock()?;
203        let key = key(req.scope, req.operation, req.idempotency_key);
204        match records.get(&key) {
205            Some(StoredEntry::Succeeded { record, .. }) if record.replay_unavailable || req.now_ms < record.retain_until_ms => {
206                return Ok(ClaimResult::Existing { record: record.clone(), store_now_ms: req.now_ms });
207            }
208            Some(StoredEntry::InProgress(record)) => {
209                return Ok(ClaimResult::InProgress { record: record.clone(), store_now_ms: req.now_ms });
210            }
211            _ => {}
212        }
213        records.insert(key, StoredEntry::InProgress(InProgressRecord {
214            claim_token: req.claim_token.to_owned(),
215            input_hash: req.input_hash.to_owned(),
216            created_at_ms: req.now_ms,
217            lease_expires_at_ms,
218        }));
219        Ok(ClaimResult::Claimed { took_over_expired_lease: false })
220    }
221
222    fn complete(&self, req: CompleteRequest<'_>) -> Result<bool, WriteSafetyError> {
223        let expires_at_ms = deadline(req.now_ms, req.ttl_ms)?;
224        let retain_until_ms = deadline(req.now_ms, retention(req.ttl_ms, req.spent_key_retention_ms)?)?;
225        let mut records = self.lock()?;
226        let key = key(req.scope, req.operation, req.idempotency_key);
227        match records.get(&key) {
228            Some(StoredEntry::Succeeded { claim_token, .. }) => Ok(claim_token == req.claim_token),
229            Some(StoredEntry::InProgress(existing)) if existing.claim_token == req.claim_token => {
230                let record = SucceededRecord {
231                    input_hash: existing.input_hash.clone(),
232                    receipt: if req.replay_unavailable { JsonValue::Null } else { req.receipt },
233                    created_at_ms: existing.created_at_ms,
234                    completed_at_ms: req.now_ms,
235                    expires_at_ms,
236                    retain_until_ms,
237                    replay_unavailable: req.replay_unavailable,
238                };
239                records.insert(key, StoredEntry::Succeeded { claim_token: req.claim_token.to_owned(), record });
240                Ok(true)
241            }
242            _ => Ok(false),
243        }
244    }
245
246    fn release(&self, req: ReleaseRequest<'_>) -> Result<bool, WriteSafetyError> {
247        let mut records = self.lock()?;
248        let key = key(req.scope, req.operation, req.idempotency_key);
249        if matches!(records.get(&key), Some(StoredEntry::InProgress(record)) if record.claim_token == req.claim_token) {
250            records.remove(&key);
251            Ok(true)
252        } else {
253            Ok(false)
254        }
255    }
256
257    fn extend_lease(&self, req: ExtendLeaseRequest<'_>) -> Result<bool, WriteSafetyError> {
258        let expires = deadline(req.now_ms, req.lease_ms)?;
259        let mut records = self.lock()?;
260        let owner = req.owner;
261        let Some(StoredEntry::InProgress(record)) = records.get_mut(&key(owner.scope, owner.operation, owner.idempotency_key)) else {
262            return Ok(false);
263        };
264        if record.claim_token != owner.claim_token || record.lease_expires_at_ms <= req.now_ms {
265            return Ok(false);
266        }
267        record.lease_expires_at_ms = record.lease_expires_at_ms.max(expires);
268        Ok(true)
269    }
270}