redjs 0.4.0

Full-control Rust embedding layer over Bun's JavaScriptCore prebuilt. C ABI designed for zero-alloc C# (NativeAOT) codegen bindings.
Documentation
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
//! `IDBDatabase` (a connection) and `IDBTransaction`.

use core::ffi::c_void;
use std::collections::VecDeque;

use super::backend::*;
use super::client::*;
use super::common::*;
use super::keypath::{self, KeyPath};
use super::server::{self, Mode, Op, ToServer};
use crate::webapi::util::*;

const D: &str = "IDBDatabase";
const T: &str = "IDBTransaction";

unsafe fn is_db(g: *mut c_void, v: u64) -> bool {
    db_of(g, v).is_some()
}

unsafe fn is_tx(g: *mut c_void, v: u64) -> bool {
    tx_of(g, v).is_some()
}

handler!(db_get_onabort, db_set_onabort, "onabort", is_db);
handler!(db_get_onclose, db_set_onclose, "onclose", is_db);
handler!(db_get_onerror, db_set_onerror, "onerror", is_db);
handler!(db_get_onversionchange, db_set_onversionchange, "onversionchange", is_db);
handler!(tx_get_onabort, tx_set_onabort, "onabort", is_tx);
handler!(tx_get_oncomplete, tx_set_oncomplete, "oncomplete", is_tx);
handler!(tx_get_onerror, tx_set_onerror, "onerror", is_tx);

pub(super) const DATABASE: ClassSpec<'static> = ClassSpec {
    name: "IDBDatabase",
    arity: 0,
    construct: None,
    parent_proto: 0,
    methods: &[
        ("transaction", 1, db_transaction),
        ("createObjectStore", 1, db_create_store),
        ("deleteObjectStore", 1, db_delete_store),
        ("close", 0, db_close),
    ],
    getters: &[("name", db_name), ("version", db_version), ("objectStoreNames", db_store_names)],
    accessors: &[
        ("onabort", db_get_onabort, db_set_onabort),
        ("onclose", db_get_onclose, db_set_onclose),
        ("onerror", db_get_onerror, db_set_onerror),
        ("onversionchange", db_get_onversionchange, db_set_onversionchange),
    ],
};

pub(super) const TRANSACTION: ClassSpec<'static> = ClassSpec {
    name: "IDBTransaction",
    arity: 0,
    construct: None,
    parent_proto: 0,
    methods: &[("objectStore", 1, tx_object_store), ("commit", 0, tx_commit), ("abort", 0, tx_abort)],
    getters: &[
        ("objectStoreNames", tx_store_names),
        ("mode", tx_mode),
        ("durability", tx_durability),
        ("db", tx_db),
        ("error", tx_error),
    ],
    accessors: &[
        ("onabort", tx_get_onabort, tx_set_onabort),
        ("oncomplete", tx_get_oncomplete, tx_set_oncomplete),
        ("onerror", tx_get_onerror, tx_set_onerror),
    ],
};

// ---------------------------------------------------------------------------
// IDBDatabase
// ---------------------------------------------------------------------------

#[crate::host_fn]
unsafe fn db_name(g: *mut c_void, cf: *mut c_void) -> u64 {
    let Some(dd) = db_of(g, cf_this(cf)) else { return illegal(g) };
    let n = dd.meta.name.clone();
    js_string16(g, &n)
}

#[crate::host_fn]
unsafe fn db_version(g: *mut c_void, cf: *mut c_void) -> u64 {
    let Some(dd) = db_of(g, cf_this(cf)) else { return illegal(g) };
    enc_f64(dd.meta.version as f64)
}

#[crate::host_fn]
unsafe fn db_store_names(g: *mut c_void, cf: *mut c_void) -> u64 {
    let Some(dd) = db_of(g, cf_this(cf)) else { return illegal(g) };
    let names = dd.meta.stores.iter().map(|s| s.name.clone()).collect();
    string_list(g, names, true)
}

/// The live (unfinished) upgrade transaction of a connection, if any.
unsafe fn live_upgrade(g: *mut c_void, db: u64) -> Option<u64> {
    let up = db_of(g, db)?.upgrade;
    if up == 0 {
        return None;
    }
    let o = cl(g).borrow().txs.get(&up).copied()?;
    Some(o)
}

