js-component-bindgen 1.18.0

JS component bindgen for transpiling WebAssembly components into JavaScript
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
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
//! Intrinsics that represent helpers that implement error contexts

use crate::intrinsics::component::ComponentIntrinsic;
use crate::intrinsics::{Intrinsic, RenderIntrinsicsArgs};
use crate::source::Source;

/// This enum contains intrinsics that implement error contexts
#[derive(Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq)]
pub enum ErrCtxIntrinsic {
    /// Storage of component-wide "global" `error-context` metadata
    ///
    /// Contexts are reference counted at both the global level, and locally for a single
    /// component.
    ///
    /// Component-global counts are used along with component-local counts in order
    /// to determine when an error context can *actually* be reclaimed/removed (i.e. no longer
    /// in use in either a local component or by the host in some fashion).
    ///
    /// You can consider the type of the value referenced by this intrinsic to be:
    ///
    /// ```ts
    /// // (in-binary component-global) ~i32, stable index for a component-model-wide error-context
    /// type ErrorContextRep = number;
    /// // (in-binary component-global) u32, number of references to the given handle
    /// type GlobalRefCount = number;
    /// // ('single', component-local) debug message represented by the given error-context
    /// type DebugMessage = string;
    /// // (in-binary component-global) metadata representative of an error-context
    /// type GlobalErrorContextMeta = { refCount: number, debugMessage: string };
    ///
    /// Map<ErrorContextRep, GlobalErrorContextMeta>
    /// ```
    ComponentGlobalTable,

    /// Map of error context table to component indices
    GlobalErrCtxTableMap,

    /// Storage of per-component "local" `error-context` metadata
    ///
    /// Contexts are reference counted at the component-local level, with counts here used
    /// in addition to global counts to determine when an error context can be removed.
    ///
    /// This structure is a multi-level lookup based on sparse arrays, indexed by:
    ///   - component
    ///   - local context-error table index (i.e. the component-local id for a context-error)
    ///   - error-context handle
    ///
    /// You can consider the type of the value referenced by this intrinsic to be:
    ///
    /// ```ts
    /// // (in-binary component-global) i32, stable index for a given subcomponent inside the current component
    /// type ComponentIndex = number;
    /// // ('single' component-local) i32, stable index for a given error-context table (effectively identifies a component)
    /// type TableIndex = number;
    /// // ('single', component-local) i32, stable index for a given component's error-context
    /// type ErrorContextHandle = number;
    /// // (in-binary component-global) i32, stable index for a component-model-wide error-context
    /// type ErrorContextRep = number;
    /// // ('single', component-local) u32, number of references to the given handle
    /// type LocalRefCount = number;
    /// // ('single', component-local) information related to the local representation of this error-context
    /// type LocalErrorContextMeta = { rep: number, refCount: number };
    ///
    /// type ErrorContextComponentLocalTable = Map<
    ///   ComponentIndex,
    ///   Map<
    ///     ComponentErrorContextTableIndex,
    ///     Map<
    ///       ErrorContextHandle,
    ///       LocalErrorContextMeta
    ///     >
    ///   >
    /// >
    /// ```
    ///
    /// Note that garbage collection of an error context cannot be done unless *all* references are dropped
    /// (locally and globally)
    ComponentLocalTable,

    /// Create a new error context
    ErrorContextNew,

    /// Drop an existing error context
    ///
    /// # Intrinsic implementation function
    ///
    /// The function that implements this intrinsic has the following definition:
    ///
    /// ```ts
    /// type i32 = number;
    /// type u64 = bigint;
    /// function errCtxDrop(tbl: ErrorContextComponentLocalTable, errContextHandle: u32): bool;
    /// ```
    ///
    /// see also: [`Intrinsic::ErrorContextComponentLocalTable`]
    ErrorContextDrop,

