haste_document_storage/providers/
postgres.rs1use std::{
19 collections::BTreeMap,
20 fmt::{self, Debug},
21};
22
23use serde::{Deserialize, Serialize};
24use sqlx::{PgPool, postgres::PgPoolOptions, types::Json};
25use time::OffsetDateTime;
26
27use crate::{
28 error::StorageError,
29 traits::{DocumentStorage, StorageFuture},
30 types::{
31 Document, DocumentBody, DocumentMetadata, DocumentName, DocumentScope, ListPage,
32 ListRequest, StoredDocument,
33 },
34};
35
36const MAX_BODY_BYTES: u64 = 1 << 30;
38const MAX_PAGE_SIZE: i64 = 1000;
41const UNDEFINED_TABLE: &str = "42P01";
43
44#[derive(Clone, Deserialize, Serialize)]
46pub struct PostgresConfig {
47 #[serde(default)]
51 pub database_url: Option<String>,
52 #[serde(default = "default_max_connections")]
54 pub max_connections: u32,
55}
56
57fn default_max_connections() -> u32 {
58 10
59}
60
61impl Default for PostgresConfig {
62 fn default() -> Self {
63 Self {
64 database_url: None,
65 max_connections: default_max_connections(),
66 }
67 }
68}
69
70impl Debug for PostgresConfig {
72 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
73 f.debug_struct("PostgresConfig")
74 .field(
75 "database_url",
76 &self.database_url.as_ref().map(|_| "REDACTED"),
77 )
78 .field("max_connections", &self.max_connections)
79 .finish()
80 }
81}
82
83pub struct PostgresDocumentStorage {
85 pool: PgPool,
86}
87
88type MetadataRow = (
92 String,
93 i32,
94 Option<String>,
95 Json<BTreeMap<String, String>>,
96 OffsetDateTime,
97);
98
99type ReadRow = (
102 Option<String>,
103 Json<BTreeMap<String, String>>,
104 OffsetDateTime,
105 Vec<u8>,
106);
107
108impl PostgresDocumentStorage {
109 pub async fn connect(config: PostgresConfig) -> Result<Self, StorageError> {
117 let Some(database_url) = config.database_url.as_deref() else {
118 return Err(StorageError::Configuration(
119 "database_url is not set".to_string(),
120 ));
121 };
122 let pool = PgPoolOptions::new()
123 .max_connections(config.max_connections)
124 .connect(database_url)
125 .await
126 .map_err(|error| {
127 StorageError::Configuration(format!(
128 "cannot connect to the document database: {error}"
129 ))
130 })?;
131 Ok(Self { pool })
132 }
133
134 #[must_use]
137 pub const fn pool(&self) -> &PgPool {
138 &self.pool
139 }
140}
141
142impl DocumentStorage for PostgresDocumentStorage {
143 fn put<'a>(
144 &'a self,
145 scope: &'a DocumentScope,
146 name: &'a DocumentName,
147 document: Document,
148 ) -> StorageFuture<'a, DocumentMetadata> {
149 Box::pin(async move {
150 let size = u64::try_from(document.body.len()).unwrap_or(u64::MAX);
151 if size >= MAX_BODY_BYTES {
152 return Err(StorageError::InvalidDocument(format!(
153 "body of {size} bytes is too large; one Postgres value holds less than \
154 {MAX_BODY_BYTES} bytes"
155 )));
156 }
157
158 let updated_at: OffsetDateTime = sqlx::query_scalar(
159 r"
160 INSERT INTO document_storage
161 (tenant, project, name, content_type, metadata, updated_at, body)
162 VALUES ($1, $2, $3, $4, $5, now(), $6)
163 ON CONFLICT (tenant, project, name) DO UPDATE SET
164 content_type = EXCLUDED.content_type,
165 metadata = EXCLUDED.metadata,
166 updated_at = EXCLUDED.updated_at,
167 body = EXCLUDED.body
168 RETURNING updated_at
169 ",
170 )
171 .bind(scope.tenant().as_ref())
172 .bind(scope.project().as_ref())
173 .bind(name.as_str())
174 .bind(document.content_type.as_deref())
175 .bind(Json(&document.metadata))
176 .bind(document.body.as_ref())
177 .fetch_one(&self.pool)
178 .await
179 .map_err(database_error)?;
180
181 Ok(DocumentMetadata {
182 scope: scope.clone(),
183 name: name.clone(),
184 size,
185 content_type: document.content_type,
186 etag: Some(etag(size, updated_at)),
187 last_modified: Some(updated_at),
188 metadata: document.metadata,
189 })
190 })
191 }
192
193 fn head<'a>(
194 &'a self,
195 scope: &'a DocumentScope,
196 name: &'a DocumentName,
197 ) -> StorageFuture<'a, DocumentMetadata> {
198 Box::pin(async move {
199 let row: Option<MetadataRow> = sqlx::query_as(
200 r"
201 SELECT name, octet_length(body), content_type, metadata, updated_at
202 FROM document_storage
203 WHERE tenant = $1 AND project = $2 AND name = $3
204 ",
205 )
206 .bind(scope.tenant().as_ref())
207 .bind(scope.project().as_ref())
208 .bind(name.as_str())
209 .fetch_optional(&self.pool)
210 .await
211 .map_err(database_error)?;
212 row.map(|row| metadata_of(scope, row))
213 .ok_or_else(|| StorageError::NotFound(format!("{scope}/{name}")))
214 })
215 }
216
217 fn get<'a>(
218 &'a self,
219 scope: &'a DocumentScope,
220 name: &'a DocumentName,
221 ) -> StorageFuture<'a, StoredDocument> {
222 Box::pin(async move {
223 let row: Option<ReadRow> = sqlx::query_as(
224 r"
225 SELECT content_type, metadata, updated_at, body
226 FROM document_storage
227 WHERE tenant = $1 AND project = $2 AND name = $3
228 ",
229 )
230 .bind(scope.tenant().as_ref())
231 .bind(scope.project().as_ref())
232 .bind(name.as_str())
233 .fetch_optional(&self.pool)
234 .await
235 .map_err(database_error)?;
236 let (content_type, metadata, updated_at, body) =
237 row.ok_or_else(|| StorageError::NotFound(format!("{scope}/{name}")))?;
238
239 let size = u64::try_from(body.len()).unwrap_or(u64::MAX);
240 Ok(StoredDocument {
241 metadata: DocumentMetadata {
242 scope: scope.clone(),
243 name: name.clone(),
244 size,
245 content_type,
246 etag: Some(etag(size, updated_at)),
247 last_modified: Some(updated_at),
248 metadata: metadata.0,
249 },
250 body: DocumentBody::from_bytes(body),
251 })
252 })
253 }
254
255 fn delete<'a>(
256 &'a self,
257 scope: &'a DocumentScope,
258 name: &'a DocumentName,
259 ) -> StorageFuture<'a, ()> {
260 Box::pin(async move {
261 sqlx::query(
262 "DELETE FROM document_storage WHERE tenant = $1 AND project = $2 AND name = $3",
263 )
264 .bind(scope.tenant().as_ref())
265 .bind(scope.project().as_ref())
266 .bind(name.as_str())
267 .execute(&self.pool)
268 .await
269 .map_err(database_error)?;
270 Ok(())
271 })
272 }
273
274 fn list<'a>(
275 &'a self,
276 scope: &'a DocumentScope,
277 request: ListRequest,
278 ) -> StorageFuture<'a, ListPage> {
279 Box::pin(async move {
280 let page_size = request.page_size.map_or(MAX_PAGE_SIZE, |size| {
281 i64::from(size).clamp(1, MAX_PAGE_SIZE)
282 });
283
284 let mut rows: Vec<MetadataRow> = sqlx::query_as(
286 r"
287 SELECT name, octet_length(body), content_type, metadata, updated_at
288 FROM document_storage
289 WHERE tenant = $1 AND project = $2
290 AND ($3::text IS NULL OR name > $3)
291 ORDER BY name
292 LIMIT $4
293 ",
294 )
295 .bind(scope.tenant().as_ref())
296 .bind(scope.project().as_ref())
297 .bind(request.page_token)
298 .bind(page_size + 1)
299 .fetch_all(&self.pool)
300 .await
301 .map_err(database_error)?;
302
303 let page_size = usize::try_from(page_size).unwrap_or_default();
304 let more = rows.len() > page_size;
305 rows.truncate(page_size);
306 let documents = rows
307 .into_iter()
308 .map(|row| metadata_of(scope, row))
309 .collect::<Vec<_>>();
310 Ok(ListPage {
311 next_page_token: if more {
312 documents
313 .last()
314 .map(|document| document.name.as_str().to_string())
315 } else {
316 None
317 },
318 documents,
319 })
320 })
321 }
322
323 fn scopes(&self) -> StorageFuture<'_, Vec<DocumentScope>> {
324 Box::pin(async move {
325 let rows: Vec<(String, String)> = sqlx::query_as(
326 r"
327 SELECT DISTINCT tenant, project
328 FROM document_storage
329 ORDER BY tenant, project
330 ",
331 )
332 .fetch_all(&self.pool)
333 .await
334 .map_err(database_error)?;
335 rows.into_iter()
336 .map(|(tenant, project)| DocumentScope::from_backend(tenant, project))
337 .collect()
338 })
339 }
340}
341
342fn metadata_of(
343 scope: &DocumentScope,
344 (name, size, content_type, metadata, updated_at): MetadataRow,
345) -> DocumentMetadata {
346 let size = u64::try_from(size).unwrap_or_default();
347 DocumentMetadata {
348 scope: scope.clone(),
349 name: DocumentName::from_backend(name),
350 size,
351 content_type,
352 etag: Some(etag(size, updated_at)),
353 last_modified: Some(updated_at),
354 metadata: metadata.0,
355 }
356}
357
358fn etag(size: u64, updated_at: OffsetDateTime) -> String {
360 format!("{size:x}-{:x}", updated_at.unix_timestamp_nanos())
361}
362
363fn database_error(error: sqlx::Error) -> StorageError {
364 match error {
365 sqlx::Error::Database(database) if database.code().as_deref() == Some(UNDEFINED_TABLE) => {
366 StorageError::Configuration(
367 "the document storage table is missing; run the migrations \
368 (`haste-health admin migrate repo`)"
369 .to_string(),
370 )
371 }
372 error @ (sqlx::Error::Io(_)
373 | sqlx::Error::Tls(_)
374 | sqlx::Error::Protocol(_)
375 | sqlx::Error::PoolTimedOut
376 | sqlx::Error::PoolClosed
377 | sqlx::Error::WorkerCrashed) => StorageError::Transport(error.to_string()),
378 error => StorageError::Database(error.to_string()),
379 }
380}