forked from livekit/uniffi-bindgen-node
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsys.ts
More file actions
541 lines (466 loc) · 17.7 KB
/
Copy pathsys.ts
File metadata and controls
541 lines (466 loc) · 17.7 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
import { join, dirname } from "path";
{% if out_dirname_api == DirnameApi::ImportMetaUrl %}
import { fileURLToPath } from 'url';
{% endif %}
{% if let LibPath::Modules(_) = out_lib_path %}
import { createRequire } from "module";
{% endif %}
import {
DataType,
JsExternal,
open,
close,
define,
arrayConstructor,
restorePointer,
wrapPointer,
unwrapPointer,
createPointer,
freePointer,
isNullPointer,
PointerType,
} from 'ffi-rs';
import {
type UniffiByteArray,
UniffiInternalError,
uniffiCreateFfiConverterString,
UniffiError,
} from 'uniffi-bindgen-react-native';
const CALL_SUCCESS = 0, CALL_ERROR = 1, CALL_UNEXPECTED_ERROR = 2, CALL_CANCELLED = 3;
let libraryLoaded = false;
/**
* Loads the dynamic library from disk into memory.
* {% if out_lib_disable_auto_loading -%}NOTE: this must be called before any other functions in this module are called.{%- endif %}
*/
function _uniffiLoad() {
const library = "lib{{ ci.crate_name() }}";
const { platform } = process;
let ext = { darwin: "dylib", win32: "dll", linux: "so" }[platform as string];
if (!ext) {
console.warn("Unsupported platform:", platform);
ext = "so";
}
{% match out_dirname_api -%}
{%- when DirnameApi::Dirname -%}
const filePath = __filename;
const libraryDirectory = __dirname;
{%- when DirnameApi::ImportMetaUrl -%}
const filePath = fileURLToPath(import.meta.url);
const libraryDirectory = dirname(filePath);
{%- endmatch %}
// Get the path to the lib to load
{% match out_lib_path -%}
{%- when LibPath::Omitted -%}
const libraryPath = join(libraryDirectory, `${library}.${ext}`);
{% when LibPath::Literal(literal) %}
{%- if literal.is_absolute() -%}
const libraryPath = "{{ literal }}";
{%- else -%}
const libraryPath = join(libraryDirectory, "{{ literal }}");
{%- endif -%}
{% when LibPath::Modules(mods) %}
let libPathModule;
let libPathModuleLastResolutionError: Error | null = null;
let libPathModuleLoadAttemptStack: Array<string> = [];
const commonjsRequire = createRequire(filePath);
{%- for switch_token in mods.as_switch_tokens() -%}
{% match switch_token -%}
{% when LibPathSwitchToken::Switch(value) -%}
switch ({{ value }}) {
{% when LibPathSwitchToken::Case(value) -%}
case "{{value}}":
{% when LibPathSwitchToken::EndCase -%}
break;
{% when LibPathSwitchToken::EndSwitch(_value) -%}
}
{% when LibPathSwitchToken::Value(value) -%}
if (!libPathModule) {
try {
libPathModule = commonjsRequire("{{ value }}");
} catch (e) {
libPathModuleLastResolutionError = e as Error;
libPathModuleLoadAttemptStack.push("{{ value }}");
}
}
{%- endmatch -%}
{%- endfor -%}
if (!libPathModule) {
const messageFragments = [
`Failed to load a native binding library!`,
`Attempted loading from the following modules in order: ${libPathModuleLoadAttemptStack.join(", ")}.`,
];
if (libPathModuleLastResolutionError) {
messageFragments.push(`The error message from the final load attempt is: ${libPathModuleLastResolutionError?.stack ?? libPathModuleLastResolutionError}`);
}
throw new Error(messageFragments.join('\n'));
}
const libraryPath = libPathModule.default().path;
{% endmatch %}
open({ library, path: libraryPath });
libraryLoaded = true;
}
/**
* Unloads the dynamic library from disk from memory. This can be used to clean up the library early
* before program execution completes.
*/
function _uniffiUnload() {
close('lib{{ ci.crate_name() }}');
libraryLoaded = false;
}
function _checkUniffiLoaded() {
if (!libraryLoaded) {
throw new Error('Uniffi function call was issued, but the native dependency was not loaded. Ensure you are calling uniffiLoad() before interacting with any uniffi backed functionality.');
}
}
{% if out_lib_disable_auto_loading %}
export { _uniffiLoad as uniffiLoad, _uniffiUnload as uniffiUnload };
{% else %}
_uniffiLoad();
{% endif %}
// Release library memory before process terminates
// TODO: is this even really required?
process.on('beforeExit', () => {
if (libraryLoaded) {
_uniffiUnload();
}
});
const [nullPointer] = unwrapPointer(createPointer({
paramsType: [DataType.Void],
paramsValue: [undefined]
}));
class UniffiFfiRsRustCaller {
rustCall<T>(
caller: (status: JsExternal) => T,
liftString: (bytes: UniffiByteArray) => string,
): T {
return this.makeRustCall(caller, liftString);
}
rustCallWithError<T, ErrorEnumAndVariant extends [string, string]>(
liftError: (buffer: UniffiByteArray) => ErrorEnumAndVariant,
caller: (status: JsExternal) => T,
liftString: (bytes: UniffiByteArray) => string,
): T {
return this.makeRustCall(caller, liftString, liftError);
}
createCallStatus(): [JsExternal] {
const $callStatus = createPointer({
paramsType: [DataType_UniffiRustCallStatus],
paramsValue: [{
code: CALL_SUCCESS,
error_buf: { capacity: 0, len: 0, data: nullPointer },
}],
});
return $callStatus as [JsExternal];
}
createErrorStatus(_code: number, _errorBuf: UniffiByteArray): JsExternal {
// FIXME: what is this supposed to do and how does it not allocate `errorBuf` when making the
// call status struct?
throw new Error('UniffiRustCaller.createErrorStatus is unimplemented.');
// const status = this.statusConstructor();
// status.code = code;
// status.errorBuf = errorBuf;
// return status;
}
makeRustCall<T, ErrorEnumAndVariant extends [string, string]>(
caller: (status: JsExternal) => T,
liftString: (bytes: UniffiByteArray) => string,
liftError?: (buffer: UniffiByteArray) => ErrorEnumAndVariant,
): T {
_checkUniffiLoaded();
const $callStatus = this.createCallStatus();
let returnedVal = caller(unwrapPointer($callStatus)[0]);
const [callStatus] = restorePointer({
retType: [DataType_UniffiRustCallStatus],
paramsValue: $callStatus,
});
uniffiCheckCallStatus(callStatus, liftString, liftError);
return returnedVal;
}
}
function uniffiCheckCallStatus<ErrorEnumAndVariant extends [string, string]>(
callStatus: UniffiRustCallStatusStruct,
liftString: (bytes: UniffiByteArray) => string,
liftError?: (buffer: UniffiByteArray) => ErrorEnumAndVariant,
) {
switch (callStatus.code) {
case CALL_SUCCESS:
return;
case CALL_ERROR: {
// - Rust will not set the data pointer for a sucessful return.
// - If unsuccesful, lift the error from the RustBuf and free.
if (!isNullPointer(callStatus.error_buf.data)) {
const struct = new UniffiRustBufferValue(callStatus.error_buf);
const errorBufBytes = struct.consumeIntoUint8Array();
if (liftError) {
const [enumName, errorVariant] = liftError(errorBufBytes);
throw new UniffiError(enumName, errorVariant);
}
}
throw new UniffiInternalError.UnexpectedRustCallError();
}
case CALL_UNEXPECTED_ERROR: {
// When the rust code sees a panic, it tries to construct a RustBuffer
// with the message. But if that code panics, then it just sends back
// an empty buffer.
if (!isNullPointer(callStatus.error_buf.data)) {
const struct = new UniffiRustBufferValue(callStatus.error_buf);
const errorBufBytes = struct.consumeIntoUint8Array();
if (errorBufBytes.byteLength > 0) {
const liftedErrorBuf = liftString(errorBufBytes);
throw new UniffiInternalError.RustPanic(liftedErrorBuf);
}
}
throw new UniffiInternalError.RustPanic("Rust panic");
}
case CALL_CANCELLED:
// #RUST_TASK_CANCELLATION:
//
// This error code is expected when a Rust Future is cancelled or aborted, either
// from the foreign side, or from within Rust itself.
//
// As of uniffi-rs v0.28.0, call cancellation is only checked for in the Swift bindings,
// and uses an Unimplemeneted error.
throw new UniffiInternalError.AbortError();
default:
throw new UniffiInternalError.UnexpectedRustCallStatusCode();
}
}
export const uniffiCaller = new UniffiFfiRsRustCaller();
export const stringConverter = (() => {
const encoder = new TextEncoder();
const decoder = new TextDecoder();
return {
stringToBytes: (s: string) => encoder.encode(s),
bytesToString: (ab: UniffiByteArray) => decoder.decode(ab),
stringByteLength: (s: string) => encoder.encode(s).byteLength,
};
})();
export const FfiConverterString = uniffiCreateFfiConverterString(stringConverter);
// Struct + Callback type definitions
export type UniffiRustBufferStruct = { capacity: bigint, len: bigint, data: JsExternal };
const DataType_UniffiRustBufferStruct = {
capacity: DataType.U64,
len: DataType.U64,
data: DataType.External,
ffiTypeTag: DataType.StackStruct,
};
export type UniffiForeignBytes = { len: number, data: JsExternal };
const DataType_UniffiForeignBytes = {
len: DataType.I32,
data: DataType.External,
ffiTypeTag: DataType.StackStruct,
};
/** A UniffiRustBufferValue represents stack allocated structure containing pointer to series of
* bytes most likely on the heap, along with the size of that data in bytes.
*
* It is often used to encode more complex function parameters / return values like structs,
* optionals, etc.
*
* `RustBufferValue`s are behind the scenes backed by manually managed memory on the rust end, and
* must be explictly destroyed when no longer used to ensure no memory is leaked.
* */
export class UniffiRustBufferValue {
private struct: UniffiRustBufferStruct | null;
constructor(struct: UniffiRustBufferStruct) {
this.struct = struct;
}
static allocateWithBytes(bytes: Uint8Array) {
const [ dataPointer ] = createPointer({
paramsType: [arrayConstructor({ type: DataType.U8Array, length: bytes.length })],
paramsValue: [bytes],
});
const rustBuffer = uniffiCaller.rustCall(
(callStatus) => {
return FFI_DYNAMIC_LIB.{{ci.ffi_rustbuffer_from_bytes().name()}}([
// TODO: figure out why this is necessary.
{ data: unwrapPointer([dataPointer])[0], len: bytes.byteLength },
callStatus,
]);
},
/*liftString:*/ {{ &Type::String | typescript_ffi_converter_name }}.lift,
);
freePointer({
paramsType: [arrayConstructor({ type: DataType.U8Array, length: bytes.byteLength })],
paramsValue: [dataPointer],
pointerType: PointerType.RsPointer
});
return new UniffiRustBufferValue(rustBuffer);
}
static allocateEmpty() {
return UniffiRustBufferValue.allocateWithBytes(new Uint8Array());
}
toStruct() {
if (!this.struct) {
throw new Error('Error getting struct data for UniffiRustBufferValue - struct.data has been freed! This is not allowed.');
}
return this.struct;
}
toUint8Array() {
if (!this.struct) {
throw new Error('Error converting rust buffer to uint8array - struct.data has been freed! This is not allowed.');
}
if (this.struct.len > Number.MAX_VALUE) {
throw new Error(`Error converting rust buffer to uint8array - rust buffer length is ${this.struct.len}, which cannot be represented as a Number safely.`)
}
const length = Number(this.struct.len);
const wrapped = wrapPointer([this.struct.data]);
try {
const [contents] = restorePointer({
retType: [arrayConstructor({ type: DataType.U8Array, length })],
paramsValue: wrapped,
});
return new Uint8Array(contents);
} finally {
freePointer({
paramsType: [arrayConstructor({ type: DataType.U8Array, length })],
paramsValue: wrapped,
pointerType: PointerType.RsPointer,
});
}
}
consumeIntoUint8Array() {
const result = this.toUint8Array();
this.destroy();
return result;
}
destroy() {
{% if out_verbose_logs -%}console.log('Rust buffer destroy called', this.struct);{%- endif %}
if (!this.struct) {
throw new Error('Error destroying UniffiRustBufferValue - already previously destroyed! Double freeing is not allowed.');
}
uniffiCaller.rustCall(
(callStatus) => {
FFI_DYNAMIC_LIB.{{ci.ffi_rustbuffer_free().name()}}([this.struct!, callStatus]);
},
/*liftString:*/ {{ &Type::String | typescript_ffi_converter_name }}.lift,
);
// freePointer({
// paramsType: [arrayConstructor({ type: DataType.U8Array, length: this.struct.len })],
// paramsValue: wrapPointer([this.struct.data]),
// pointerType: PointerType.RsPointer,
// });
// console.log('DONE');
this.struct = null;
}
}
export type UniffiRustCallStatusStruct = { code: number, error_buf: UniffiRustBufferStruct };
const DataType_UniffiRustCallStatus = {
code: DataType.U8,
error_buf: DataType_UniffiRustBufferStruct,
};
{%- for definition in ci.ffi_definitions() -%}
{%- match definition %}
{%- when FfiDefinition::CallbackFunction(callback) %}
export type {{ callback.name() | typescript_callback_name }} = (
{%- for arg in callback.arguments() %}
{{ arg.name() }}: {{ arg.type_().borrow() | typescript_ffi_type_name }}{% if !loop.last %}, {% endif %}
{%- endfor %}
{%- if callback.has_rust_call_status_arg() -%}
{% if callback.arguments().len() > 0 %}, {% endif %}{{ &FfiType::RustCallStatus | typescript_ffi_type_name }}
{%- endif %}
) => {% match callback.return_type() %}
{%- when Some(return_type) -%}
{{- return_type | typescript_ffi_type_name -}}
{%- when None -%}
void
{%- endmatch %};
{%- when FfiDefinition::Struct(struct_data) -%}
export type {{ struct_data.name() | typescript_ffi_struct_name }} = {
{%- for field_def in struct_data.fields() -%}
{{field_def.name() | typescript_var_name}}: {{field_def.type_().borrow() | typescript_ffi_type_name}};
{%- endfor %}
};
const DataType_{{ struct_data.name() | typescript_ffi_struct_name }} = {
{% for field_def in struct_data.fields() -%}
{{field_def.name() | typescript_var_name}}: {{field_def.type_().borrow() | typescript_ffi_datatype_name}},
{% endfor %}
// Ensure that the struct is stack defined, without this ffi-rs isn't able to decode the
// struct properly
ffiTypeTag: DataType.StackStruct,
};
{%- else -%}
{%- endmatch %}
{%- endfor %}
// Actual FFI functions from dynamic library
/** This direct / "extern C" type FFI interface is bound directly to the functions exposed by the
* dynamic library. Using this manually from end-user javascript code is unsafe and this is not
* recommended. */
const FFI_DYNAMIC_LIB = define({
{%- for definition in ci.ffi_definitions() %}
{%- match definition %}
{%- when FfiDefinition::CallbackFunction(callback) %}
{{ callback.name() }}: {
library: "lib{{ ci.crate_name() }}",
retType: {%- match callback.return_type() %}
{%- when Some(return_type) %}
{{- return_type | typescript_ffi_datatype_name -}}
{%- when None %}
DataType.Void
{%- endmatch %},
paramsType: [
{%- for arg in callback.arguments() %}
{{ arg.type_().borrow() | typescript_ffi_datatype_name }}{% if !loop.last %}, {% endif %}
{%- endfor %}
{%- if callback.has_rust_call_status_arg() -%}
{% if callback.arguments().len() > 0 %}, {% endif %}{{ &FfiType::RustCallStatus | typescript_ffi_datatype_name }}
{%- endif %}
],
},
{%- when FfiDefinition::Function(func) %}
{{ func.name() }}: {
library: "lib{{ ci.crate_name() }}",
retType: {%- match func.return_type() %}
{%- when Some(return_type) %}
{{- return_type | typescript_ffi_datatype_name -}}
{%- when None %}
DataType.Void
{%- endmatch %},
paramsType: [
{%- for arg in func.arguments() %}
{{ arg.type_().borrow() | typescript_ffi_datatype_name }}{% if !loop.last %}, {% endif %}
{%- endfor %}
{%- if func.has_rust_call_status_arg() -%}
{% if func.arguments().len() > 0 %}, {% endif -%}
{{ &FfiType::RustCallStatus | typescript_ffi_datatype_name }}
{%- endif %}
],
},
{%- else %}
{%- endmatch %}
{%- endfor %}
}) as unknown as {
{%- for definition in ci.ffi_definitions() %}
{%- match definition %}
{%- when FfiDefinition::CallbackFunction(callback) %}
{{ callback.name() }}: (args: [
{%- for arg in callback.arguments() %}
/* {{ arg.name() }} */ {{ arg.type_().borrow() | typescript_ffi_type_name }}{% if !loop.last %}, {% endif %}
{%- endfor %}
{%- if callback.has_rust_call_status_arg() -%}
{% if callback.arguments().len() > 0 %}, {% endif %} RustCallStatus
{%- endif %}
]) => {%- match callback.return_type() %}
{%- when Some(return_type) %}
{{- return_type | typescript_ffi_type_name -}}
{%- when None %}
void
{%- endmatch %},
{%- when FfiDefinition::Function(func) %}
{{ func.name() }}: (args: [
{%- for arg in func.arguments() %}
/* {{ arg.name() }} */ {{ arg.type_().borrow() | typescript_ffi_type_name }}{% if !loop.last %}, {% endif %}
{%- endfor %}
{%- if func.has_rust_call_status_arg() -%}
{% if func.arguments().len() > 0 %}, {% endif %}{{ &FfiType::RustCallStatus | typescript_ffi_type_name }}
{%- endif %}
]) => {%- match func.return_type() %}
{%- when Some(return_type) %}
{{- return_type | typescript_ffi_type_name -}}
{%- when None %}
void
{%- endmatch %},
{%- else %}
{%- endmatch %}
{%- endfor %}
};
export default FFI_DYNAMIC_LIB;