Skip to main content

ProjectionId

Struct ProjectionId 

Source
pub struct ProjectionId(/* private fields */);
Expand description

Names a read model within a projection store.

Distinct projections advance independently, so each needs its own checkpoint, and the id is that checkpoint’s key: a store keeps it byte for byte (PS-39).

Validated, like its siblings EventType and Tag, by the same rules plus one (VT-35, ADR-0082). There is no infallible way in, because two constructors enforcing different rules is the defect that makes an invalid value reachable through the weaker one.

§Examples

use happenstance_core::ProjectionId;

let id = ProjectionId::new("van_stock")?;
assert_eq!(id.as_str(), "van_stock");

A string does not become an id by conversion alone. There is no From<&str>, because an infallible door would bypass the rules:

ⓘ
use happenstance_core::ProjectionId;

let id: ProjectionId = "van_stock".into();

Backed by Cow<'static, str> rather than Box<str> so that from_static can build one in a const without allocating, the trade VT-32 records for EventType.

Implementations§

Source§

impl ProjectionId

Source

pub fn new(value: impl Into<String>) -> Result<Self, InvalidProjectionId>

Creates a projection identifier.

The value is kept exactly as given: nothing is trimmed, folded or normalised, so an accepted id’s as_str is byte for byte its input.

§Errors

Returns InvalidProjectionId, checking in this order, if the value is empty; longer than MAX_PROJECTION_ID_LEN bytes; contains a character in Unicode general category Cc or one of the explicit bidirectional formatting controls U+202A–U+202E or U+2066–U+2069, reporting whichever comes first; or begins with one of the reserved prefixes happenstance/ and sync/, compared as exact bytes. Cf in general is accepted, so the joiners U+200C and U+200D that Persian, Hindi and emoji sequences need are kept.

A sync/ id is built only by sync_watermark.

Source

