Skip to main content

adk_harness/website/
drafts.rs

1//! The back office's drafts, kept durable (spec 3.5 §7.8.2 step 1, §7.6, §7.11): the store is
2//! the source of truth for what a [`SiteRuntime`](super::SiteRuntime) holds between tool
3//! calls, so it survives a restart and every replica over one store sees the same drafts.
4//!
5//! | Kind | What is kept |
6//! |---|---|
7//! | [`DraftKind::Content`] | A content draft: its items, its media, where it came from, its proposer, job and action class |
8//! | [`DraftKind::Charter`] | A charter draft |
9//! | [`DraftKind::CharterSign`] | A charter signing request and the signatures it has |
10//! | [`DraftKind::Promotion`] | A request that the owner promote a job |
11//!
12//! A [`SiteDraftStore`] keeps each record as JSON by site, kind and id, with a version:
13//!
14//! | Operation | Contract |
15//! |---|---|
16//! | [`create`](SiteDraftStore::create) | Allocates the id `{prefix}-{n}` from a per-site, per-kind counter that never hands a number out twice, at version 1 |
17//! | [`replace`](SiteDraftStore::replace) | A compare-and-swap on the version: of two writers at one version exactly one succeeds |
18//! | [`list`](SiteDraftStore::list) | The site's records of one kind, in creation order |
19//!
20//! [`InMemorySiteDraftStore`] serves tests and a single process; [`SqliteSiteDraftStore`]
21//! (feature `sqlite`) a served site; `PostgresSiteDraftStore` (feature `postgres`) and
22//! `RedisSiteDraftStore` (feature `redis`) every replica of one. Every implementation
23//! passes the [`conformance`] suite,
24//! which [`site_draft_store_conformance_tests!`](crate::site_draft_store_conformance_tests)
25//! runs. A preview is not kept: it names the build it staged, so a process makes it again.
26
27use std::collections::BTreeMap;
28use std::fmt;
29
30use adk_core::{AdkError, ErrorCategory, ErrorComponent, Result};
31use adk_site::pipeline::{Change, Draft, EntryPoint};
32use async_trait::async_trait;
33use awp_types::ContentItem;
34use base64::Engine as _;
35use serde::{Deserialize, Serialize};
36use serde_json::Value;
37use tokio::sync::Mutex;
38use uuid::Uuid;
39
40/// What a stored record is (spec 3.5 §7.8.2, §7.6, §7.11).
41#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
42pub enum DraftKind {
43    /// A content draft.
44    Content,
45    /// A charter draft.
46    Charter,
47    /// A charter signing request.
48    CharterSign,
49    /// A job promotion request.
50    Promotion,
51}
52
53impl DraftKind {
54    /// Every kind.
55    pub const ALL: [DraftKind; 4] =
56        [DraftKind::Content, DraftKind::Charter, DraftKind::CharterSign, DraftKind::Promotion];
57
58    /// The stored name: `content`, `charter`, `charter_sign` or `promotion`.
59    pub fn as_str(self) -> &'static str {
60        match self {
61            Self::Content => "content",
62            Self::Charter => "charter",
63            Self::CharterSign => "charter_sign",
64            Self::Promotion => "promotion",
65        }
66    }
67
68    /// The prefix of the ids a store allocates: `draft`, `charter`, `charter-sign` or
69    /// `promotion`, so a content draft is `draft-1`.
70    ///
71    /// # Example
72    ///
73    /// ```rust
74    /// use adk_harness::website::DraftKind;
75    ///
76    /// assert_eq!(DraftKind::Content.id_prefix(), "draft");
77    /// assert_eq!(DraftKind::CharterSign.id_prefix(), "charter-sign");
78    /// ```
79    pub fn id_prefix(self) -> &'static str {
80        match self {
81            Self::Content => "draft",
82            Self::Charter => "charter",
83            Self::CharterSign => "charter-sign",
84            Self::Promotion => "promotion",
85        }
86    }
87
88    /// The number of `id` when the store allocated it for this kind: `7` for `draft-7`.
89    pub(crate) fn number(self, id: &str) -> Option<u64> {
90        id.strip_prefix(self.id_prefix())?.strip_prefix('-')?.parse().ok()
91    }
92}
93
94impl fmt::Display for DraftKind {
95    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
96        f.write_str(match self {
97            Self::Content => "content draft",
98            Self::Charter => "charter draft",
99            Self::CharterSign => "charter signing request",
100            Self::Promotion => "promotion request",
101        })
102    }
103}
104
105/// One stored record: its store-allocated id, its version, and its value.
106///
107/// # Example
108///
109/// ```rust
110/// use adk_harness::website::StoredRecord;
111///
112/// let record = StoredRecord { id: "draft-1".into(), version: 1, value: serde_json::json!({}) };
113/// assert_eq!(serde_json::to_value(&record).unwrap()["version"], 1);
114/// ```
115#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
116#[serde(rename_all = "camelCase")]
117pub struct StoredRecord {
118    /// The id the store allocated, such as `draft-7`.
119    pub id: String,
120    /// Starts at 1 and grows by one with every [`replace`](SiteDraftStore::replace).
121    pub version: u64,
122    /// The record.
123    pub value: Value,
124}
125
126/// Where a site runtime keeps its drafts (spec 3.5 §7.8.2 step 1).
127///
128/// # Example
129///
130/// ```rust
131/// use adk_harness::website::{DraftKind, InMemorySiteDraftStore, SiteDraftStore};
132///
133/// # #[tokio::main(flavor = "current_thread")]
134/// # async fn main() -> adk_core::Result<()> {
135/// let store = InMemorySiteDraftStore::default();
136/// let site = uuid::Uuid::nil();
137/// let created = store.create(site, DraftKind::Charter, &serde_json::json!({ "v": 1 })).await?;
138/// assert_eq!((created.id.as_str(), created.version), ("charter-1", 1));
139/// assert!(store.replace(site, DraftKind::Charter, "charter-1", &serde_json::json!({ "v": 2 }), 1).await?);
140/// assert!(!store.replace(site, DraftKind::Charter, "charter-1", &serde_json::json!({ "v": 3 }), 1).await?);
141/// # Ok(())
142/// # }
143/// ```
144#[async_trait]
145pub trait SiteDraftStore: Send + Sync {
146    /// Keeps `value` as a new record of `kind` for `site`, at version 1, under an id the
147    /// store allocates: `{prefix}-{n}` with the kind's [`id_prefix`](DraftKind::id_prefix)
148    /// and a number no earlier record of the site and kind had.
149    ///
150    /// # Errors
151    ///
152    /// The store's error.
153    async fn create(&self, site: Uuid, kind: DraftKind, value: &Value) -> Result<StoredRecord>;
154
155    /// The record `id` of `kind` for `site`; `None` when there is none.
156    ///
157    /// # Errors
158    ///
159    /// The store's error.
160    async fn get(&self, site: Uuid, kind: DraftKind, id: &str) -> Result<Option<StoredRecord>>;
161
162    /// Replaces the record `id` with `value` when it is at `expected_version`, raising its
163    /// version by one. `false`, writing nothing, when it is at another version or gone.
164    ///
165    /// # Errors
166    ///
167    /// The store's error.
168    async fn replace(
169        &self,
170        site: Uuid,
171        kind: DraftKind,
172        id: &str,
173        value: &Value,
174        expected_version: u64,
175    ) -> Result<bool>;
176
177    /// Forgets `id` of `kind` for `site`; nothing when there is none. Its number is never
178    /// allocated again.
179    ///
180    /// # Errors
181    ///
182    /// The store's error.
183    async fn remove(&self, site: Uuid, kind: DraftKind, id: &str) -> Result<()>;
184
185    /// Every record of `kind` for `site`, in creation order.
186    ///
187    /// # Errors
188    ///
189    /// The store's error.
190    async fn list(&self, site: Uuid, kind: DraftKind) -> Result<Vec<StoredRecord>>;
191}
192
193#[derive(Debug, Default)]
194struct Records {
195    /// The last number allocated per site and kind.
196    last: BTreeMap<(Uuid, DraftKind), u64>,
197    /// By site, kind and number: the id, the version and the value.
198    records: BTreeMap<(Uuid, DraftKind, u64), StoredRecord>,
199}
200
201/// A [`SiteDraftStore`] in memory, for tests and a single process.
202#[derive(Debug, Default)]
203pub struct InMemorySiteDraftStore {
204    inner: Mutex<Records>,
205}
206
207impl InMemorySiteDraftStore {
208    fn find(records: &Records, site: Uuid, kind: DraftKind, id: &str) -> Option<u64> {
209        kind.number(id).filter(|n| records.records.contains_key(&(site, kind, *n)))
210    }
211}
212
213#[async_trait]
214impl SiteDraftStore for InMemorySiteDraftStore {
215    async fn create(&self, site: Uuid, kind: DraftKind, value: &Value) -> Result<StoredRecord> {
216        let mut inner = self.inner.lock().await;
217        let last = inner.last.entry((site, kind)).or_default();
218        *last += 1;
219        let n = *last;
220        let record = StoredRecord {
221            id: format!("{}-{n}", kind.id_prefix()),
222            version: 1,
223            value: value.clone(),
224        };
225        inner.records.insert((site, kind, n), record.clone());
226        Ok(record)
227    }
228
229    async fn get(&self, site: Uuid, kind: DraftKind, id: &str) -> Result<Option<StoredRecord>> {
230        let inner = self.inner.lock().await;
231        Ok(Self::find(&inner, site, kind, id)
232            .and_then(|n| inner.records.get(&(site, kind, n)).cloned()))
233    }
234
235    async fn replace(
236        &self,
237        site: Uuid,
238        kind: DraftKind,
239        id: &str,
240        value: &Value,
241        expected_version: u64,
242    ) -> Result<bool> {
243        let mut inner = self.inner.lock().await;
244        let Some(n) = Self::find(&inner, site, kind, id) else { return Ok(false) };
245        match inner.records.get_mut(&(site, kind, n)) {
246            Some(record) if record.version == expected_version => {
247                record.value = value.clone();
248                record.version += 1;
249                Ok(true)
250            }
251            Some(_) | None => Ok(false),
252        }
253    }
254
255    async fn remove(&self, site: Uuid, kind: DraftKind, id: &str) -> Result<()> {
256        let mut inner = self.inner.lock().await;
257        if let Some(n) = Self::find(&inner, site, kind, id) {
258            inner.records.remove(&(site, kind, n));
259        }
260        Ok(())
261    }
262
263    async fn list(&self, site: Uuid, kind: DraftKind) -> Result<Vec<StoredRecord>> {
264        Ok(self
265            .inner
266            .lock()
267            .await
268            .records
269            .range((site, kind, 0)..=(site, kind, u64::MAX))
270            .map(|(_, record)| record.clone())
271            .collect())
272    }
273}
274
275pub(crate) fn store_error(error: impl fmt::Display) -> AdkError {
276    AdkError::new(
277        ErrorComponent::Tool,
278        ErrorCategory::Unavailable,
279        "website.drafts.store",
280        format!("the site's draft store: {error}"),
281    )
282}
283
284/// The error of a write that lost its compare-and-swap: the record changed since it was read.
285pub(crate) fn conflict(kind: DraftKind, id: &str) -> AdkError {
286    AdkError::new(
287        ErrorComponent::Tool,
288        ErrorCategory::Conflict,
289        "website.drafts.conflict",
290        format!(
291            "the {kind} '{id}' changed or was removed while this change was made; read it \
292             again and repeat the change"
293        ),
294    )
295}
296
297/// A stored version as SQL's signed integer.
298#[cfg(any(feature = "sqlite", feature = "postgres"))]
299fn sql_version(version: u64) -> Result<i64> {
300    i64::try_from(version).map_err(|_| store_error(format!("version {version} is out of range")))
301}
302
303/// A [`SiteDraftStore`] in SQLite, such as a served site's `data/edge.db` (feature
304/// `sqlite`).
305///
306/// [`migrate`](Self::migrate) upgrades a table an earlier release created in place: its
307/// records start at version 1, and new ids continue after the highest one it holds.
308///
309/// # Example
310///
311/// ```rust,ignore
312/// let drafts = SqliteSiteDraftStore::new(pool);
313/// drafts.migrate().await?;
314/// let runtime = SiteRuntime::builder(site, base, store, generator, host, log, work)
315///     .drafts(Arc::new(drafts))
316///     .build()?;
317/// ```
318#[cfg(feature = "sqlite")]
319#[derive(Debug, Clone)]
320pub struct SqliteSiteDraftStore {
321    pool: sqlx::SqlitePool,
322}
323
324#[cfg(feature = "sqlite")]
325impl SqliteSiteDraftStore {
326    /// A store over `pool`; call [`migrate`](Self::migrate) once.
327    pub fn new(pool: sqlx::SqlitePool) -> Self {
328        Self { pool }
329    }
330
331    /// Creates the tables, or upgrades the table of an earlier release.
332    ///
333    /// # Errors
334    ///
335    /// The database's error.
336    pub async fn migrate(&self) -> Result<()> {
337        for statement in [
338            "CREATE TABLE IF NOT EXISTS adk_website_drafts (
339                site TEXT NOT NULL,
340                kind TEXT NOT NULL,
341                id TEXT NOT NULL,
342                value TEXT NOT NULL,
343                version INTEGER NOT NULL DEFAULT 1,
344                seq INTEGER NOT NULL DEFAULT 0,
345                PRIMARY KEY (site, kind, id)
346            )",
347            "CREATE TABLE IF NOT EXISTS adk_website_draft_ids (
348                site TEXT NOT NULL,
349                kind TEXT NOT NULL,
350                last INTEGER NOT NULL,
351                PRIMARY KEY (site, kind)
352            )",
353        ] {
354            sqlx::query(statement).execute(&self.pool).await.map_err(store_error)?;
355        }
356        // A table from before versions gains `version` and `seq`; its ids carry the numbers.
357        for (column, statement) in [
358            (
359                "version",
360                "ALTER TABLE adk_website_drafts ADD COLUMN version INTEGER NOT NULL DEFAULT 1",
361            ),
362            ("seq", "ALTER TABLE adk_website_drafts ADD COLUMN seq INTEGER NOT NULL DEFAULT 0"),
363        ] {
364            if !self.has_column(column).await? {
365                let added = sqlx::query(statement).execute(&self.pool).await;
366                // Another process may have added it first.
367                if let Err(error) = added
368                    && !self.has_column(column).await?
369                {
370                    return Err(store_error(error));
371                }
372            }
373        }
374        let unnumbered: Vec<(String, String, String)> =
375            sqlx::query_as("SELECT site, kind, id FROM adk_website_drafts WHERE seq = 0")
376                .fetch_all(&self.pool)
377                .await
378                .map_err(store_error)?;
379        for (site, kind, id) in unnumbered {
380            let Some(n) = DraftKind::ALL
381                .into_iter()
382                .find(|known| known.as_str() == kind)
383                .and_then(|known| known.number(&id))
384            else {
385                continue;
386            };
387            sqlx::query(
388                "UPDATE adk_website_drafts SET seq = ? WHERE site = ? AND kind = ? AND id = ?",
389            )
390            .bind(sql_version(n)?)
391            .bind(&site)
392            .bind(&kind)
393            .bind(&id)
394            .execute(&self.pool)
395            .await
396            .map_err(store_error)?;
397        }
398        // New ids continue after the highest number already stored.
399        sqlx::query(
400            "INSERT INTO adk_website_draft_ids (site, kind, last)
401             SELECT site, kind, MAX(seq) FROM adk_website_drafts WHERE true GROUP BY site, kind
402             ON CONFLICT (site, kind) DO UPDATE
403             SET last = MAX(adk_website_draft_ids.last, excluded.last)",
404        )
405        .execute(&self.pool)
406        .await
407        .map_err(store_error)?;
408        Ok(())
409    }
410
411    async fn has_column(&self, column: &str) -> Result<bool> {
412        let (count,): (i64,) = sqlx::query_as(
413            "SELECT COUNT(*) FROM pragma_table_info('adk_website_drafts') WHERE name = ?",
414        )
415        .bind(column)
416        .fetch_one(&self.pool)
417        .await
418        .map_err(store_error)?;
419        Ok(count > 0)
420    }
421}
422
423#[cfg(any(feature = "sqlite", feature = "postgres"))]
424fn stored(id: String, version: i64, value: &str) -> Result<StoredRecord> {
425    Ok(StoredRecord {
426        id,
427        version: u64::try_from(version).map_err(store_error)?,
428        value: serde_json::from_str(value).map_err(store_error)?,
429    })
430}
431
432#[cfg(feature = "sqlite")]
433#[async_trait]
434impl SiteDraftStore for SqliteSiteDraftStore {
435    async fn create(&self, site: Uuid, kind: DraftKind, value: &Value) -> Result<StoredRecord> {
436        let (n,): (i64,) = sqlx::query_as(
437            "INSERT INTO adk_website_draft_ids (site, kind, last) VALUES (?, ?, 1)
438             ON CONFLICT (site, kind) DO UPDATE SET last = adk_website_draft_ids.last + 1
439             RETURNING last",
440        )
441        .bind(site.to_string())
442        .bind(kind.as_str())
443        .fetch_one(&self.pool)
444        .await
445        .map_err(store_error)?;
446        let id = format!("{}-{n}", kind.id_prefix());
447        sqlx::query(
448            "INSERT INTO adk_website_drafts (site, kind, id, value, version, seq)
449             VALUES (?, ?, ?, ?, 1, ?)",
450        )
451        .bind(site.to_string())
452        .bind(kind.as_str())
453        .bind(&id)
454        .bind(value.to_string())
455        .bind(n)
456        .execute(&self.pool)
457        .await
458        .map_err(store_error)?;
459        Ok(StoredRecord { id, version: 1, value: value.clone() })
460    }
461
462    async fn get(&self, site: Uuid, kind: DraftKind, id: &str) -> Result<Option<StoredRecord>> {
463        let row: Option<(i64, String)> = sqlx::query_as(
464            "SELECT version, value FROM adk_website_drafts WHERE site = ? AND kind = ? AND id = ?",
465        )
466        .bind(site.to_string())
467        .bind(kind.as_str())
468        .bind(id)
469        .fetch_optional(&self.pool)
470        .await
471        .map_err(store_error)?;
472        row.map(|(version, value)| stored(id.to_string(), version, &value)).transpose()
473    }
474
475    async fn replace(
476        &self,
477        site: Uuid,
478        kind: DraftKind,
479        id: &str,
480        value: &Value,
481        expected_version: u64,
482    ) -> Result<bool> {
483        let updated = sqlx::query(
484            "UPDATE adk_website_drafts SET value = ?, version = version + 1
485             WHERE site = ? AND kind = ? AND id = ? AND version = ?",
486        )
487        .bind(value.to_string())
488        .bind(site.to_string())
489        .bind(kind.as_str())
490        .bind(id)
491        .bind(sql_version(expected_version)?)
492        .execute(&self.pool)
493        .await
494        .map_err(store_error)?;
495        Ok(updated.rows_affected() == 1)
496    }
497
498    async fn remove(&self, site: Uuid, kind: DraftKind, id: &str) -> Result<()> {
499        sqlx::query("DELETE FROM adk_website_drafts WHERE site = ? AND kind = ? AND id = ?")
500            .bind(site.to_string())
501            .bind(kind.as_str())
502            .bind(id)
503            .execute(&self.pool)
504            .await
505            .map_err(store_error)?;
506        Ok(())
507    }
508
509    async fn list(&self, site: Uuid, kind: DraftKind) -> Result<Vec<StoredRecord>> {
510        let rows: Vec<(String, i64, String)> = sqlx::query_as(
511            "SELECT id, version, value FROM adk_website_drafts
512             WHERE site = ? AND kind = ? ORDER BY seq, id",
513        )
514        .bind(site.to_string())
515        .bind(kind.as_str())
516        .fetch_all(&self.pool)
517        .await
518        .map_err(store_error)?;
519        rows.into_iter().map(|(id, version, value)| stored(id, version, &value)).collect()
520    }
521}
522
523#[cfg(feature = "postgres")]
524const POSTGRES_DRAFT_MIGRATIONS: &[(i64, &str, &str)] = &[(
525    1,
526    "create site draft tables",
527    "CREATE TABLE IF NOT EXISTS adk_website_drafts (\
528        site TEXT NOT NULL, kind TEXT NOT NULL, id TEXT NOT NULL, value TEXT NOT NULL, \
529        version BIGINT NOT NULL, seq BIGINT NOT NULL, \
530        PRIMARY KEY (site, kind, id)); \
531     CREATE INDEX IF NOT EXISTS adk_website_drafts_in_order \
532        ON adk_website_drafts (site, kind, seq); \
533     CREATE TABLE IF NOT EXISTS adk_website_draft_ids (\
534        site TEXT NOT NULL, kind TEXT NOT NULL, last BIGINT NOT NULL, \
535        PRIMARY KEY (site, kind));",
536)];
537
538/// A [`SiteDraftStore`] in PostgreSQL, shared by every replica of a served site (feature
539/// `postgres`).
540///
541/// Records live in `adk_website_drafts` by site, kind and id with their version; the
542/// counter that allocates ids is a row per site and kind in `adk_website_draft_ids`,
543/// incremented by an upsert, so replicas creating at once get distinct ids.
544/// [`migrate`](Self::migrate) records its steps in `_adk_website_draft_migrations` under an
545/// advisory lock, so replicas starting together migrate one at a time.
546///
547/// # Example
548///
549/// ```rust,no_run
550/// use adk_harness::website::{DraftKind, PostgresSiteDraftStore, SiteDraftStore};
551///
552/// # async fn example() -> adk_core::Result<()> {
553/// let store = PostgresSiteDraftStore::connect("postgres://localhost/site").await?;
554/// store.migrate().await?;
555/// let drafts = store.list(uuid::Uuid::nil(), DraftKind::Content).await?;
556/// # let _ = drafts;
557/// # Ok(())
558/// # }
559/// ```
560#[cfg(feature = "postgres")]
561#[derive(Debug, Clone)]
562pub struct PostgresSiteDraftStore {
563    pool: sqlx::PgPool,
564}
565
566#[cfg(feature = "postgres")]
567impl PostgresSiteDraftStore {
568    /// A store over `pool`, such as the one the site's other stores use; call
569    /// [`migrate`](Self::migrate) once.
570    pub fn new(pool: sqlx::PgPool) -> Self {
571        Self { pool }
572    }
573
574    /// Connects to `database_url` with a pool of its own.
575    ///
576    /// # Errors
577    ///
578    /// `website.drafts.store` when the server cannot be reached.
579    pub async fn connect(database_url: &str) -> Result<Self> {
580        Ok(Self::new(sqlx::PgPool::connect(database_url).await.map_err(store_error)?))
581    }
582
583    /// Creates or upgrades the store's tables.
584    ///
585    /// # Errors
586    ///
587    /// The database's error, or a version mismatch when a newer release migrated the
588    /// database.
589    pub async fn migrate(&self) -> Result<()> {
590        crate::fsutil::migrate_postgres(
591            &self.pool,
592            "_adk_website_draft_migrations",
593            POSTGRES_DRAFT_MIGRATIONS,
594        )
595        .await
596    }
597}
598
599#[cfg(feature = "postgres")]
600#[async_trait]
601impl SiteDraftStore for PostgresSiteDraftStore {
602    async fn create(&self, site: Uuid, kind: DraftKind, value: &Value) -> Result<StoredRecord> {
603        let mut tx = self.pool.begin().await.map_err(store_error)?;
604        let (n,): (i64,) = sqlx::query_as(
605            "INSERT INTO adk_website_draft_ids (site, kind, last) VALUES ($1, $2, 1)
606             ON CONFLICT (site, kind) DO UPDATE SET last = adk_website_draft_ids.last + 1
607             RETURNING last",
608        )
609        .bind(site.to_string())
610        .bind(kind.as_str())
611        .fetch_one(&mut *tx)
612        .await
613        .map_err(store_error)?;
614        let id = format!("{}-{n}", kind.id_prefix());
615        sqlx::query(
616            "INSERT INTO adk_website_drafts (site, kind, id, value, version, seq)
617             VALUES ($1, $2, $3, $4, 1, $5)",
618        )
619        .bind(site.to_string())
620        .bind(kind.as_str())
621        .bind(&id)
622        .bind(value.to_string())
623        .bind(n)
624        .execute(&mut *tx)
625        .await
626        .map_err(store_error)?;
627        tx.commit().await.map_err(store_error)?;
628        Ok(StoredRecord { id, version: 1, value: value.clone() })
629    }
630
631    async fn get(&self, site: Uuid, kind: DraftKind, id: &str) -> Result<Option<StoredRecord>> {
632        let row: Option<(i64, String)> = sqlx::query_as(
633            "SELECT version, value FROM adk_website_drafts
634             WHERE site = $1 AND kind = $2 AND id = $3",
635        )
636        .bind(site.to_string())
637        .bind(kind.as_str())
638        .bind(id)
639        .fetch_optional(&self.pool)
640        .await
641        .map_err(store_error)?;
642        row.map(|(version, value)| stored(id.to_string(), version, &value)).transpose()
643    }
644
645    async fn replace(
646        &self,
647        site: Uuid,
648        kind: DraftKind,
649        id: &str,
650        value: &Value,
651        expected_version: u64,
652    ) -> Result<bool> {
653        let updated = sqlx::query(
654            "UPDATE adk_website_drafts SET value = $1, version = version + 1
655             WHERE site = $2 AND kind = $3 AND id = $4 AND version = $5",
656        )
657        .bind(value.to_string())
658        .bind(site.to_string())
659        .bind(kind.as_str())
660        .bind(id)
661        .bind(sql_version(expected_version)?)
662        .execute(&self.pool)
663        .await
664        .map_err(store_error)?;
665        Ok(updated.rows_affected() == 1)
666    }
667
668    async fn remove(&self, site: Uuid, kind: DraftKind, id: &str) -> Result<()> {
669        sqlx::query("DELETE FROM adk_website_drafts WHERE site = $1 AND kind = $2 AND id = $3")
670            .bind(site.to_string())
671            .bind(kind.as_str())
672            .bind(id)
673            .execute(&self.pool)
674            .await
675            .map_err(store_error)?;
676        Ok(())
677    }
678
679    async fn list(&self, site: Uuid, kind: DraftKind) -> Result<Vec<StoredRecord>> {
680        let rows: Vec<(String, i64, String)> = sqlx::query_as(
681            "SELECT id, version, value FROM adk_website_drafts
682             WHERE site = $1 AND kind = $2 ORDER BY seq, id",
683        )
684        .bind(site.to_string())
685        .bind(kind.as_str())
686        .fetch_all(&self.pool)
687        .await
688        .map_err(store_error)?;
689        rows.into_iter().map(|(id, version, value)| stored(id, version, &value)).collect()
690    }
691}
692
693/// KEYS: counters, values, versions, order. ARGV: kind, id prefix, value JSON. Allocates the
694/// kind's next number and stores the record at version 1; returns its id.
695#[cfg(feature = "redis")]
696const CREATE_DRAFT_SCRIPT: &str = r#"
697local n = redis.call('HINCRBY', KEYS[1], ARGV[1], 1)
698local id = ARGV[2] .. '-' .. n
699redis.call('HSET', KEYS[2], id, ARGV[3])
700redis.call('HSET', KEYS[3], id, 1)
701redis.call('ZADD', KEYS[4], n, id)
702return id
703"#;
704
705/// KEYS: values, versions. ARGV: id. Returns the record's version and value, or nothing.
706#[cfg(feature = "redis")]
707const GET_DRAFT_SCRIPT: &str = r#"
708local value = redis.call('HGET', KEYS[1], ARGV[1])
709if not value then return {} end
710return { redis.call('HGET', KEYS[2], ARGV[1]), value }
711"#;
712
713/// KEYS: values, versions. ARGV: id, value JSON, expected version. Writes the value and
714/// raises the version when the record is at the expected one; returns 1 when it wrote.
715#[cfg(feature = "redis")]
716const REPLACE_DRAFT_SCRIPT: &str = r#"
717local version = redis.call('HGET', KEYS[2], ARGV[1])
718if not version or version ~= ARGV[3] then return 0 end
719redis.call('HSET', KEYS[1], ARGV[1], ARGV[2])
720redis.call('HINCRBY', KEYS[2], ARGV[1], 1)
721return 1
722"#;
723
724/// KEYS: values, versions, order. ARGV: id. Forgets the record.
725#[cfg(feature = "redis")]
726const REMOVE_DRAFT_SCRIPT: &str = r#"
727redis.call('HDEL', KEYS[1], ARGV[1])
728redis.call('HDEL', KEYS[2], ARGV[1])
729redis.call('ZREM', KEYS[3], ARGV[1])
730return 1
731"#;
732
733/// KEYS: values, versions, order. Returns id, version and value of every record in creation
734/// order, read atomically.
735#[cfg(feature = "redis")]
736const LIST_DRAFTS_SCRIPT: &str = r#"
737local out = {}
738for _, id in ipairs(redis.call('ZRANGE', KEYS[3], 0, -1)) do
739  local value = redis.call('HGET', KEYS[1], id)
740  if value then
741    table.insert(out, id)
742    table.insert(out, redis.call('HGET', KEYS[2], id))
743    table.insert(out, value)
744  end
745end
746return out
747"#;
748
749/// A [`SiteDraftStore`] in Redis, shared by every replica of a served site (feature
750/// `redis`).
751///
752/// A site's keys share its hash tag, so they sit in one Redis Cluster slot and every change
753/// runs as one atomic script:
754///
755/// | Key | Type | Contents |
756/// |-----|------|----------|
757/// | `<namespace>:{<site>}:draft-ids` | Hash | Kind → the last number allocated |
758/// | `<namespace>:{<site>}:drafts:<kind>` | Hash | Id → value JSON |
759/// | `<namespace>:{<site>}:draft-versions:<kind>` | Hash | Id → version |
760/// | `<namespace>:{<site>}:draft-order:<kind>` | Sorted set | Ids by number, for creation order |
761///
762/// The namespace is `adk:harness` unless [`with_namespace`](Self::with_namespace) sets
763/// another.
764///
765/// # Example
766///
767/// ```rust,no_run
768/// use adk_harness::website::{DraftKind, RedisSiteDraftStore, SiteDraftStore};
769///
770/// # async fn example() -> adk_core::Result<()> {
771/// let store = RedisSiteDraftStore::connect("redis://localhost:6379").await?;
772/// store.migrate().await?;
773/// let drafts = store.list(uuid::Uuid::nil(), DraftKind::Content).await?;
774/// # let _ = drafts;
775/// # Ok(())
776/// # }
777/// ```
778#[cfg(feature = "redis")]
779#[derive(Debug, Clone)]
780pub struct RedisSiteDraftStore {
781    client: fred::prelude::Client,
782    namespace: String,
783}
784
785#[cfg(feature = "redis")]
786fn redis_error(action: &str, error: &dyn fmt::Display) -> AdkError {
787    store_error(format!("could not {action}: {error}"))
788}
789
790#[cfg(feature = "redis")]
791impl RedisSiteDraftStore {
792    /// A store over an initialized client, such as one shared with the harness's other
793    /// Redis stores.
794    pub fn from_client(client: fred::prelude::Client) -> Self {
795        Self { client, namespace: crate::fsutil::REDIS_NAMESPACE.to_string() }
796    }
797
798    /// Connects to `url`.
799    ///
800    /// # Errors
801    ///
802    /// `harness.store.database` when the server cannot be reached.
803    pub async fn connect(url: &str) -> Result<Self> {
804        Ok(Self::from_client(crate::fsutil::redis_connect(url).await?))
805    }
806
807    /// Keeps the store's keys under `namespace` instead of `adk:harness`, for example to
808    /// separate deployments that share a server.
809    #[must_use]
810    pub fn with_namespace(mut self, namespace: impl Into<String>) -> Self {
811        self.namespace = crate::fsutil::redis_namespace(&namespace.into());
812        self
813    }
814
815    /// Loads the store's scripts into the server's script cache.
816    ///
817    /// # Errors
818    ///
819    /// `website.drafts.store` when the server rejects a script.
820    pub async fn migrate(&self) -> Result<()> {
821        use fred::prelude::LuaInterface as _;
822        for script in [
823            CREATE_DRAFT_SCRIPT,
824            GET_DRAFT_SCRIPT,
825            REPLACE_DRAFT_SCRIPT,
826            REMOVE_DRAFT_SCRIPT,
827            LIST_DRAFTS_SCRIPT,
828        ] {
829            let _: String = self
830                .client
831                .script_load(script)
832                .await
833                .map_err(|error| redis_error("load a script", &error))?;
834        }
835        Ok(())
836    }
837
838    /// The site's counters key, then the kind's values, versions and order keys.
839    fn keys(&self, site: Uuid, kind: DraftKind) -> [String; 4] {
840        let prefix =
841            format!("{}:{{{}}}", self.namespace, crate::fsutil::redis_segment(&site.to_string()));
842        let kind = kind.as_str();
843        [
844            format!("{prefix}:draft-ids"),
845            format!("{prefix}:drafts:{kind}"),
846            format!("{prefix}:draft-versions:{kind}"),
847            format!("{prefix}:draft-order:{kind}"),
848        ]
849    }
850}
851
852#[cfg(feature = "redis")]
853fn redis_record(id: String, version: &str, value: &str) -> Result<StoredRecord> {
854    Ok(StoredRecord {
855        id,
856        version: version.parse().map_err(store_error)?,
857        value: serde_json::from_str(value).map_err(store_error)?,
858    })
859}
860
861#[cfg(feature = "redis")]
862#[async_trait]
863impl SiteDraftStore for RedisSiteDraftStore {
864    async fn create(&self, site: Uuid, kind: DraftKind, value: &Value) -> Result<StoredRecord> {
865        use fred::prelude::LuaInterface as _;
866        let id: String = self
867            .client
868            .eval(
869                CREATE_DRAFT_SCRIPT,
870                self.keys(site, kind).to_vec(),
871                vec![kind.as_str().to_string(), kind.id_prefix().to_string(), value.to_string()],
872            )
873            .await
874            .map_err(|error| redis_error("create a draft", &error))?;
875        Ok(StoredRecord { id, version: 1, value: value.clone() })
876    }
877
878    async fn get(&self, site: Uuid, kind: DraftKind, id: &str) -> Result<Option<StoredRecord>> {
879        use fred::prelude::LuaInterface as _;
880        let [_, values, versions, _] = self.keys(site, kind);
881        let reply: Vec<String> = self
882            .client
883            .eval(GET_DRAFT_SCRIPT, vec![values, versions], vec![id.to_string()])
884            .await
885            .map_err(|error| redis_error("read a draft", &error))?;
886        match reply.as_slice() {
887            [version, value] => Ok(Some(redis_record(id.to_string(), version, value)?)),
888            _ => Ok(None),
889        }
890    }
891
892    async fn replace(
893        &self,
894        site: Uuid,
895        kind: DraftKind,
896        id: &str,
897        value: &Value,
898        expected_version: u64,
899    ) -> Result<bool> {
900        use fred::prelude::LuaInterface as _;
901        let [_, values, versions, _] = self.keys(site, kind);
902        let written: i64 = self
903            .client
904            .eval(
905                REPLACE_DRAFT_SCRIPT,
906                vec![values, versions],
907                vec![id.to_string(), value.to_string(), expected_version.to_string()],
908            )
909            .await
910            .map_err(|error| redis_error("replace a draft", &error))?;
911        Ok(written == 1)
912    }
913
914    async fn remove(&self, site: Uuid, kind: DraftKind, id: &str) -> Result<()> {
915        use fred::prelude::LuaInterface as _;
916        let [_, values, versions, order] = self.keys(site, kind);
917        let _: i64 = self
918            .client
919            .eval(REMOVE_DRAFT_SCRIPT, vec![values, versions, order], vec![id.to_string()])
920            .await
921            .map_err(|error| redis_error("remove a draft", &error))?;
922        Ok(())
923    }
924
925    async fn list(&self, site: Uuid, kind: DraftKind) -> Result<Vec<StoredRecord>> {
926        use fred::prelude::LuaInterface as _;
927        let [_, values, versions, order] = self.keys(site, kind);
928        let reply: Vec<String> = self
929            .client
930            .eval(LIST_DRAFTS_SCRIPT, vec![values, versions, order], Vec::<String>::new())
931            .await
932            .map_err(|error| redis_error("list drafts", &error))?;
933        reply
934            .chunks(3)
935            .map(|record| match record {
936                [id, version, value] => redis_record(id.clone(), version, value),
937                _ => Err(store_error("a draft listing came back incomplete")),
938            })
939            .collect()
940    }
941}
942
943/// A content draft as it is stored: the change, its media base64-encoded.
944#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
945#[serde(rename_all = "camelCase")]
946pub(crate) struct StoredDraft {
947    pub(crate) items: Vec<ContentItem>,
948    #[serde(default, skip_serializing_if = "Vec::is_empty")]
949    media: Vec<(String, String)>,
950    pub(crate) entry: EntryPoint,
951    proposer: String,
952    job: String,
953    action_class: String,
954}
955
956impl StoredDraft {
957    pub(crate) fn of(draft: &Draft) -> Self {
958        let engine = base64::engine::general_purpose::STANDARD;
959        Self {
960            items: draft.change.items.clone(),
961            media: draft
962                .change
963                .media
964                .iter()
965                .map(|(path, bytes)| (path.clone(), engine.encode(bytes)))
966                .collect(),
967            entry: draft.change.entry.clone(),
968            proposer: draft.change.proposer.clone(),
969            job: draft.change.job.clone(),
970            action_class: draft.change.action_class.clone(),
971        }
972    }
973
974    pub(crate) fn into_draft(self) -> Result<Draft> {
975        let engine = base64::engine::general_purpose::STANDARD;
976        let media = self
977            .media
978            .into_iter()
979            .map(|(path, data)| {
980                let bytes = engine.decode(data.as_bytes()).map_err(store_error)?;
981                Ok((path, bytes::Bytes::from(bytes)))
982            })
983            .collect::<Result<Vec<_>>>()?;
984        let ids = self.items.iter().map(|item| item.id.clone()).collect();
985        Ok(Draft {
986            change: Change {
987                items: self.items,
988                media,
989                entry: self.entry,
990                proposer: self.proposer,
991                job: self.job,
992                action_class: self.action_class,
993            },
994            ids,
995        })
996    }
997}
998
999/// The conformance suite every [`SiteDraftStore`] passes (spec 3.5 §7.8.2), run with
1000/// [`site_draft_store_conformance_tests!`](crate::site_draft_store_conformance_tests).
1001///
1002/// | Case | Contract |
1003/// |------|----------|
1004/// | [`records_are_kept_apart_in_creation_order`](conformance::records_are_kept_apart_in_creation_order) | Records are kept by site and kind, listed in creation order, read back by id, and removed idempotently |
1005/// | [`ids_are_never_reused`](conformance::ids_are_never_reused) | A removed record's number, the highest one included, is never allocated again |
1006/// | [`concurrent_creates_are_distinct`](conformance::concurrent_creates_are_distinct) | Records created at once across two handles get distinct ids |
1007/// | [`replace_is_a_compare_and_swap`](conformance::replace_is_a_compare_and_swap) | `replace` writes only at the expected version, raising it by one, and never revives a removed record |
1008/// | [`concurrent_replace_has_one_winner`](conformance::concurrent_replace_has_one_winner) | Of two replaces at one version across two handles, exactly one succeeds |
1009/// | [`records_survive_a_restart`](conformance::records_survive_a_restart) | Records, versions and the id counter read back unchanged through a new handle |
1010///
1011/// Every case uses sites of its own, so cases share one database.
1012pub mod conformance {
1013    use std::collections::BTreeSet;
1014    use std::sync::Arc;
1015
1016    use async_trait::async_trait;
1017    use serde_json::json;
1018    use uuid::Uuid;
1019
1020    use super::{DraftKind, SiteDraftStore, StoredRecord};
1021
1022    /// Opens a [`SiteDraftStore`] backend for the conformance suite.
1023    ///
1024    /// # Example
1025    ///
1026    /// ```rust
1027    /// use std::sync::Arc;
1028    /// use adk_harness::website::draft_conformance::SiteDraftStoreHarness;
1029    /// use adk_harness::website::{InMemorySiteDraftStore, SiteDraftStore};
1030    ///
1031    /// struct InMemory(Arc<InMemorySiteDraftStore>);
1032    ///
1033    /// #[async_trait::async_trait]
1034    /// impl SiteDraftStoreHarness for InMemory {
1035    ///     async fn open(&self) -> Arc<dyn SiteDraftStore> {
1036    ///         self.0.clone()
1037    ///     }
1038    /// }
1039    /// ```
1040    #[async_trait]
1041    pub trait SiteDraftStoreHarness: Send + Sync {
1042        /// Opens the store.
1043        ///
1044        /// For a durable backend every call returns a new handle over the same stored data,
1045        /// as a restarted process or a second replica sees it. A process-local backend
1046        /// returns the same store every time. Panics when the backend cannot be opened.
1047        async fn open(&self) -> Arc<dyn SiteDraftStore>;
1048    }
1049
1050    fn ids(records: &[StoredRecord]) -> Vec<&str> {
1051        records.iter().map(|record| record.id.as_str()).collect()
1052    }
1053
1054    /// Records are kept apart by site and kind, listed in creation order — `draft-10` after
1055    /// `draft-9` — read back by id, and removed idempotently.
1056    ///
1057    /// # Panics
1058    ///
1059    /// When the store breaks its contract.
1060    pub async fn records_are_kept_apart_in_creation_order<H: SiteDraftStoreHarness + ?Sized>(
1061        harness: &H,
1062    ) {
1063        let store = harness.open().await;
1064        let (site, other) = (Uuid::new_v4(), Uuid::new_v4());
1065        let mut created = Vec::new();
1066        for n in 1..=10 {
1067            created.push(store.create(site, DraftKind::Content, &json!({ "n": n })).await.unwrap());
1068        }
1069        assert_eq!(created[0].id, "draft-1");
1070        assert_eq!(created[9].id, "draft-10");
1071        assert!(created.iter().all(|record| record.version == 1), "created at version 1");
1072        let charter = store.create(site, DraftKind::Charter, &json!({ "c": 1 })).await.unwrap();
1073        assert_eq!(charter.id, "charter-1", "each kind counts on its own");
1074        let elsewhere =
1075            store.create(other, DraftKind::Content, &json!({ "other": 1 })).await.unwrap();
1076        assert_eq!(elsewhere.id, "draft-1", "each site counts on its own");
1077
1078        let listed = store.list(site, DraftKind::Content).await.unwrap();
1079        assert_eq!(listed, created, "listed in creation order, this site's and kind's only");
1080        assert_eq!(store.list(site, DraftKind::Charter).await.unwrap(), vec![charter.clone()]);
1081        assert!(store.list(site, DraftKind::Promotion).await.unwrap().is_empty());
1082        assert_eq!(store.list(other, DraftKind::Content).await.unwrap(), vec![elsewhere]);
1083        assert_eq!(
1084            store.get(site, DraftKind::Content, "draft-2").await.unwrap(),
1085            Some(created[1].clone())
1086        );
1087        assert_eq!(store.get(site, DraftKind::CharterSign, "charter-1").await.unwrap(), None);
1088        assert_eq!(store.get(other, DraftKind::Charter, "charter-1").await.unwrap(), None);
1089
1090        store.remove(site, DraftKind::Content, "draft-2").await.unwrap();
1091        store.remove(site, DraftKind::Content, "draft-2").await.unwrap();
1092        store.remove(site, DraftKind::Content, "draft-99").await.unwrap();
1093        assert_eq!(store.get(site, DraftKind::Content, "draft-2").await.unwrap(), None);
1094        let left = store.list(site, DraftKind::Content).await.unwrap();
1095        assert_eq!(left.len(), 9);
1096        assert!(!ids(&left).contains(&"draft-2"));
1097        assert_eq!(store.get(site, DraftKind::Charter, "charter-1").await.unwrap(), Some(charter));
1098    }
1099
1100    /// A removed record's number is never allocated again, the highest one included.
1101    ///
1102    /// # Panics
1103    ///
1104    /// When the store breaks its contract.
1105    pub async fn ids_are_never_reused<H: SiteDraftStoreHarness + ?Sized>(harness: &H) {
1106        let store = harness.open().await;
1107        let site = Uuid::new_v4();
1108        for n in 1..=3 {
1109            store.create(site, DraftKind::Promotion, &json!(n)).await.unwrap();
1110        }
1111        for id in ["promotion-3", "promotion-2", "promotion-1"] {
1112            store.remove(site, DraftKind::Promotion, id).await.unwrap();
1113        }
1114        let next = store.create(site, DraftKind::Promotion, &json!(4)).await.unwrap();
1115        assert_eq!(next.id, "promotion-4", "numbers of removed records are not handed out again");
1116        assert_eq!(ids(&store.list(site, DraftKind::Promotion).await.unwrap()), ["promotion-4"]);
1117    }
1118
1119    /// Records created at once across two handles get distinct ids, and every one is kept.
1120    ///
1121    /// # Panics
1122    ///
1123    /// When the store breaks its contract.
1124    pub async fn concurrent_creates_are_distinct<H: SiteDraftStoreHarness + ?Sized>(harness: &H) {
1125        let (first, second) = (harness.open().await, harness.open().await);
1126        let site = Uuid::new_v4();
1127        let creates = (0..20).map(|n| {
1128            let store = if n % 2 == 0 { first.clone() } else { second.clone() };
1129            async move { store.create(site, DraftKind::Content, &json!({ "n": n })).await }
1130        });
1131        let created: Vec<StoredRecord> = futures::future::join_all(creates)
1132            .await
1133            .into_iter()
1134            .collect::<adk_core::Result<_>>()
1135            .unwrap();
1136        let distinct: BTreeSet<&str> = ids(&created).into_iter().collect();
1137        assert_eq!(distinct.len(), 20, "every create got its own id: {distinct:?}");
1138        assert_eq!(first.list(site, DraftKind::Content).await.unwrap().len(), 20);
1139    }
1140
1141    /// `replace` writes only at the expected version and raises it by one; a stale version or
1142    /// a removed record writes nothing.
1143    ///
1144    /// # Panics
1145    ///
1146    /// When the store breaks its contract.
1147    pub async fn replace_is_a_compare_and_swap<H: SiteDraftStoreHarness + ?Sized>(harness: &H) {
1148        let store = harness.open().await;
1149        let site = Uuid::new_v4();
1150        let created = store.create(site, DraftKind::Charter, &json!({ "v": 1 })).await.unwrap();
1151        assert!(
1152            store
1153                .replace(site, DraftKind::Charter, &created.id, &json!({ "v": 2 }), 1)
1154                .await
1155                .unwrap()
1156        );
1157        assert!(
1158            !store
1159                .replace(site, DraftKind::Charter, &created.id, &json!({ "v": 3 }), 1)
1160                .await
1161                .unwrap(),
1162            "a stale version writes nothing"
1163        );
1164        assert!(
1165            !store
1166                .replace(site, DraftKind::Content, &created.id, &json!({ "v": 3 }), 2)
1167                .await
1168                .unwrap(),
1169            "another kind's record is not this one"
1170        );
1171        assert_eq!(
1172            store.get(site, DraftKind::Charter, &created.id).await.unwrap(),
1173            Some(StoredRecord { id: created.id.clone(), version: 2, value: json!({ "v": 2 }) })
1174        );
1175        store.remove(site, DraftKind::Charter, &created.id).await.unwrap();
1176        assert!(
1177            !store
1178                .replace(site, DraftKind::Charter, &created.id, &json!({ "v": 4 }), 2)
1179                .await
1180                .unwrap(),
1181            "a removed record is not revived"
1182        );
1183        assert_eq!(store.get(site, DraftKind::Charter, &created.id).await.unwrap(), None);
1184    }
1185
1186    /// Of two replaces at one version, across two handles, exactly one succeeds.
1187    ///
1188    /// # Panics
1189    ///
1190    /// When the store breaks its contract.
1191    pub async fn concurrent_replace_has_one_winner<H: SiteDraftStoreHarness + ?Sized>(harness: &H) {
1192        let (first, second) = (harness.open().await, harness.open().await);
1193        let site = Uuid::new_v4();
1194        for _ in 0..5 {
1195            let created = first.create(site, DraftKind::Content, &json!("base")).await.unwrap();
1196            let (one, two) = (json!("first"), json!("second"));
1197            let (a, b) = futures::join!(
1198                first.replace(site, DraftKind::Content, &created.id, &one, 1),
1199                second.replace(site, DraftKind::Content, &created.id, &two, 1),
1200            );
1201            let (a, b) = (a.unwrap(), b.unwrap());
1202            assert!(a ^ b, "exactly one replace wins: {a} {b}");
1203            let stored = second.get(site, DraftKind::Content, &created.id).await.unwrap().unwrap();
1204            assert_eq!(stored.version, 2);
1205            assert_eq!(stored.value, if a { one } else { two });
1206        }
1207    }
1208
1209    /// Records, their versions and the id counter read back unchanged through a new handle.
1210    ///
1211    /// # Panics
1212    ///
1213    /// When the store breaks its contract.
1214    pub async fn records_survive_a_restart<H: SiteDraftStoreHarness + ?Sized>(harness: &H) {
1215        let site = Uuid::new_v4();
1216        let (kept, edited) = {
1217            let store = harness.open().await;
1218            let kept =
1219                store.create(site, DraftKind::CharterSign, &json!({ "k": 1 })).await.unwrap();
1220            let edited =
1221                store.create(site, DraftKind::CharterSign, &json!({ "k": 2 })).await.unwrap();
1222            assert!(
1223                store
1224                    .replace(site, DraftKind::CharterSign, &edited.id, &json!({ "k": 3 }), 1)
1225                    .await
1226                    .unwrap()
1227            );
1228            (kept, edited)
1229        };
1230        let reopened = harness.open().await;
1231        assert_eq!(
1232            reopened.list(site, DraftKind::CharterSign).await.unwrap(),
1233            vec![kept, StoredRecord { id: edited.id, version: 2, value: json!({ "k": 3 }) }]
1234        );
1235        let next = reopened.create(site, DraftKind::CharterSign, &json!({ "k": 4 })).await.unwrap();
1236        assert_eq!(next.id, "charter-sign-3", "the counter survives the restart");
1237    }
1238}
1239
1240/// Generates one test per [`conformance`](crate::website::draft_conformance) case for a
1241/// [`SiteDraftStoreHarness`](crate::website::draft_conformance::SiteDraftStoreHarness).
1242///
1243/// # Example
1244///
1245/// ```rust,ignore
1246/// adk_harness::site_draft_store_conformance_tests!(harness = SqliteHarness::new());
1247/// ```
1248#[macro_export]
1249macro_rules! site_draft_store_conformance_tests {
1250    ($(#[$attr:meta])* harness = $harness:expr $(,)?) => {
1251        $(#[$attr])*
1252        #[::tokio::test(flavor = "multi_thread", worker_threads = 4)]
1253        async fn site_drafts_are_kept_apart_in_creation_order() {
1254            $crate::website::draft_conformance::records_are_kept_apart_in_creation_order(
1255                &$harness,
1256            )
1257            .await;
1258        }
1259        $(#[$attr])*
1260        #[::tokio::test(flavor = "multi_thread", worker_threads = 4)]
1261        async fn site_draft_ids_are_never_reused() {
1262            $crate::website::draft_conformance::ids_are_never_reused(&$harness).await;
1263        }
1264        $(#[$attr])*
1265        #[::tokio::test(flavor = "multi_thread", worker_threads = 4)]
1266        async fn site_draft_concurrent_creates_are_distinct() {
1267            $crate::website::draft_conformance::concurrent_creates_are_distinct(&$harness).await;
1268        }
1269        $(#[$attr])*
1270        #[::tokio::test(flavor = "multi_thread", worker_threads = 4)]
1271        async fn site_draft_replace_is_a_compare_and_swap() {
1272            $crate::website::draft_conformance::replace_is_a_compare_and_swap(&$harness).await;
1273        }
1274        $(#[$attr])*
1275        #[::tokio::test(flavor = "multi_thread", worker_threads = 4)]
1276        async fn site_draft_concurrent_replace_has_one_winner() {
1277            $crate::website::draft_conformance::concurrent_replace_has_one_winner(&$harness)
1278                .await;
1279        }
1280        $(#[$attr])*
1281        #[::tokio::test(flavor = "multi_thread", worker_threads = 4)]
1282        async fn site_drafts_survive_a_restart() {
1283            $crate::website::draft_conformance::records_survive_a_restart(&$harness).await;
1284        }
1285    };
1286}
1287
1288#[cfg(test)]
1289mod tests {
1290    use std::sync::Arc;
1291
1292    use super::conformance::SiteDraftStoreHarness;
1293    use super::*;
1294
1295    struct InMemory(Arc<InMemorySiteDraftStore>);
1296
1297    #[async_trait]
1298    impl SiteDraftStoreHarness for InMemory {
1299        async fn open(&self) -> Arc<dyn SiteDraftStore> {
1300            self.0.clone()
1301        }
1302    }
1303
1304    mod in_memory {
1305        use super::*;
1306
1307        crate::site_draft_store_conformance_tests!(
1308            harness = InMemory(Arc::new(InMemorySiteDraftStore::default()))
1309        );
1310    }
1311
1312    #[cfg(feature = "sqlite")]
1313    mod sqlite {
1314        use super::*;
1315
1316        /// A database file every `open` connects to anew, as a second process does.
1317        struct Sqlite(tempfile::TempDir);
1318
1319        impl Sqlite {
1320            fn new() -> Self {
1321                Self(tempfile::tempdir().unwrap())
1322            }
1323
1324            fn url(&self) -> String {
1325                format!("sqlite://{}?mode=rwc", self.0.path().join("drafts.db").display())
1326            }
1327        }
1328
1329        #[async_trait]
1330        impl SiteDraftStoreHarness for Sqlite {
1331            async fn open(&self) -> Arc<dyn SiteDraftStore> {
1332                let pool = sqlx::SqlitePool::connect(&self.url()).await.unwrap();
1333                let store = SqliteSiteDraftStore::new(pool);
1334                store.migrate().await.unwrap();
1335                Arc::new(store)
1336            }
1337        }
1338
1339        crate::site_draft_store_conformance_tests!(harness = Sqlite::new());
1340
1341        #[tokio::test]
1342        async fn a_table_from_before_versions_is_upgraded_in_place() {
1343            let harness = Sqlite::new();
1344            let pool = sqlx::SqlitePool::connect(&harness.url()).await.unwrap();
1345            // The table as the first release created it.
1346            sqlx::query(
1347                "CREATE TABLE adk_website_drafts (
1348                    site TEXT NOT NULL,
1349                    kind TEXT NOT NULL,
1350                    id TEXT NOT NULL,
1351                    value TEXT NOT NULL,
1352                    PRIMARY KEY (site, kind, id)
1353                )",
1354            )
1355            .execute(&pool)
1356            .await
1357            .unwrap();
1358            let site = Uuid::new_v4();
1359            for (kind, id) in [
1360                ("content", "draft-10"),
1361                ("content", "draft-2"),
1362                ("charter", "charter-3"),
1363                ("charter_sign", "charter-sign-4"),
1364            ] {
1365                sqlx::query(
1366                    "INSERT INTO adk_website_drafts (site, kind, id, value) VALUES (?, ?, ?, ?)",
1367                )
1368                .bind(site.to_string())
1369                .bind(kind)
1370                .bind(id)
1371                .bind(serde_json::json!({ "id": id }).to_string())
1372                .execute(&pool)
1373                .await
1374                .unwrap();
1375            }
1376            let store = harness.open().await;
1377            let listed = store.list(site, DraftKind::Content).await.unwrap();
1378            assert_eq!(
1379                listed,
1380                vec![
1381                    StoredRecord {
1382                        id: "draft-2".into(),
1383                        version: 1,
1384                        value: serde_json::json!({ "id": "draft-2" })
1385                    },
1386                    StoredRecord {
1387                        id: "draft-10".into(),
1388                        version: 1,
1389                        value: serde_json::json!({ "id": "draft-10" })
1390                    },
1391                ],
1392                "earlier records read back at version 1, in number order"
1393            );
1394            assert!(
1395                store
1396                    .replace(site, DraftKind::Content, "draft-2", &serde_json::json!(2), 1)
1397                    .await
1398                    .unwrap()
1399            );
1400            let next =
1401                store.create(site, DraftKind::Content, &serde_json::json!(11)).await.unwrap();
1402            assert_eq!(next.id, "draft-11", "new ids continue after the stored ones");
1403            let charter =
1404                store.create(site, DraftKind::Charter, &serde_json::json!(4)).await.unwrap();
1405            assert_eq!(charter.id, "charter-4");
1406            // Migrating again changes nothing.
1407            let again = harness.open().await;
1408            assert_eq!(again.list(site, DraftKind::Content).await.unwrap().len(), 3);
1409            let sign =
1410                again.create(site, DraftKind::CharterSign, &serde_json::json!(5)).await.unwrap();
1411            assert_eq!(sign.id, "charter-sign-5");
1412        }
1413    }
1414
1415    #[test]
1416    fn a_stored_draft_reads_back_with_its_media() {
1417        let draft = Draft {
1418            change: Change {
1419                items: Vec::new(),
1420                media: vec![("content/a/b.png".into(), bytes::Bytes::from_static(&[0, 159, 255]))],
1421                entry: EntryPoint::WebEditor,
1422                proposer: "amina".into(),
1423                job: "content".into(),
1424                action_class: "publish".into(),
1425            },
1426            ids: Default::default(),
1427        };
1428        let stored = StoredDraft::of(&draft);
1429        let back: StoredDraft =
1430            serde_json::from_value(serde_json::to_value(&stored).unwrap()).unwrap();
1431        let read = back.into_draft().unwrap();
1432        assert_eq!(read.change.media, draft.change.media);
1433        assert_eq!(
1434            (read.change.proposer, read.change.entry),
1435            ("amina".into(), EntryPoint::WebEditor)
1436        );
1437    }
1438
1439    #[test]
1440    fn a_kind_reads_the_numbers_of_its_own_ids() {
1441        assert_eq!(DraftKind::Content.number("draft-12"), Some(12));
1442        assert_eq!(DraftKind::Charter.number("charter-sign-3"), None);
1443        assert_eq!(DraftKind::CharterSign.number("charter-sign-3"), Some(3));
1444        assert_eq!(DraftKind::Promotion.number("draft-1"), None);
1445    }
1446}