ingraph 0.1.0

A declaration-driven indexing framework: records and nodes are written as Rust types, and the storage rows, the dataflow between them and the GraphQL query surface are emitted from the declaration.
Documentation
//! **THE MONGODB LEDGER**: one collection per root family, one document per retired key.
//!
//! ```json
//! // __ig_retired_media
//! { "_id": "0193f2c1-…", "retired_second": 1756…, "retired_nanosecond": 0,
//!   "origin": "vanished", "late_tails": false }
//! ```
//!
//! # `ready` DOES NOTHING, and that is the honest implementation
//!
//! A MongoDB collection springs into existence on its first write, so there is no creation to
//! perform and none is performed. The verb still exists because the SEAM has it — a SQL ledger
//! genuinely must create its table — and answering `Ok` having done nothing is what the trait's own
//! note asks a store with no creation to do. Nothing is stubbed and nothing is pretended.
//!
//! # THE KEY IS TEXT, and the bound is asked HERE rather than widened
//!
//! `_id` holds the key's [`Display`](core::fmt::Display) rendering, read back through
//! [`FromStr`](core::str::FromStr). That is [`Registries::expose`](crate::Registries::expose)'s own
//! trade one module over, made for that door's reason: the SQL ledgers cross a key through
//! [`IdColumn`](crate::IdColumn), which is the vocabulary's own per-dialect storage seam and which
//! has no MongoDB dialect — there is no `sqlx::Database` here to project it through. Rather than
//! mint a second storage vocabulary for one backend, this door asks the two traits a text `_id`
//! actually needs, and asks them where they are needed: `RootKey` stays exactly as wide as it was,
//! and the SQL side pays nothing for a bound only this store reaches for.
//!
//! It is also the shape a MongoDB `_id` wants. A string `_id` is indexed, is comparable, and is
//! readable by a person opening the collection — and every id this framework admits renders to one
//! canonically and parses back from it, which is what `#[derive(ingraph::Id)]` writes.

use core::{marker::PhantomData, str::FromStr};

use bson::{Bson, Document, doc};
use mongodb::Database;
use smol_bytes::Utf8Bytes;

use crate::{
  Timestamp,
  drive::registry::{RetireOrigin, RootKey},
};

use super::{Landing, RetiredRow, RetiredStore, RetiredStoreError, RetiredTable, UnnameableFamily};

/// The field a MongoDB document's own key rides in — the driver's, not this framework's.
const ID: &str = "_id";

/// A field the ledger will not read — the wrong BSON type, where the driver's own accessor errors
/// carry the field's absence and this one carries its shape.
///
/// Its own type rather than one of `bson`'s, because the accessor that would have produced one is
/// not the accessor used: an integer field is read by matching both widths (see
/// [`integer`](MongoRetired::integer)), and neither `get_i32` nor `get_i64` is asked, so neither
/// has an error to hand over.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct MalformedField;

impl core::fmt::Display for MalformedField {
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    f.write_str("the field is absent or holds a type the ledger does not write")
  }
}

impl core::error::Error for MalformedField {}

/// **ONE ROOT FAMILY'S LEDGER, IN A MONGODB COLLECTION.**
///
/// It holds a [`Database`] rather than opening one, on the SQL ledgers' own posture: a deployment
/// whose records already live here hands over the handle it has.
pub struct MongoRetired<Root> {
  /// Where the documents go.
  database: Database,
  /// Which collection they go in — `__ig_retired_<family>`, the SAME name the SQL ledgers give
  /// their table, because a family's ledger is one thing whatever holds it.
  table: RetiredTable,
  /// The family's key type — never held, so the store is `Send + Sync` whatever the key is.
  root: PhantomData<fn() -> Root>,
}

impl<Root> core::fmt::Debug for MongoRetired<Root> {
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    f.debug_struct("MongoRetired")
      .field("collection", &self.table.name())
      .finish_non_exhaustive()
  }
}

impl<Root> Clone for MongoRetired<Root> {
  fn clone(&self) -> Self {
    Self {
      database: self.database.clone(),
      table: self.table.clone(),
      root: PhantomData,
    }
  }
}

impl<Root> MongoRetired<Root> {
  /// `family`'s ledger, in `database`.
  ///
  /// # Errors
  ///
  /// [`UnnameableFamily`], where `family` is not a bare identifier. A collection name has fewer
  /// hazards than a spliced table name, but the ledger's name is ONE name across the four engines —
  /// a family MongoDB would take and SQLite would refuse is a deployment that cannot move its
  /// ledger, so the rule is the same rule everywhere.
  pub fn new(database: Database, family: impl Into<Utf8Bytes>) -> Result<Self, UnnameableFamily> {
    Ok(Self {
      database,
      table: RetiredTable::new(family)?,
      root: PhantomData,
    })
  }

  /// The collection this ledger writes.
  #[inline]
  #[must_use]
  pub const fn table(&self) -> &RetiredTable {
    &self.table
  }

  /// The driver's handle on it.
  fn collection(&self) -> mongodb::Collection<Document> {
    self.database.collection::<Document>(self.table.name())
  }

  /// A refusal, wearing the verb it was refused at.
  fn refuse(&self, verb: &'static str, source: mongodb::error::Error) -> RetiredStoreError {
    RetiredStoreError::new(verb, self.table.named(), source)
  }
}

