-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathlib.rs
More file actions
1142 lines (1081 loc) · 46.3 KB
/
lib.rs
File metadata and controls
1142 lines (1081 loc) · 46.3 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
//! Defines sys calls to interact with SpacetimeDB.
//! This forms an ABI of sorts that modules written in Rust can use.
extern crate alloc;
use core::fmt;
use core::mem::MaybeUninit;
use core::num::NonZeroU16;
use std::ptr;
use spacetimedb_primitives::{errno, errnos, ColId, IndexId, TableId};
/// Provides a raw set of sys calls which abstractions can be built atop of.
pub mod raw {
use spacetimedb_primitives::{ColId, IndexId, TableId};
// this module identifier determines the abi version that modules built with this crate depend
// on. Any non-breaking additions to the abi surface should be put in a new `extern {}` block
// with a module identifier with a minor version 1 above the previous highest minor version.
// For breaking changes, all functions should be moved into one new `spacetime_X.0` block.
#[link(wasm_import_module = "spacetime_10.0")]
extern "C" {
/// Queries the `table_id` associated with the given (table) `name`
/// where `name` is the UTF-8 slice in WASM memory at `name_ptr[..name_len]`.
///
/// The table id is written into the `out` pointer.
///
/// # Traps
///
/// Traps if:
/// - `name_ptr` is NULL or `name` is not in bounds of WASM memory.
/// - `name` is not valid UTF-8.
/// - `out` is NULL or `out[..size_of::<TableId>()]` is not in bounds of WASM memory.
///
/// # Errors
///
/// Returns an error:
///
/// - `NOT_IN_TRANSACTION`, when called outside of a transaction.
/// - `NO_SUCH_TABLE`, when `name` is not the name of a table.
pub fn table_id_from_name(name: *const u8, name_len: usize, out: *mut TableId) -> u16;
/// Queries the `index_id` associated with the given (index) `name`
/// where `name` is the UTF-8 slice in WASM memory at `name_ptr[..name_len]`.
///
/// If a `name` was provided for the `RawIndexDef` for this index, that is the name of the index.
/// If no name was provided, a name was autogenerated like so:
/// ```
/// let table_name: String = "my_table".into();
/// let column_names: Vec<String> = vec!["bananas".into(), "oranges".into()];
/// let column_names = column_names.join("_");
/// let name = format!("{table_name}_{column_names}_idx_btree");
/// ```
/// (See the function `spacetimedb_schema::def::validate::v9::generate_index_name` for more
/// information.)
///
/// The index id is written into the `out` pointer.
///
/// # Traps
///
/// Traps if:
/// - `name_ptr` is NULL or `name` is not in bounds of WASM memory.
/// - `name` is not valid UTF-8.
/// - `out` is NULL or `out[..size_of::<IndexId>()]` is not in bounds of WASM memory.
///
/// # Errors
///
/// Returns an error:
///
/// - `NOT_IN_TRANSACTION`, when called outside of a transaction.
/// - `NO_SUCH_INDEX`, when `name` is not the name of an index.
pub fn index_id_from_name(name_ptr: *const u8, name_len: usize, out: *mut IndexId) -> u16;
/// Writes the number of rows currently in table identified by `table_id` to `out`.
///
/// # Traps
///
/// Traps if:
/// - `out` is NULL or `out[..size_of::<u64>()]` is not in bounds of WASM memory.
///
/// # Errors
///
/// Returns an error:
///
/// - `NOT_IN_TRANSACTION`, when called outside of a transaction.
/// - `NO_SUCH_TABLE`, when `table_id` is not a known ID of a table.
pub fn datastore_table_row_count(table_id: TableId, out: *mut u64) -> u16;
/// Starts iteration on each row, as BSATN-encoded, of a table identified by `table_id`.
///
/// On success, the iterator handle is written to the `out` pointer.
/// This handle can be advanced by [`row_iter_bsatn_advance`].
///
/// # Traps
///
/// This function does not trap.
///
/// # Errors
///
/// Returns an error:
///
/// - `NOT_IN_TRANSACTION`, when called outside of a transaction.
/// - `NO_SUCH_TABLE`, when `table_id` is not a known ID of a table.
pub fn datastore_table_scan_bsatn(table_id: TableId, out: *mut RowIter) -> u16;
/// Finds all rows in the index identified by `index_id`,
/// according to the:
/// - `prefix = prefix_ptr[..prefix_len]`,
/// - `rstart = rstart_ptr[..rstart_len]`,
/// - `rend = rend_ptr[..rend_len]`,
///
/// in WASM memory.
///
/// The index itself has a schema/type.
/// The `prefix` is decoded to the initial `prefix_elems` `AlgebraicType`s
/// whereas `rstart` and `rend` are decoded to the `prefix_elems + 1` `AlgebraicType`
/// where the `AlgebraicValue`s are wrapped in `Bound`.
/// That is, `rstart, rend` are BSATN-encoded `Bound<AlgebraicValue>`s.
///
/// Matching is then defined by equating `prefix`
/// to the initial `prefix_elems` columns of the index
/// and then imposing `rstart` as the starting bound
/// and `rend` as the ending bound on the `prefix_elems + 1` column of the index.
/// Remaining columns of the index are then unbounded.
/// Note that the `prefix` in this case can be empty (`prefix_elems = 0`),
/// in which case this becomes a ranged index scan on a single-col index
/// or even a full table scan if `rstart` and `rend` are both unbounded.
///
/// The relevant table for the index is found implicitly via the `index_id`,
/// which is unique for the module.
///
/// On success, the iterator handle is written to the `out` pointer.
/// This handle can be advanced by [`row_iter_bsatn_advance`].
///
/// # Non-obvious queries
///
/// For an index on columns `[a, b, c]`:
///
/// - `a = x, b = y` is encoded as a prefix `[x, y]`
/// and a range `Range::Unbounded`,
/// or as a prefix `[x]` and a range `rstart = rend = Range::Inclusive(y)`.
/// - `a = x, b = y, c = z` is encoded as a prefix `[x, y]`
/// and a range `rstart = rend = Range::Inclusive(z)`.
/// - A sorted full scan is encoded as an empty prefix
/// and a range `Range::Unbounded`.
///
/// # Traps
///
/// Traps if:
/// - `prefix_elems > 0`
/// and (`prefix_ptr` is NULL or `prefix` is not in bounds of WASM memory).
/// - `rstart` is NULL or `rstart` is not in bounds of WASM memory.
/// - `rend` is NULL or `rend` is not in bounds of WASM memory.
/// - `out` is NULL or `out[..size_of::<RowIter>()]` is not in bounds of WASM memory.
///
/// # Errors
///
/// Returns an error:
///
/// - `NOT_IN_TRANSACTION`, when called outside of a transaction.
/// - `NO_SUCH_INDEX`, when `index_id` is not a known ID of an index.
/// - `WRONG_INDEX_ALGO` if the index is not a range-compatible index.
/// - `BSATN_DECODE_ERROR`, when `prefix` cannot be decoded to
/// a `prefix_elems` number of `AlgebraicValue`
/// typed at the initial `prefix_elems` `AlgebraicType`s of the index's key type.
/// Or when `rstart` or `rend` cannot be decoded to an `Bound<AlgebraicValue>`
/// where the inner `AlgebraicValue`s are
/// typed at the `prefix_elems + 1` `AlgebraicType` of the index's key type.
pub fn datastore_index_scan_range_bsatn(
index_id: IndexId,
prefix_ptr: *const u8,
prefix_len: usize,
prefix_elems: ColId,
rstart_ptr: *const u8, // Bound<AlgebraicValue>
rstart_len: usize,
rend_ptr: *const u8, // Bound<AlgebraicValue>
rend_len: usize,
out: *mut RowIter,
) -> u16;
/// This is the same as [`datastore_index_scan_range_bsatn`].
#[deprecated = "use `datastore_index_scan_range_bsatn` instead"]
#[doc(alias = "datastore_index_scan_range_bsatn")]
pub fn datastore_btree_scan_bsatn(
index_id: IndexId,
prefix_ptr: *const u8,
prefix_len: usize,
prefix_elems: ColId,
rstart_ptr: *const u8, // Bound<AlgebraicValue>
rstart_len: usize,
rend_ptr: *const u8, // Bound<AlgebraicValue>
rend_len: usize,
out: *mut RowIter,
) -> u16;
/// Deletes all rows found in the index identified by `index_id`,
/// according to the:
/// - `prefix = prefix_ptr[..prefix_len]`,
/// - `rstart = rstart_ptr[..rstart_len]`,
/// - `rend = rend_ptr[..rend_len]`,
///
/// in WASM memory.
///
/// This syscall will delete all the rows found by
/// [`datastore_index_scan_range_bsatn`] with the same arguments passed,
/// including `prefix_elems`.
/// See `datastore_index_scan_range_bsatn` for details.
///
/// The number of rows deleted is written to the WASM pointer `out`.
///
/// # Traps
///
/// Traps if:
/// - `prefix_elems > 0`
/// and (`prefix_ptr` is NULL or `prefix` is not in bounds of WASM memory).
/// - `rstart` is NULL or `rstart` is not in bounds of WASM memory.
/// - `rend` is NULL or `rend` is not in bounds of WASM memory.
/// - `out` is NULL or `out[..size_of::<u32>()]` is not in bounds of WASM memory.
///
/// # Errors
///
/// Returns an error:
///
/// - `NOT_IN_TRANSACTION`, when called outside of a transaction.
/// - `NO_SUCH_INDEX`, when `index_id` is not a known ID of an index.
/// - `WRONG_INDEX_ALGO` if the index is not a range-compatible index.
/// - `BSATN_DECODE_ERROR`, when `prefix` cannot be decoded to
/// a `prefix_elems` number of `AlgebraicValue`
/// typed at the initial `prefix_elems` `AlgebraicType`s of the index's key type.
/// Or when `rstart` or `rend` cannot be decoded to an `Bound<AlgebraicValue>`
/// where the inner `AlgebraicValue`s are
/// typed at the `prefix_elems + 1` `AlgebraicType` of the index's key type.
pub fn datastore_delete_by_index_scan_range_bsatn(
index_id: IndexId,
prefix_ptr: *const u8,
prefix_len: usize,
prefix_elems: ColId,
rstart_ptr: *const u8, // Bound<AlgebraicValue>
rstart_len: usize,
rend_ptr: *const u8, // Bound<AlgebraicValue>
rend_len: usize,
out: *mut u32,
) -> u16;
/// This is the same as [`datastore_delete_by_index_scan_range_bsatn`].
#[deprecated = "use `datastore_delete_by_index_scan_range_bsatn` instead"]
#[doc(alias = "datastore_delete_by_index_scan_range_bsatn")]
pub fn datastore_delete_by_btree_scan_bsatn(
index_id: IndexId,
prefix_ptr: *const u8,
prefix_len: usize,
prefix_elems: ColId,
rstart_ptr: *const u8, // Bound<AlgebraicValue>
rstart_len: usize,
rend_ptr: *const u8, // Bound<AlgebraicValue>
rend_len: usize,
out: *mut u32,
) -> u16;
/// Deletes those rows, in the table identified by `table_id`,
/// that match any row in the byte string `rel = rel_ptr[..rel_len]` in WASM memory.
///
/// Matching is defined by first BSATN-decoding
/// the byte string pointed to at by `relation` to a `Vec<ProductValue>`
/// according to the row schema of the table
/// and then using `Ord for AlgebraicValue`.
/// A match happens when `Ordering::Equal` is returned from `fn cmp`.
/// This occurs exactly when the row's BSATN-encoding is equal to the encoding of the `ProductValue`.
///
/// The number of rows deleted is written to the WASM pointer `out`.
///
/// # Traps
///
/// Traps if:
/// - `rel_ptr` is NULL or `rel` is not in bounds of WASM memory.
/// - `out` is NULL or `out[..size_of::<u32>()]` is not in bounds of WASM memory.
///
/// # Errors
///
/// Returns an error:
///
/// - `NOT_IN_TRANSACTION`, when called outside of a transaction.
/// - `NO_SUCH_TABLE`, when `table_id` is not a known ID of a table.
/// - `BSATN_DECODE_ERROR`, when `rel` cannot be decoded to `Vec<ProductValue>`
/// where each `ProductValue` is typed at the `ProductType` the table's schema specifies.
pub fn datastore_delete_all_by_eq_bsatn(
table_id: TableId,
rel_ptr: *const u8,
rel_len: usize,
out: *mut u32,
) -> u16;
/// Reads rows from the given iterator registered under `iter`.
///
/// Takes rows from the iterator
/// and stores them in the memory pointed to by `buffer = buffer_ptr[..buffer_len]`,
/// encoded in BSATN format.
///
/// The `buffer_len = buffer_len_ptr[..size_of::<usize>()]` stores the capacity of `buffer`.
/// On success (`0` or `-1` is returned),
/// `buffer_len` is set to the combined length of the encoded rows.
/// When `-1` is returned, the iterator has been exhausted
/// and there are no more rows to read,
/// leading to the iterator being immediately destroyed.
/// Note that the host is free to reuse allocations in a pool,
/// destroying the handle logically does not entail that memory is necessarily reclaimed.
///
/// # Traps
///
/// Traps if:
///
/// - `buffer_len_ptr` is NULL or `buffer_len` is not in bounds of WASM memory.
/// - `buffer_ptr` is NULL or `buffer` is not in bounds of WASM memory.
///
/// # Errors
///
/// Returns an error:
///
/// - `NO_SUCH_ITER`, when `iter` is not a valid iterator.
/// - `BUFFER_TOO_SMALL`, when there are rows left but they cannot fit in `buffer`.
/// When this occurs, `buffer_len` is set to the size of the next item in the iterator.
/// To make progress, the caller should reallocate the buffer to at least that size and try again.
pub fn row_iter_bsatn_advance(iter: RowIter, buffer_ptr: *mut u8, buffer_len_ptr: *mut usize) -> i16;
/// Destroys the iterator registered under `iter`.
///
/// Once `row_iter_bsatn_close` is called on `iter`, the `iter` is invalid.
/// That is, `row_iter_bsatn_close(iter)` the second time will yield `NO_SUCH_ITER`.
///
/// # Errors
///
/// Returns an error:
///
/// - `NO_SUCH_ITER`, when `iter` is not a valid iterator.
pub fn row_iter_bsatn_close(iter: RowIter) -> u16;
/// Inserts a row into the table identified by `table_id`,
/// where the row is read from the byte string `row = row_ptr[..row_len]` in WASM memory
/// where `row_len = row_len_ptr[..size_of::<usize>()]` stores the capacity of `row`.
///
/// The byte string `row` must be a BSATN-encoded `ProductValue`
/// typed at the table's `ProductType` row-schema.
///
/// To handle auto-incrementing columns,
/// when the call is successful,
/// the `row` is written back to with the generated sequence values.
/// These values are written as a BSATN-encoded `pv: ProductValue`.
/// Each `v: AlgebraicValue` in `pv` is typed at the sequence's column type.
/// The `v`s in `pv` are ordered by the order of the columns, in the schema of the table.
/// When the table has no sequences,
/// this implies that the `pv`, and thus `row`, will be empty.
/// The `row_len` is set to the length of `bsatn(pv)`.
///
/// # Traps
///
/// Traps if:
/// - `row_len_ptr` is NULL or `row_len` is not in bounds of WASM memory.
/// - `row_ptr` is NULL or `row` is not in bounds of WASM memory.
///
/// # Errors
///
/// Returns an error:
///
/// - `NOT_IN_TRANSACTION`, when called outside of a transaction.
/// - `NO_SUCH_TABLE`, when `table_id` is not a known ID of a table.
/// - `BSATN_DECODE_ERROR`, when `row` cannot be decoded to a `ProductValue`.
/// typed at the `ProductType` the table's schema specifies.
/// - `UNIQUE_ALREADY_EXISTS`, when inserting `row` would violate a unique constraint.
/// - `SCHEDULE_AT_DELAY_TOO_LONG`, when the delay specified in the row was too long.
pub fn datastore_insert_bsatn(table_id: TableId, row_ptr: *mut u8, row_len_ptr: *mut usize) -> u16;
/// Updates a row in the table identified by `table_id` to `row`
/// where the row is read from the byte string `row = row_ptr[..row_len]` in WASM memory
/// where `row_len = row_len_ptr[..size_of::<usize>()]` stores the capacity of `row`.
///
/// The byte string `row` must be a BSATN-encoded `ProductValue`
/// typed at the table's `ProductType` row-schema.
///
/// The row to update is found by projecting `row`
/// to the type of the *unique* index identified by `index_id`.
/// If no row is found, the error `NO_SUCH_ROW` is returned.
///
/// To handle auto-incrementing columns,
/// when the call is successful,
/// the `row` is written back to with the generated sequence values.
/// These values are written as a BSATN-encoded `pv: ProductValue`.
/// Each `v: AlgebraicValue` in `pv` is typed at the sequence's column type.
/// The `v`s in `pv` are ordered by the order of the columns, in the schema of the table.
/// When the table has no sequences,
/// this implies that the `pv`, and thus `row`, will be empty.
/// The `row_len` is set to the length of `bsatn(pv)`.
///
/// # Traps
///
/// Traps if:
/// - `row_len_ptr` is NULL or `row_len` is not in bounds of WASM memory.
/// - `row_ptr` is NULL or `row` is not in bounds of WASM memory.
///
/// # Errors
///
/// Returns an error:
///
/// - `NOT_IN_TRANSACTION`, when called outside of a transaction.
/// - `NO_SUCH_TABLE`, when `table_id` is not a known ID of a table.
/// - `NO_SUCH_INDEX`, when `index_id` is not a known ID of an index.
/// - `INDEX_NOT_UNIQUE`, when the index was not unique.
/// - `NO_SUCH_ROW`, when the row was not found in the unique index.
/// - `BSATN_DECODE_ERROR`, when `row` cannot be decoded to a `ProductValue`
/// typed at the `ProductType` the table's schema specifies
/// or when it cannot be projected to the index identified by `index_id`.
/// - `UNIQUE_ALREADY_EXISTS`, when inserting `row` would violate a unique constraint.
/// - `SCHEDULE_AT_DELAY_TOO_LONG`, when the delay specified in the row was too long.
pub fn datastore_update_bsatn(
table_id: TableId,
index_id: IndexId,
row_ptr: *mut u8,
row_len_ptr: *mut usize,
) -> u16;
/// Schedules a reducer to be called asynchronously, nonatomically,
/// and immediately on a best effort basis.
///
/// The reducer is named as the valid UTF-8 slice `(name, name_len)`,
/// and is passed the slice `(args, args_len)` as its argument.
///
/// Traps if
/// - `name` does not point to valid UTF-8
/// - `name + name_len` or `args + args_len` overflow a 64-bit integer
#[cfg(feature = "unstable")]
pub fn volatile_nonatomic_schedule_immediate(
name: *const u8,
name_len: usize,
args: *const u8,
args_len: usize,
);
/// Writes up to `buffer_len` bytes from `buffer = buffer_ptr[..buffer_len]`,
/// to the `sink`, registered in the host environment.
///
/// The `buffer_len = buffer_len_ptr[..size_of::<usize>()]` stores the capacity of `buffer`.
/// On success (`0` is returned),
/// `buffer_len` is set to the number of bytes written to `sink`.
///
/// # Traps
///
/// - `buffer_len_ptr` is NULL or `buffer_len` is not in bounds of WASM memory.
/// - `buffer_ptr` is NULL or `buffer` is not in bounds of WASM memory.
///
/// # Errors
///
/// Returns an error:
///
/// - `NO_SUCH_BYTES`, when `sink` is not a valid bytes sink.
/// - `NO_SPACE`, when there is no room for more bytes in `sink`.
pub fn bytes_sink_write(sink: BytesSink, buffer_ptr: *const u8, buffer_len_ptr: *mut usize) -> u16;
/// Reads bytes from `source`, registered in the host environment,
/// and stores them in the memory pointed to by `buffer = buffer_ptr[..buffer_len]`.
///
/// The `buffer_len = buffer_len_ptr[..size_of::<usize>()]` stores the capacity of `buffer`.
/// On success (`0` or `-1` is returned),
/// `buffer_len` is set to the number of bytes written to `buffer`.
/// When `-1` is returned, the resource has been exhausted
/// and there are no more bytes to read,
/// leading to the resource being immediately destroyed.
/// Note that the host is free to reuse allocations in a pool,
/// destroying the handle logically does not entail that memory is necessarily reclaimed.
///
/// # Traps
///
/// Traps if:
///
/// - `buffer_len_ptr` is NULL or `buffer_len` is not in bounds of WASM memory.
/// - `buffer_ptr` is NULL or `buffer` is not in bounds of WASM memory.
///
/// # Errors
///
/// Returns an error:
///
/// - `NO_SUCH_BYTES`, when `source` is not a valid bytes source.
///
/// # Example
///
/// The typical use case for this ABI is in `__call_reducer__`,
/// to read and deserialize the `args`.
/// An example definition, dealing with `args` might be:
/// ```rust,ignore
/// /// #[no_mangle]
/// extern "C" fn __call_reducer__(..., args: BytesSource, ...) -> i16 {
/// // ...
///
/// let mut buf = Vec::<u8>::with_capacity(1024);
/// loop {
/// // Write into the spare capacity of the buffer.
/// let buf_ptr = buf.spare_capacity_mut();
/// let spare_len = buf_ptr.len();
/// let mut buf_len = buf_ptr.len();
/// let buf_ptr = buf_ptr.as_mut_ptr().cast();
/// let ret = unsafe { bytes_source_read(args, buf_ptr, &mut buf_len) };
/// // SAFETY: `bytes_source_read` just appended `spare_len` bytes to `buf`.
/// unsafe { buf.set_len(buf.len() + spare_len) };
/// match ret {
/// // Host side source exhausted, we're done.
/// -1 => break,
/// // Wrote the entire spare capacity.
/// // Need to reserve more space in the buffer.
/// 0 if spare_len == buf_len => buf.reserve(1024),
/// // Host didn't write as much as possible.
/// // Try to read some more.
/// // The host will likely not trigger this branch,
/// // but a module should be prepared for it.
/// 0 => {}
/// _ => unreachable!(),
/// }
/// }
///
/// // ...
/// }
/// ```
pub fn bytes_source_read(source: BytesSource, buffer_ptr: *mut u8, buffer_len_ptr: *mut usize) -> i16;
/// Logs at `level` a `message` message occurring in `filename:line_number`
/// with `target` being the module path at the `log!` invocation site.
///
/// These various pointers are interpreted lossily as UTF-8 strings with a corresponding `_len`.
///
/// The `target` and `filename` pointers are ignored by passing `NULL`.
/// The line number is ignored if `line_number == u32::MAX`.
///
/// No message is logged if
/// - `target != NULL && target + target_len > u64::MAX`
/// - `filename != NULL && filename + filename_len > u64::MAX`
/// - `message + message_len > u64::MAX`
///
/// # Traps
///
/// Traps if:
/// - `target` is not NULL and `target_ptr[..target_len]` is not in bounds of WASM memory.
/// - `filename` is not NULL and `filename_ptr[..filename_len]` is not in bounds of WASM memory.
/// - `message` is not NULL and `message_ptr[..message_len]` is not in bounds of WASM memory.
///
/// [target]: https://docs.rs/log/latest/log/struct.Record.html#method.target
pub fn console_log(
level: u8,
target_ptr: *const u8,
target_len: usize,
filename_ptr: *const u8,
filename_len: usize,
line_number: u32,
message_ptr: *const u8,
message_len: usize,
);
/// Begins a timing span with `name = name_ptr[..name_len]`.
///
/// When the returned `ConsoleTimerId` is passed to [`console_timer_end`],
/// the duration between the calls will be printed to the module's logs.
///
/// The `name` is interpreted lossily as UTF-8.
///
/// # Traps
///
/// Traps if:
/// - `name_ptr` is NULL or `name` is not in bounds of WASM memory.
pub fn console_timer_start(name_ptr: *const u8, name_len: usize) -> u32;
/// End a timing span.
///
/// The `timer_id` must be the result of a call to `console_timer_start`.
/// The duration between the two calls will be computed and printed to the module's logs.
/// Once `console_timer_end` is called on `id: ConsoleTimerId`, the `id` is invalid.
/// That is, `console_timer_end(id)` the second time will yield `NO_SUCH_CONSOLE_TIMER`.
///
/// Note that the host is free to reuse allocations in a pool,
/// destroying the handle logically does not entail that memory is necessarily reclaimed.
///
/// # Errors
///
/// Returns an error:
/// - `NO_SUCH_CONSOLE_TIMER`, when `timer_id` does not exist.
pub fn console_timer_end(timer_id: u32) -> u16;
/// Writes the identity of the module into `out = out_ptr[..32]`.
///
/// # Traps
///
/// Traps if:
///
/// - `out_ptr` is NULL or `out` is not in bounds of WASM memory.
pub fn identity(out_ptr: *mut u8);
}
/// What strategy does the database index use?
///
/// See also: <https://www.postgresql.org/docs/current/sql-createindex.html>
#[repr(u8)]
#[non_exhaustive]
pub enum IndexType {
/// Indexing works by putting the index key into a b-tree.
BTree = 0,
/// Indexing works by hashing the index key.
Hash = 1,
}
/// The error log level. See [`console_log`].
pub const LOG_LEVEL_ERROR: u8 = 0;
/// The warn log level. See [`console_log`].
pub const LOG_LEVEL_WARN: u8 = 1;
/// The info log level. See [`console_log`].
pub const LOG_LEVEL_INFO: u8 = 2;
/// The debug log level. See [`console_log`].
pub const LOG_LEVEL_DEBUG: u8 = 3;
/// The trace log level. See [`console_log`].
pub const LOG_LEVEL_TRACE: u8 = 4;
/// The panic log level. See [`console_log`].
///
/// A panic level is emitted just before a fatal error causes the WASM module to trap.
pub const LOG_LEVEL_PANIC: u8 = 101;
/// A handle into a buffer of bytes in the host environment that can be read from.
///
/// Used for transporting bytes from host to WASM linear memory.
#[derive(PartialEq, Eq, Copy, Clone)]
#[repr(transparent)]
pub struct BytesSource(u32);
impl BytesSource {
/// An invalid handle, used e.g., when the reducer arguments were empty.
pub const INVALID: Self = Self(0);
}
/// A handle into a buffer of bytes in the host environment that can be written to.
///
/// Used for transporting bytes from WASM linear memory to host.
#[derive(PartialEq, Eq, Copy, Clone)]
#[repr(transparent)]
pub struct BytesSink(u32);
/// Represents table iterators.
#[derive(PartialEq, Eq, Copy, Clone)]
#[repr(transparent)]
pub struct RowIter(u32);
impl RowIter {
/// An invalid handle, used e.g., when the iterator has been exhausted.
pub const INVALID: Self = Self(0);
}
#[cfg(any())]
mod module_exports {
type Encoded<T> = Buffer;
type Identity = Encoded<[u8; 32]>;
/// Microseconds since the unix epoch
type Timestamp = u64;
/// Buffer::INVALID => Ok(()); else errmsg => Err(errmsg)
type Result = Buffer;
extern "C" {
/// All functions prefixed with `__preinit__` are run first in alphabetical order.
/// For those it's recommended to use /etc/xxxx.d conventions of like `__preinit__20_do_thing`:
/// <https://man7.org/linux/man-pages/man5/sysctl.d.5.html#CONFIGURATION_DIRECTORIES_AND_PRECEDENCE>
fn __preinit__XX_XXXX();
/// Optional. Run after `__preinit__`; can return an error. Intended for dynamic languages; this
/// would be where you would initialize the interepreter and load the user module into it.
fn __setup__() -> Result;
/// Required. Runs after `__setup__`; returns all the exports for the module.
fn __describe_module__() -> Encoded<ModuleDef>;
/// Required. id is an index into the `ModuleDef.reducers` returned from `__describe_module__`.
/// args is a bsatn-encoded product value defined by the schema at `reducers[id]`.
fn __call_reducer__(
id: usize,
sender_0: u64,
sender_1: u64,
sender_2: u64,
sender_3: u64,
conn_id_0: u64,
conn_id_1: u64,
timestamp: u64,
args: Buffer,
) -> Result;
/// Currently unused?
fn __migrate_database__XXXX(sender: Identity, timestamp: Timestamp, something: Buffer) -> Result;
}
}
}
/// Error values used in the safe bindings API.
#[derive(Copy, Clone, PartialEq, Eq)]
#[repr(transparent)]
pub struct Errno(NonZeroU16);
// once Error gets exposed from core this crate can be no_std again
impl std::error::Error for Errno {}
pub type Result<T, E = Errno> = core::result::Result<T, E>;
macro_rules! def_errno {
($($err_name:ident($errno:literal, $errmsg:literal),)*) => {
impl Errno {
$(#[doc = $errmsg] pub const $err_name: Errno = Errno(errno::$err_name);)*
}
};
}
errnos!(def_errno);
impl Errno {
/// Returns a description of the errno value, if any.
pub const fn message(self) -> Option<&'static str> {
errno::strerror(self.0)
}
/// Converts the given `code` to an error number in `Errno`'s representation.
#[inline]
pub const fn from_code(code: u16) -> Option<Self> {
match NonZeroU16::new(code) {
Some(code) => Some(Errno(code)),
None => None,
}
}
/// Converts this `errno` into a primitive error code.
#[inline]
pub const fn code(self) -> u16 {
self.0.get()
}
}
impl fmt::Debug for Errno {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut fmt = f.debug_struct("Errno");
fmt.field("code", &self.code());
if let Some(msg) = self.message() {
fmt.field("message", &msg);
}
fmt.finish()
}
}
impl fmt::Display for Errno {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let message = self.message().unwrap_or("Unknown error");
write!(f, "{message} (error {})", self.code())
}
}
/// Convert the status value `x` into a result.
/// When `x = 0`, we have a success status.
fn cvt(x: u16) -> Result<(), Errno> {
match Errno::from_code(x) {
None => Ok(()),
Some(err) => Err(err),
}
}
/// Runs the given function `f` provided with an uninitialized `out` pointer.
///
/// Assuming the call to `f` succeeds (`Ok(_)`), the `out` pointer's value is returned.
///
/// # Safety
///
/// This function is safe to call, if and only if,
/// - The function `f` writes a safe and valid `T` to the `out` pointer.
/// It's not required to write to `out` when `f(out)` returns an error code.
/// - The function `f` never reads a safe and valid `T` from the `out` pointer
/// before writing a safe and valid `T` to it.
#[inline]
unsafe fn call<T: Copy>(f: impl FnOnce(*mut T) -> u16) -> Result<T, Errno> {
let mut out = MaybeUninit::uninit();
let f_code = f(out.as_mut_ptr());
cvt(f_code)?;
Ok(out.assume_init())
}
/// Queries the `table_id` associated with the given (table) `name`.
///
/// The table id is returned.
///
/// # Errors
///
/// Returns an error:
///
/// - `NOT_IN_TRANSACTION`, when called outside of a transaction.
/// - `NO_SUCH_TABLE`, when `name` is not the name of a table.
#[inline]
pub fn table_id_from_name(name: &str) -> Result<TableId, Errno> {
unsafe { call(|out| raw::table_id_from_name(name.as_ptr(), name.len(), out)) }
}
/// Queries the `index_id` associated with the given (index) `name`.
///
/// The index id is returned.
///
/// # Errors
///
/// Returns an error:
///
/// - `NOT_IN_TRANSACTION`, when called outside of a transaction.
/// - `NO_SUCH_INDEX`, when `name` is not the name of an index.
#[inline]
pub fn index_id_from_name(name: &str) -> Result<IndexId, Errno> {
unsafe { call(|out| raw::index_id_from_name(name.as_ptr(), name.len(), out)) }
}
/// Returns the number of rows currently in table identified by `table_id`.
///
/// # Errors
///
/// Returns an error:
///
/// - `NOT_IN_TRANSACTION`, when called outside of a transaction.
/// - `NO_SUCH_TABLE`, when `table_id` is not a known ID of a table.
#[inline]
pub fn datastore_table_row_count(table_id: TableId) -> Result<u64, Errno> {
unsafe { call(|out| raw::datastore_table_row_count(table_id, out)) }
}
/// Inserts a row into the table identified by `table_id`,
/// where the row is a BSATN-encoded `ProductValue`
/// matching the table's `ProductType` row-schema.
///
/// The `row` is `&mut` due to auto-incrementing columns.
/// So `row` is written to with the inserted row re-encoded.
///
/// Returns an error if
/// - a table with the provided `table_id` doesn't exist
/// - there were unique constraint violations
/// - `row` doesn't decode from BSATN to a `ProductValue`
/// according to the `ProductType` that the table's schema specifies.
#[inline]
pub fn datastore_insert_bsatn(table_id: TableId, row: &mut [u8]) -> Result<&[u8], Errno> {
let row_ptr = row.as_mut_ptr();
let row_len = &mut row.len();
cvt(unsafe { raw::datastore_insert_bsatn(table_id, row_ptr, row_len) }).map(|()| &row[..*row_len])
}
/// Updates a row into the table identified by `table_id`,
/// where the row is a BSATN-encoded `ProductValue`
/// matching the table's `ProductType` row-schema.
///
/// The row to update is found by projecting `row`
/// to the type of the *unique* index identified by `index_id`.
/// If no row is found, `row` is inserted.
///
/// The `row` is `&mut` due to auto-incrementing columns.
/// So `row` is written to with the updated row re-encoded.
///
/// Returns an error if
/// - a table with the provided `table_id` doesn't exist
/// - an index with the provided `index_id` doesn't exist or if the index was not unique.
/// - there were unique constraint violations
/// - `row` doesn't decode from BSATN to a `ProductValue`
/// according to the `ProductType` that the table's schema specifies
/// or if `row` cannot project to the index's type.
/// - the row was not found
#[inline]
pub fn datastore_update_bsatn(table_id: TableId, index_id: IndexId, row: &mut [u8]) -> Result<&[u8], Errno> {
let row_ptr = row.as_mut_ptr();
let row_len = &mut row.len();
cvt(unsafe { raw::datastore_update_bsatn(table_id, index_id, row_ptr, row_len) }).map(|()| &row[..*row_len])
}
/// Deletes those rows, in the table identified by `table_id`,
/// that match any row in the byte string `relation`.
///
/// Matching is defined by first BSATN-decoding
/// the byte string pointed to at by `relation` to a `Vec<ProductValue>`
/// according to the row schema of the table
/// and then using `Ord for AlgebraicValue`.
/// A match happens when `Ordering::Equal` is returned from `fn cmp`.
/// This occurs exactly when the row's BSATN-encoding is equal to the encoding of the `ProductValue`.
///
/// The number of rows deleted is returned.
///
/// # Errors
///
/// Returns an error:
///
/// - `NOT_IN_TRANSACTION`, when called outside of a transaction.
/// - `NO_SUCH_TABLE`, when `table_id` is not a known ID of a table.
/// - `BSATN_DECODE_ERROR`, when `rel` cannot be decoded to `Vec<ProductValue>`
/// where each `ProductValue` is typed at the `ProductType` the table's schema specifies.
#[inline]
pub fn datastore_delete_all_by_eq_bsatn(table_id: TableId, relation: &[u8]) -> Result<u32, Errno> {
unsafe { call(|out| raw::datastore_delete_all_by_eq_bsatn(table_id, relation.as_ptr(), relation.len(), out)) }
}
/// Starts iteration on each row, as BSATN-encoded, of a table identified by `table_id`.
/// Returns iterator handle is written to the `out` pointer.
/// This handle can be advanced by [`RowIter::read`].
///
/// # Errors
///
/// Returns an error:
///
/// - `NOT_IN_TRANSACTION`, when called outside of a transaction.
/// - `NO_SUCH_TABLE`, when `table_id` is not a known ID of a table.
pub fn datastore_table_scan_bsatn(table_id: TableId) -> Result<RowIter, Errno> {
let raw = unsafe { call(|out| raw::datastore_table_scan_bsatn(table_id, out))? };
Ok(RowIter { raw })
}
/// Finds all rows in the index identified by `index_id`,
/// according to the `prefix`, `rstart`, and `rend`.
///
/// The index itself has a schema/type.
/// The `prefix` is decoded to the initial `prefix_elems` `AlgebraicType`s
/// whereas `rstart` and `rend` are decoded to the `prefix_elems + 1` `AlgebraicType`
/// where the `AlgebraicValue`s are wrapped in `Bound`.
/// That is, `rstart, rend` are BSATN-encoded `Bound<AlgebraicValue>`s.
///
/// Matching is then defined by equating `prefix`
/// to the initial `prefix_elems` columns of the index
/// and then imposing `rstart` as the starting bound
/// and `rend` as the ending bound on the `prefix_elems + 1` column of the index.
/// Remaining columns of the index are then unbounded.
/// Note that the `prefix` in this case can be empty (`prefix_elems = 0`),
/// in which case this becomes a ranged index scan on a single-col index
/// or even a full table scan if `rstart` and `rend` are both unbounded.
///
/// The relevant table for the index is found implicitly via the `index_id`,
/// which is unique for the module.
///
/// On success, the iterator handle is written to the `out` pointer.
/// This handle can be advanced by [`RowIter::read`].
///
/// # Non-obvious queries
///
/// For an index on columns `[a, b, c]`:
///
/// - `a = x, b = y` is encoded as a prefix `[x, y]`
/// and a range `Range::Unbounded`,
/// or as a prefix `[x]` and a range `rstart = rend = Range::Inclusive(y)`.
/// - `a = x, b = y, c = z` is encoded as a prefix `[x, y]`
/// and a range `rstart = rend = Range::Inclusive(z)`.
/// - A sorted full scan is encoded as an empty prefix
/// and a range `Range::Unbounded`.
///
/// # Errors
///
/// Returns an error:
///
/// - `NOT_IN_TRANSACTION`, when called outside of a transaction.
/// - `NO_SUCH_INDEX`, when `index_id` is not a known ID of an index.
/// - `WRONG_INDEX_ALGO` if the index is not a range-compatible index.
/// - `BSATN_DECODE_ERROR`, when `prefix` cannot be decoded to
/// a `prefix_elems` number of `AlgebraicValue`
/// typed at the initial `prefix_elems` `AlgebraicType`s of the index's key type.
/// Or when `rstart` or `rend` cannot be decoded to an `Bound<AlgebraicValue>`
/// where the inner `AlgebraicValue`s are
/// typed at the `prefix_elems + 1` `AlgebraicType` of the index's key type.
pub fn datastore_index_scan_range_bsatn(
index_id: IndexId,
prefix: &[u8],
prefix_elems: ColId,
rstart: &[u8],
rend: &[u8],
) -> Result<RowIter, Errno> {
let raw = unsafe {
call(|out| {
raw::datastore_index_scan_range_bsatn(
index_id,
prefix.as_ptr(),
prefix.len(),
prefix_elems,
rstart.as_ptr(),
rstart.len(),
rend.as_ptr(),
rend.len(),
out,
)
})?
};
Ok(RowIter { raw })
}
/// Deletes all rows found in the index identified by `index_id`,
/// according to the `prefix`, `rstart`, and `rend`.
///
/// This syscall will delete all the rows found by
/// [`datastore_index_scan_range_bsatn`] with the same arguments passed,
/// including `prefix_elems`.
/// See `datastore_index_scan_range_bsatn` for details.
///
/// The number of rows deleted is returned on success.
///
/// # Errors
///
/// Returns an error:
///
/// - `NOT_IN_TRANSACTION`, when called outside of a transaction.
/// - `NO_SUCH_INDEX`, when `index_id` is not a known ID of an index.
/// - `WRONG_INDEX_ALGO` if the index is not a range-compatible index.
/// - `BSATN_DECODE_ERROR`, when `prefix` cannot be decoded to
/// a `prefix_elems` number of `AlgebraicValue`
/// typed at the initial `prefix_elems` `AlgebraicType`s of the index's key type.
/// Or when `rstart` or `rend` cannot be decoded to an `Bound<AlgebraicValue>`
/// where the inner `AlgebraicValue`s are
/// typed at the `prefix_elems + 1` `AlgebraicType` of the index's key type.
pub fn datastore_delete_by_index_scan_range_bsatn(
index_id: IndexId,
prefix: &[u8],