pub const fn from_static(value: &'static str) -> Self

Creates a projection identifier from a string literal, validating at compile time.

Enforces exactly the rules new enforces — one function checks both — so a ProjectionId is always a validated value, with some of that validation having happened before the program ran.

§Panics

Panics if the value would be rejected by new. Where that panic surfaces depends on the call site, and the difference is sharp enough to be worth stating:

Call siteWhen the invalid value is caught
a free constcargo check, as error[E0080]
an associated const that is read somewherecargo build
an associated const that is never readnever
a let bindingat run time, as a panic

The third row is the one to design around: an associated const is evaluated lazily, so an invalid one that nothing reads survives check, clippy, build and test. Prefer a free const for anything whose validity you want the compiler to guarantee:

use happenstance_core::ProjectionId;

const VAN_STOCK: ProjectionId = ProjectionId::from_static("van_stock");

An invalid value at the same free const site is a compile error, and a reserved prefix is invalid:

ⓘ
use happenstance_core::ProjectionId;

const X: ProjectionId = ProjectionId::from_static("sync/x");

Spelled bare compile_fail rather than compile_fail,E0080: rustdoc on 1.97.1 silently ignores an error-code annotation it cannot match, so the stricter-looking spelling is the weaker check. It is also deliberately weaker than a trybuild snapshot — it does not pin the diagnostic — and ADR-0015 records that phase 6 owns the trybuild dependency decision. The passing example above it is the control: the two differ only in the literal, so the failure is the validator’s and nothing else’s.

Examples found in repository?
examples/rebuilding-read-models/src/main.rs (line 1075)
1075const STOCK_ON_HAND: ProjectionId = ProjectionId::from_static("stock_on_hand");
1076
1077impl StockOnHand {
1078    /// The view over every SKU.
1079    fn new() -> Self {
1080        Self {
1081            id: STOCK_ON_HAND,
1082            scope: Tags::empty(),
1083        }
1084    }
1085}
1086
1087impl Projection for StockOnHand {
1088    type Event = Fulfilment;
1089    type Store = SqliteProjectionStore;
1090    type Error = SqliteProjectionStoreError;
1091
1092    fn id(&self) -> &ProjectionId {
1093        &self.id
1094    }
1095
1096    fn scope(&self) -> &Tags {
1097        &self.scope
1098    }
1099
1100    async fn apply(
1101        &mut self,
1102        event: Delivered<Fulfilment>,
1103        batch: &mut SqliteBatch,
1104    ) -> Result<(), SqliteProjectionStoreError> {
1105        let (sku, delta) = match event.into_event() {
1106            Fulfilment::StockReceived { sku, quantity }
1107            | Fulfilment::OrderCancelled { sku, quantity, .. } => (sku, i64::from(quantity)),
1108            Fulfilment::OrderPlaced { sku, quantity, .. } => (sku, -i64::from(quantity)),
1109            Fulfilment::OrderDispatched { sku, .. } => (sku, 0),
1110        };
1111
1112        batch.push(
1113            "INSERT INTO stock_on_hand (sku, on_hand) VALUES (?1, ?2) \
1114             ON CONFLICT(sku) \
1115             DO UPDATE SET on_hand = stock_on_hand.on_hand + excluded.on_hand",
1116            [Value::Text(sku.into()), Value::Integer(delta)],
1117        );
1118
1119        Ok(())
1120    }
1121}
1122
1123/// Where each order has got to.
1124///
1125/// Unlike the shelf, this view writes an *absolute* value: the status is the
1126/// last one seen, not an accumulation, so replaying it from any checkpoint
1127/// lands on the same answer.
1128#[derive(Debug)]
1129struct OrderStatus {
1130    /// Which read model this is, within the projection store.
1131    id: ProjectionId,
1132    /// Every event, so the tags constrain nothing.
1133    scope: Tags,
1134}
1135
1136/// The order view's projection id.
1137const ORDER_STATUS: ProjectionId = ProjectionId::from_static("order_status");
1138
1139impl OrderStatus {
1140    /// The view over every order.
1141    fn new() -> Self {
1142        Self {
1143            id: ORDER_STATUS,
1144            scope: Tags::empty(),
1145        }
1146    }
1147}
1148
1149impl Projection for OrderStatus {
1150    type Event = Fulfilment;
1151    type Store = SqliteProjectionStore;
1152    type Error = SqliteProjectionStoreError;
1153
1154    fn id(&self) -> &ProjectionId {
1155        &self.id
1156    }
1157
1158    fn scope(&self) -> &Tags {
1159        &self.scope
1160    }
1161
1162    async fn apply(
1163        &mut self,
1164        event: Delivered<Fulfilment>,
1165        batch: &mut SqliteBatch,
1166    ) -> Result<(), SqliteProjectionStoreError> {
1167        let (order, status, sku, quantity) = match event.into_event() {
1168            Fulfilment::OrderPlaced {
1169                order,
1170                sku,
1171                quantity,
1172            } => (order, "placed", sku, quantity),
1173            Fulfilment::OrderDispatched {
1174                order,
1175                sku,
1176                quantity,
1177                ..
1178            } => (order, "dispatched", sku, quantity),
1179            Fulfilment::OrderCancelled {
1180                order,
1181                sku,
1182                quantity,
1183            } => (order, "cancelled", sku, quantity),
1184            // Nominated and ignored. The derived query is the event set crossed
1185            // with the scope, and this view's scope is empty, so a stock
1186            // receipt arrives here whether it is wanted or not — the checkpoint
1187            // still advances past it, which is what "the position considered"
1188            // means.
1189            Fulfilment::StockReceived { .. } => return Ok(()),
1190        };
1191
1192        batch.push(
1193            "INSERT INTO order_status (order_ref, status, sku, quantity) \
1194             VALUES (?1, ?2, ?3, ?4) \
1195             ON CONFLICT(order_ref) DO UPDATE SET status = excluded.status",
1196            [
1197                Value::Text(order.into()),
1198                Value::Text(status.to_owned()),
1199                Value::Text(sku.into()),
1200                Value::Integer(i64::from(quantity)),
1201            ],
1202        );
1203
1204        Ok(())
1205    }
1206}
1207
1208/// The upsert into the first table, and into the second.
1209///
1210/// Two constants rather than one `format!` over a table name, and the reason is
1211/// [`SqliteBatch::push`], which takes `&'static str`. Interpolating a
1212/// table name here was *safe* — it was a `&'static str` chosen by one of the
1213/// three constructors below and could never hold user input — but that safety
1214/// lived in a comment, and a comment is what the signature stopped accepting.
1215/// The two statements differ in one identifier, which is exactly the amount of
1216/// duplication that buys the property.
1217///
1218/// [`push_raw_sql`](SqliteBatch::push_raw_sql) is the escape hatch for
1219/// a statement whose *shape* is decided at run time — an `IN (…)` list sized by
1220/// how many keys are being written. This one's shape is not: only which of two
1221/// fixed statements runs is decided at run time, and that is a choice between
1222/// constants rather than a statement built from a value.
1223const UPSERT_DAILY_DISPATCHES: &str = "INSERT INTO daily_dispatches (day, dispatched) VALUES (?1, ?2) \
1224     ON CONFLICT(day) \
1225     DO UPDATE SET dispatched = daily_dispatches.dispatched + excluded.dispatched";
1226
1227/// The same statement against the backfill's own table. See
1228/// [`UPSERT_DAILY_DISPATCHES`] for why this is a second constant.
1229const UPSERT_DAILY_DISPATCHES_V2: &str = "INSERT INTO daily_dispatches_v2 (day, dispatched) VALUES (?1, ?2) \
1230     ON CONFLICT(day) \
1231     DO UPDATE SET dispatched = daily_dispatches_v2.dispatched + excluded.dispatched";
1232
1233/// The blue/green swap, run as the retiring view's reset batch.
1234///
1235/// No `DELETE` first: the drop takes blue's rows with it. A delete naming
1236/// `daily_dispatches` would be a hazard rather than a redundancy anywhere after
1237/// the rename, because the name by then belongs to green.
1238const PROMOTION: [&str; 2] = [
1239    "DROP TABLE daily_dispatches",
1240    "ALTER TABLE daily_dispatches_v2 RENAME TO daily_dispatches",
1241];
1242
1243/// The same swap with the new table's name mistyped, so it fails *after* the
1244/// drop has run — the one point at which a promotion split across two
1245/// transactions would already have committed blue's retirement.
1246const MISTYPED_PROMOTION: [&str; 2] = [
1247    "DROP TABLE daily_dispatches",
1248    "ALTER TABLE daily_dispatch_v2 RENAME TO daily_dispatches",
1249];
1250
1251/// How much went out each day, counted one of two ways.
1252///
1253/// One type with two configurations rather than two types, because the blue
1254/// and green halves of a rebuild differ in exactly the way a real one does:
1255/// the fold changed its mind about what it was counting, and everything else
1256/// stayed put.
1257#[derive(Debug)]
1258struct DailyDispatches {
1259    /// Which read model this is. **It does not change when the table is
1260    /// promoted** — the checkpoint is keyed by this name and the derived
1261    /// query, and renaming it to match the promoted table would discard the
1262    /// resume point.
1263    id: ProjectionId,
1264    /// Every event, so the tags constrain nothing.
1265    scope: Tags,
1266    /// The upsert this instance issues, and with it the table it writes into.
1267    upsert: &'static str,
1268    /// What one dispatch adds to its day.
1269    counting: Counting,
1270}
1271
1272/// What one dispatch adds to its day's total.
1273#[derive(Debug, Clone, Copy)]
1274enum Counting {
1275    /// One per order that went out.
1276    Orders,
1277    /// One per unit that went out.
1278    Units,
1279}
1280
1281/// The first attempt's projection id.
1282const DAILY_DISPATCHES: ProjectionId = ProjectionId::from_static("daily_dispatches");
1283
1284/// The replacement's projection id, kept across the promotion: the checkpoint
1285/// travels with the id, not with the table.
1286const DAILY_DISPATCHES_V2: ProjectionId = ProjectionId::from_static("daily_dispatches_v2");
1287
1288impl DailyDispatches {
1289    /// The first attempt: one per order.
1290    fn counting_orders() -> Self {
1291        Self {
1292            id: DAILY_DISPATCHES,
1293            scope: Tags::empty(),
1294            upsert: UPSERT_DAILY_DISPATCHES,
1295            counting: Counting::Orders,
1296        }
1297    }
1298
1299    /// The replacement, backfilled beside the first into its own table.
1300    fn counting_units() -> Self {
1301        Self {
1302            id: DAILY_DISPATCHES_V2,
1303            scope: Tags::empty(),
1304            upsert: UPSERT_DAILY_DISPATCHES_V2,
1305            counting: Counting::Units,
1306        }
1307    }
1308
1309    /// The replacement after the swap: the same id, the promoted table.
1310    fn promoted() -> Self {
1311        Self {
1312            id: DAILY_DISPATCHES_V2,
1313            scope: Tags::empty(),
1314            upsert: UPSERT_DAILY_DISPATCHES,
1315            counting: Counting::Units,
1316        }
1317    }
1318}
1319
1320impl Projection for DailyDispatches {
1321    type Event = Fulfilment;
1322    type Store = SqliteProjectionStore;
1323    type Error = SqliteProjectionStoreError;
1324
1325    fn id(&self) -> &ProjectionId {
1326        &self.id
1327    }
1328
1329    fn scope(&self) -> &Tags {
1330        &self.scope
1331    }
1332
1333    async fn apply(
1334        &mut self,
1335        event: Delivered<Fulfilment>,
1336        batch: &mut SqliteBatch,
1337    ) -> Result<(), SqliteProjectionStoreError> {
1338        let (day, delta) = match event.into_event() {
1339            Fulfilment::OrderDispatched { day, quantity, .. } => match self.counting {
1340                Counting::Orders => (day, 1),
1341                Counting::Units => (day, i64::from(quantity)),
1342            },
1343            // Nominated and ignored, for the reason `order_status` gives.
1344            Fulfilment::StockReceived { .. }
1345            | Fulfilment::OrderPlaced { .. }
1346            | Fulfilment::OrderCancelled { .. } => return Ok(()),
1347        };
1348
1349        // Which of the two constants runs is the whole of what this instance's
1350        // configuration decides. SQLite binds values and not identifiers, so a
1351        // table name can only ever reach a statement by being part of its text —
1352        // which is why the statement, and not the name, is the thing chosen.
1353        batch.push(self.upsert, [Value::Text(day), Value::Integer(delta)]);
1354
1355        Ok(())
1356    }
1357}
1358
1359/// The view that was written against a field the log does not carry.
1360///
1361/// It compiles, its query is well formed, and it nominates exactly the events
1362/// it means to. The disagreement is in the payload, and the payload is the one
1363/// thing no signature describes.
1364#[derive(Debug)]
1365struct Couriered {
1366    /// Which read model this is, within the projection store.
1367    id: ProjectionId,
1368    /// Every dispatch, so the tags constrain nothing.
1369    scope: Tags,
1370}
1371
1372/// The courier view's projection id.
1373const COURIERED: ProjectionId = ProjectionId::from_static("couriered");
More examples
Hide additional examples
examples/transfers-on-sqlite/src/main.rs (line 532)
532const ACCOUNT_BALANCE: ProjectionId = ProjectionId::from_static("account_balance");
examples/tickets-over-http/src/lib.rs (line 54)
54pub const PROJECTION: ProjectionId = ProjectionId::from_static("seat_holder");
examples/two-devices-one-seat/src/timeline.rs (line 59)
59const SEAT_TIMELINE: ProjectionId = ProjectionId::from_static("seat_timeline");
Source

pub fn sync_watermark(peer: StoreId) -> Self

The replication watermark for peer: sync/ followed by the peer’s StoreId as 32 lowercase hex digits, 37 bytes in all.

The only constructor of a sync/ id (SY-31, VT-35). Every other one refuses the prefix, so no application projection can collide with a watermark, and the reservation is enforced rather than advised: there is no unchecked constructor behind it.

The rendered format is part of VT-35 and frozen, because changing it orphans every persisted watermark. A peer restored from a backup re-mints its StoreId and so gets a new watermark, which is correct: a new incarnation is new history.

use happenstance_core::{ProjectionId, StoreId};

let peer = StoreId::from_bytes([0xab; 16]);
let watermark = ProjectionId::sync_watermark(peer);
assert_eq!(watermark.as_str(), "sync/abababababababababababababababab");
assert!(ProjectionId::new(watermark.as_str()).is_err());
Source

pub fn as_str(&self) -> &str

The identifier as a string slice.

Trait Implementations§

Source§

impl AsRef<str> for ProjectionId

Source§

fn as_ref(&self) -> &str

Converts this type into a shared reference of the (usually inferred) input type.
Source§

impl Borrow<str> for ProjectionId

Source§

fn borrow(&self) -> &str

Immutably borrows from an owned value. Read more
Source§

impl Clone for ProjectionId

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for ProjectionId

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for ProjectionId

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Eq for ProjectionId

Source§

impl FromStr for ProjectionId

Source§

type Err = InvalidProjectionId

The associated error which can be returned from parsing.
Source§

fn from_str(value: &str) -> Result<Self, Self::Err>

Parses a string s to return a value of this type. Read more
Source§

impl Hash for ProjectionId

Source§

fn hash<H: Hasher>(&self, state: &mut H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl Ord for ProjectionId

Source§

fn cmp(&self, other: &Self) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 (const: unstable) · Source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 (const: unstable) · Source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 (const: unstable) · Source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized,

Restrict a value to a certain interval. Read more
Source§

fn clamp_to<R>(self, range: R) -> Self
where Self: Sized, R: ClampBounds<Self>,

🔬This is a nightly-only experimental API. (clamp_to)
Restrict a value to a certain range. Read more
Source§

impl PartialEq for ProjectionId

Source§

fn eq(&self, other: &Self) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl PartialOrd for ProjectionId

Source§

fn partial_cmp(&self, other: &Self) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 (const: unstable) · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 (const: unstable) · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 (const: unstable) · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 (const: unstable) · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl TryFrom<&str> for ProjectionId

Source§

type Error = InvalidProjectionId

The type returned in the event of a conversion error.
Source§

fn try_from(value: &str) -> Result<Self, Self::Error>

Performs the conversion.
Source§

impl TryFrom<String> for ProjectionId

Source§

type Error = InvalidProjectionId

The type returned in the event of a conversion error.
Source§

fn try_from(value: String) -> Result<Self, Self::Error>

Performs the conversion.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.