#[crate::host_fn]
unsafe fn db_transaction(g: *mut c_void, cf: *mut c_void) -> u64 {
    let this = cf_this(cf);
    if !is_db(g, this) {
        return illegal(g);
    }
    if !args(g, cf, 1, D, "transaction") {
        return UNDEF;
    }
    let names = match keypath::from_js(g, cf_arg(cf, 0)) {
        Ok(KeyPath::String(s)) => vec![s],
        Ok(KeyPath::List(l)) => l,
        Err(()) => return UNDEF,
    };
    let mv = cf_arg(cf, 1);
    let mode = if mv == UNDEF {
        Mode::ReadOnly
    } else {
        let Ok(s) = str16(g, mv) else { return UNDEF };
        match String::from_utf16_lossy(&s).as_str() {
            "readonly" => Mode::ReadOnly,
            "readwrite" => Mode::ReadWrite,
            "versionchange" => Mode::VersionChange,
            other => {
                return throw_type_error(
                    g,
                    &format!("Failed to execute 'transaction' on 'IDBDatabase': The provided value '{other}' is not a valid enum value of type IDBTransactionMode."),
                )
            }
        }
    };
    let ov = cf_arg(cf, 2);
    let durability = if ov == UNDEF || ov == NULL {
        Durability::Default
    } else if !is_object(g, ov) {
        return throw_type_error(g, "Failed to execute 'transaction' on 'IDBDatabase': The provided value is not of type 'IDBTransactionOptions'.");
    } else {
        let Ok(d) = try_get(g, ov, "durability") else { return UNDEF };
        if d == UNDEF {
            Durability::Default
        } else {
            let Ok(s) = str16(g, d) else { return UNDEF };
            match String::from_utf16_lossy(&s).as_str() {
                "default" => Durability::Default,
                "strict" => Durability::Strict,
                "relaxed" => Durability::Relaxed,
                other => {
                    return throw_type_error(
                        g,
                        &format!("Failed to read the 'durability' property from 'IDBTransactionOptions': The provided value '{other}' is not a valid enum value of type IDBTransactionDurability."),
                    )
                }
            }
        }
    };
    if let Some(up) = live_upgrade(g, this) {
        if tx_of(g, up).map(|t| t.state != TxState::Finished).unwrap_or(false) {
            return fail(g, "InvalidStateError", D, "transaction", "A version change transaction is running.");
        }
    }
    let Some(dd) = db_of(g, this) else { return UNDEF };
    if dd.close_pending {
        return fail(g, "InvalidStateError", D, "transaction", "The database connection is closing.");
    }
    let mut scope = names;
    scope.sort();
    scope.dedup();
    let mut ids = Vec::with_capacity(scope.len());
    for n in &scope {
        match dd.meta.store_by_name(n) {
            Some(s) => ids.push(s.id),
            None => return fail(g, "NotFoundError", D, "transaction", "One of the specified object stores was not found."),
        }
    }
    if scope.is_empty() {
        return fail(g, "InvalidAccessError", D, "transaction", "The storeNames parameter was empty.");
    }
    if mode == Mode::VersionChange {
        return throw_type_error(g, "Failed to execute 'transaction' on 'IDBDatabase': The mode provided ('versionchange') is not one of 'readonly' or 'readwrite'.");
    }
    let conn = dd.conn;
    let id = super::next_id();
    let data = TxData {
        id,
        mode,
        durability,
        state: TxState::Active,
        names: scope,
        pending: VecDeque::new(),
        outstanding: 0,
        commit_sent: false,
        upgrade: false,
        snapshot: None,
        handles: Vec::new(),
        aborted_reqs: Vec::new(),
    };
    let tx = new_transaction(g, data, this);
    let ctx = {
        let mut c = cl(g).borrow_mut();
        c.fresh.push(id);
        c.ctx
    };
    server::send(ToServer::Begin { ctx, conn, tx: id, scope: ids, mode, durability });
    if crate::web::in_coalesced_callback() {
        super::advise_d1();
    }
    tx
}

/// The upgrade transaction, active, or the exception thrown.
unsafe fn upgrade_tx(g: *mut c_void, db: u64, method: &str) -> Option<u64> {
    let Some(tx) = live_upgrade(g, db) else {
        fail(g, "InvalidStateError", D, method, "The database is not running a version change transaction.");
        return None;
    };
    if tx_of(g, tx).map(|t| t.state != TxState::Active).unwrap_or(true) {
        fail(g, "TransactionInactiveError", D, method, "The transaction is not active.");
        return None;
    }
    Some(tx)
}

