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
extern crate alloc;

#[macro_use]
mod errno;

use core::fmt;
use core::mem::MaybeUninit;
use core::num::NonZeroU16;
use std::ptr::{self};

use alloc::boxed::Box;

pub const ABI_VERSION: u32 = 0x0002_0000;

pub mod raw {
    use core::mem::ManuallyDrop;

    #[link(wasm_import_module = "spacetime")]
    extern "C" {
        pub fn _create_table(
            name: *const u8,
            name_len: usize,
            schema: *const u8,
            schema_len: usize,
            out: *mut u32,
        ) -> u16;
        pub fn _get_table_id(name: *const u8, name_len: usize, out: *mut u32) -> u16;
        pub fn _create_index(
            index_name: *const u8,
            index_name_len: usize,
            table_id: u32,
            index_type: u8,
            col_ids: *const u8,
            col_len: usize,
        ) -> u16;
        pub fn _seek_eq(table_id: u32, col_id: u32, value: *const u8, value_len: usize, out: *mut Buffer) -> u16;

        pub fn _insert(table_id: u32, row: *mut u8, row_len: usize) -> u16;

        pub fn _delete_pk(table_id: u32, pk: *const u8, pk_len: usize) -> u16;
        pub fn _delete_value(table_id: u32, row: *const u8, row_len: usize) -> u16;
        pub fn _delete_eq(table_id: u32, col_id: u32, value: *const u8, value_len: usize, out: *mut u32) -> u16;
        pub fn _delete_range(
            table_id: u32,
            col_id: u32,
            range_start: *const u8,
            range_start_len: usize,
            range_end: *const u8,
            range_end_len: usize,
            out: *mut u32,
        ) -> u16;

        // pub fn _filter_eq(table_id: u32, col_id: u32, src_ptr: *const u8, result_ptr: *const u8);

        pub fn _iter_start(table_id: u32, out: *mut BufferIter) -> u16;
        pub fn _iter_start_filtered(table_id: u32, filter: *const u8, filter_len: usize, out: *mut BufferIter) -> u16;
        pub fn _iter_next(iter: ManuallyDrop<BufferIter>, out: *mut Buffer) -> u16;
        pub fn _iter_drop(iter: ManuallyDrop<BufferIter>) -> u16;
        pub fn _console_log(
            level: u8,
            target: *const u8,
            target_len: usize,
            filename: *const u8,
            filename_len: usize,
            line_number: u32,
            text: *const u8,
            text_len: usize,
        );

        pub fn _schedule_reducer(
            name: *const u8,
            name_len: usize,
            args: *const u8,
            args_len: usize,
            time: u64,
            out: *mut u64,
        );
        pub fn _cancel_reducer(id: u64);

        pub fn _buffer_len(bufh: ManuallyDrop<Buffer>) -> usize;
        pub fn _buffer_consume(bufh: Buffer, into: *mut u8, len: usize);
        pub fn _buffer_alloc(data: *const u8, data_len: usize) -> Buffer;
    }

    #[repr(u8)]
    #[non_exhaustive]
    pub enum IndexType {
        BTree = 0,
        Hash = 1,
    }

    pub const LOG_LEVEL_ERROR: u8 = 0;
    pub const LOG_LEVEL_WARN: u8 = 1;
    pub const LOG_LEVEL_INFO: u8 = 2;
    pub const LOG_LEVEL_DEBUG: u8 = 3;
    pub const LOG_LEVEL_TRACE: u8 = 4;
    pub const LOG_LEVEL_PANIC: u8 = 101;

    #[repr(transparent)]
    pub struct Buffer {
        raw: u32,
    }
    impl Buffer {
        /// Returns a "handle" that can be passed across the FFI boundary
        /// as if it was the Buffer itself, but without consuming it.
        pub const fn handle(&self) -> ManuallyDrop<Self> {
            ManuallyDrop::new(Self { raw: self.raw })
        }

        pub const INVALID: Self = Self { raw: u32::MAX };

        pub const fn is_invalid(&self) -> bool {
            self.raw == Self::INVALID.raw
        }
    }

    // Similar API to Buffer, but represents table iterators.
    #[repr(transparent)]
    pub struct BufferIter {
        raw: u32,
    }
    impl BufferIter {
        pub const fn handle(&self) -> ManuallyDrop<Self> {
            ManuallyDrop::new(Self { raw: self.raw })
        }
    }

