-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathlib.rs
More file actions
1685 lines (1586 loc) · 59.4 KB
/
lib.rs
File metadata and controls
1685 lines (1586 loc) · 59.4 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
#![doc = include_str!("../README.md")]
// ^ if you are working on docs, go read the top comment of README.md please.
use core::cell::{Cell, LazyCell, OnceCell, RefCell};
use core::ops::Deref;
use spacetimedb_lib::bsatn;
use std::rc::Rc;
#[cfg(feature = "unstable")]
pub mod http;
pub mod log_stopwatch;
mod logger;
#[cfg(feature = "rand08")]
mod rng;
#[doc(hidden)]
pub mod rt;
#[doc(hidden)]
pub mod table;
#[doc(hidden)]
pub use spacetimedb_query_builder as query_builder;
pub use log;
#[cfg(feature = "rand")]
pub use rand08 as rand;
#[cfg(feature = "rand")]
use rand08::RngCore;
#[cfg(feature = "rand08")]
pub use rng::StdbRng;
pub use sats::SpacetimeType;
#[doc(hidden)]
pub use spacetimedb_bindings_macro::__TableHelper;
pub use spacetimedb_bindings_sys as sys;
pub use spacetimedb_lib;
pub use spacetimedb_lib::de::{Deserialize, DeserializeOwned};
pub use spacetimedb_lib::sats;
pub use spacetimedb_lib::ser::Serialize;
pub use spacetimedb_lib::AlgebraicValue;
pub use spacetimedb_lib::ConnectionId;
// `FilterableValue` re-exported purely for rustdoc.
pub use spacetimedb_lib::FilterableValue;
pub use spacetimedb_lib::Identity;
pub use spacetimedb_lib::ScheduleAt;
pub use spacetimedb_lib::TimeDuration;
pub use spacetimedb_lib::Timestamp;
pub use spacetimedb_lib::Uuid;
pub use spacetimedb_primitives::TableId;
pub use sys::Errno;
pub use table::{
AutoIncOverflow, PointIndex, PointIndexReadOnly, RangedIndex, RangedIndexReadOnly, Table, TryInsertError,
UniqueColumn, UniqueColumnReadOnly, UniqueConstraintViolation,
};
pub type ReducerResult = core::result::Result<(), Box<str>>;
pub type ProcedureResult = Vec<u8>;
pub use spacetimedb_bindings_macro::duration;
/// Declares a table with a particular row type.
///
/// This attribute is applied to a struct type with named fields.
/// This derives [`Serialize`], [`Deserialize`], [`SpacetimeType`], and [`Debug`] for the annotated struct.
///
/// Elements of the struct type are NOT automatically inserted into any global table.
/// They are regular structs, with no special behavior.
/// In particular, modifying them does not automatically modify the database!
///
/// Instead, a type implementing [`Table<Row = Self>`] is generated. This can be looked up in a [`ReducerContext`]
/// using `ctx.db.{table_name}()`. This type represents a handle to a database table, and can be used to
/// iterate and modify the table's elements. It is a view of the entire table -- the entire set of rows at the time of the reducer call.
///
/// # Example
///
/// ```ignore
/// use spacetimedb::{table, ReducerContext};
///
/// #[table(name = user, public,
/// index(name = popularity_and_username, btree(columns = [popularity, username])),
/// )]
/// pub struct User {
/// #[auto_inc]
/// #[primary_key]
/// pub id: u32,
/// #[unique]
/// pub username: String,
/// #[index(btree)]
/// pub popularity: u32,
/// }
///
/// fn demo(ctx: &ReducerContext) {
/// // Use the name of the table to get a struct
/// // implementing `spacetimedb::Table<Row = User>`.
/// let user: user__TableHandle = ctx.db.user();
///
/// // You can use methods from `spacetimedb::Table`
/// // on the table.
/// log::debug!("User count: {}", user.count());
/// for user in user.iter() {
/// log::debug!("{:?}", user);
/// }
///
/// // For every `#[index(btree)]`, the table has an extra method
/// // for getting a corresponding `spacetimedb::BTreeIndex`.
/// let by_popularity: RangedIndex<_, (u32,), _> =
/// user.popularity();
/// for popular_user in by_popularity.filter(95..) {
/// log::debug!("Popular user: {:?}", popular_user);
/// }
///
/// // There are similar methods for multi-column indexes.
/// let by_popularity_and_username: RangedIndex<_, (u32, String), _> = user.popularity_and_username();
/// for popular_user in by_popularity.filter((100, "a"..)) {
/// log::debug!("Popular user whose name starts with 'a': {:?}", popular_user);
/// }
///
/// // For every `#[unique]` or `#[primary_key]` field,
/// // the table has an extra method that allows getting a
/// // corresponding `spacetimedb::UniqueColumn`.
/// let by_username: spacetimedb::UniqueColumn<_, String, _> = user.id();
/// by_username.delete(&"test_user".to_string());
/// }
/// ```
///
/// See [`Table`], [`RangedIndex`], and [`UniqueColumn`] for more information on the methods available on these types.
///
/// # Browsing generated documentation
///
/// The `#[table]` macro generates different APIs depending on the contents of your table.
///
/// To browse the complete generated API for your tables, run `cargo doc` in your SpacetimeDB module project. Navigate to `[YOUR PROJECT/target/doc/spacetime_module/index.html` in your file explorer, and right click -> open it in a web browser.
///
/// For the example above, we would see three items:
/// - A struct `User`. This is the struct you declared. It stores rows of the table `user`.
/// - A struct `user__TableHandle`. This is an opaque handle that allows you to interact with the table `user`.
/// - A trait `user` containing a single `fn user(&self) -> user__TableHandle`.
/// This trait is implemented for the `db` field of a [`ReducerContext`], allowing you to get a
/// `user__TableHandle` using `ctx.db.user()`.
///
/// # Macro arguments
///
/// The `#[table(...)]` attribute accepts any number of the following arguments, separated by commas.
///
/// Multiple `table` annotations can be present on the same type. This will generate
/// multiple tables of the same row type, but with different names.
///
/// ### `name`
///
/// Specify the name of the table in the database. The name can be any valid Rust identifier.
///
/// The table name is used to get a handle to the table from a [`ReducerContext`].
/// For a table *table*, use `ctx.db.{table}()` to do this.
/// For example:
/// ```ignore
/// #[table(name = user)]
/// pub struct User {
/// #[auto_inc]
/// #[primary_key]
/// pub id: u32,
/// #[unique]
/// pub username: String,
/// #[index(btree)]
/// pub popularity: u32,
/// }
/// #[reducer]
/// fn demo(ctx: &ReducerContext) {
/// let user: user__TableHandle = ctx.db.user();
/// }
/// ```
///
/// ### `public` and `private`
///
/// Tables are private by default. This means that clients cannot read their contents
/// or see that they exist.
///
/// If you'd like to make your table publicly accessible by clients,
/// put `public` in the macro arguments (e.g.
/// `#[spacetimedb::table(public)]`). You can also specify `private` if
/// you'd like to be specific.
///
/// This is fully separate from Rust's module visibility
/// system; `pub struct` or `pub(crate) struct` do not affect the table visibility, only
/// the visibility of the items in your own source code.
///
/// ### `index(...)`
///
/// You can specify an index on one or more of the table's columns with the syntax:
/// `index(name = my_index, btree(columns = [a, b, c]))`
///
/// You can also just put `#[index(btree)]` on the field itself if you only need
/// a single-column index; see column attributes below.
///
/// A table may declare any number of indexes.
///
/// You can use indexes to efficiently [`filter`](crate::RangedIndex::filter) and
/// [`delete`](crate::RangedIndex::delete) rows. This is encapsulated in the struct [`RangedIndex`].
///
/// For a table *table* and an index *index*, use:
/// ```text
/// ctx.db.{table}().{index}()
/// ```
/// to get a [`RangedIndex`] for a [`ReducerContext`].
///
/// For example:
/// ```ignore
/// let by_id_and_username: spacetimedb::RangedIndex<_, (u32, String), _> =
/// ctx.db.user().by_id_and_username();
/// ```
///
/// ### `scheduled(reducer_name)`
///
/// Used to declare a [scheduled reducer](macro@crate::reducer#scheduled-reducers).
///
/// The annotated struct type must have at least the following fields:
/// - `scheduled_id: u64`
/// - [`scheduled_at: ScheduleAt`](crate::ScheduleAt)
///
/// # Column (field) attributes
///
/// ### `#[auto_inc]`
///
/// Creates an auto-increment constraint.
///
/// When a row is inserted with the annotated field set to `0` (zero),
/// the sequence is incremented, and this value is used instead.
///
/// Can only be used on numeric types.
///
/// May be combined with indexes or unique constraints.
///
/// Note that using `#[auto_inc]` on a field does not also imply `#[primary_key]` or `#[unique]`.
/// If those semantics are desired, those attributes should also be used.
///
/// When `#[auto_inc]` is combined with a unique key,
/// be wary not to manually insert values larger than the allocated sequence value.
/// In this case, the sequence will eventually catch up, allocate a value that's already present,
/// and cause a unique constraint violation.
///
/// ### `#[unique]`
///
/// Creates an unique constraint and index for the annotated field.
///
/// You can [`find`](crate::UniqueColumn::find), [`update`](crate::UniqueColumn::update),
/// and [`delete`](crate::UniqueColumn::delete) rows by their unique columns.
/// This is encapsulated in the struct [`UniqueColumn`].
///
/// For a table *table* and a column *column*, use:
/// ```text
/// ctx.db.{table}().{column}()`
/// ```
/// to get a [`UniqueColumn`] from a [`ReducerContext`].
///
/// For example:
/// ```ignore
/// let by_username: spacetimedb::UniqueColumn<_, String, _> = ctx.db.user().username();
/// ```
///
/// When there is a unique column constraint on the table, insertion can fail if a uniqueness constraint is violated.
/// If we insert two rows which have the same value of a unique column, the second will fail.
/// This will be via a panic with [`Table::insert`] or via a `Result::Err` with [`Table::try_insert`].
///
/// For example:
/// ```no_run
/// # #[cfg(target_arch = "wasm32")] mod demo {
/// use spacetimedb::{
/// table,
/// reducer,
/// ReducerContext,
/// // Make sure to import the `Table` trait to use `insert` or `try_insert`.
/// Table
/// };
///
/// type CountryCode = String;
///
/// #[table(name = country)]
/// struct Country {
/// #[unique]
/// code: CountryCode,
/// national_bird: String
/// }
///
/// #[reducer]
/// fn insert_unique_demo(ctx: &ReducerContext) {
/// let result = ctx.db.country().try_insert(Country {
/// code: "AU".into(), national_bird: "Emu".into()
/// });
/// assert!(result.is_ok());
///
/// let result = ctx.db.country().try_insert(Country {
/// code: "AU".into(), national_bird: "Great Egret".into()
/// // Whoops, this was Austria's national bird, not Australia's.
/// // We should have used the country code "AT", not "AU".
/// });
/// // since there's already a country in the database with the code "AU",
/// // SpacetimeDB gives us an error.
/// assert!(result.is_err());
///
/// // The following line would panic, since we use `insert` rather than `try_insert`.
/// // let result = ctx.db.country().insert(Country { code: "CN".into(), national_bird: "Blue Magpie".into() });
///
/// // If we wanted to *update* the row for Australia, we can use the `update` method of `UniqueIndex`.
/// // The following line will succeed:
/// ctx.db.country().code().update(Country {
/// code: "AU".into(), national_bird: "Australian Emu".into()
/// });
/// }
/// # }
/// ```
///
/// ### `#[primary_key]`
///
/// Implies `#[unique]`. Also generates additional methods client-side for handling updates to the table.
/// <!-- TODO: link to client-side documentation. -->
///
/// ### `#[index(btree)]`
///
/// Creates a single-column index with the specified algorithm.
///
/// It is an error to specify this attribute together with `#[unique]`.
/// Unique constraints implicitly create a unique index, which is accessed using the [`UniqueColumn`] struct instead of the
/// [`RangedIndex`] struct.
///
/// The created index has the same name as the column.
///
/// For a table *table* and an indexed *column*, use:
/// ```text
/// ctx.db.{table}().{column}()
/// ```
/// to get a [`RangedIndex`] from a [`ReducerContext`].
///
/// For example:
///
/// ```ignore
/// ctx.db.cities().latitude()
/// ```
///
/// # Generated code
///
/// For each `[table(name = {name})]` annotation on a type `{T}`, generates a struct
/// `{name}__TableHandle` implementing [`Table<Row={T}>`](crate::Table), and a trait that allows looking up such a
/// `{name}Handle` in a [`ReducerContext`].
///
/// The struct `{name}__TableHandle` is public and lives next to the row struct.
/// Users are encouraged not to write the name of this table handle struct,
/// or to store table handles in variables; operate through a `ReducerContext` instead.
///
/// For each named index declaration, add a method to `{name}__TableHandle` for getting a corresponding
/// [`RangedIndex`].
///
/// For each field with a `#[unique]` or `#[primary_key]` annotation,
/// add a method to `{name}Handle` for getting a corresponding [`UniqueColumn`].
///
/// The following pseudocode illustrates the general idea. Curly braces are used to indicate templated
/// names.
///
/// ```ignore
/// use spacetimedb::{RangedIndex, UniqueColumn, Table, DbView};
///
/// // This generated struct is hidden and cannot be directly accessed.
/// struct {name}__TableHandle { /* ... */ };
///
/// // It is a table handle.
/// impl Table for {name}__TableHandle {
/// type Row = {T};
/// /* ... */
/// }
///
/// // It can be looked up in a `ReducerContext`,
/// // using `ctx.db().{name}()`.
/// trait {name} {
/// fn {name}(&self) -> Row = {T}>;
/// }
/// impl {name} for <ReducerContext as DbContext>::DbView { /* ... */ }
///
/// // Once looked up, it can be used to look up indexes.
/// impl {name}Handle {
/// // For each `#[unique]` or `#[primary_key]` field `{field}` of type `{F}`:
/// fn {field}(&self) -> UniqueColumn<_, {F}, _> { /* ... */ };
///
/// // For each named index `{index}` on fields of type `{(F1, ..., FN)}`:
/// fn {index}(&self) -> RangedIndex<_, {(F1, ..., FN)}, _>;
/// }
/// ```
///
/// [`Table<Row = Self>`]: `Table`
#[doc(inline)]
pub use spacetimedb_bindings_macro::table;
/// Marks a function as a spacetimedb reducer.
///
/// A reducer is a function with read/write access to the database
/// that can be invoked remotely by [clients].
///
/// Each reducer call runs in its own database transaction,
/// and its updates to the database are only committed if the reducer returns successfully.
///
/// The first argument of a reducer is always a [`&ReducerContext`]. This context object
/// allows accessing the database and viewing information about the caller, among other things.
///
/// After this, a reducer can take any number of arguments.
/// These arguments must implement the [`SpacetimeType`], [`Serialize`], and [`Deserialize`] traits.
/// All of these traits can be derived at once by marking a type with `#[derive(SpacetimeType)]`.
///
/// Reducers may return either `()` or `Result<(), E>` where [`E: std::fmt::Display`](std::fmt::Display).
///
/// ```no_run
/// # #[cfg(target_arch = "wasm32")] mod demo {
/// use spacetimedb::{reducer, SpacetimeType, ReducerContext};
/// use log::info;
/// use std::fmt;
///
/// #[reducer]
/// pub fn hello_world(context: &ReducerContext) {
/// info!("Hello, World!");
/// }
///
/// #[reducer]
/// pub fn add_person(context: &ReducerContext, name: String, age: u16) {
/// // add a "person" to the database.
/// }
///
/// #[derive(SpacetimeType, Debug)]
/// struct Coordinates {
/// x: f32,
/// y: f32,
/// }
///
/// enum AddPlaceError {
/// InvalidCoordinates(Coordinates),
/// InvalidName(String),
/// }
///
/// impl fmt::Display for AddPlaceError {
/// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
/// match self {
/// AddPlaceError::InvalidCoordinates(coords) => {
/// write!(f, "invalid coordinates: {coords:?}")
/// },
/// AddPlaceError::InvalidName(name) => {
/// write!(f, "invalid name: {name:?}")
/// },
/// }
/// }
/// }
///
/// #[reducer]
/// pub fn add_place(
/// context: &ReducerContext,
/// name: String,
/// x: f32,
/// y: f32,
/// area: f32,
/// ) -> Result<(), AddPlaceError> {
/// // ... add a place to the database...
/// # Ok(())
/// }
/// # }
/// ```
///
/// Reducers may fail by returning a [`Result::Err`](std::result::Result) or by [panicking](std::panic!).
/// Failures will abort the active database transaction.
/// Any changes to the database made by the failed reducer call will be rolled back.
///
/// Reducers are limited in their ability to interact with the outside world.
/// They do not directly return data aside from errors, and have no access to any
/// network or filesystem interfaces.
/// Calling methods from [`std::io`], [`std::net`], or [`std::fs`]
/// inside a reducer will result in runtime errors.
///
/// Reducers can communicate information to the outside world in two ways:
/// - They can modify tables in the database.
/// See the `#[table]`(#table) macro documentation for information on how to declare and use tables.
/// - They can call logging macros from the [`log`] crate.
/// This writes to a private debug log attached to the database.
/// Run `spacetime logs <DATABASE_IDENTITY>` to browse these.
///
/// Reducers are permitted to call other reducers, simply by passing their `ReducerContext` as the first argument.
/// This is a regular function call, and does not involve any network communication. The callee will run within the
/// caller's transaction, and any changes made by the callee will be committed or rolled back with the caller.
///
/// # Lifecycle Reducers
///
/// You can specify special lifecycle reducers that are run at set points in
/// the module's lifecycle. You can have one of each per module.
///
/// These reducers cannot be called manually
/// and may not have any parameters except for `ReducerContext`.
///
/// ### The `init` reducer
///
/// This reducer is marked with `#[spacetimedb::reducer(init)]`. It is run the first time a module is published
/// and any time the database is cleared. (It does not have to be named `init`.)
///
/// If an error occurs when initializing, the module will not be published.
///
/// This reducer can be used to configure any static data tables used by your module. It can also be used to start running [scheduled reducers](#scheduled-reducers).
///
/// ### The `client_connected` reducer
///
/// This reducer is marked with `#[spacetimedb::reducer(client_connected)]`. It is run when a client connects to the SpacetimeDB module.
/// Their identity can be found in the sender value of the `ReducerContext`.
///
/// If an error occurs in the reducer, the client will be disconnected.
///
/// ### The `client_disconnected` reducer
///
/// This reducer is marked with `#[spacetimedb::reducer(client_disconnected)]`. It is run when a client disconnects from the SpacetimeDB module.
/// Their identity can be found in the sender value of the `ReducerContext`.
///
/// If an error occurs in the disconnect reducer,
/// the client is still recorded as disconnected.
///
// TODO(docs): Move these docs to be on `table`, rather than `reducer`. This will reduce duplication with procedure docs.
/// # Scheduled reducers
///
/// In addition to life cycle annotations, reducers can be made **scheduled**.
/// This allows calling the reducers at a particular time, or in a loop.
/// This can be used for game loops.
///
/// The scheduling information for a reducer is stored in a table.
/// This table has two mandatory fields:
/// - A primary key that identifies scheduled reducer calls.
/// - A [`ScheduleAt`] field that says when to call the reducer.
///
/// Managing timers with a scheduled table is as simple as inserting or deleting rows from the table.
/// This makes scheduling transactional in SpacetimeDB. If a reducer A first schedules B but then errors for some other reason, B will not be scheduled to run.
///
/// A [`ScheduleAt`] can be created from a [`spacetimedb::Timestamp`](crate::Timestamp), in which case the reducer will be scheduled once,
/// or from a [`std::time::Duration`], in which case the reducer will be scheduled in a loop. In either case the conversion can be performed using [`Into::into`].
///
/// ```no_run
/// # #[cfg(target_arch = "wasm32")] mod demo {
/// use spacetimedb::{table, reducer, ReducerContext, Timestamp, TimeDuration, ScheduleAt, Table};
/// use log::debug;
///
/// // First, we declare the table with scheduling information.
///
/// #[table(name = send_message_schedule, scheduled(send_message))]
/// struct SendMessageSchedule {
/// // Mandatory fields:
/// // ============================
///
/// /// An identifier for the scheduled reducer call.
/// #[primary_key]
/// #[auto_inc]
/// scheduled_id: u64,
///
/// /// Information about when the reducer should be called.
/// scheduled_at: ScheduleAt,
///
/// // In addition to the mandatory fields, any number of fields can be added.
/// // These can be used to provide extra information to the scheduled reducer.
///
/// // Custom fields:
/// // ============================
///
/// /// The text of the scheduled message to send.
/// text: String,
/// }
///
/// // Then, we declare the scheduled reducer.
/// // The first argument of the reducer should be, as always, a `&ReducerContext`.
/// // The second argument should be a row of the scheduling information table.
///
/// #[reducer]
/// fn send_message(ctx: &ReducerContext, arg: SendMessageSchedule) -> Result<(), String> {
/// let message_to_send = arg.text;
///
/// // ... send the message ...
///
/// Ok(())
/// }
///
/// // Now, we want to actually start scheduling reducers.
/// // It's convenient to do this inside the `init` reducer.
/// #[reducer(init)]
/// fn init(ctx: &ReducerContext) {
///
/// let current_time = ctx.timestamp;
///
/// let ten_seconds = TimeDuration::from_micros(10_000_000);
///
/// let future_timestamp: Timestamp = ctx.timestamp + ten_seconds;
/// ctx.db.send_message_schedule().insert(SendMessageSchedule {
/// scheduled_id: 1,
/// text:"I'm a bot sending a message one time".to_string(),
///
/// // Creating a `ScheduleAt` from a `Timestamp` results in the reducer
/// // being called once, at exactly the time `future_timestamp`.
/// scheduled_at: future_timestamp.into()
/// });
///
/// let loop_duration: TimeDuration = ten_seconds;
/// ctx.db.send_message_schedule().insert(SendMessageSchedule {
/// scheduled_id: 0,
/// text:"I'm a bot sending a message every 10 seconds".to_string(),
///
/// // Creating a `ScheduleAt` from a `Duration` results in the reducer
/// // being called in a loop, once every `loop_duration`.
/// scheduled_at: loop_duration.into()
/// });
/// }
/// # }
/// ```
///
/// Scheduled reducers are called on a best-effort basis and may be slightly delayed in their execution
/// when a database is under heavy load.
///
/// ### Restricting scheduled reducers
///
/// Scheduled reducers are normal reducers, and may still be called by clients.
/// If a scheduled reducer should only be called by the scheduler,
/// consider beginning it with a check that the caller `Identity` is the module:
///
/// ```no_run
/// # #[cfg(target_arch = "wasm32")] mod demo {
/// use spacetimedb::{reducer, ReducerContext};
///
/// # #[derive(spacetimedb::SpacetimeType)] struct ScheduledArgs {}
///
/// #[reducer]
/// fn scheduled(ctx: &ReducerContext, args: ScheduledArgs) -> Result<(), String> {
/// if ctx.sender() != ctx.identity() {
/// return Err("Reducer `scheduled` may not be invoked by clients, only via scheduling.".into());
/// }
/// // Reducer body...
/// # Ok(())
/// }
/// # }
/// ```
///
/// <!-- TODO: SLAs? -->
///
/// [`&ReducerContext`]: `ReducerContext`
/// [clients]: https://spacetimedb.com/docs/#client
#[doc(inline)]
pub use spacetimedb_bindings_macro::reducer;
/// Marks a function as a SpacetimeDB procedure.
///
/// A procedure is a function that runs within the database and can be invoked remotely by [clients],
/// but unlike a [`reducer`], a procedure is not automatically transactional.
/// This allows procedures to perform certain side-effecting operations,
/// but also means that module developers must be more careful not to corrupt the database state
/// when execution aborts or operations fail.
///
/// When in doubt, prefer writing [`reducer`]s unless you need to perform an operation only available to procedures.
///
/// The first argument of a procedure is always `&mut ProcedureContext`.
/// The [`ProcedureContext`] exposes information about the caller and allows side-effecting operations.
///
/// After this, a procedure can take any number of arguments.
/// These arguments must implement the [`SpacetimeType`], [`Serialize`], and [`Deserialize`] traits.
/// All of these traits can be derived at once by marking a type with `#[derive(SpacetimeType)]`.
///
/// A procedure may return any type that implements [`SpacetimeType`], [`Serialize`] and [`Deserialize`].
/// Unlike [reducer]s, SpacetimeDB does not assign any special semantics to [`Result`] return values.
///
/// If a procedure returns successfully (as opposed to panicking), its return value will be sent to the calling client.
/// If a procedure panics, its panic message will be sent to the calling client instead.
/// Procedure arguments and return values are not otherwise broadcast to clients.
///
/// ```no_run
/// # use spacetimedb::{procedure, SpacetimeType, ProcedureContext, Timestamp};
/// #[procedure]
/// fn return_value(ctx: &mut ProcedureContext, arg: MyArgument) -> MyReturnValue {
/// MyReturnValue {
/// a: format!("Hello, {}", ctx.sender()),
/// b: ctx.timestamp,
/// }
/// }
///
/// #[derive(SpacetimeType)]
/// struct MyArgument {
/// val: u32,
/// }
///
/// #[derive(SpacetimeType)]
/// struct MyReturnValue {
/// a: String,
/// b: Timestamp,
/// }
/// ```
///
/// # Blocking operations
///
/// Procedures are allowed to perform certain operations which take time.
/// During the execution of these operations, the procedure's execution will be suspended,
/// allowing other database operations to run in parallel.
///
/// Procedures must not hold open a transaction while performing a blocking operation.
// TODO(procedure-http): add example with an HTTP request.
// TODO(procedure-transaction): document obtaining and using a transaction within a procedure.
///
/// # Scheduled procedures
// TODO(docs): after moving scheduled reducer docs into table secion, link there.
///
/// Like [reducer]s, procedures can be made **scheduled**.
/// This allows calling procedures at a particular time, or in a loop.
/// It also allows reducers to enqueue procedure runs.
///
/// Scheduled procedures are called on a best-effort basis and may be slightly delayed in their execution
/// when a database is under heavy load.
///
/// [clients]: https://spacetimedb.com/docs/#client
// TODO(procedure-async): update docs and examples with `async`-ness.
#[doc(inline)]
#[cfg(feature = "unstable")]
pub use spacetimedb_bindings_macro::procedure;
/// Marks a function as a spacetimedb view.
///
/// A view is a function with read-only access to the database.
///
/// The first argument of a view is always a [`&ViewContext`] or [`&AnonymousViewContext`].
/// The former can only read from the database whereas latter can also access info about the caller.
///
/// After this, a view can take any number of arguments just like reducers.
/// These arguments must implement the [`SpacetimeType`], [`Serialize`], and [`Deserialize`] traits.
/// All of these traits can be derived at once by marking a type with `#[derive(SpacetimeType)]`.
///
/// Views return `Vec<T>` or `Option<T>` where `T` is a `SpacetimeType`.
///
/// ```no_run
/// # mod demo {
/// use spacetimedb::{view, table, AnonymousViewContext, SpacetimeType, ViewContext};
/// use spacetimedb_lib::Identity;
///
/// #[table(name = player)]
/// struct Player {
/// #[auto_inc]
/// #[primary_key]
/// id: u64,
///
/// #[unique]
/// identity: Identity,
///
/// #[index(btree)]
/// level: u32,
/// }
///
/// impl Player {
/// fn merge(self, location: Location) -> PlayerAndLocation {
/// PlayerAndLocation {
/// player_id: self.id,
/// level: self.level,
/// x: location.x,
/// y: location.y,
/// }
/// }
/// }
///
/// #[derive(SpacetimeType)]
/// struct PlayerId {
/// id: u64,
/// }
///
/// #[table(name = location, index(name = coordinates, btree(columns = [x, y])))]
/// struct Location {
/// #[unique]
/// player_id: u64,
/// x: u64,
/// y: u64,
/// }
///
/// #[derive(SpacetimeType)]
/// struct PlayerAndLocation {
/// player_id: u64,
/// level: u32,
/// x: u64,
/// y: u64,
/// }
///
/// // A view that selects at most one row from a table
/// #[view(name = my_player, public)]
/// fn my_player(ctx: &ViewContext) -> Option<Player> {
/// ctx.db.player().identity().find(ctx.sender())
/// }
///
/// // An example of column projection
/// #[view(name = my_player_id, public)]
/// fn my_player_id(ctx: &ViewContext) -> Option<PlayerId> {
/// ctx.db.player().identity().find(ctx.sender()).map(|Player { id, .. }| PlayerId { id })
/// }
///
/// // An example that is analogous to a semijoin in sql
/// #[view(name = players_at_coordinates, public)]
/// fn players_at_coordinates(ctx: &AnonymousViewContext) -> Vec<Player> {
/// ctx
/// .db
/// .location()
/// .coordinates()
/// .filter((3u64, 5u64))
/// .filter_map(|location| ctx.db.player().id().find(location.player_id))
/// .collect()
/// }
///
/// // An example of a join that combines fields from two different tables
/// #[view(name = players_with_coordinates, public)]
/// fn players_with_coordinates(ctx: &AnonymousViewContext) -> Vec<PlayerAndLocation> {
/// ctx
/// .db
/// .location()
/// .coordinates()
/// .filter((3u64, 5u64))
/// .filter_map(|location| ctx
/// .db
/// .player()
/// .id()
/// .find(location.player_id)
/// .map(|player| player.merge(location))
/// )
/// .collect()
/// }
/// # }
/// ```
///
/// Just like reducers, views are limited in their ability to interact with the outside world.
/// They have no access to any network or filesystem interfaces.
/// Calling methods from [`std::io`], [`std::net`], or [`std::fs`] will result in runtime errors.
///
/// Views are callable by reducers and other views simply by passing their `ViewContext`..
/// This is a regular function call.
/// The callee will run within the caller's transaction.
///
///
/// [`&ViewContext`]: `ViewContext`
/// [`&AnonymousViewContext`]: `AnonymousViewContext`
#[doc(inline)]
pub use spacetimedb_bindings_macro::view;
pub struct QueryBuilder {}
pub use query_builder::Query;
/// One of two possible types that can be passed as the first argument to a `#[view]`.
/// The other is [`ViewContext`].
/// Use this type if the view does not depend on the caller's identity.
pub struct AnonymousViewContext {
pub db: LocalReadOnly,
pub from: QueryBuilder,
}
impl Default for AnonymousViewContext {
fn default() -> Self {
Self {
db: LocalReadOnly {},
from: QueryBuilder {},
}
}
}
/// One of two possible types that can be passed as the first argument to a `#[view]`.
/// The other is [`AnonymousViewContext`].
/// Use this type if the view depends on the caller's identity.
pub struct ViewContext {
sender: Identity,
pub db: LocalReadOnly,
pub from: QueryBuilder,
}
impl ViewContext {
pub fn new(sender: Identity) -> Self {
Self {
sender,
db: LocalReadOnly {},
from: QueryBuilder {},
}
}
/// The `Identity` of the client that invoked the view.
pub fn sender(&self) -> Identity {
self.sender
}
}
/// The context that any reducer is provided with.
///
/// This must be the first argument of the reducer. Clients of the module will
/// only see arguments after the `ReducerContext`.
///
/// Includes information about the client calling the reducer and the time of invocation,
/// as well as a view into the module's database.
///
/// If the crate was compiled with the `rand` feature, also includes faculties for random
/// number generation.
///
/// Implements the `DbContext` trait for accessing views into a database.
#[non_exhaustive]
pub struct ReducerContext {
/// The `Identity` of the client that invoked the reducer.
sender: Identity,
/// The time at which the reducer was started.
pub timestamp: Timestamp,
/// The `ConnectionId` of the client that invoked the reducer.
///
/// Will be `None` for certain reducers invoked automatically by the host,
/// including `init` and scheduled reducers.
pub connection_id: Option<ConnectionId>,
sender_auth: AuthCtx,
/// Allows accessing the local database attached to a module.
///
/// This slightly strange type appears to have no methods, but that is misleading.
/// The `#[table]` macro uses the trait system to add table accessors to this type.
/// These are generated methods that allow you to access specific tables.
///
/// For a table named *table*, use `ctx.db.{table}()` to get a handle.
/// For example:
/// ```no_run
/// # mod demo { // work around doctest+index issue
/// # #![cfg(target_arch = "wasm32")]
/// use spacetimedb::{table, reducer, ReducerContext};
///
/// #[table(name = book)]
/// #[derive(Debug)]
/// struct Book {
/// #[primary_key]
/// id: u64,
/// isbn: String,
/// name: String,
/// #[index(btree)]
/// author: String
/// }
///
/// #[reducer]
/// fn find_books_by(ctx: &ReducerContext, author: String) {
/// let book: &book__TableHandle = ctx.db.book();
///
/// log::debug!("looking up books by {author}...");
/// for book in book.author().filter(&author) {
/// log::debug!("- {book:?}");
/// }
/// }
/// # }
/// ```
/// See the [`#[table]`](macro@crate::table) macro for more information.
pub db: Local,
#[cfg(feature = "rand08")]
rng: std::cell::OnceCell<StdbRng>,
/// A counter used for generating UUIDv7 values.
/// **Note:** must be 0..=u32::MAX
#[cfg(feature = "rand")]
counter_uuid: Cell<u32>,
}
impl ReducerContext {
#[doc(hidden)]
pub fn __dummy() -> Self {
Self {
db: Local {},
sender: Identity::__dummy(),
timestamp: Timestamp::UNIX_EPOCH,
connection_id: None,
sender_auth: AuthCtx::internal(),
#[cfg(feature = "rand08")]
rng: std::cell::OnceCell::new(),
#[cfg(feature = "rand")]
counter_uuid: Cell::new(0),
}
}
#[doc(hidden)]
fn new(db: Local, sender: Identity, connection_id: Option<ConnectionId>, timestamp: Timestamp) -> Self {
Self {
db,
sender,
timestamp,
connection_id,
sender_auth: AuthCtx::from_connection_id_opt(connection_id),
#[cfg(feature = "rand08")]
rng: std::cell::OnceCell::new(),
#[cfg(feature = "rand")]
counter_uuid: Cell::new(0),
}
}
/// The `Identity` of the client that invoked the reducer.
pub fn sender(&self) -> Identity {
self.sender
}
/// Returns the authorization information for the caller of this reducer.
pub fn sender_auth(&self) -> &AuthCtx {
&self.sender_auth
}
/// Read the current module's [`Identity`].
pub fn identity(&self) -> Identity {
// Hypothetically, we *could* read the module identity out of the system tables.
// However, this would be:
// - Onerous, because we have no tooling to inspect the system tables from module code.
// - Slow (at least relatively),
// because it would involve multiple host calls which hit the datastore,
// as compared to a single host call which does not.
// As such, we've just defined a host call
// which reads the module identity out of the `InstanceEnv`.
Identity::from_byte_array(spacetimedb_bindings_sys::identity())