    /// Transfer a remote error context to a local one, from one component to another
    ///
    /// Error contexts are stored and managed via the ErrorContexts intrinsic,
    /// and this intrinsic builds on that by implementing a function that will
    /// move an error context with a handle from one component that owns it to another.
    ///
    /// This intrinsic is normally invoked when an error-context is passed across a component
    /// boundary (ex. function output, closing a stream/future with an error, etc.)
    ///
    /// NOTE that error contexts unlike streams/futures/resources are reference counted --
    /// transferring one does not not drop an error context.
    ///
    /// # Intrinsic implementation function
    ///
    /// The function that implements this intrinsic has the following definition:
    ///
    /// ```ts
    /// type i32 = number;
    /// type u64 = bigint;
    /// function errCtxTransfer(tbl: ErrorContextComponentLocalTable, errContextHandle: u32): bool;
    /// ```
    ///
    ErrorContextTransfer,

    /// Retrieve the debug message for an existing error context
    ///
    /// # Intrinsic implementation function
    ///
    /// The function that implements this intrinsic has the following definition:
    ///
    /// ```ts
    /// type i32 = number;
    /// type OuputStringWriteFn = (s: string, outputPtr: u32) => void;
    /// type Options = {
    ///   callbackFnIdx?: u32,
    ///   postReturnFnIdx?: u32,
    ///   async?: bool,
    /// }
    ///
    /// function errCtxDebugMessage(
    ///   opts: Options,
    ///   writeOutput: OuputStringWriteFn,
    ///   tbl: ErrorContextComponentLocalTable,
    ///   errContextHandle: u32, // provided by CABI
    ///   outputStrPtr: u32, // provided by CABI
    /// );
    /// ```
    ///
    ErrorContextDebugMessage,

    /// Retrieve the per component sparse array lookup of error contexts
    ///
    /// See [`Intrinsics::ErrorcontextComponentLocalTable`] for the shape of the lookup.
    ///
    /// This is a utility function that is used internally but does not translate to an actual component model intrinsic.
    GetLocalTable,

    /// Increment the ref count for a component-global error-context
    ///
    /// See [`Intrinsics::ErrorcontextComponentLocalTable`] for the shape of the global error-context table.
    ///
    /// This is a utility function that is used internally but does not translate to an actual component model intrinsic.
    GlobalRefCountAdd,

    /// Create a local handle in a given component table
    ///
    /// See [`Intrinsics::ErrorcontextComponentLocalTable`] for the shape of the global error-context table.
    ///
    /// Note that this function is expected to receive a table *already* indexed by component.
    ///
    /// This is a utility function that is used internally but does not translate to an actual component model intrinsic.
    CreateLocalHandle,

    /// Reserve a new error context at the global scope, given a debug message to use
    ReserveGlobalRep,
}