    #[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: Identity, timestamp: Timestamp, args: Buffer) -> Result;
            /// Optional. Called when a client connects to the database.
            fn __identity_connected__(sender: Identity, timestamp: Timestamp) -> Result;
            /// Optional. Called when a client disconnects to the database.
            fn __identity_disconnected__(sender: Identity, timestamp: Timestamp) -> Result;
            /// Currently unused?
            fn __migrate_database__XXXX(sender: Identity, timestamp: Timestamp, something: Buffer) -> Result;
        }
    }
}

#[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 {}

macro_rules! def_errno {
    ($($name:ident => $desc:literal,)*) => {
        impl Errno {
            $(#[doc = $desc] pub const $name: Errno = Errno(unsafe { NonZeroU16::new_unchecked(errno::$name) });)*
        }
        const fn strerror(err: Errno) -> Option<&'static str> {
            match err {
                $(Errno::$name => Some($desc),)*
                _ => None,
            }
        }
    };
}
errnos!(def_errno);

impl Errno {
    /// Get a description of the errno value, if it has one
    pub const fn message(self) -> Option<&'static str> {
        strerror(self)
    }
    #[inline]
    pub const fn from_code(code: u16) -> Option<Self> {
        match NonZeroU16::new(code) {
            Some(code) => Some(Errno(code)),
            None => None,
        }
    }
    #[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())
    }
}

fn cvt(x: u16) -> Result<(), Errno> {
    match Errno::from_code(x) {
        None => Ok(()),
        Some(err) => Err(err),
    }
}

#[inline]
unsafe fn call<T>(f: impl FnOnce(*mut T) -> u16) -> Result<T, Errno> {
    let mut ret = MaybeUninit::uninit();
    cvt(f(ret.as_mut_ptr()))?;
    Ok(ret.assume_init())
}

#[inline]
pub fn create_table(name: &str, schema: &[u8]) -> Result<u32, Errno> {
    unsafe { call(|out| raw::_create_table(name.as_ptr(), name.len(), schema.as_ptr(), schema.len(), out)) }
}

#[inline]
pub fn get_table_id(name: &str) -> Result<u32, Errno> {
    unsafe { call(|out| raw::_get_table_id(name.as_ptr(), name.len(), out)) }
}

#[inline]
pub fn create_index(index_name: &str, table_id: u32, index_type: u8, col_ids: &[u8]) -> Result<(), Errno> {
    cvt(unsafe {
        raw::_create_index(
            index_name.as_ptr(),
            index_name.len(),
            table_id,
            index_type,
            col_ids.as_ptr(),
            col_ids.len(),
        )
    })
}

#[inline]
pub fn seek_eq(table_id: u32, col_id: u32, val: &[u8]) -> Result<Buffer, Errno> {
    unsafe { call(|out| raw::_seek_eq(table_id, col_id, val.as_ptr(), val.len(), out)) }
}

#[inline]
pub fn insert(table_id: u32, row: &mut [u8]) -> Result<(), Errno> {
    cvt(unsafe { raw::_insert(table_id, row.as_mut_ptr(), row.len()) })
}

#[inline]
pub fn delete_pk(table_id: u32, pk: &[u8]) -> Result<(), Errno> {
    cvt(unsafe { raw::_delete_pk(table_id, pk.as_ptr(), pk.len()) })
}
#[inline]
pub fn delete_value(table_id: u32, row: &[u8]) -> Result<(), Errno> {
    cvt(unsafe { raw::_delete_value(table_id, row.as_ptr(), row.len()) })
}
#[inline]
pub fn delete_eq(table_id: u32, col_id: u32, value: &[u8]) -> Result<u32, Errno> {
    unsafe { call(|out| raw::_delete_eq(table_id, col_id, value.as_ptr(), value.len(), out)) }
}
#[inline]
pub fn delete_range(table_id: u32, col_id: u32, range_start: &[u8], range_end: &[u8]) -> Result<u32, Errno> {
    unsafe {
        call(|out| {
            raw::_delete_range(
                table_id,
                col_id,
                range_start.as_ptr(),
                range_start.len(),
                range_end.as_ptr(),
                range_end.len(),
                out,
            )
        })
    }
}

// not yet implemented
// #[inline]
// pub fn filter_eq(table_id: u32, col_id: u32, src_ptr: *mut u8, result_ptr: *mut u8) {}

