-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathrt.rs
More file actions
1362 lines (1219 loc) · 50.1 KB
/
rt.rs
File metadata and controls
1362 lines (1219 loc) · 50.1 KB
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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#![deny(unsafe_op_in_unsafe_fn)]
use crate::query_builder::{FromWhere, HasCols, LeftSemiJoin, RawQuery, RightSemiJoin, Table as QbTable};
use crate::table::IndexAlgo;
use crate::{sys, AnonymousViewContext, IterBuf, ReducerContext, ReducerResult, SpacetimeType, Table, ViewContext};
use spacetimedb_lib::bsatn::EncodeError;
use spacetimedb_lib::db::raw_def::v10::{
CaseConversionPolicy, ExplicitNames as RawExplicitNames, RawModuleDefV10Builder,
};
pub use spacetimedb_lib::db::raw_def::v9::Lifecycle as LifecycleReducer;
use spacetimedb_lib::db::raw_def::v9::{RawIndexAlgorithm, TableType, ViewResultHeader};
use spacetimedb_lib::de::{self, Deserialize, DeserializeOwned, Error as _, SeqProductAccess};
use spacetimedb_lib::sats::typespace::TypespaceBuilder;
use spacetimedb_lib::sats::{impl_deserialize, impl_serialize, ProductTypeElement};
use spacetimedb_lib::ser::{Serialize, SerializeSeqProduct};
use spacetimedb_lib::{bsatn, AlgebraicType, ConnectionId, Identity, ProductType, RawModuleDef, Timestamp};
use spacetimedb_primitives::*;
use std::convert::Infallible;
use std::fmt;
use std::marker::PhantomData;
use std::sync::{Mutex, OnceLock};
pub use sys::raw::{BytesSink, BytesSource};
#[cfg(feature = "unstable")]
use crate::{ProcedureContext, ProcedureResult};
pub trait IntoVec<T> {
fn into_vec(self) -> Vec<T>;
}
impl<T> IntoVec<T> for Vec<T> {
fn into_vec(self) -> Vec<T> {
self
}
}
impl<T> IntoVec<T> for Option<T> {
fn into_vec(self) -> Vec<T> {
self.into_iter().collect()
}
}
/// The `sender` invokes `reducer` at `timestamp` and provides it with the given `args`.
///
/// Returns an invalid buffer on success
/// and otherwise the error is written into the fresh one returned.
pub fn invoke_reducer<'a, A: Args<'a>>(
reducer: impl Reducer<'a, A>,
ctx: &ReducerContext,
args: &'a [u8],
) -> Result<(), Box<str>> {
// Deserialize the arguments from a bsatn encoding.
let SerDeArgs(args) = bsatn::from_slice(args).expect("unable to decode args");
reducer.invoke(ctx, args)
}
#[cfg(feature = "unstable")]
pub fn invoke_procedure<'a, A: Args<'a>, Ret: IntoProcedureResult>(
procedure: impl Procedure<'a, A, Ret>,
ctx: &mut ProcedureContext,
args: &'a [u8],
) -> ProcedureResult {
// Deserialize the arguments from a bsatn encoding.
let SerDeArgs(args) = bsatn::from_slice(args).expect("unable to decode args");
let res = procedure.invoke(ctx, args);
res.to_result()
}
/// A trait for types representing the *execution logic* of a reducer.
#[expect(clippy::duplicated_attributes, reason = "false positive")]
#[diagnostic::on_unimplemented(
message = "invalid reducer signature",
label = "this reducer signature is not valid",
note = "",
note = "reducer signatures must match the following pattern:",
note = " `Fn(&ReducerContext, [T1, ...]) [-> Result<(), impl Display>]`",
note = "where each `Ti` type implements `SpacetimeType`.",
note = ""
)]
pub trait Reducer<'de, A: Args<'de>> {
fn invoke(&self, ctx: &ReducerContext, args: A) -> ReducerResult;
}
/// Invoke a caller-specific view.
/// Returns a BSATN encoded `Vec` of rows.
pub fn invoke_view<'a, A: Args<'a>, T: ViewReturn>(
view: impl View<'a, A, T>,
ctx: ViewContext,
args: &'a [u8],
) -> Vec<u8> {
// Deserialize the arguments from a bsatn encoding.
let SerDeArgs(args) = bsatn::from_slice(args).expect("unable to decode args");
let retn = view.invoke(&ctx, args);
let mut buf = IterBuf::take();
retn.to_writer(&mut buf).expect("unable to encode view return value");
std::mem::take(&mut *buf)
}
/// A trait for types representing the execution logic of a caller-specific view.
#[expect(clippy::duplicated_attributes, reason = "false positive")]
#[diagnostic::on_unimplemented(
message = "invalid view signature",
label = "this view signature is not valid",
note = "",
note = "view signatures must match:",
note = " `Fn(&ViewContext, [T1, ...]) -> Vec<Tn> | Option<Tn>`",
note = "where each `Ti` implements `SpacetimeType`.",
note = ""
)]
pub trait View<'de, A: Args<'de>, T: ViewReturn> {
fn invoke(&self, ctx: &ViewContext, args: A) -> T;
}
/// Invoke an anonymous view.
/// Returns a BSATN encoded `Vec` of rows.
pub fn invoke_anonymous_view<'a, A: Args<'a>, T: ViewReturn>(
view: impl AnonymousView<'a, A, T>,
ctx: AnonymousViewContext,
args: &'a [u8],
) -> Vec<u8> {
// Deserialize the arguments from a bsatn encoding.
let SerDeArgs(args) = bsatn::from_slice(args).expect("unable to decode args");
let retn = view.invoke(&ctx, args);
let mut buf = IterBuf::take();
retn.to_writer(&mut buf).expect("unable to encode view return value");
std::mem::take(&mut *buf)
}
/// A trait for types representing the execution logic of an anonymous view.
#[expect(clippy::duplicated_attributes, reason = "false positive")]
#[diagnostic::on_unimplemented(
message = "invalid anonymous view signature",
label = "this view signature is not valid",
note = "",
note = "anonymous view signatures must match:",
note = " `Fn(&AnonymousViewContext, [T1, ...]) -> Vec<Tn> | Option<Tn>`",
note = "where each `Ti` implements `SpacetimeType`.",
note = ""
)]
pub trait AnonymousView<'de, A: Args<'de>, T: ViewReturn> {
fn invoke(&self, ctx: &AnonymousViewContext, args: A) -> T;
}
/// A trait for types that can *describe* a callable function such as a reducer or view.
pub trait FnInfo: ExplicitNames {
/// The type of function to invoke.
type Invoke;
#[cfg_attr(
feature = "unstable",
doc = "One of [`FnKindReducer`], [`FnKindProcedure`] or [`FnKindView`]."
)]
#[cfg_attr(not(feature = "unstable"), doc = "Either [`FnKindReducer`] or [`FnKindView`].")]
///
/// Used as a type argument to [`ExportFunctionForScheduledTable`] and [`scheduled_typecheck`].
/// See <https://willcrichton.net/notes/defeating-coherence-rust/> for details on this technique.
type FnKind;
/// The name of the function.
const NAME: &'static str;
/// The lifecycle of the function, if there is one.
const LIFECYCLE: Option<LifecycleReducer> = None;
/// A description of the parameter names of the function.
const ARG_NAMES: &'static [Option<&'static str>];
/// The function to invoke.
const INVOKE: Self::Invoke;
/// The return type of this function.
/// Currently only implemented for views.
fn return_type(_ts: &mut impl TypespaceBuilder) -> Option<AlgebraicType> {
None
}
}
#[cfg(feature = "unstable")]
pub trait Procedure<'de, A: Args<'de>, Ret: IntoProcedureResult> {
fn invoke(&self, ctx: &mut ProcedureContext, args: A) -> Ret;
}
/// A trait of types representing the arguments of a reducer, procedure or view.
///
/// This does not include the context first argument,
/// only the client-provided args.
/// As such, the same trait can be used for all sorts of exported functions.
pub trait Args<'de>: Sized {
/// How many arguments does the reducer accept?
const LEN: usize;
/// Deserialize the arguments from the sequence `prod` which knows when there are next elements.
fn visit_seq_product<A: SeqProductAccess<'de>>(prod: A) -> Result<Self, A::Error>;
/// Serialize the arguments in `self` into the sequence `prod` according to the type `S`.
fn serialize_seq_product<S: SerializeSeqProduct>(&self, prod: &mut S) -> Result<(), S::Error>;
/// Returns the schema of the args for this function provided a `typespace`.
fn schema<I: FnInfo>(typespace: &mut impl TypespaceBuilder) -> ProductType;
}
/// A trait of types representing the result of executing a reducer.
#[diagnostic::on_unimplemented(
message = "`{Self}` is not a valid reducer return type",
note = "reducers cannot return values -- you can only return `()` or `Result<(), impl Display>`"
)]
pub trait IntoReducerResult {
/// Convert the result into form where there is no value
/// and the error message is a string.
fn into_result(self) -> Result<(), Box<str>>;
}
impl IntoReducerResult for () {
#[inline]
fn into_result(self) -> Result<(), Box<str>> {
Ok(self)
}
}
impl<E: fmt::Display> IntoReducerResult for Result<(), E> {
#[inline]
fn into_result(self) -> Result<(), Box<str>> {
self.map_err(|e| e.to_string().into())
}
}
#[cfg(feature = "unstable")]
#[diagnostic::on_unimplemented(
message = "The procedure return type `{Self}` does not implement `SpacetimeType`",
note = "if you own the type, try adding `#[derive(SpacetimeType)]` to its definition"
)]
pub trait IntoProcedureResult: SpacetimeType + Serialize {
#[inline]
fn to_result(&self) -> ProcedureResult {
bsatn::to_vec(&self).expect("Failed to serialize procedure result")
}
}
#[cfg(feature = "unstable")]
impl<T: SpacetimeType + Serialize> IntoProcedureResult for T {}
#[diagnostic::on_unimplemented(
message = "the first argument of a reducer must be `&ReducerContext`",
label = "first argument must be `&ReducerContext`"
)]
pub trait ReducerContextArg {
// a little hack used in the macro to make error messages nicer. it generates <T as ReducerContextArg>::_ITEM
#[doc(hidden)]
const _ITEM: () = ();
}
impl ReducerContextArg for &ReducerContext {}
/// A trait of types that can be an argument of a reducer.
#[diagnostic::on_unimplemented(
message = "the reducer argument `{Self}` does not implement `SpacetimeType`",
note = "if you own the type, try adding `#[derive(SpacetimeType)]` to its definition"
)]
pub trait ReducerArg {
// a little hack used in the macro to make error messages nicer. it generates <T as ReducerArg>::_ITEM
#[doc(hidden)]
const _ITEM: () = ();
}
impl<T: SpacetimeType> ReducerArg for T {}
#[cfg(feature = "unstable")]
#[diagnostic::on_unimplemented(
message = "the first argument of a procedure must be `&mut ProcedureContext`",
label = "first argument must be `&mut ProcedureContext`"
)]
pub trait ProcedureContextArg {
// a little hack used in the macro to make error messages nicer. it generates <T as ReducerContextArg>::_ITEM
#[doc(hidden)]
const _ITEM: () = ();
}
#[cfg(feature = "unstable")]
impl ProcedureContextArg for &mut ProcedureContext {}
/// A trait of types that can be an argument of a procedure.
#[cfg(feature = "unstable")]
#[diagnostic::on_unimplemented(
message = "the procedure argument `{Self}` does not implement `SpacetimeType`",
note = "if you own the type, try adding `#[derive(SpacetimeType)]` to its definition"
)]
pub trait ProcedureArg {
// a little hack used in the macro to make error messages nicer. it generates <T as ReducerArg>::_ITEM
#[doc(hidden)]
const _ITEM: () = ();
}
#[cfg(feature = "unstable")]
impl<T: SpacetimeType> ProcedureArg for T {}
#[diagnostic::on_unimplemented(
message = "The first parameter of a `#[view]` must be `&ViewContext` or `&AnonymousViewContext`"
)]
pub trait ViewContextArg {
#[doc(hidden)]
const _ITEM: () = ();
}
impl ViewContextArg for ViewContext {}
impl ViewContextArg for AnonymousViewContext {}
/// A trait of types that can be an argument of a view.
#[diagnostic::on_unimplemented(
message = "the view argument `{Self}` does not implement `SpacetimeType`",
note = "if you own the type, try adding `#[derive(SpacetimeType)]` to its definition"
)]
pub trait ViewArg {
#[doc(hidden)]
const _ITEM: () = ();
}
impl<T: SpacetimeType> ViewArg for T {}
/// A trait of types that can be the return type of a view.
#[diagnostic::on_unimplemented(message = "Views must return `Vec<T>` or `Option<T>` where `T` is a `SpacetimeType`")]
pub trait ViewReturn {
#[doc(hidden)]
const _ITEM: () = ();
fn to_writer(self, w: &mut Vec<u8>) -> Result<(), EncodeError>;
}
impl<T: SpacetimeType + Serialize> ViewReturn for Vec<T> {
fn to_writer(self, buf: &mut Vec<u8>) -> Result<(), EncodeError> {
bsatn::to_writer(buf, &ViewResultHeader::RowData)?;
bsatn::to_writer(buf, &self)
}
}
impl<T: SpacetimeType + Serialize> ViewReturn for Option<T> {
fn to_writer(self, buf: &mut Vec<u8>) -> Result<(), EncodeError> {
bsatn::to_writer(buf, &ViewResultHeader::RowData)?;
bsatn::to_writer(buf, self.as_slice())
}
}
impl<T: SpacetimeType + Serialize> ViewReturn for RawQuery<T> {
fn to_writer(self, buf: &mut Vec<u8>) -> Result<(), EncodeError> {
bsatn::to_writer(buf, &ViewResultHeader::RawSql(self.sql().to_string()))
}
}
impl<T: HasCols + SpacetimeType + Serialize> ViewReturn for QbTable<T> {
fn to_writer(self, buf: &mut Vec<u8>) -> Result<(), EncodeError> {
self.build().to_writer(buf)
}
}
impl<T: HasCols + SpacetimeType + Serialize> ViewReturn for FromWhere<T> {
fn to_writer(self, buf: &mut Vec<u8>) -> Result<(), EncodeError> {
self.build().to_writer(buf)
}
}
impl<L: HasCols + SpacetimeType + Serialize> ViewReturn for LeftSemiJoin<L> {
fn to_writer(self, buf: &mut Vec<u8>) -> Result<(), EncodeError> {
self.build().to_writer(buf)
}
}
impl<R: HasCols + SpacetimeType + Serialize, L: HasCols> ViewReturn for RightSemiJoin<R, L> {
fn to_writer(self, buf: &mut Vec<u8>) -> Result<(), EncodeError> {
self.build().to_writer(buf)
}
}
/// Map the correct dispatcher based on the `Ctx` type
pub struct ViewKind<Ctx> {
_marker: PhantomData<Ctx>,
}
pub trait ViewKindTrait {
type InvokeFn;
}
impl ViewKindTrait for ViewKind<ViewContext> {
type InvokeFn = ViewFn;
}
impl ViewKindTrait for ViewKind<AnonymousViewContext> {
type InvokeFn = AnonymousFn;
}
/// Invoke the correct dispatcher based on the `Ctx` type
pub struct ViewDispatcher<Ctx> {
_marker: PhantomData<Ctx>,
}
impl ViewDispatcher<ViewContext> {
#[inline]
pub fn invoke<'a, A, T, V>(view: V, ctx: ViewContext, args: &'a [u8]) -> Vec<u8>
where
A: Args<'a>,
T: ViewReturn,
V: View<'a, A, T>,
{
invoke_view(view, ctx, args)
}
}
impl ViewDispatcher<AnonymousViewContext> {
#[inline]
pub fn invoke<'a, A, T, V>(view: V, ctx: AnonymousViewContext, args: &'a [u8]) -> Vec<u8>
where
A: Args<'a>,
T: ViewReturn,
V: AnonymousView<'a, A, T>,
{
invoke_anonymous_view(view, ctx, args)
}
}
/// Register the correct dispatcher based on the `Ctx` type
pub struct ViewRegistrar<Ctx> {
_marker: PhantomData<Ctx>,
}
impl ViewRegistrar<ViewContext> {
#[inline]
pub fn register<'a, A, I, T, V>(view: V)
where
A: Args<'a>,
T: ViewReturn,
I: FnInfo<Invoke = ViewFn>,
V: View<'a, A, T>,
{
register_view::<A, I, T>(view)
}
}
impl ViewRegistrar<AnonymousViewContext> {
#[inline]
pub fn register<'a, A, I, T, V>(view: V)
where
A: Args<'a>,
T: ViewReturn,
I: FnInfo<Invoke = AnonymousFn>,
V: AnonymousView<'a, A, T>,
{
register_anonymous_view::<A, I, T>(view)
}
}
/// Assert that a reducer type-checks with a given type.
pub const fn scheduled_typecheck<'de, Row, FnKind>(_x: impl ExportFunctionForScheduledTable<'de, Row, FnKind>)
where
Row: SpacetimeType + Serialize + Deserialize<'de>,
{
core::mem::forget(_x);
}
/// Tacit marker argument to [`ExportFunctionForScheduledTable`] for reducers.
pub struct FnKindReducer {
_never: Infallible,
}
#[cfg(feature = "unstable")]
/// Tacit marker argument to [`ExportFunctionForScheduledTable`] for procedures.
///
/// Holds the procedure's return type in order to avoid an error due to an unconstrained type argument.
pub struct FnKindProcedure<Ret> {
_never: Infallible,
_ret_ty: PhantomData<fn() -> Ret>,
}
/// Tacit marker argument to [`ExportFunctionForScheduledTable`] for views.
///
/// Because views are never scheduled, we don't need to distinguish between anonymous or sender-identity views,
/// or to include their return type.
pub struct FnKindView {
_never: Infallible,
}
/// Trait bound for [`scheduled_typecheck`], which the [`crate::table`] macro generates to typecheck scheduled functions.
///
/// The `FnKind` parameter here is a coherence-defeating marker, which Will Crichton calls a "tacit parameter."
/// See <https://willcrichton.net/notes/defeating-coherence-rust/> for details on this technique.
#[cfg_attr(
feature = "unstable",
doc = "It will be one of [`FnKindReducer`] or [`FnKindProcedure`] in modules that compile successfully."
)]
#[cfg_attr(
not(feature = "unstable"),
doc = "It will be [`FnKindReducer`] in modules that compile successfully."
)]
///
/// It may be [`FnKindView`], but that will always fail to typecheck, as views cannot be used as scheduled functions.
#[diagnostic::on_unimplemented(
message = "invalid signature for scheduled table reducer or procedure",
note = "views cannot be scheduled",
note = "the scheduled function must take `{TableRow}` as its sole argument",
note = "e.g: `fn scheduled_reducer(ctx: &ReducerContext, arg: {TableRow})`",
// note = "or `fn scheduled_procedure(ctx: &mut ProcedureContext, arg: {TableRow})`"
)]
pub trait ExportFunctionForScheduledTable<'de, TableRow, FnKind> {}
impl<'de, TableRow: SpacetimeType + Serialize + Deserialize<'de>, F: Reducer<'de, (TableRow,)>>
ExportFunctionForScheduledTable<'de, TableRow, FnKindReducer> for F
{
}
#[cfg(feature = "unstable")]
impl<
'de,
TableRow: SpacetimeType + Serialize + Deserialize<'de>,
Ret: SpacetimeType + Serialize + Deserialize<'de>,
F: Procedure<'de, (TableRow,), Ret>,
> ExportFunctionForScheduledTable<'de, TableRow, FnKindProcedure<Ret>> for F
{
}
// the macro generates <T as SpacetimeType>::make_type::<DummyTypespace>
pub struct DummyTypespace;
impl TypespaceBuilder for DummyTypespace {
fn add(
&mut self,
_: std::any::TypeId,
_: Option<&'static str>,
_: impl FnOnce(&mut Self) -> spacetimedb_lib::AlgebraicType,
) -> spacetimedb_lib::AlgebraicType {
unreachable!()
}
}
#[diagnostic::on_unimplemented(
message = "the column type `{Self}` does not implement `SpacetimeType`",
note = "table column types all must implement `SpacetimeType`",
note = "if you own the type, try adding `#[derive(SpacetimeType)]` to its definition"
)]
pub trait TableColumn {
// a little hack used in the macro to make error messages nicer. it generates <T as TableColumn>::_ITEM
#[doc(hidden)]
const _ITEM: () = ();
}
impl<T: SpacetimeType> TableColumn for T {}
/// Assert that the primary_key column of a scheduled table is a u64.
pub const fn assert_scheduled_table_primary_key<T: ScheduledTablePrimaryKey>() {}
/// Assert that the primary_key column of an outbox table is a u64.
pub const fn assert_outbox_table_primary_key<T: OutboxTablePrimaryKey>() {}
/// Verify at compile time that a function has the correct signature for an outbox `on_result` reducer.
///
/// The reducer must accept `(OutboxRow, Result<T, String>)` as its user-supplied arguments:
/// `fn on_result(ctx: &ReducerContext, request: OutboxRow, result: Result<T, String>)`
pub const fn outbox_typecheck<'de, OutboxRow, T>(_x: impl Reducer<'de, (OutboxRow, Result<T, String>)>)
where
OutboxRow: spacetimedb_lib::SpacetimeType + Serialize + Deserialize<'de>,
T: spacetimedb_lib::SpacetimeType + Serialize + Deserialize<'de>,
{
core::mem::forget(_x);
}
mod sealed {
pub trait Sealed {}
}
#[diagnostic::on_unimplemented(
message = "scheduled table primary key must be a `u64`",
label = "should be `u64`, not `{Self}`"
)]
pub trait ScheduledTablePrimaryKey: sealed::Sealed {}
impl sealed::Sealed for u64 {}
impl ScheduledTablePrimaryKey for u64 {}
#[diagnostic::on_unimplemented(
message = "outbox table primary key must be a `u64`",
label = "should be `u64`, not `{Self}`"
)]
pub trait OutboxTablePrimaryKey: sealed::Sealed {}
impl OutboxTablePrimaryKey for u64 {}
/// Used in the last type parameter of `Reducer` to indicate that the
/// context argument *should* be passed to the reducer logic.
pub struct ContextArg;
/// A visitor providing a deserializer for a type `A: Args`.
struct ArgsVisitor<A> {
_marker: PhantomData<A>,
}
impl<'de, A: Args<'de>> de::ProductVisitor<'de> for ArgsVisitor<A> {
type Output = A;
fn product_name(&self) -> Option<&str> {
None
}
fn product_len(&self) -> usize {
A::LEN
}
fn product_kind(&self) -> de::ProductKind {
de::ProductKind::ReducerArgs
}
fn visit_seq_product<Acc: SeqProductAccess<'de>>(self, prod: Acc) -> Result<Self::Output, Acc::Error> {
A::visit_seq_product(prod)
}
fn visit_named_product<Acc: de::NamedProductAccess<'de>>(self, _prod: Acc) -> Result<Self::Output, Acc::Error> {
Err(Acc::Error::named_products_not_supported())
}
}
macro_rules! impl_reducer_procedure_view {
($($T1:ident $(, $T:ident)*)?) => {
impl_reducer_procedure_view!(@impl $($T1 $(, $T)*)?);
$(impl_reducer_procedure_view!($($T),*);)?
};
(@impl $($T:ident),*) => {
// Implement `Args` for the tuple type `($($T,)*)`.
impl<'de, $($T: SpacetimeType + Deserialize<'de> + Serialize),*> Args<'de> for ($($T,)*) {
const LEN: usize = impl_reducer_procedure_view!(@count $($T)*);
#[allow(non_snake_case)]
#[allow(unused)]
fn visit_seq_product<Acc: SeqProductAccess<'de>>(mut prod: Acc) -> Result<Self, Acc::Error> {
let vis = ArgsVisitor { _marker: PhantomData::<Self> };
// Counts the field number; only relevant for errors.
let i = 0;
// For every element in the product, deserialize.
$(
let $T = prod.next_element::<$T>()?.ok_or_else(|| de::Error::missing_field(i, None, &vis))?;
let i = i + 1;
)*
Ok(($($T,)*))
}
#[allow(non_snake_case)]
fn serialize_seq_product<Ser: SerializeSeqProduct>(&self, _prod: &mut Ser) -> Result<(), Ser::Error> {
// For every element in the product, serialize.
let ($($T,)*) = self;
$(_prod.serialize_element($T)?;)*
Ok(())
}
#[inline]
#[allow(non_snake_case, irrefutable_let_patterns)]
fn schema<Info: FnInfo>(_typespace: &mut impl TypespaceBuilder) -> ProductType {
// Extract the names of the arguments.
let [.., $($T),*] = Info::ARG_NAMES else { panic!() };
ProductType::new(vec![
$(ProductTypeElement {
name: $T.map(Into::into),
algebraic_type: <$T>::make_type(_typespace),
}),*
].into())
}
}
// Implement `Reducer<..., ContextArg>` for the tuple type `($($T,)*)`.
impl<'de, Func, Ret, $($T: SpacetimeType + Deserialize<'de> + Serialize),*> Reducer<'de, ($($T,)*)> for Func
where
Func: Fn(&ReducerContext, $($T),*) -> Ret,
Ret: IntoReducerResult
{
#[allow(non_snake_case)]
fn invoke(&self, ctx: &ReducerContext, args: ($($T,)*)) -> Result<(), Box<str>> {
let ($($T,)*) = args;
self(ctx, $($T),*).into_result()
}
}
#[cfg(feature = "unstable")]
impl<'de, Func, Ret, $($T: SpacetimeType + Deserialize<'de> + Serialize),*> Procedure<'de, ($($T,)*), Ret> for Func
where
Func: Fn(&mut ProcedureContext, $($T),*) -> Ret,
Ret: IntoProcedureResult,
{
#[allow(non_snake_case)]
fn invoke(&self, ctx: &mut ProcedureContext, args: ($($T,)*)) -> Ret {
let ($($T,)*) = args;
self(ctx, $($T),*)
}
}
// Implement `View<..., ViewContext>` for the tuple type `($($T,)*)`.
impl<'de, Func, Retn, $($T),*>
View<'de, ($($T,)*), Retn> for Func
where
$($T: SpacetimeType + Deserialize<'de> + Serialize,)*
Func: Fn(&ViewContext, $($T),*) -> Retn,
Retn: ViewReturn,
{
#[allow(non_snake_case)]
fn invoke(&self, ctx: &ViewContext, args: ($($T,)*)) -> Retn {
let ($($T,)*) = args;
self(ctx, $($T),*)
}
}
// Implement `View<..., AnonymousViewContext>` for the tuple type `($($T,)*)`.
impl<'de, Func, Retn, $($T),*>
AnonymousView<'de, ($($T,)*), Retn> for Func
where
$($T: SpacetimeType + Deserialize<'de> + Serialize,)*
Func: Fn(&AnonymousViewContext, $($T),*) -> Retn,
Retn: ViewReturn,
{
#[allow(non_snake_case)]
fn invoke(&self, ctx: &AnonymousViewContext, args: ($($T,)*)) -> Retn {
let ($($T,)*) = args;
self(ctx, $($T),*)
}
}
};
// Counts the number of elements in the tuple.
(@count $($T:ident)*) => {
0 $(+ impl_reducer_procedure_view!(@drop $T 1))*
};
(@drop $a:tt $b:tt) => { $b };
}
impl_reducer_procedure_view!(
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, AA, AB, AC, AD, AE, AF
);
/// Provides deserialization and serialization for any type `A: Args`.
struct SerDeArgs<A>(A);
impl_deserialize!(
[A: Args<'de>] SerDeArgs<A>,
de => de.deserialize_product(ArgsVisitor { _marker: PhantomData }).map(Self)
);
impl_serialize!(['de, A: Args<'de>] SerDeArgs<A>, (self, ser) => {
let mut prod = ser.serialize_seq_product(A::LEN)?;
self.0.serialize_seq_product(&mut prod)?;
prod.end()
});
/// A trait for types that can *describe* a row-level security policy.
pub trait RowLevelSecurityInfo {
/// The SQL expression for the row-level security policy.
const SQL: &'static str;
}
/// A function which will be registered by [`register_describer`] into [`DESCRIBERS`],
/// which will be called by [`__describe_module__`] to construct a module definition.
///
/// May be a closure over static data, so that e.g.
/// [`register_row_level_security`] doesn't need to take a type parameter.
/// Permitted by the type system to be a [`FnMut`] mutable closure,
/// since [`DESCRIBERS`] is in a [`Mutex`] anyways,
/// but will likely cause weird misbehaviors if a non-idempotent function is used.
trait DescriberFn: FnMut(&mut ModuleBuilder) + Send + 'static {}
impl<F: FnMut(&mut ModuleBuilder) + Send + 'static> DescriberFn for F {}
/// Registers into `DESCRIBERS` a function `f` to modify the module builder.
fn register_describer(f: impl DescriberFn) {
DESCRIBERS.lock().unwrap().push(Box::new(f))
}
/// Registers a describer for the `SpacetimeType` `T`.
pub fn register_reftype<T: SpacetimeType>() {
register_describer(|module| {
T::make_type(&mut module.inner);
})
}
/// Registers a describer for the `TableType` `T`.
pub fn register_table<T: Table>() {
register_describer(|module| {
let product_type_ref = *T::Row::make_type(&mut module.inner).as_ref().unwrap();
if let Some(schedule) = T::SCHEDULE {
module.inner.add_schedule(
T::TABLE_NAME,
schedule.scheduled_at_column,
schedule.reducer_or_procedure_name,
);
}
let mut table = module
.inner
.build_table(T::TABLE_NAME, product_type_ref)
.with_type(TableType::User)
.with_access(T::TABLE_ACCESS)
.with_event(T::IS_EVENT);
for &col in T::UNIQUE_COLUMNS {
table = table.with_unique_constraint(col);
}
for index in T::INDEXES {
table = table.with_index(index.algo.into(), index.source_name, index.accessor_name);
}
if let Some(primary_key) = T::PRIMARY_KEY {
table = table.with_primary_key(primary_key);
}
for &col in T::SEQUENCES {
table = table.with_column_sequence(col);
}
for col in T::get_default_col_values().iter_mut() {
table = table.with_default_column_value(col.col_id, col.value.clone())
}
table.finish();
if let Some(outbox) = T::OUTBOX {
module
.inner
.add_outbox(T::TABLE_NAME, outbox.remote_reducer_name, outbox.on_result_reducer_name);
}
module.inner.add_explicit_names(T::explicit_names());
})
}
impl From<IndexAlgo<'_>> for RawIndexAlgorithm {
fn from(algo: IndexAlgo<'_>) -> RawIndexAlgorithm {
match algo {
IndexAlgo::BTree { columns } => RawIndexAlgorithm::BTree {
columns: columns.iter().copied().collect(),
},
IndexAlgo::Hash { columns } => RawIndexAlgorithm::Hash {
columns: columns.iter().copied().collect(),
},
IndexAlgo::Direct { column } => RawIndexAlgorithm::Direct { column: column.into() },
}
}
}
/// Registers a describer for the reducer `I` with arguments `A`.
pub fn register_reducer<'a, A: Args<'a>, I: FnInfo<Invoke = ReducerFn>>(_: impl Reducer<'a, A>) {
register_describer(|module| {
let params = A::schema::<I>(&mut module.inner);
if let Some(lifecycle) = I::LIFECYCLE {
module.inner.add_lifecycle_reducer(lifecycle, I::NAME, params);
} else {
module.inner.add_reducer(I::NAME, params);
}
module.reducers.push(I::INVOKE);
module.inner.add_explicit_names(I::explicit_names());
})
}
#[cfg(feature = "unstable")]
pub fn register_procedure<'a, A, Ret, I>(_: impl Procedure<'a, A, Ret>)
where
A: Args<'a>,
Ret: SpacetimeType + Serialize,
I: FnInfo<Invoke = ProcedureFn>,
{
register_describer(|module| {
let params = A::schema::<I>(&mut module.inner);
let ret_ty = <Ret as SpacetimeType>::make_type(&mut module.inner);
module.inner.add_procedure(I::NAME, params, ret_ty);
module.procedures.push(I::INVOKE);
module.inner.add_explicit_names(I::explicit_names());
})
}
/// Registers a describer for the view `I` with arguments `A` and return type `Vec<T>`.
pub fn register_view<'a, A, I, T>(_: impl View<'a, A, T>)
where
A: Args<'a>,
I: FnInfo<Invoke = ViewFn>,
T: ViewReturn,
{
register_describer(|module| {
let params = A::schema::<I>(&mut module.inner);
let return_type = I::return_type(&mut module.inner).unwrap();
module
.inner
.add_view(I::NAME, module.views.len(), true, false, params, return_type);
module.views.push(I::INVOKE);
module.inner.add_explicit_names(I::explicit_names());
})
}
/// Registers a describer for the anonymous view `I` with arguments `A` and return type `Vec<T>`.
pub fn register_anonymous_view<'a, A, I, T>(_: impl AnonymousView<'a, A, T>)
where
A: Args<'a>,
I: FnInfo<Invoke = AnonymousFn>,
T: ViewReturn,
{
register_describer(|module| {
let params = A::schema::<I>(&mut module.inner);
let return_type = I::return_type(&mut module.inner).unwrap();
module
.inner
.add_view(I::NAME, module.views_anon.len(), true, true, params, return_type);
module.views_anon.push(I::INVOKE);
module.inner.add_explicit_names(I::explicit_names());
})
}
/// Registers a row-level security policy.
pub fn register_row_level_security(sql: &'static str) {
register_describer(|module| {
module.inner.add_row_level_security(sql);
})
}
/// Set the case conversion policy for this module.
///
/// This is called by the `#[spacetimedb::settings]` attribute macro.
/// Do not call directly; use the attribute instead:
///
/// ```ignore
/// #[spacetimedb::settings]
/// const CASE_CONVERSION_POLICY: CaseConversionPolicy = CaseConversionPolicy::SnakeCase;
/// ```
#[doc(hidden)]
pub fn register_case_conversion_policy(policy: CaseConversionPolicy) {
register_describer(move |module| {
module.inner.set_case_conversion_policy(policy);
})
}
/// A builder for a module.
#[derive(Default)]
pub struct ModuleBuilder {
/// The module definition.
inner: RawModuleDefV10Builder,
/// The reducers of the module.
reducers: Vec<ReducerFn>,
/// The procedures of the module.
#[cfg(feature = "unstable")]
procedures: Vec<ProcedureFn>,
/// The client specific views of the module.
views: Vec<ViewFn>,
/// The anonymous views of the module.
views_anon: Vec<AnonymousFn>,
}
// Not actually a mutex; because WASM is single-threaded this basically just turns into a refcell.
static DESCRIBERS: Mutex<Vec<Box<dyn DescriberFn>>> = Mutex::new(Vec::new());
/// A reducer function takes in `(ReducerContext, Args)`
/// and returns a result with a possible error message.
pub type ReducerFn = fn(&ReducerContext, &[u8]) -> ReducerResult;
static REDUCERS: OnceLock<Vec<ReducerFn>> = OnceLock::new();
#[cfg(feature = "unstable")]
pub type ProcedureFn = fn(&mut ProcedureContext, &[u8]) -> ProcedureResult;
#[cfg(feature = "unstable")]
static PROCEDURES: OnceLock<Vec<ProcedureFn>> = OnceLock::new();
/// A view function takes in `(ViewContext, Args)` and returns a Vec of bytes.
pub type ViewFn = fn(ViewContext, &[u8]) -> Vec<u8>;
static VIEWS: OnceLock<Vec<ViewFn>> = OnceLock::new();
/// An anonymous view function takes in `(AnonymousViewContext, Args)` and returns a Vec of bytes.
pub type AnonymousFn = fn(AnonymousViewContext, &[u8]) -> Vec<u8>;
static ANONYMOUS_VIEWS: OnceLock<Vec<AnonymousFn>> = OnceLock::new();
/// Called by the host when the module is initialized
/// to describe the module into a serialized form that is returned.
///
/// This is also the module's opportunity to ready `__call_reducer__`
/// (by writing the set of `REDUCERS`).
///
/// To `description`, a BSATN-encoded ModuleDef` should be written,.
/// For the time being, the definition of `ModuleDef` is not stabilized,
/// as it is being changed by the schema proposal.
///
/// The `ModuleDef` is used to define tables, constraints, indexes, reducers, etc.
/// This affords the module the opportunity
/// to define and, to a limited extent, alter the schema at initialization time,
/// including when modules are updated (re-publishing).
/// After initialization, the module cannot alter the schema.
#[unsafe(no_mangle)]
extern "C" fn __describe_module__(description: BytesSink) {
// Collect the `module`.
let mut module = ModuleBuilder::default();
for describer in &mut *DESCRIBERS.lock().unwrap() {
describer(&mut module)
}
// Serialize the module to bsatn.
let module_def = module.inner.finish();
let module_def = RawModuleDef::V10(module_def);
let bytes = bsatn::to_vec(&module_def).expect("unable to serialize typespace");
// Write the sets of reducers, procedures and views.
REDUCERS.set(module.reducers).ok().unwrap();
#[cfg(feature = "unstable")]
PROCEDURES.set(module.procedures).ok().unwrap();
VIEWS.set(module.views).ok().unwrap();
ANONYMOUS_VIEWS.set(module.views_anon).ok().unwrap();
// Write the bsatn data into the sink.
write_to_sink(description, &bytes);
}
// TODO(1.0): update `__call_reducer__` docs + for `BytesSink`.
/// Called by the host to execute a reducer
/// when the `sender` calls the reducer identified by `id` at `timestamp` with `args`.
///
/// The `sender_{0-3}` are the pieces of a `[u8; 32]` (`u256`) representing the sender's `Identity`.
/// They are encoded as follows (assuming `identity.to_byte_array(): [u8; 32]`):
/// - `sender_0` contains bytes `[0 ..8 ]`.
/// - `sender_1` contains bytes `[8 ..16]`.
/// - `sender_2` contains bytes `[16..24]`.
/// - `sender_3` contains bytes `[24..32]`.
///
/// Note that `to_byte_array` uses LITTLE-ENDIAN order! This matches most host systems.
///
/// The `conn_id_{0-1}` are the pieces of a `[u8; 16]` (`u128`) representing the callers's [`ConnectionId`].
/// They are encoded as follows (assuming `conn_id.as_le_byte_array(): [u8; 16]`):
/// - `conn_id_0` contains bytes `[0 ..8 ]`.
/// - `conn_id_1` contains bytes `[8 ..16]`.
///
/// Again, note that `to_byte_array` uses LITTLE-ENDIAN order! This matches most host systems.