1use std::sync::Arc;
2
3use nopace_core::{
4 AdmissionRequest, Completion, CompletionResult, LeaseRenewal, LeaseRenewalResult, PartitionKey,
5 PolicyId, ResetReport, Retention, ScopeKey, ScopeState, Store, StoreDecision, StorePeek,
6 StoreSnapshot, collect_at, decide_at, finish_at, peek_at, renew_at, reset_policy, snapshot_at,
7};
8use thiserror::Error;
9use tokio::sync::Mutex;
10use tokio_postgres::{Client, NoTls};
11
12#[derive(Clone)]
13pub struct PostgresStore {
14 client: Arc<Mutex<Client>>,
15 retention: Retention,
16}
17
18impl PostgresStore {
19 pub async fn connect(connection_string: &str) -> Result<Self, PostgresError> {
20 let (client, connection) = tokio_postgres::connect(connection_string, NoTls).await?;
21 tokio::spawn(async move {
22 if let Err(error) = connection.await {
23 eprintln!("nopace postgres connection failed: {error}");
24 }
25 });
26 Self::from_client(client).await
27 }
28
29 pub async fn from_client(mut client: Client) -> Result<Self, PostgresError> {
30 let transaction = client.transaction().await?;
31 transaction
32 .batch_execute(
33 "SELECT pg_advisory_xact_lock(6934058159269381729); \
34 CREATE TABLE IF NOT EXISTS nopace_scope_state_v1 ( \
35 scope TEXT PRIMARY KEY, \
36 state BYTEA NOT NULL, \
37 updated_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp() \
38 )",
39 )
40 .await?;
41 transaction.commit().await?;
42 Ok(Self {
43 client: Arc::new(Mutex::new(client)),
44 retention: Retention::default(),
45 })
46 }
47
48 pub fn with_retention(mut self, retention: Retention) -> Self {
49 self.retention = retention;
50 self
51 }
52
53 pub async fn collect(&self) -> Result<u64, PostgresError> {
54 let mut client = self.client.lock().await;
55 let transaction = client.transaction().await?;
56 let rows = transaction.query(
57 "SELECT scope, state, floor(extract(epoch FROM clock_timestamp()) * 1000)::bigint AS now_ms FROM nopace_scope_state_v1 FOR UPDATE",
58 &[],
59 ).await?;
60 let mut changed = 0;
61 for row in rows {
62 let scope: String = row.get("scope");
63 let bytes: Vec<u8> = row.get("state");
64 let now: i64 = row.get("now_ms");
65 let mut state: ScopeState = bincode::deserialize(&bytes)?;
66 collect_at(&mut state, now.max(0) as u64, self.retention);
67 let bytes = bincode::serialize(&state)?;
68 transaction.execute(
69 "UPDATE nopace_scope_state_v1 SET state = $2, updated_at = clock_timestamp() WHERE scope = $1",
70 &[&scope, &bytes],
71 ).await?;
72 changed += 1;
73 }
74 transaction.commit().await?;
75 Ok(changed)
76 }
77
78 pub async fn snapshot(&self, scope: &ScopeKey) -> Result<Option<StoreSnapshot>, PostgresError> {
79 let client = self.client.lock().await;
80 let row = client
81 .query_opt(
82 "SELECT state FROM nopace_scope_state_v1 WHERE scope = $1",
83 &[&scope.as_str()],
84 )
85 .await?;
86 row.map(|row| {
87 bincode::deserialize::<ScopeState>(&row.get::<_, Vec<u8>>("state"))
88 .map(|state| snapshot_at(&state))
89 })
90 .transpose()
91 .map_err(PostgresError::from)
92 }
93
94 pub async fn reset_policy(
95 &self,
96 scope: &ScopeKey,
97 policy: &PolicyId,
98 partition: Option<&PartitionKey>,
99 ) -> Result<ResetReport, PostgresError> {
100 self.transaction(scope, |state, _| reset_policy(state, policy, partition))
101 .await
102 }
103
104 async fn transaction<T>(
105 &self,
106 scope: &ScopeKey,
107 operation: impl FnOnce(&mut ScopeState, u64) -> T,
108 ) -> Result<T, PostgresError> {
109 let mut client = self.client.lock().await;
110 let transaction = client.transaction().await?;
111 let empty = bincode::serialize(&ScopeState::default())?;
112 let row = transaction
113 .query_one(
114 r#"
115 INSERT INTO nopace_scope_state_v1(scope, state)
116 VALUES ($1, $2)
117 ON CONFLICT (scope) DO UPDATE SET scope = EXCLUDED.scope
118 RETURNING state, floor(extract(epoch FROM clock_timestamp()) * 1000)::bigint AS now_ms
119 "#,
120 &[&scope.as_str(), &empty],
121 )
122 .await?;
123 let bytes: Vec<u8> = row.get("state");
124 let now: i64 = row.get("now_ms");
125 let mut state: ScopeState = bincode::deserialize(&bytes)?;
126 let result = operation(&mut state, now.max(0) as u64);
127 let bytes = bincode::serialize(&state)?;
128 transaction.execute(
129 "UPDATE nopace_scope_state_v1 SET state = $2, updated_at = clock_timestamp() WHERE scope = $1",
130 &[&scope.as_str(), &bytes],
131 ).await?;
132 transaction.commit().await?;
133 Ok(result)
134 }
135}
136
137impl Store for PostgresStore {
138 type Error = PostgresError;
139
140 async fn decide(&self, request: AdmissionRequest) -> Result<StoreDecision, Self::Error> {
141 let scope = request.scope.clone();
142 self.transaction(&scope, |state, now| {
143 decide_at(state, &request, now, self.retention)
144 })
145 .await
146 }
147
148 async fn peek(&self, request: AdmissionRequest) -> Result<StorePeek, Self::Error> {
149 let client = self.client.lock().await;
150 let row = client
151 .query_opt(
152 "SELECT state, floor(extract(epoch FROM clock_timestamp()) * 1000)::bigint AS now_ms FROM nopace_scope_state_v1 WHERE scope = $1",
153 &[&request.scope.as_str()],
154 )
155 .await?;
156 let (state, now) = match row {
157 Some(row) => (
158 bincode::deserialize::<ScopeState>(&row.get::<_, Vec<u8>>("state"))?,
159 row.get::<_, i64>("now_ms").max(0) as u64,
160 ),
161 None => (ScopeState::default(), nopace_core::unix_millis()),
162 };
163 Ok(peek_at(&state, &request, now))
164 }
165
166 async fn renew(&self, renewal: LeaseRenewal) -> Result<LeaseRenewalResult, Self::Error> {
167 let scope = renewal.scope.clone();
168 self.transaction(&scope, |state, now| {
169 renew_at(state, &renewal, now, self.retention)
170 })
171 .await
172 }
173
174 async fn finish(&self, completion: Completion) -> Result<CompletionResult, Self::Error> {
175 let scope = completion.scope.clone();
176 self.transaction(&scope, |state, now| {
177 finish_at(state, &completion, now, self.retention)
178 })
179 .await
180 }
181}
182
183#[derive(Debug, Error)]
184pub enum PostgresError {
185 #[error("postgres operation failed: {0}")]
186 Postgres(#[from] tokio_postgres::Error),
187 #[error("stored nopace state is invalid: {0}")]
188 Serialization(#[from] bincode::Error),
189}