1use std::future::Future;
8use std::pin::Pin;
9use std::sync::Arc;
10
11use vantage_types::{EmptyEntity, Entity, Record};
12
13use crate::table::Table;
14use crate::traits::table_source::TableSource;
15use crate::write_context::WriteContext;
16
17#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
20pub enum Phase {
21 Normalize,
23 Populate,
25 Validate,
27}
28
29pub enum HookReturn {
31 Proceed,
33 Handled,
36}
37
38pub type BoxFuture<'r, X> = Pin<Box<dyn Future<Output = X> + Send + 'r>>;
40
41#[non_exhaustive]
53pub struct BeforeCx<'r, T: TableSource> {
54 pub record: &'r mut Record<T::Value>,
55 pub id: Option<&'r T::Id>,
56 pub stored: Option<&'r Record<T::Value>>,
57 pub patch: bool,
58 pub context: Option<&'r WriteContext>,
59 pub table: &'r Table<T, EmptyEntity>,
60}
61
62#[non_exhaustive]
66pub struct AfterCx<'r, T: TableSource> {
67 pub id: &'r T::Id,
68 pub record: &'r Record<T::Value>,
69 pub before: Option<&'r Record<T::Value>>,
70 pub context: Option<&'r WriteContext>,
71 pub table: &'r Table<T, EmptyEntity>,
72}
73
74#[non_exhaustive]
76pub struct DeleteCx<'r, T: TableSource> {
77 pub id: &'r T::Id,
78 pub record: &'r Record<T::Value>,
79 pub context: Option<&'r WriteContext>,
80 pub table: &'r Table<T, EmptyEntity>,
81}
82
83#[non_exhaustive]
86pub struct DeleteAllCx<'r, T: TableSource> {
87 pub context: Option<&'r WriteContext>,
88 pub table: &'r Table<T, EmptyEntity>,
89}
90
91pub type DeleteAllFn<T> = Arc<
93 dyn for<'r> Fn(DeleteAllCx<'r, T>) -> BoxFuture<'r, vantage_core::Result<()>> + Send + Sync,
94>;
95
96pub fn delete_all_hook<T, F>(f: F) -> DeleteAllFn<T>
98where
99 T: TableSource,
100 F: for<'r> Fn(DeleteAllCx<'r, T>) -> BoxFuture<'r, vantage_core::Result<()>>
101 + Send
102 + Sync
103 + 'static,
104{
105 Arc::new(f)
106}
107
108pub type BeforeFn<T> =
111 Arc<dyn for<'r> Fn(BeforeCx<'r, T>) -> BoxFuture<'r, vantage_core::Result<()>> + Send + Sync>;
112
113pub type BeforeDeleteFn<T> = Arc<
116 dyn for<'r> Fn(DeleteCx<'r, T>) -> BoxFuture<'r, vantage_core::Result<HookReturn>>
117 + Send
118 + Sync,
119>;
120
121pub type AfterFn<T> =
124 Arc<dyn for<'r> Fn(AfterCx<'r, T>) -> BoxFuture<'r, vantage_core::Result<()>> + Send + Sync>;
125
126pub fn before_hook<T, F>(f: F) -> BeforeFn<T>
128where
129 T: TableSource,
130 F: for<'r> Fn(BeforeCx<'r, T>) -> BoxFuture<'r, vantage_core::Result<()>>
131 + Send
132 + Sync
133 + 'static,
134{
135 Arc::new(f)
136}
137
138pub fn before_delete_hook<T, F>(f: F) -> BeforeDeleteFn<T>
140where
141 T: TableSource,
142 F: for<'r> Fn(DeleteCx<'r, T>) -> BoxFuture<'r, vantage_core::Result<HookReturn>>
143 + Send
144 + Sync
145 + 'static,
146{
147 Arc::new(f)
148}
149
150pub fn before_hook_sync<T: TableSource>(
154 f: impl Fn(&mut Record<T::Value>, Option<&WriteContext>) -> vantage_core::Result<()>
155 + Send
156 + Sync
157 + 'static,
158) -> BeforeFn<T> {
159 Arc::new(move |cx: BeforeCx<'_, T>| {
160 let outcome = f(cx.record, cx.context);
161 Box::pin(std::future::ready(outcome))
162 })
163}
164
165pub fn before_hook_sync_cx<T: TableSource>(
168 f: impl for<'r> Fn(BeforeCx<'r, T>) -> vantage_core::Result<()> + Send + Sync + 'static,
169) -> BeforeFn<T> {
170 Arc::new(move |cx: BeforeCx<'_, T>| Box::pin(std::future::ready(f(cx))))
171}
172
173pub fn before_delete_hook_sync<T: TableSource>(
176 f: impl Fn(&T::Id, Option<&WriteContext>) -> vantage_core::Result<()> + Send + Sync + 'static,
177) -> BeforeDeleteFn<T> {
178 Arc::new(move |cx: DeleteCx<'_, T>| {
179 let outcome = f(cx.id, cx.context).map(|()| HookReturn::Proceed);
180 Box::pin(std::future::ready(outcome))
181 })
182}
183
184pub fn after_hook<T, F>(f: F) -> AfterFn<T>
186where
187 T: TableSource,
188 F: for<'r> Fn(AfterCx<'r, T>) -> BoxFuture<'r, vantage_core::Result<()>>
189 + Send
190 + Sync
191 + 'static,
192{
193 Arc::new(f)
194}
195
196#[non_exhaustive]
200pub struct SelectCx<'r, T: TableSource> {
201 pub context: Option<&'r WriteContext>,
202 pub table: &'r Table<T, EmptyEntity>,
203}
204
205pub type SelectFn<T> =
207 Arc<dyn for<'r> Fn(SelectCx<'r, T>) -> BoxFuture<'r, vantage_core::Result<()>> + Send + Sync>;
208
209pub fn select_hook<T, F>(f: F) -> SelectFn<T>
211where
212 T: TableSource,
213 F: for<'r> Fn(SelectCx<'r, T>) -> BoxFuture<'r, vantage_core::Result<()>>
214 + Send
215 + Sync
216 + 'static,
217{
218 Arc::new(f)
219}
220
221#[non_exhaustive]
224pub struct LoadCx<'r, T: TableSource> {
225 pub id: &'r T::Id,
226 pub record: &'r mut Record<T::Value>,
227 pub context: Option<&'r WriteContext>,
228 pub table: &'r Table<T, EmptyEntity>,
229}
230
231pub type AfterLoadFn<T> =
233 Arc<dyn for<'r> Fn(LoadCx<'r, T>) -> BoxFuture<'r, vantage_core::Result<()>> + Send + Sync>;
234
235pub fn after_load_hook<T, F>(f: F) -> AfterLoadFn<T>
237where
238 T: TableSource,
239 F: for<'r> Fn(LoadCx<'r, T>) -> BoxFuture<'r, vantage_core::Result<()>> + Send + Sync + 'static,
240{
241 Arc::new(f)
242}
243
244pub fn after_load_hook_sync<T: TableSource>(
247 f: impl Fn(&mut Record<T::Value>, Option<&WriteContext>) -> vantage_core::Result<()>
248 + Send
249 + Sync
250 + 'static,
251) -> AfterLoadFn<T> {
252 Arc::new(move |cx: LoadCx<'_, T>| {
253 let outcome = f(cx.record, cx.context);
254 Box::pin(std::future::ready(outcome))
255 })
256}
257
258#[non_exhaustive]
262pub enum Hook<T: TableSource> {
263 BeforeSelect(SelectFn<T>),
281 AfterLoad(AfterLoadFn<T>),
288 BeforeInsert(Phase, BeforeFn<T>),
289 BeforeUpdate(Phase, BeforeFn<T>),
290 BeforeSave(Phase, BeforeFn<T>),
291 BeforeDelete(BeforeDeleteFn<T>),
292 AfterInsert(AfterFn<T>),
293 AfterUpdate(AfterFn<T>),
294 AfterSave(AfterFn<T>),
295 AfterDelete(AfterFn<T>),
296 BeforeDeleteAll(DeleteAllFn<T>),
300 AfterDeleteAll(DeleteAllFn<T>),
301}
302
303#[derive(Clone)]
306pub struct Hooks<T: TableSource> {
307 pub(crate) before_select: Vec<SelectFn<T>>,
308 pub(crate) after_load: Vec<AfterLoadFn<T>>,
309 pub(crate) before_insert: Vec<(Phase, BeforeFn<T>)>,
310 pub(crate) before_update: Vec<(Phase, BeforeFn<T>)>,
311 pub(crate) before_delete: Vec<BeforeDeleteFn<T>>,
312 pub(crate) after_insert: Vec<AfterFn<T>>,
313 pub(crate) after_update: Vec<AfterFn<T>>,
314 pub(crate) after_delete: Vec<AfterFn<T>>,
315 pub(crate) before_delete_all: Vec<DeleteAllFn<T>>,
316 pub(crate) after_delete_all: Vec<DeleteAllFn<T>>,
317}
318
319impl<T: TableSource> Default for Hooks<T> {
320 fn default() -> Self {
321 Self {
322 before_select: Vec::new(),
323 after_load: Vec::new(),
324 before_insert: Vec::new(),
325 before_update: Vec::new(),
326 before_delete: Vec::new(),
327 after_insert: Vec::new(),
328 after_update: Vec::new(),
329 after_delete: Vec::new(),
330 before_delete_all: Vec::new(),
331 after_delete_all: Vec::new(),
332 }
333 }
334}
335
336impl<T: TableSource, E: Entity<T::Value>> Table<T, E> {
337 pub(crate) fn before_insert_hooks(&self) -> &[(Phase, BeforeFn<T>)] {
338 &self.hooks.before_insert
339 }
340 pub(crate) fn before_update_hooks(&self) -> &[(Phase, BeforeFn<T>)] {
341 &self.hooks.before_update
342 }
343 pub(crate) fn before_delete_hooks(&self) -> &[BeforeDeleteFn<T>] {
344 &self.hooks.before_delete
345 }
346 pub(crate) fn after_insert_hooks(&self) -> &[AfterFn<T>] {
347 &self.hooks.after_insert
348 }
349 pub(crate) fn after_update_hooks(&self) -> &[AfterFn<T>] {
350 &self.hooks.after_update
351 }
352 pub(crate) fn after_delete_hooks(&self) -> &[AfterFn<T>] {
353 &self.hooks.after_delete
354 }
355 pub(crate) fn before_delete_all_hooks(&self) -> &[DeleteAllFn<T>] {
356 &self.hooks.before_delete_all
357 }
358 pub(crate) fn after_delete_all_hooks(&self) -> &[DeleteAllFn<T>] {
359 &self.hooks.after_delete_all
360 }
361
362 pub fn add_hook(&mut self, hook: Hook<T>) {
366 let hooks = &mut self.hooks;
367 match hook {
368 Hook::BeforeSelect(f) => hooks.before_select.push(f),
369 Hook::AfterLoad(f) => hooks.after_load.push(f),
370 Hook::BeforeInsert(phase, f) => push_phased(&mut hooks.before_insert, phase, f),
371 Hook::BeforeUpdate(phase, f) => push_phased(&mut hooks.before_update, phase, f),
372 Hook::BeforeSave(phase, f) => {
373 push_phased(&mut hooks.before_insert, phase, f.clone());
374 push_phased(&mut hooks.before_update, phase, f);
375 }
376 Hook::BeforeDelete(f) => hooks.before_delete.push(f),
377 Hook::AfterInsert(f) => hooks.after_insert.push(f),
378 Hook::AfterUpdate(f) => hooks.after_update.push(f),
379 Hook::AfterSave(f) => {
380 hooks.after_insert.push(f.clone());
381 hooks.after_update.push(f);
382 }
383 Hook::AfterDelete(f) => hooks.after_delete.push(f),
384 Hook::BeforeDeleteAll(f) => hooks.before_delete_all.push(f),
385 Hook::AfterDeleteAll(f) => hooks.after_delete_all.push(f),
386 }
387 }
388
389 pub fn with_hook(mut self, hook: Hook<T>) -> Self {
391 self.add_hook(hook);
392 self
393 }
394
395 pub async fn check_read(&self) -> vantage_core::Result<()> {
400 if self.hooks.before_select.is_empty() {
401 return Ok(());
402 }
403 let context = WriteContext::current();
404 let table = self.as_entity_erased();
405 for hook in &self.hooks.before_select {
406 hook(SelectCx {
407 context: context.as_ref(),
408 table,
409 })
410 .await?;
411 }
412 Ok(())
413 }
414
415 pub async fn finish_read(
419 &self,
420 id: &T::Id,
421 record: &mut Record<T::Value>,
422 ) -> vantage_core::Result<()> {
423 self.run_after_load(id, record).await?;
424 self.apply_lazy_expressions(record).await
425 }
426
427 pub(crate) async fn run_after_load(
428 &self,
429 id: &T::Id,
430 record: &mut Record<T::Value>,
431 ) -> vantage_core::Result<()> {
432 if self.hooks.after_load.is_empty() {
433 return Ok(());
434 }
435 let context = WriteContext::current();
436 let table = self.as_entity_erased();
437 for hook in &self.hooks.after_load {
438 hook(LoadCx {
439 id,
440 record: &mut *record,
441 context: context.as_ref(),
442 table,
443 })
444 .await?;
445 }
446 Ok(())
447 }
448
449 pub(crate) fn reads_rewrite_rows(&self) -> bool {
450 !self.hooks.after_load.is_empty() || !self.lazy_expressions.is_empty()
451 }
452}
453
454fn push_phased<T: TableSource>(
457 hooks: &mut Vec<(Phase, BeforeFn<T>)>,
458 phase: Phase,
459 f: BeforeFn<T>,
460) {
461 hooks.push((phase, f));
462 hooks.sort_by_key(|(p, _)| *p);
463}