#[crate::host_fn]
unsafe fn db_create_store(g: *mut c_void, cf: *mut c_void) -> u64 {
    let this = cf_this(cf);
    if !is_db(g, this) {
        return illegal(g);
    }
    if !args(g, cf, 1, D, "createObjectStore") {
        return UNDEF;
    }
    let Ok(name) = str16(g, cf_arg(cf, 0)) else { return UNDEF };
    let ov = cf_arg(cf, 1);
    let (auto_increment, key_path) = if ov == UNDEF || ov == NULL {
        (false, None)
    } else if !is_object(g, ov) {
        return throw_type_error(g, "Failed to execute 'createObjectStore' on 'IDBDatabase': The provided value is not of type 'IDBObjectStoreParameters'.");
    } else {
        // Dictionary members in lexicographic order.
        let Ok(ai) = try_get(g, ov, "autoIncrement") else { return UNDEF };
        let ai = crate::glue::rjs_to_boolean(g, ai) != 0;
        let Ok(kv) = try_get(g, ov, "keyPath") else { return UNDEF };
        let kp = if kv == UNDEF || kv == NULL {
            None
        } else {
            match keypath::from_js(g, kv) {
                Ok(k) => Some(k),
                Err(()) => return UNDEF,
            }
        };
        (ai, kp)
    };
    let Some(tx) = upgrade_tx(g, this, "createObjectStore") else { return UNDEF };
    if let Some(kp) = &key_path {
        if !keypath::valid(g, kp) {
            return fail(g, "SyntaxError", D, "createObjectStore", "The keyPath option is not a valid key path.");
        }
    }
    let Some(dd) = db_of(g, this) else { return UNDEF };
    if dd.meta.store_by_name(&name).is_some() {
        return fail(g, "ConstraintError", D, "createObjectStore", "An object store with the specified name already exists.");
    }
    if auto_increment && matches!(&key_path, Some(k) if k.is_list() || k.is_empty_string()) {
        return fail(
            g,
            "InvalidAccessError",
            D,
            "createObjectStore",
            "The autoIncrement option was set but the keyPath option was empty or an array.",
        );
    }
    let id = dd.alloc_id();
    let meta = StoreMeta { id, name, key_path, auto_increment, indexes: Vec::new() };
    dd.meta.stores.push(meta.clone());
    schema_op(g, tx, Op::CreateStore(meta.clone()));
    store_handle(g, tx, &meta)
}

#[crate::host_fn]
unsafe fn db_delete_store(g: *mut c_void, cf: *mut c_void) -> u64 {
    let this = cf_this(cf);
    if !is_db(g, this) {
        return illegal(g);
    }
    if !args(g, cf, 1, D, "deleteObjectStore") {
        return UNDEF;
    }
    let Ok(name) = str16(g, cf_arg(cf, 0)) else { return UNDEF };
    let Some(tx) = upgrade_tx(g, this, "deleteObjectStore") else { return UNDEF };
    let Some(dd) = db_of(g, this) else { return UNDEF };
    let Some(pos) = dd.meta.stores.iter().position(|s| s.name == name) else {
        return fail(g, "NotFoundError", D, "deleteObjectStore", "The specified object store was not found.");
    };
    let meta = dd.meta.stores.remove(pos);
    mark_store_deleted(g, tx, meta.id);
    schema_op(g, tx, Op::DeleteStore(meta.id));
    UNDEF
}

/// The handle of a deleted store (and its index handles) reports deleted.
unsafe fn mark_store_deleted(g: *mut c_void, tx: u64, id: StoreId) {
    let Some(i) = tx_of(g, tx).and_then(|t| t.handles.iter().position(|s| *s == id)) else { return };
    let h = get_i(g, bget(g, tx, "stores"), i as u32);
    let Some(sd) = store_of(g, h) else { return };
    sd.deleted = true;
    // "Remove all entries from its index set" (indexNames is empty at once).
    sd.meta.indexes.clear();
    let n = sd.handles.len();
    let arr = bget(g, h, "indexes");
    for j in 0..n {
        if let Some(idd) = index_of(g, get_i(g, arr, j as u32)) {
            idd.deleted = true;
        }
    }
}