impl ErrCtxIntrinsic {
    /// Retrieve dependencies for this intrinsic
    pub fn deps() -> &'static [&'static Intrinsic] {
        &[]
    }

    /// Retrieve global names for
    pub fn get_global_names() -> impl IntoIterator<Item = &'static str> {
        [
            "errCtxGlobal",
            "errCtxLocal",
            "errCtxNew",
            "errCtxDrop",
            "errCtxTransfer",
            "errCtxDebugMessage",
            "errCtxGlobalRefCountAdd",
            "errCtxGetLocalTable",
            "errCtxCreateLocalHandle",
            "errCtxReserveGlobalRep",
        ]
    }

    /// Get the name for the intrinsic
    pub fn name(&self) -> &'static str {
        match self {
            Self::ComponentGlobalTable => "GlobalErrorContextTable",
            Self::GlobalErrCtxTableMap => "ERR_CTX_TABLES",
            Self::ComponentLocalTable => "errCtxLocal",
            Self::ErrorContextNew => "errCtxNew",
            Self::ErrorContextDrop => "errCtxDrop",
            Self::ErrorContextTransfer => "errCtxTransfer",
            Self::ErrorContextDebugMessage => "errCtxDebugMessage",
            Self::GlobalRefCountAdd => "errCtxGlobalRefCountAdd",
            Self::GetLocalTable => "errCtxGetLocalTable",
            Self::CreateLocalHandle => "errCtxCreateLocalHandle",
            Self::ReserveGlobalRep => "errCtxReserveGlobalRep",
        }
    }

    /// Render an intrinsic to a string
    pub fn render(&self, output: &mut Source, _render_args: &RenderIntrinsicsArgs<'_>) {
        match self {
            Self::ComponentGlobalTable => {
                let name = Self::ComponentGlobalTable.name();
                let rep_table_class = Intrinsic::RepTableClass.name();
                output.push_str(&format!(r#"
                class {name} {{
                     static data = null;
                     static get() {{
                         if ({name}.data === null) {{
                             {name}.data = new {rep_table_class}({{ target: "global error context table" }});
                         }}
                         return {name}.data;
                     }}
                }}
                "#));
            }

            Self::GlobalErrCtxTableMap => {
                let global_err_ctx_table_map = Self::GlobalErrCtxTableMap.name();
                output.push_str(&format!(
                    r#"
                    const {global_err_ctx_table_map} = {{}};
                    "#
                ));
            }

            // NOTE: the top and middle level of the component local table are regular maps, with
            // leaves being actual `RepTable`s
            Self::ComponentLocalTable => {
                let name = Self::ComponentLocalTable.name();
                output.push_str(&format!(r#"let {name} = new Map();"#));
            }

            Self::ErrorContextNew => {
                let debug_log_fn = Intrinsic::DebugLog.name();
                let create_local_handle_fn = Self::CreateLocalHandle.name();
                let reserve_global_err_ctx_fn = Self::ReserveGlobalRep.name();
                let err_ctx_new_fn = Self::ErrorContextNew.name();
                let get_local_tbl_fn = Self::GetLocalTable.name();

                output.push_str(&format!(
                    r#"
                    function {err_ctx_new_fn}(args, msgPtr, msgLen) {{
                        {debug_log_fn}('[{err_ctx_new_fn}()] args', {{ args, msgPtr, msgLen }});
                        const {{ componentIdx, localTableIdx, readStrFn }} = args;

                        const localTable = {get_local_tbl_fn}(componentIdx, localTableIdx);
                        const debugMessage = readStrFn(msgPtr, msgLen);

                        const {{ globalRep, errCtx: globalErrCtx }} = {reserve_global_err_ctx_fn}(debugMessage, 0);

                        const {{ waitableIdx, localIdx }} = {create_local_handle_fn}(componentIdx, localTable, globalRep);

                        globalErrCtx.localIdx = localIdx;
                        globalErrCtx.waitableIdx = waitableIdx;
                        globalErrCtx.componentIdx = componentIdx;
                        globalErrCtx.localTableIdx = localTableIdx;

                        return waitableIdx;
                    }}
                "#
                ));
            }

            Self::ErrorContextDebugMessage => {
                let debug_log_fn = Intrinsic::DebugLog.name();
                let global_tbl = Self::ComponentGlobalTable.name();
                let err_ctx_debug_msg_fn = Self::ErrorContextDebugMessage.name();
                let get_or_create_async_state_fn = ComponentIntrinsic::GetOrCreateAsyncState.name();

                output.push_str(&format!(r#"
                    function {err_ctx_debug_msg_fn}(ctx, handle, outputStrPtr) {{
                        {debug_log_fn}('[{err_ctx_debug_msg_fn}()] ctx', {{ ctx, handle, outputStrPtr }});
                        const {{ componentIdx, writeStrFn }} = ctx;
                        const globalTable = {global_tbl}.get();

                        const cstate = {get_or_create_async_state_fn}(componentIdx);
                        const errCtx = cstate.handles.get(handle);
                        if (!errCtx || errCtx.globalRep === undefined) {{
                            throw new Error(`missing error context (handle [${{handle}}]) in component idx [${{componentIdx}}] during debug msg`);
                        }}

                        const msg = globalTable.get(errCtx.globalRep).debugMessage;
                        writeStrFn(msg, outputStrPtr);
                    }}
                "#));
            }

            Self::ErrorContextDrop => {
                let global_ref_count_add_fn = Self::GlobalRefCountAdd.name();
                let global_tbl = Self::ComponentGlobalTable.name();
                let err_ctx_drop_fn = Self::ErrorContextDrop.name();
                let get_local_tbl_fn = Self::GetLocalTable.name();
                let debug_log_fn = Intrinsic::DebugLog.name();
                let get_or_create_async_state_fn = ComponentIntrinsic::GetOrCreateAsyncState.name();

                output.push_str(&format!(r#"
                    function {err_ctx_drop_fn}(ctx, handle) {{
                        {debug_log_fn}('[{err_ctx_drop_fn}()] ctx', {{ ctx, handle }});
                        const {{ componentIdx, localTableIdx }} = ctx;
                        const globalTable = {global_tbl}.get();

                        const cstate = {get_or_create_async_state_fn}(componentIdx);
                        const errCtx = cstate.handles.get(handle);
                        if (!errCtx || errCtx.globalRep === undefined) {{
                            throw new Error(`missing error context (handle [${{handle}}]) in component idx [${{componentIdx}}] during drop`);
                        }}

                        const localErrCtxTable = {get_local_tbl_fn}(componentIdx, localTableIdx);
                        if (!localErrCtxTable.get(errCtx.localIdx)) {{
                            throw new Error(`missing error-context with handle [${{handle}}] in component [${{componentIdx}}] during drop`);
                        }}

                        errCtx.refCount -= 1;
                        if (errCtx.refCount <= 0) {{
                            localErrCtxTable.remove(errCtx.localIdx);
                            cstate.handles.remove(handle);
                        }}

                        const globalRefCount = {global_ref_count_add_fn}(errCtx.globalRep, -1);
                        if (globalRefCount === 0) {{
                            if (errCtx.refCount !== 0) {{ throw new Error('local refCount exceeds global during removal'); }}
                            globalTable.remove(errCtx.globalRep);
                        }}
                    }}
                "#));
            }

            Self::ErrorContextTransfer => {
                let debug_log_fn = Intrinsic::DebugLog.name();
                let get_local_tbl_fn = Self::GetLocalTable.name();
                let err_ctx_transfer_fn = Self::ErrorContextTransfer.name();
                let create_local_handle_fn = Self::CreateLocalHandle.name();
                let global_err_ctx_table_map = Self::GlobalErrCtxTableMap.name();
                let get_or_create_async_state_fn = ComponentIntrinsic::GetOrCreateAsyncState.name();

                // TODO: error contexts should be stored in handles like streams are

                // NOTE: the handle described below is *not* the error-context rep, but rather the
                // component-local handle for the canonical rep of a certain global error-context.
                //
                // handles are component instance local, reps are component (model) global
                //
                // When an error transfer context is called, we expect to be in a task that performed
                // the transfer, and we get the result of where the transfer should go.
                output.push_str(&format!(r#"
                    function {err_ctx_transfer_fn}(waitableIdx, srcTableIdx, destTableIdx) {{
                        {debug_log_fn}('[{err_ctx_transfer_fn}()] args', {{ waitableIdx, srcTableIdx, destTableIdx }});

                        const {{ componentIdx: srcComponentIdx }} = {global_err_ctx_table_map}[srcTableIdx];
                        const {{ componentIdx: destComponentIdx }} = {global_err_ctx_table_map}[destTableIdx];

                        const fromTbl = {get_local_tbl_fn}(srcComponentIdx, srcTableIdx);
                        const toTbl = {get_local_tbl_fn}(destComponentIdx, destTableIdx, {{ upsert: true }});

                        const srcComponentState = {get_or_create_async_state_fn}(srcComponentIdx);

                        const errCtx = srcComponentState.handles.get(waitableIdx);
                        if (!errCtx) {{
                            throw new Error(`missing error context (waitable idx [${{waitableIdx}}])`);
                        }}
                        if (!errCtx.localIdx) {{
                            throw new Error(`unexpectedly missing local idx from error context object`);
                        }}
                        if (!errCtx.globalRep) {{
                            throw new Error(`unexpectedly missing globalRep from error context object`);
                        }}

                        errCtx.refCount -= 1;
                        // NOTE: we avoid automatic removal here because return functions (e.g. in composed components)
                        // may attempt to drop *after* the transfer. This change is really only about ownership,
                        // even though we update the refcount

                        const {{ waitableIdx: newWaitableIdx, localIdx }} = {create_local_handle_fn}(
                            destComponentIdx,
                            toTbl,
                            errCtx.globalRep,
                        );

                        {debug_log_fn}('[{err_ctx_transfer_fn}()] successfully transferred', {{
                            dest: {{
                                errCtxHandle: localIdx,
                                errCtxWaitableIdx: newWaitableIdx,
                                tableIdx: destTableIdx,
                                componentIdx: destComponentIdx,
                            }},
                            src: {{
                                errCtxWaitableIdx: waitableIdx,
                                tableIdx: srcTableIdx,
                                componentIdx: srcComponentIdx,
                            }},
                        }});

                        return newWaitableIdx;
                    }}
                "#));
            }

            Self::GlobalRefCountAdd => {
                let global_tbl = Self::ComponentGlobalTable.name();
                let err_ctx_global_ref_count_add_fn = Self::GlobalRefCountAdd.name();
                output.push_str(&format!("
                    function {err_ctx_global_ref_count_add_fn}(globalRep, amount) {{
                        const globalTable = {global_tbl}.get();
                        const errCtx = globalTable.get(globalRep);
                        if (!errCtx) {{
                            throw new Error(`missing global error-context [${{globalRep}}] while incrementing refcount`);
                        }}
                        return errCtx.refCount += amount ?? 1;
                    }}
                "));
            }

            Self::GetLocalTable => {
                let get_local_tbl_fn = Self::GetLocalTable.name();
                let local_tbl_var = Self::ComponentLocalTable.name();
                let rep_table_class = Intrinsic::RepTableClass.name();
                // let local_tbl_var = Self::GlobalErrCtxTableMap.name()

                output.push_str(&format!(r#"
                    function {get_local_tbl_fn}(componentIdx, tableIdx, opts) {{
                        const localTables = {local_tbl_var};
                        let tables = localTables.get(componentIdx);
                        if (!tables) {{
                            if (opts?.upsert) {{
                                tables = new Map();
                                localTables.set(componentIdx, tables);
                            }} else {{
                                throw new Error(`missing local error context table for component [${{componentIdx}}] while getting local table`);
                            }}
                        }}

                        let errCtxTable = tables.get(tableIdx);
                        if (!errCtxTable) {{
                            if (opts?.upsert) {{
                                errCtxTable = new {rep_table_class}({{ target: `component [${{componentIdx}}] error contexts` }});
                                tables.set(tableIdx, errCtxTable);
                            }} else {{
                                throw new Error(`missing table [${{tableIdx}}] in tables for component [${{componentIdx}}] while getting local table`);
                            }}
                        }}

                        return errCtxTable;
                    }}
                "#));
            }

            Self::CreateLocalHandle => {
                // NOTE: `rep`s are global component model representations, `handle`s are component-local table indices
                let create_local_handle_fn = Self::CreateLocalHandle.name();
                let global_tbl = Self::ComponentGlobalTable.name();
                let get_or_create_async_state_fn = ComponentIntrinsic::GetOrCreateAsyncState.name();

                output.push_str(&format!(r#"
                    function {create_local_handle_fn}(componentIdx, componentLocalTable, globalRep) {{
                        const globalTable = {global_tbl}.get();
                        if (!globalTable.contains(globalRep)) {{
                            throw new Error(`missing global error-context [${{globalRep}}] during local handle create`);
                        }}

                        const cstate = {get_or_create_async_state_fn}(componentIdx);

                        const newErrCtx = {{ globalRep, refCount: 1 }};
                        const waitableIdx = cstate.handles.insert(newErrCtx);

                        const localIdx = componentLocalTable.insert(waitableIdx);
                        newErrCtx.localIdx = localIdx;

                        globalTable.get(globalRep).refCount += 1;

                        return {{ waitableIdx, localIdx }};
                    }}
                "#));
            }

            Self::ReserveGlobalRep => {
                let global_tbl = Self::ComponentGlobalTable.name();
                let reserve_global_rep_fn = Self::ReserveGlobalRep.name();
                output.push_str(&format!(
                    r#"
                    function {reserve_global_rep_fn}(debugMessage, refCount) {{
                        const globalTable = {global_tbl}.get();
                        const errCtx = {{ refCount, debugMessage }};
                        const globalRep = globalTable.insert(errCtx);
                        return {{ globalRep, errCtx }};
                    }}
                "#
                ));
            }
        }
    }
}