#[inline]
pub fn iter(table_id: u32, filter: Option<&[u8]>) -> Result<BufferIter, Errno> {
    unsafe {
        call(|out| match filter {
            None => raw::_iter_start(table_id, out),
            Some(filter) => raw::_iter_start_filtered(table_id, filter.as_ptr(), filter.len(), out),
        })
    }
}

#[repr(u8)]
pub enum LogLevel {
    Error = raw::LOG_LEVEL_ERROR,
    Warn = raw::LOG_LEVEL_WARN,
    Info = raw::LOG_LEVEL_INFO,
    Debug = raw::LOG_LEVEL_DEBUG,
    Trace = raw::LOG_LEVEL_TRACE,
    Panic = raw::LOG_LEVEL_PANIC,
}
#[inline]
pub fn console_log(
    level: LogLevel,
    target: Option<&str>,
    filename: Option<&str>,
    line_number: Option<u32>,
    text: &str,
) {
    let opt_ptr = |b: Option<&str>| b.map_or(ptr::null(), |b| b.as_ptr());
    let opt_len = |b: Option<&str>| b.map_or(0, |b| b.len());
    unsafe {
        raw::_console_log(
            level as u8,
            opt_ptr(target),
            opt_len(target),
            opt_ptr(filename),
            opt_len(filename),
            line_number.unwrap_or(u32::MAX),
            text.as_ptr(),
            text.len(),
        )
    }
}

/// not fully implemented yet
#[inline]
pub fn schedule(name: &str, args: &[u8], time: u64) -> u64 {
    let mut out = 0;
    unsafe { raw::_schedule_reducer(name.as_ptr(), name.len(), args.as_ptr(), args.len(), time, &mut out) }
    out
}
pub fn cancel_reducer(id: u64) {
    unsafe { raw::_cancel_reducer(id) }
}

pub use raw::{Buffer, BufferIter};

impl Buffer {
    pub fn data_len(&self) -> usize {
        unsafe { raw::_buffer_len(self.handle()) }
    }

    pub fn read(self) -> Box<[u8]> {
        let len = self.data_len();
        let mut buf = alloc::vec::Vec::with_capacity(len);
        self.read_uninit(buf.spare_capacity_mut());
        unsafe { buf.set_len(len) };
        buf.into_boxed_slice()
    }

    /// if the length is wrong the module will crash
    pub fn read_array<const N: usize>(self) -> [u8; N] {
        // use MaybeUninit::uninit_array once stable
        let mut arr = unsafe { MaybeUninit::<[MaybeUninit<u8>; N]>::uninit().assume_init() };
        self.read_uninit(&mut arr);
        // use MaybeUninit::array_assume_init once stable
        unsafe { (&arr as *const [_; N]).cast::<[u8; N]>().read() }
    }

    pub fn read_uninit(self, buf: &mut [MaybeUninit<u8>]) {
        unsafe { raw::_buffer_consume(self, buf.as_mut_ptr().cast(), buf.len()) }
    }

    pub fn alloc(data: &[u8]) -> Self {
        unsafe { raw::_buffer_alloc(data.as_ptr(), data.len()) }
    }
}

impl Iterator for BufferIter {
    type Item = Result<Box<[u8]>, Errno>;

    fn next(&mut self) -> Option<Self::Item> {
        let buf = unsafe { call(|out| raw::_iter_next(self.handle(), out)) };
        match buf {
            Ok(buf) if buf.is_invalid() => None,
            Ok(buf) => Some(Ok(buf.read())),
            Err(e) => Some(Err(e)),
        }
    }
}

impl Drop for BufferIter {
    fn drop(&mut self) {
        cvt(unsafe { raw::_iter_drop(self.handle()) }).unwrap();
    }
}

// TODO: eventually there should be a way to set a consistent random seed for a module
#[cfg(feature = "getrandom")]
fn fake_random(buf: &mut [u8]) -> Result<(), getrandom::Error> {
    #[allow(clippy::needless_range_loop)]
    for i in 0..buf.len() {
        let start = match i % 4 {
            0 => 0x64,
            1 => 0xe9,
            2 => 0x48,
            _ => 0xb5,
        };
        buf[i] = (start ^ i) as u8;
    }

    Result::Ok(())
}
#[cfg(feature = "getrandom")]
getrandom::register_custom_getrandom!(fake_random);