#[crate::host_fn]
unsafe fn db_close(g: *mut c_void, cf: *mut c_void) -> u64 {
    let this = cf_this(cf);
    let Some(dd) = db_of(g, this) else { return illegal(g) };
    if !dd.close_pending {
        dd.close_pending = true;
        let conn = dd.conn;
        server::send(ToServer::Close { conn });
        let o = cl(g).borrow_mut().conns.remove(&conn);
        if let Some(o) = o {
            unprotect(g, o);
        }
    }
    UNDEF
}

// ---------------------------------------------------------------------------
// IDBTransaction
// ---------------------------------------------------------------------------

#[crate::host_fn]
unsafe fn tx_object_store(g: *mut c_void, cf: *mut c_void) -> u64 {
    let this = cf_this(cf);
    if !is_tx(g, this) {
        return illegal(g);
    }
    if !args(g, cf, 1, T, "objectStore") {
        return UNDEF;
    }
    let Ok(name) = str16(g, cf_arg(cf, 0)) else { return UNDEF };
    let Some(td) = tx_of(g, this) else { return UNDEF };
    if td.state == TxState::Finished {
        return fail(g, "InvalidStateError", T, "objectStore", "The transaction has finished.");
    }
    let in_scope = td.upgrade || td.names.contains(&name);
    let db = bget(g, this, "db");
    let meta = if in_scope { db_of(g, db).and_then(|d| d.meta.store_by_name(&name).cloned()) } else { None };
    let Some(meta) = meta else {
        return fail(g, "NotFoundError", T, "objectStore", "The specified object store was not found.");
    };
    store_handle(g, this, &meta)
}

#[crate::host_fn]
unsafe fn tx_commit(g: *mut c_void, cf: *mut c_void) -> u64 {
    let this = cf_this(cf);
    let Some(td) = tx_of(g, this) else { return illegal(g) };
    if td.state != TxState::Active {
        return fail(g, "InvalidStateError", T, "commit", "The transaction is not active.");
    }
    commit(g, this);
    UNDEF
}

#[crate::host_fn]
unsafe fn tx_abort(g: *mut c_void, cf: *mut c_void) -> u64 {
    let this = cf_this(cf);
    let Some(td) = tx_of(g, this) else { return illegal(g) };
    if matches!(td.state, TxState::Committing | TxState::Finished) {
        return fail(g, "InvalidStateError", T, "abort", "The transaction has already been committed or aborted.");
    }
    td.state = TxState::Inactive;
    abort_tx(g, this, NULL, true);
    UNDEF
}

#[crate::host_fn]
unsafe fn tx_store_names(g: *mut c_void, cf: *mut c_void) -> u64 {
    let this = cf_this(cf);
    let Some(td) = tx_of(g, this) else { return illegal(g) };
    if td.upgrade {
        let db = bget(g, this, "db");
        let names = db_of(g, db).map(|d| d.meta.stores.iter().map(|s| s.name.clone()).collect()).unwrap_or_default();
        return string_list(g, names, true);
    }
    let names = td.names.clone();
    string_list(g, names, false)
}

#[crate::host_fn]
unsafe fn tx_mode(g: *mut c_void, cf: *mut c_void) -> u64 {
    let Some(td) = tx_of(g, cf_this(cf)) else { return illegal(g) };
    js_string(
        g,
        match td.mode {
            Mode::ReadOnly => "readonly",
            Mode::ReadWrite => "readwrite",
            Mode::VersionChange => "versionchange",
        },
    )
}

#[crate::host_fn]
unsafe fn tx_durability(g: *mut c_void, cf: *mut c_void) -> u64 {
    let Some(td) = tx_of(g, cf_this(cf)) else { return illegal(g) };
    js_string(
        g,
        match td.durability {
            Durability::Default => "default",
            Durability::Strict => "strict",
            Durability::Relaxed => "relaxed",
        },
    )
}

#[crate::host_fn]
unsafe fn tx_db(g: *mut c_void, cf: *mut c_void) -> u64 {
    let this = cf_this(cf);
    if !is_tx(g, this) {
        return illegal(g);
    }
    bget(g, this, "db")
}

#[crate::host_fn]
unsafe fn tx_error(g: *mut c_void, cf: *mut c_void) -> u64 {
    let this = cf_this(cf);
    if !is_tx(g, this) {
        return illegal(g);
    }
    bget(g, this, "error")
}