1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
use proc_macro2::TokenStream;
use quote::quote;
use super::options::*;
/// Emitted only for `#[es_repo(snapshot)]` repos: two private helpers used by
/// `forget_in_op` and by the batch write paths' stale-snapshot refresh —
/// `__full_history_find_by_id_in_op` (loads an entity by replaying its full
/// event history, bypassing any stored snapshot) and
/// `__persist_snapshot_in_op` (writes `capture()`'s result for an entity with
/// no staged events, guarded so a concurrent writer wins).
pub struct SnapshotFns<'a> {
entity: &'a syn::Ident,
id: &'a syn::Ident,
table_name: &'a str,
events_table_name: &'a str,
snapshot_table_name: &'a str,
forgettable_table_name: Option<&'a str>,
}
impl<'a> SnapshotFns<'a> {
pub fn from(opts: &'a RepositoryOptions) -> Option<Self> {
let snapshot_table_name = opts.snapshot_table_name()?;
Some(Self {
entity: opts.entity(),
id: opts.id(),
table_name: opts.table_name(),
events_table_name: opts.events_table_name(),
snapshot_table_name,
forgettable_table_name: opts.forgettable_table_name(),
})
}
/// Goes inside `impl #repo { .. }`.
pub fn in_impl_tokens(&self) -> TokenStream {
let entity = self.entity;
let id_type = self.id;
let snapshot_tbl = self.snapshot_table_name;
let table_name = self.table_name;
let events_table_name = self.events_table_name;
let entity_name = entity.to_string();
let forgettable_tbl_arg = match self.forgettable_table_name {
Some(tbl) => quote! { forgettable_tbl = #tbl, },
None => quote! {},
};
let find_by_id_sql = format!("SELECT id FROM {table_name} WHERE id = $1");
// Bypasses the public `es_query!` wrapper (whose arms don't carry a
// `snapshot_fingerprint` override) and calls the underlying proc
// macro directly — this is the one place that needs the fingerprint
// forced to `NO_SNAPSHOT_FINGERPRINT` rather than the type's own.
let query_call = quote! {
es_entity::expand_es_query!(
entity = #entity,
#forgettable_tbl_arg
snapshot_tbl = #snapshot_tbl,
snapshot_fingerprint = es_entity::NO_SNAPSHOT_FINGERPRINT,
sql = #find_by_id_sql,
args = [id as &#id_type,]
)
};
// A stale row's own sequence can equal the head it is being
// refreshed to (its shape changed, but nothing new was appended
// since) — `>=` lets that refresh through; same-sequence,
// same-fingerprint rewrites are idempotent.
let persist_snapshot_query = format!(
"INSERT INTO {snapshot_tbl} (id, sequence, fingerprint, snapshot, first_recorded_at, recorded_at) \
SELECT $1, $2, $3, $4, COALESCE($5, COALESCE($6, NOW())), COALESCE($6, NOW()) \
WHERE (SELECT MAX(sequence) FROM {events_table_name} WHERE id = $1) = $2 \
ON CONFLICT (id) DO UPDATE SET sequence = EXCLUDED.sequence, fingerprint = EXCLUDED.fingerprint, \
snapshot = EXCLUDED.snapshot, first_recorded_at = EXCLUDED.first_recorded_at, recorded_at = EXCLUDED.recorded_at \
WHERE EXCLUDED.sequence >= {snapshot_tbl}.sequence \
RETURNING recorded_at"
);
let (payload_upsert_sql, payload_delete_sql) = match self.forgettable_table_name {
Some(tbl) => (
format!(
"INSERT INTO {tbl} (entity_id, sequence, payload) VALUES ($1, 0, $2) \
ON CONFLICT (entity_id, sequence) DO UPDATE SET payload = EXCLUDED.payload"
),
format!("DELETE FROM {tbl} WHERE entity_id = $1 AND sequence = 0"),
),
None => (String::new(), String::new()),
};
let payload_code = if self.forgettable_table_name.is_some() {
quote! {
match <<#entity as es_entity::EsEntity>::Snapshot as es_entity::EsSnapshot>::extract_forgettable_payloads(&state) {
Some(payload) => {
sqlx::query!(#payload_upsert_sql, id as &#id_type, payload)
.execute(op.as_executor())
.await?;
}
None => {
sqlx::query!(#payload_delete_sql, id as &#id_type)
.execute(op.as_executor())
.await?;
}
}
}
} else {
quote! {}
};
quote! {
async fn __full_history_find_by_id_in_op<'a, OP>(
&self,
op: OP,
id: &#id_type,
) -> Result<#entity, es_entity::RepoFault>
where
OP: es_entity::IntoOneTimeExecutor<'a>,
{
#query_call
.fetch_optional(op)
.await?
.ok_or_else(|| es_entity::NotFound::new(
#entity_name,
Some("id"),
{
use es_entity::ToNotFoundValueFallback;
es_entity::NotFoundValue(id).to_not_found_value()
},
).into())
}
/// Writes `capture()`'s result for an entity with no staged
/// events, guarded so a concurrent writer (including a `forget`
/// that staged its own erasure event) makes this a no-op rather
/// than an error. Errors if `entity` has unpersisted staged
/// events — persist them first.
///
/// Always `RepoFault`, never `RepoWriteError<CV>`: this upserts
/// the snapshot table by its own `id` primary key, classifying
/// nothing — there is no constraint here for a caller's own
/// `ConstraintViolation` to ever carry.
async fn __persist_snapshot_in_op<OP>(
&self,
op: &mut OP,
entity: &mut #entity,
) -> Result<bool, es_entity::RepoFault>
where
OP: es_entity::AtomicOperation + ?Sized,
{
if entity.events().any_new() {
return Err(errlanes::Fault::from(errlanes::Fatal::invariant(
"snapshot with unpersisted events",
)));
}
let state = match <#entity as es_entity::HeadSnapshot>::capture(&*entity) {
Some(state) => state,
None => return Ok(false),
};
let snapshot_json = es_entity::prelude::serde_json::to_value(&state)
.expect("Failed to serialize snapshot");
let head = entity.events().len_persisted() as i32;
let first = entity.events().entity_first_persisted_at();
let id = &entity.id;
let row = sqlx::query!(
#persist_snapshot_query,
id as &#id_type,
head,
<<#entity as es_entity::EsEntity>::Snapshot as es_entity::EsSnapshot>::FINGERPRINT,
snapshot_json,
first,
op.maybe_now(),
)
.fetch_optional(op.as_executor())
.await?;
match row {
Some(row) => {
#payload_code
entity.events_mut().compact_to_snapshot(
state,
row.recorded_at,
first.unwrap_or(row.recorded_at),
);
Ok(true)
}
None => Ok(false),
}
}
}
}
}