impl<Root> RetiredStore<Root> for MongoRetired<Root>
where
  Root: RootKey + core::fmt::Display + FromStr,
  <Root as FromStr>::Err: core::error::Error + Send + Sync + 'static,
{
  /// Nothing to create — see the [module note](self).
  fn ready(&self) -> Landing<'_, ()> {
    Box::pin(core::future::ready(Ok(())))
  }

  /// **ONE UPSERT**, whose `$set` is the ORIGIN alone.
  ///
  /// `upsert(true)` over a `$set` of `origin` and a `$setOnInsert` of everything else is exactly
  /// the SQL side's `ON CONFLICT DO UPDATE SET origin = …`: a first record writes the whole
  /// document, and a stronger-origin re-record moves the origin and leaves `at` and `late_tails`
  /// saying what they said. See the [module note](super) for the state machine's arm that rules it.
  fn record<'a>(&'a self, row: &'a RetiredRow<Root>) -> Landing<'a, ()> {
    Box::pin(async move {
      let filter = doc! { ID: row.key().to_string() };
      let update = doc! {
        "$set": { RetiredTable::ORIGIN: row.origin().as_str() },
        "$setOnInsert": {
          RetiredTable::RETIRED_SECOND: row.at().as_second(),
          RetiredTable::RETIRED_NANOSECOND: row.at().subsec_nanosecond(),
          RetiredTable::LATE_TAILS: row.late_tails(),
        },
      };
      self
        .collection()
        .update_one(filter, update)
        .upsert(true)
        .await
        .map(|_written| ())
        .map_err(|source| self.refuse("record", source))
    })
  }

  /// **ONE DELETE** — total on a key the collection does not hold, exactly as the seam asks.
  fn erase<'a>(&'a self, key: &'a Root) -> Landing<'a, ()> {
    Box::pin(async move {
      self
        .collection()
        .delete_one(doc! { ID: key.to_string() })
        .await
        .map(|_gone| ())
        .map_err(|source| self.refuse("erase", source))
    })
  }

  /// **EVERY DOCUMENT**, walked with `advance`/`deserialize_current` rather than as a stream — the
  /// read lane's own idiom one module over, and for its reason: the cursor's own two verbs need no
  /// `futures` combinator and no pinning ceremony.
  fn roll(&self) -> Landing<'_, Vec<RetiredRow<Root>>> {
    Box::pin(async move {
      let mut cursor = self
        .collection()
        .find(doc! {})
        .await
        .map_err(|source| self.refuse("roll", source))?;
      let mut rows = Vec::new();
      while cursor
        .advance()
        .await
        .map_err(|source| self.refuse("roll", source))?
      {
        let document = cursor
          .deserialize_current()
          .map_err(|source| self.refuse("roll", source))?;
        rows.push(self.read(&document)?);
      }
      Ok(rows)
    })
  }
}

impl<Root> MongoRetired<Root>
where
  Root: RootKey + core::fmt::Display + FromStr,
  <Root as FromStr>::Err: core::error::Error + Send + Sync + 'static,
{
  /// ONE DOCUMENT, READ BACK — the inverse of [`record`](RetiredStore::record)'s update.
  ///
  /// Every field is refused BY NAME rather than defaulted. A ledger whose documents are missing a
  /// field is a ledger somebody else has been writing, and answering `Idle` for a key whose
  /// retirement this deployment could not read would be the one failure mode a durable ledger
  /// exists to prevent.
  fn read(&self, document: &Document) -> Result<RetiredRow<Root>, RetiredStoreError> {
    let key = self.text(document, ID)?;
    let key = Root::from_str(&key).map_err(|refusal| self.malformed(ID, refusal))?;
    let second = self.integer(document, RetiredTable::RETIRED_SECOND)?;
    let nanosecond = self.integer(document, RetiredTable::RETIRED_NANOSECOND)?;
    let nanosecond = i32::try_from(nanosecond)
      .map_err(|refusal| self.malformed(RetiredTable::RETIRED_NANOSECOND, refusal))?;
    let at = Timestamp::from_parts(second, nanosecond)
      .map_err(|refusal| self.malformed(RetiredTable::RETIRED_SECOND, refusal))?;
    let origin = self.text(document, RetiredTable::ORIGIN)?;
    let late_tails = document
      .get_bool(RetiredTable::LATE_TAILS)
      .map_err(|refusal| self.malformed(RetiredTable::LATE_TAILS, refusal))?;
    Ok(RetiredRow::new(
      key,
      at,
      RetireOrigin::from(origin),
      late_tails,
    ))
  }

  /// One string field, or a refusal naming it.
  fn text(&self, document: &Document, field: &'static str) -> Result<String, RetiredStoreError> {
    document
      .get_str(field)
      .map(ToOwned::to_owned)
      .map_err(|refusal| self.malformed(field, refusal))
  }

  /// One integer field, widened — the driver stores an `i32` where it can and an `i64` where it
  /// must, and `retired_second` is written as an `i64` while `retired_nanosecond` fits in an `i32`,
  /// so a reader that demanded one width would refuse its own writes.
  fn integer(&self, document: &Document, field: &'static str) -> Result<i64, RetiredStoreError> {
    match document.get(field) {
      Some(Bson::Int64(value)) => Ok(*value),
      Some(Bson::Int32(value)) => Ok(i64::from(*value)),
      _ => Err(self.malformed(field, MalformedField)),
    }
  }

  /// A document this ledger will not read, wearing the field that stopped it.
  fn malformed(
    &self,
    field: &'static str,
    source: impl core::error::Error + Send + Sync + 'static,
  ) -> RetiredStoreError {
    RetiredStoreError::new(
      "roll",
      Utf8Bytes::from(format!("{table}.{field}", table = self.table.name())),
      source,
    )
  }
}