@aztec/foundation 0.23.0 → 0.24.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dest/fields/fields.js +3 -3
- package/package.json +2 -2
- package/src/abi/abi.ts +337 -0
- package/src/abi/buffer.ts +36 -0
- package/src/abi/decoder.ts +176 -0
- package/src/abi/encoder.ts +143 -0
- package/src/abi/index.ts +6 -0
- package/src/abi/selector.ts +243 -0
- package/src/abi/utils.ts +50 -0
- package/src/array/array.ts +86 -0
- package/src/array/index.ts +1 -0
- package/src/async-map/index.ts +18 -0
- package/src/aztec-address/index.ts +36 -0
- package/src/bigint-buffer/index.ts +87 -0
- package/src/collection/array.ts +64 -0
- package/src/collection/index.ts +1 -0
- package/src/committable/committable.ts +46 -0
- package/src/committable/index.ts +1 -0
- package/src/crypto/index.ts +16 -0
- package/src/crypto/keccak/index.ts +33 -0
- package/src/crypto/pedersen/index.ts +1 -0
- package/src/crypto/pedersen/pedersen.elliptic.ts +584 -0
- package/src/crypto/pedersen/pedersen.noble.ts +573 -0
- package/src/crypto/pedersen/pedersen.wasm.ts +42 -0
- package/src/crypto/random/index.ts +42 -0
- package/src/crypto/sha256/index.ts +3 -0
- package/src/errors/index.ts +6 -0
- package/src/eth-address/index.ts +234 -0
- package/src/fields/coordinate.ts +104 -0
- package/src/fields/fields.ts +328 -0
- package/src/fields/index.ts +3 -0
- package/src/fields/point.ts +145 -0
- package/src/fifo/bounded_serial_queue.ts +100 -0
- package/src/fifo/index.ts +4 -0
- package/src/fifo/memory_fifo.ts +118 -0
- package/src/fifo/semaphore.ts +33 -0
- package/src/fifo/serial_queue.ts +81 -0
- package/src/index.ts +29 -0
- package/src/json-rpc/README.md +55 -0
- package/src/json-rpc/class_converter.ts +213 -0
- package/src/json-rpc/client/index.ts +1 -0
- package/src/json-rpc/client/json_rpc_client.ts +147 -0
- package/src/json-rpc/convert.ts +163 -0
- package/src/json-rpc/fixtures/class_a.ts +15 -0
- package/src/json-rpc/fixtures/class_b.ts +15 -0
- package/src/json-rpc/fixtures/test_state.ts +59 -0
- package/src/json-rpc/index.ts +8 -0
- package/src/json-rpc/js_utils.ts +20 -0
- package/src/json-rpc/server/index.ts +2 -0
- package/src/json-rpc/server/json_proxy.ts +60 -0
- package/src/json-rpc/server/json_rpc_server.ts +269 -0
- package/src/log/console.ts +39 -0
- package/src/log/debug.ts +83 -0
- package/src/log/index.ts +5 -0
- package/src/log/log_fn.ts +5 -0
- package/src/log/log_history.ts +44 -0
- package/src/log/logger.ts +137 -0
- package/src/mutex/index.ts +83 -0
- package/src/mutex/mutex_database.ts +12 -0
- package/src/noir/index.ts +1 -0
- package/src/noir/noir_package_config.ts +54 -0
- package/src/retry/index.ts +99 -0
- package/src/running-promise/index.ts +60 -0
- package/src/serialize/buffer_reader.ts +286 -0
- package/src/serialize/field_reader.ts +143 -0
- package/src/serialize/free_funcs.ts +147 -0
- package/src/serialize/index.ts +5 -0
- package/src/serialize/serialize.ts +303 -0
- package/src/serialize/types.ts +40 -0
- package/src/sleep/index.ts +71 -0
- package/src/testing/index.ts +1 -0
- package/src/testing/test_data.ts +36 -0
- package/src/timer/elapsed.ts +23 -0
- package/src/timer/index.ts +3 -0
- package/src/timer/timeout.ts +64 -0
- package/src/timer/timer.ts +48 -0
- package/src/transport/browser/index.ts +4 -0
- package/src/transport/browser/message_port_socket.ts +48 -0
- package/src/transport/browser/shared_worker_connector.ts +21 -0
- package/src/transport/browser/shared_worker_listener.ts +53 -0
- package/src/transport/browser/worker_connector.ts +30 -0
- package/src/transport/browser/worker_listener.ts +54 -0
- package/src/transport/dispatch/create_dispatch_fn.ts +35 -0
- package/src/transport/dispatch/create_dispatch_proxy.ts +141 -0
- package/src/transport/dispatch/messages.ts +58 -0
- package/src/transport/index.ts +11 -0
- package/src/transport/interface/connector.ts +9 -0
- package/src/transport/interface/listener.ts +16 -0
- package/src/transport/interface/socket.ts +15 -0
- package/src/transport/interface/transferable.ts +125 -0
- package/src/transport/node/index.ts +2 -0
- package/src/transport/node/node_connector.ts +30 -0
- package/src/transport/node/node_connector_socket.ts +52 -0
- package/src/transport/node/node_listener.ts +34 -0
- package/src/transport/node/node_listener_socket.ts +48 -0
- package/src/transport/transport_client.ts +131 -0
- package/src/transport/transport_server.ts +108 -0
- package/src/trees/index.ts +54 -0
- package/src/types/index.ts +8 -0
- package/src/url/index.ts +73 -0
- package/src/wasm/README.md +6 -0
- package/src/wasm/empty_wasi_sdk.ts +166 -0
- package/src/wasm/fixtures/gcd.wasm +0 -0
- package/src/wasm/fixtures/gcd.wat +27 -0
- package/src/wasm/index.ts +1 -0
- package/src/wasm/wasm_module.ts +260 -0
- package/src/worker/browser/index.ts +2 -0
- package/src/worker/browser/start_web_module.ts +23 -0
- package/src/worker/browser/web_data_store.ts +38 -0
- package/src/worker/browser/web_worker.ts +24 -0
- package/src/worker/data_store.ts +19 -0
- package/src/worker/index.ts +2 -0
- package/src/worker/node/index.ts +2 -0
- package/src/worker/node/node_data_store.ts +27 -0
- package/src/worker/node/node_worker.ts +22 -0
- package/src/worker/node/start_node_module.ts +29 -0
- package/src/worker/wasm_worker.ts +7 -0
- package/src/worker/worker_pool.ts +73 -0
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { InterruptError } from '../errors/index.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* InterruptibleSleep is a utility class that allows you to create an interruptible sleep function.
|
|
5
|
+
* The sleep function can be interrupted at any time by calling the `interrupt` method, which can
|
|
6
|
+
* also specify whether the sleep should throw an error or just return. This is useful when you need
|
|
7
|
+
* to terminate long-running processes or perform cleanup tasks in response to external events.
|
|
8
|
+
*
|
|
9
|
+
* @example
|
|
10
|
+
* const sleeper = new InterruptibleSleep();
|
|
11
|
+
*
|
|
12
|
+
* async function longRunningTask() \{
|
|
13
|
+
* try \{
|
|
14
|
+
* await sleeper.sleep(3000);
|
|
15
|
+
* console.log('Task completed after 3 seconds');
|
|
16
|
+
* \} catch (e) \{
|
|
17
|
+
* console.log('Task was interrupted');
|
|
18
|
+
* \}
|
|
19
|
+
* \}
|
|
20
|
+
*
|
|
21
|
+
* setTimeout(() =\> sleeper.interrupt(true), 1500); // Interrupt the sleep after 1.5 seconds
|
|
22
|
+
*/
|
|
23
|
+
export class InterruptibleSleep {
|
|
24
|
+
private interruptResolve: (shouldThrow: boolean) => void = () => {};
|
|
25
|
+
private interruptPromise = new Promise<boolean>(resolve => (this.interruptResolve = resolve));
|
|
26
|
+
private timeouts: NodeJS.Timeout[] = [];
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Sleep for a specified amount of time in milliseconds.
|
|
30
|
+
* The sleep function will pause the execution of the current async function
|
|
31
|
+
* for the given time period, allowing other tasks to run before resuming.
|
|
32
|
+
*
|
|
33
|
+
* @param ms - The number of milliseconds to sleep.
|
|
34
|
+
* @returns A Promise that resolves after the specified time has passed.
|
|
35
|
+
*/
|
|
36
|
+
public async sleep(ms: number) {
|
|
37
|
+
let timeout!: NodeJS.Timeout;
|
|
38
|
+
const promise = new Promise<boolean>(resolve => (timeout = setTimeout(() => resolve(false), ms)));
|
|
39
|
+
this.timeouts.push(timeout);
|
|
40
|
+
const shouldThrow = await Promise.race([promise, this.interruptPromise]);
|
|
41
|
+
clearTimeout(timeout);
|
|
42
|
+
this.timeouts.splice(this.timeouts.indexOf(timeout), 1);
|
|
43
|
+
if (shouldThrow) {
|
|
44
|
+
throw new InterruptError('Interrupted.');
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Interrupts the current sleep operation and optionally throws an error if specified.
|
|
50
|
+
* By default, when interrupted, the sleep operation will resolve without throwing.
|
|
51
|
+
* If 'sleepShouldThrow' is set to true, the sleep operation will throw an InterruptError instead.
|
|
52
|
+
*
|
|
53
|
+
* @param sleepShouldThrow - A boolean value indicating whether the sleep operation should throw an error when interrupted. Default is false.
|
|
54
|
+
*/
|
|
55
|
+
public interrupt(sleepShouldThrow = false) {
|
|
56
|
+
this.interruptResolve(sleepShouldThrow);
|
|
57
|
+
this.interruptPromise = new Promise(resolve => (this.interruptResolve = resolve));
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Puts the current execution context to sleep for a specified duration.
|
|
63
|
+
* This simulates a blocking sleep operation by using an asynchronous function and a Promise that resolves after the given duration.
|
|
64
|
+
* The sleep function can be interrupted by the 'interrupt' method of the InterruptibleSleep class.
|
|
65
|
+
*
|
|
66
|
+
* @param ms - The duration in milliseconds for which the sleep operation should last.
|
|
67
|
+
* @returns A Promise that resolves after the specified duration, allowing the use of 'await' to pause execution.
|
|
68
|
+
*/
|
|
69
|
+
export function sleep(ms: number) {
|
|
70
|
+
return new Promise(resolve => setTimeout(resolve, ms));
|
|
71
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from './test_data.js';
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
const testData: { [key: string]: { toBuffer(): Buffer }[] } = {};
|
|
2
|
+
|
|
3
|
+
/** Returns whether test data generation is enabled */
|
|
4
|
+
export function isGenerateTestDataEnabled() {
|
|
5
|
+
return process.env.AZTEC_GENERATE_TEST_DATA === '1' && typeof expect !== 'undefined';
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
/** Pushes test data with the given name, only if test data generation is enabled. */
|
|
9
|
+
export function pushTestData(itemName: string, data: { toBuffer(): Buffer }) {
|
|
10
|
+
if (!isGenerateTestDataEnabled()) {
|
|
11
|
+
return;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
if (typeof expect === 'undefined') {
|
|
15
|
+
return;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
const testName = expect.getState().currentTestName;
|
|
19
|
+
const fullItemName = `${testName} ${itemName}`;
|
|
20
|
+
|
|
21
|
+
if (!testData[fullItemName]) {
|
|
22
|
+
testData[fullItemName] = [];
|
|
23
|
+
}
|
|
24
|
+
testData[fullItemName].push(data);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Returns all instances of pushed test data with the given name, or empty if test data generation is not enabled. */
|
|
28
|
+
export function getTestData(itemName: string): { toBuffer(): Buffer }[] {
|
|
29
|
+
if (!isGenerateTestDataEnabled()) {
|
|
30
|
+
return [];
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const testName = expect.getState().currentTestName;
|
|
34
|
+
const fullItemName = `${testName} ${itemName}`;
|
|
35
|
+
return testData[fullItemName];
|
|
36
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { Timer } from './timer.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Measures the elapsed execution time of a function call or promise once it is awaited.
|
|
5
|
+
* @param fn - Function or promise.
|
|
6
|
+
* @returns The number of ms and the result.
|
|
7
|
+
*/
|
|
8
|
+
export async function elapsed<T>(fn: Promise<T> | (() => T | Promise<T>)): Promise<[number, T]> {
|
|
9
|
+
const timer = new Timer();
|
|
10
|
+
const result = await (typeof fn === 'function' ? fn() : fn);
|
|
11
|
+
return [timer.ms(), result];
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Measures the elapsed execution time of a synchronous function call once it is awaited.
|
|
16
|
+
* @param fn - Function.
|
|
17
|
+
* @returns The number of ms and the result.
|
|
18
|
+
*/
|
|
19
|
+
export function elapsedSync<T>(fn: () => T): [number, T] {
|
|
20
|
+
const timer = new Timer();
|
|
21
|
+
const result = fn();
|
|
22
|
+
return [timer.ms(), result];
|
|
23
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* TimeoutTask class creates an instance for managing and executing a given asynchronous function with a specified timeout duration.
|
|
3
|
+
* The task will be automatically interrupted if it exceeds the given timeout duration, and will throw a custom error message.
|
|
4
|
+
* Additional information such as execution time can be retrieved using getTime method after the task has been executed.
|
|
5
|
+
*
|
|
6
|
+
* @typeparam T - The return type of the asynchronous function to be executed.
|
|
7
|
+
*/
|
|
8
|
+
export class TimeoutTask<T> {
|
|
9
|
+
private interruptPromise!: Promise<any>;
|
|
10
|
+
private interrupt = () => {};
|
|
11
|
+
private totalTime = 0;
|
|
12
|
+
|
|
13
|
+
constructor(private fn: () => Promise<T>, private timeout = 0, fnName = '') {
|
|
14
|
+
this.interruptPromise = new Promise<T>((_, reject) => {
|
|
15
|
+
this.interrupt = () => reject(new Error(`Timeout${fnName ? ` running ${fnName}` : ''} after ${timeout}ms.`));
|
|
16
|
+
});
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Executes the given function with a specified timeout.
|
|
21
|
+
* If the function takes longer than the timeout, it will be interrupted and an error will be thrown.
|
|
22
|
+
* The total execution time of the function will be stored in the totalTime property.
|
|
23
|
+
*
|
|
24
|
+
* @returns The result of the executed function if completed within the timeout.
|
|
25
|
+
* @throws An error with a message indicating the function was interrupted due to exceeding the specified timeout.
|
|
26
|
+
*/
|
|
27
|
+
public async exec() {
|
|
28
|
+
const interruptTimeout = !this.timeout ? 0 : setTimeout(this.interrupt, this.timeout);
|
|
29
|
+
try {
|
|
30
|
+
const start = Date.now();
|
|
31
|
+
const result = await Promise.race<T>([this.fn(), this.interruptPromise]);
|
|
32
|
+
this.totalTime = Date.now() - start;
|
|
33
|
+
return result;
|
|
34
|
+
} finally {
|
|
35
|
+
clearTimeout(interruptTimeout);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Returns the interrupt promise associated with the TimeoutTask instance.
|
|
41
|
+
* The interrupt promise is used internally to reject the task when a timeout occurs.
|
|
42
|
+
* This method can be helpful when debugging or tracking the state of the task.
|
|
43
|
+
*
|
|
44
|
+
* @returns The interrupt promise associated with the task.
|
|
45
|
+
*/
|
|
46
|
+
public getInterruptPromise() {
|
|
47
|
+
return this.interruptPromise;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Get the total time spent on the most recent execution of the wrapped function.
|
|
52
|
+
* This method provides the duration from the start to the end of the function execution, whether it completed or timed out.
|
|
53
|
+
*
|
|
54
|
+
* @returns The total time in milliseconds spent on the most recent function execution.
|
|
55
|
+
*/
|
|
56
|
+
public getTime() {
|
|
57
|
+
return this.totalTime;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export const executeTimeout = async <T>(fn: () => Promise<T>, timeout = 0, fnName = '') => {
|
|
62
|
+
const task = new TimeoutTask(fn, timeout, fnName);
|
|
63
|
+
return await task.exec();
|
|
64
|
+
};
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Timer class to measure time intervals in milliseconds and seconds.
|
|
3
|
+
* Upon instantiation, it stores the current timestamp as the starting point.
|
|
4
|
+
* The 'ms()' method returns the elapsed time in milliseconds,
|
|
5
|
+
* while the 's()' method returns the elapsed time in seconds.
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* const timer = new Timer();
|
|
9
|
+
* setTimeout(() =\> \{
|
|
10
|
+
* console.log(`Elapsed time: ${timer.ms()} ms`);
|
|
11
|
+
* \}, 1000);
|
|
12
|
+
*/
|
|
13
|
+
export class Timer {
|
|
14
|
+
private start: number;
|
|
15
|
+
|
|
16
|
+
constructor() {
|
|
17
|
+
this.start = performance.now();
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Return microseconds.
|
|
22
|
+
*/
|
|
23
|
+
public us() {
|
|
24
|
+
return this.ms() * 1000;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Returns the elapsed time in milliseconds since the Timer instance was created.
|
|
29
|
+
* Provides a simple and convenient way to measure the time duration between two events
|
|
30
|
+
* or monitor performance of specific code sections.
|
|
31
|
+
*
|
|
32
|
+
* @returns The elapsed time in milliseconds.
|
|
33
|
+
*/
|
|
34
|
+
public ms() {
|
|
35
|
+
return performance.now() - this.start;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Returns the time elapsed since the Timer instance was created, in seconds.
|
|
40
|
+
* The value is calculated by subtracting the initial start time from the current time
|
|
41
|
+
* and dividing the result by 1000 to convert milliseconds to seconds.
|
|
42
|
+
*
|
|
43
|
+
* @returns The elapsed time in seconds.
|
|
44
|
+
*/
|
|
45
|
+
public s() {
|
|
46
|
+
return this.ms() / 1000;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { Socket } from '../interface/socket.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* An implementation of a TransportSocket using MessagePorts.
|
|
5
|
+
*/
|
|
6
|
+
export class MessagePortSocket implements Socket {
|
|
7
|
+
constructor(private port: MessagePort) {}
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Send a message to the connected MessagePort, optionally transferring ownership of certain objects.
|
|
11
|
+
* The 'msg' parameter can be any structured data type and will be sent to the other end of the MessagePort.
|
|
12
|
+
* The optional 'transfer' parameter is an array of Transferable objects whose ownership will be transferred,
|
|
13
|
+
* making them inaccessible on the sending side. This can improve performance for large data transfers.
|
|
14
|
+
*
|
|
15
|
+
* @param msg - The message to be sent through the MessagePort.
|
|
16
|
+
* @param transfer - An optional array of Transferable objects to transfer ownership.
|
|
17
|
+
* @returns A Promise that resolves when the message has been sent.
|
|
18
|
+
*/
|
|
19
|
+
send(msg: any, transfer: Transferable[] = []): Promise<void> {
|
|
20
|
+
this.port.postMessage(msg, transfer);
|
|
21
|
+
return Promise.resolve();
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Register a callback function to handle incoming messages from the MessagePort.
|
|
26
|
+
* The provided callback will be invoked with the message data whenever a new message arrives.
|
|
27
|
+
* Note that only one callback can be registered at a time. Subsequent calls to this method
|
|
28
|
+
* will overwrite the previously registered callback.
|
|
29
|
+
*
|
|
30
|
+
* @param cb - The callback function to handle incoming messages.
|
|
31
|
+
*/
|
|
32
|
+
registerHandler(cb: (msg: any) => any): void {
|
|
33
|
+
this.port.onmessage = event => cb(event.data);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Close the MessagePort, unregister the message handler, and send an undefined message.
|
|
38
|
+
* The 'close' function is useful for gracefully shutting down a connection between two
|
|
39
|
+
* endpoints by sending an undefined message as an indication of disconnection before
|
|
40
|
+
* closing the port. After calling this method, the MessagePortSocket instance should not
|
|
41
|
+
* be used again.
|
|
42
|
+
*/
|
|
43
|
+
close() {
|
|
44
|
+
void this.send(undefined);
|
|
45
|
+
this.port.onmessage = null;
|
|
46
|
+
this.port.close();
|
|
47
|
+
}
|
|
48
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { Connector } from '../interface/connector.js';
|
|
2
|
+
import { MessagePortSocket } from './message_port_socket.js';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* SharedWorkerConnector is an implementation of the Connector interface, specifically for SharedWorkers.
|
|
6
|
+
* It enables the creation of MessagePortSockets that communicate with a shared worker and allow
|
|
7
|
+
* multiple scripts to communicate with the worker using the same connection.
|
|
8
|
+
*/
|
|
9
|
+
export class SharedWorkerConnector implements Connector {
|
|
10
|
+
constructor(private worker: SharedWorker) {}
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Creates a new MessagePortSocket instance using the SharedWorker's port.
|
|
14
|
+
* This method allows for easy creation of sockets to communicate with the SharedWorker.
|
|
15
|
+
*
|
|
16
|
+
* @returns A Promise that resolves to a new MessagePortSocket instance.
|
|
17
|
+
*/
|
|
18
|
+
createSocket() {
|
|
19
|
+
return Promise.resolve(new MessagePortSocket(this.worker.port));
|
|
20
|
+
}
|
|
21
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import EventEmitter from 'events';
|
|
2
|
+
|
|
3
|
+
import { Listener } from '../interface/listener.js';
|
|
4
|
+
import { MessagePortSocket } from './message_port_socket.js';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Represents the global scope of a Shared Worker.
|
|
8
|
+
* Provides functionality to handle incoming connections and manage communication with other scripts
|
|
9
|
+
* running in a shared context, enabling concurrent access and efficient resource sharing among those scripts.
|
|
10
|
+
*/
|
|
11
|
+
declare interface SharedWorkerGlobalScope {
|
|
12
|
+
/**
|
|
13
|
+
* Event handler for new connections to the Shared Worker.
|
|
14
|
+
*/
|
|
15
|
+
onconnect: (...args: any) => any;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* SharedWorkerListener is an extension of the EventEmitter class that implements the Listener interface.
|
|
20
|
+
* It provides functionality to handle incoming messages from a shared worker and emit events for new sockets
|
|
21
|
+
* created in response to these incoming connections. This class is meant to be used in the context of managing
|
|
22
|
+
* MessagePort connections within the SharedWorkerGlobalScope.
|
|
23
|
+
*/
|
|
24
|
+
export class SharedWorkerListener extends EventEmitter implements Listener {
|
|
25
|
+
constructor(private worker: SharedWorkerGlobalScope) {
|
|
26
|
+
super();
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Initializes the shared worker listener by assigning the 'handleMessageEvent' method as the event handler
|
|
31
|
+
* for the 'onconnect' event of the SharedWorkerGlobalScope. The 'handleMessageEvent' function will be called
|
|
32
|
+
* whenever a new connection is established with the shared worker.
|
|
33
|
+
*/
|
|
34
|
+
open() {
|
|
35
|
+
this.worker.onconnect = this.handleMessageEvent;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Closes the SharedWorkerListener by detaching the 'onconnect' event handler.
|
|
40
|
+
* This stops the listener from emitting new sockets on incoming connections.
|
|
41
|
+
*/
|
|
42
|
+
close() {
|
|
43
|
+
this.worker.onconnect = () => {};
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
private handleMessageEvent = (event: MessageEvent) => {
|
|
47
|
+
const [port] = event.ports;
|
|
48
|
+
if (!port) {
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
51
|
+
this.emit('new_socket', new MessagePortSocket(port));
|
|
52
|
+
};
|
|
53
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { Connector } from '../interface/connector.js';
|
|
2
|
+
import { MessagePortSocket } from './message_port_socket.js';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* WorkerConnector is a class implementing the Connector interface for creating communication sockets
|
|
6
|
+
* with Web Workers. It allows to establish a connection with the worker and create MessagePortSockets
|
|
7
|
+
* using MessageChannels, enabling seamless communication between the main thread and worker threads.
|
|
8
|
+
*
|
|
9
|
+
* @example
|
|
10
|
+
* const worker = new Worker('./myWorker.js');
|
|
11
|
+
* const connector = new WorkerConnector(worker);
|
|
12
|
+
* const socket = await connector.createSocket();
|
|
13
|
+
* socket.send('Hello, worker!');
|
|
14
|
+
*/
|
|
15
|
+
export class WorkerConnector implements Connector {
|
|
16
|
+
constructor(private worker: Worker) {}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Creates a new MessagePortSocket instance by establishing a connection between the Worker and the main thread.
|
|
20
|
+
* A MessageChannel is created, and one of its ports is sent to the Worker using postMessage.
|
|
21
|
+
* The other port is used to create a new MessagePortSocket which is then returned as a Promise.
|
|
22
|
+
*
|
|
23
|
+
* @returns A Promise that resolves to a new MessagePortSocket instance.
|
|
24
|
+
*/
|
|
25
|
+
createSocket() {
|
|
26
|
+
const channel = new MessageChannel();
|
|
27
|
+
this.worker.postMessage('', [channel.port2]);
|
|
28
|
+
return Promise.resolve(new MessagePortSocket(channel.port1));
|
|
29
|
+
}
|
|
30
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import EventEmitter from 'events';
|
|
2
|
+
|
|
3
|
+
import { Listener } from '../interface/listener.js';
|
|
4
|
+
import { MessagePortSocket } from './message_port_socket.js';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Represents a DedicatedWorkerGlobalScope, which is the global execution context for a dedicated worker.
|
|
8
|
+
* Provides properties and methods to manage the worker's lifecycle and communication with other threads or workers.
|
|
9
|
+
*/
|
|
10
|
+
declare interface DedicatedWorkerGlobalScope {
|
|
11
|
+
/**
|
|
12
|
+
* Handler for incoming messages from other threads or workers.
|
|
13
|
+
*/
|
|
14
|
+
onmessage: any;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* WorkerListener is a class that extends EventEmitter and implements the Listener interface.
|
|
19
|
+
* It listens for incoming connections on a dedicated worker global scope, and emits a 'new_socket' event
|
|
20
|
+
* with a MessagePortSocket instance for each new connection. This allows applications to communicate
|
|
21
|
+
* with other workers or main thread through the MessagePortSocket abstraction.
|
|
22
|
+
*
|
|
23
|
+
* The open() method starts listening for incoming connections, while the close() method stops it.
|
|
24
|
+
*/
|
|
25
|
+
export class WorkerListener extends EventEmitter implements Listener {
|
|
26
|
+
constructor(private worker: DedicatedWorkerGlobalScope) {
|
|
27
|
+
super();
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Initializes the WorkerListener by setting the 'onmessage' event handler of the worker.
|
|
32
|
+
* The 'onmessage' event will be triggered when the worker receives a message, and it will then
|
|
33
|
+
* call the handleMessageEvent method to handle incoming connections.
|
|
34
|
+
*/
|
|
35
|
+
open() {
|
|
36
|
+
this.worker.onmessage = this.handleMessageEvent;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Close the worker listener by removing the 'onmessage' event handler.
|
|
41
|
+
* This method effectively stops the WorkerListener from reacting to new incoming messages.
|
|
42
|
+
*/
|
|
43
|
+
close() {
|
|
44
|
+
this.worker.onmessage = () => {};
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
private handleMessageEvent = (event: MessageEvent) => {
|
|
48
|
+
const [port] = event.ports;
|
|
49
|
+
if (!port) {
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
this.emit('new_socket', new MessagePortSocket(port));
|
|
53
|
+
};
|
|
54
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { format } from 'util';
|
|
2
|
+
|
|
3
|
+
import { createDebugLogger } from '../../log/index.js';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Represents a message object for dispatching function calls.
|
|
7
|
+
* Contains the function name ('fn') and an array of arguments ('args') required to call the target method.
|
|
8
|
+
*/
|
|
9
|
+
export interface DispatchMsg {
|
|
10
|
+
/**
|
|
11
|
+
* Name of the target method to be called.
|
|
12
|
+
*/
|
|
13
|
+
fn: string;
|
|
14
|
+
/**
|
|
15
|
+
* An array of arguments to be passed to the target method.
|
|
16
|
+
*/
|
|
17
|
+
args: any[];
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Creates a dispatch function that calls the target's specified method with provided arguments.
|
|
22
|
+
* The created dispatch function takes a DispatchMsg object as input, which contains the name of
|
|
23
|
+
* the method to be called ('fn') and an array of arguments to be passed to the method ('args').
|
|
24
|
+
*
|
|
25
|
+
* @param targetFn - A function that returns the target object containing the methods to be dispatched.
|
|
26
|
+
* @param debug - Optional logging function for debugging purposes.
|
|
27
|
+
* @returns A dispatch function that accepts a DispatchMsg object and calls the target's method with provided arguments.
|
|
28
|
+
*/
|
|
29
|
+
export function createDispatchFn(targetFn: () => any, debug = createDebugLogger('aztec:foundation:dispatch')) {
|
|
30
|
+
return async ({ fn, args }: DispatchMsg) => {
|
|
31
|
+
const target = targetFn();
|
|
32
|
+
debug(format(`dispatching to ${target}: ${fn}`, args));
|
|
33
|
+
return await target[fn](...args);
|
|
34
|
+
};
|
|
35
|
+
}
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
import { EventEmitter } from 'events';
|
|
2
|
+
|
|
3
|
+
import { TransferDescriptor, isTransferDescriptor } from '../interface/transferable.js';
|
|
4
|
+
import { TransportClient } from '../transport_client.js';
|
|
5
|
+
import { DispatchMsg } from './create_dispatch_fn.js';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* FilterOutAttributes type filters out all non-method properties of an object, leaving only the attributes
|
|
9
|
+
* that are functions. This is useful for creating proxies or wrappers around objects while focusing only
|
|
10
|
+
* on their methods and ignoring other properties.
|
|
11
|
+
*/
|
|
12
|
+
type FilterOutAttributes<Base> = {
|
|
13
|
+
[Key in keyof Base]: Base[Key] extends (...any: any) => any ? Base[Key] : never;
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Takes a function type `F` and returns a new function type with the same input parameters as `F`,
|
|
18
|
+
* but returning a Promise of the original return type of `F`. This is useful for converting sync
|
|
19
|
+
* functions or functions that take callbacks into a version that returns a Promise.
|
|
20
|
+
*/
|
|
21
|
+
type PromisifyFunction<F extends (...any: any) => any> = (...args: Parameters<F>) => Promise<ReturnType<F>>;
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Transforms the provided object type by converting each of its function properties into their
|
|
25
|
+
* promise-returning counterparts. If a function property already returns a promise, it remains unchanged.
|
|
26
|
+
* This is useful when wrapping synchronous methods to return promises in order to standardize the API for
|
|
27
|
+
* asynchronous operations.
|
|
28
|
+
*
|
|
29
|
+
* @typeParam Base - The type of the object whose function properties need to be converted into their
|
|
30
|
+
* promise-returning versions.
|
|
31
|
+
*/
|
|
32
|
+
type Promisify<Base extends { [key: string]: (...any: any) => any }> = {
|
|
33
|
+
[Key in keyof Base]: ReturnType<Base[Key]> extends Promise<any> ? Base[Key] : PromisifyFunction<Base[Key]>;
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Type that transforms a tuple of types, replacing each type 'T' with either 'T' or a `TransferDescriptor<T>` if 'T' is `Transferable`.
|
|
38
|
+
* This is useful for handling arguments of functions that may accept both original and transferable representations of objects.
|
|
39
|
+
*/
|
|
40
|
+
type TransferTypes<Tuple extends [...args: any]> = {
|
|
41
|
+
[Index in keyof Tuple]: Tuple[Index] | (Tuple[Index] extends Transferable ? TransferDescriptor<Tuple[Index]> : never);
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Annoying.
|
|
46
|
+
* @see https://github.com/microsoft/TypeScript/issues/29919
|
|
47
|
+
* There's a bug that means we can't map over the tuple or function parameter types to make them transferrable, if
|
|
48
|
+
* we use the Parameters builtin, and then try to map.
|
|
49
|
+
* So instead we inline the Parameters builtin and apply the TransferTypes to the parameters within the inline.
|
|
50
|
+
* Once the above is fixed we could in theory just do:
|
|
51
|
+
*
|
|
52
|
+
* type MakeFunctionTransferrable\<TFunction extends (...args: any) =\> any\> = (
|
|
53
|
+
* ...args: TransferTypes\<Parameters\<TFunction\>\>
|
|
54
|
+
* ) =\> ReturnType<TFunction>;
|
|
55
|
+
*/
|
|
56
|
+
type MakeFunctionTransferrable<TFunction extends (...args: any) => any> = (
|
|
57
|
+
...args: TFunction extends (...args: infer P) => any ? TransferTypes<P> : never
|
|
58
|
+
) => ReturnType<TFunction>;
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Transferrable type represents a utility type that maps over the provided Base object's methods,
|
|
62
|
+
* transforming their argument types to support transferable objects. This is useful when dealing
|
|
63
|
+
* with operations across different environments or threads, such as Web Workers or Node.js processes,
|
|
64
|
+
* where certain objects need to be transferred instead of being serialized and deserialized.
|
|
65
|
+
*/
|
|
66
|
+
type Transferrable<Base extends { [key: string]: (...any: any) => any }> = {
|
|
67
|
+
[Key in keyof Base]: MakeFunctionTransferrable<Base[Key]>;
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Proxify is a mapped type that takes an object with functions as its properties and returns
|
|
72
|
+
* a new object with the same properties, but with each function transformed to return a Promise
|
|
73
|
+
* and accept Transferable types in place of their original parameters. This type is useful for
|
|
74
|
+
* creating proxies that communicate over different environments or threads while maintaining
|
|
75
|
+
* the original class's method signatures, allowing for type-safe interaction with remote instances.
|
|
76
|
+
*/
|
|
77
|
+
export type Proxify<T> = Promisify<Transferrable<FilterOutAttributes<T>>>;
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Creates a proxy object for the provided class, wrapping each method in a request function.
|
|
81
|
+
* The resulting proxy object allows invoking methods of the original class, but their execution
|
|
82
|
+
* is delegated to the request function. This is useful when executing methods across different
|
|
83
|
+
* environments or threads, such as Web Workers or Node.js processes.
|
|
84
|
+
*
|
|
85
|
+
* @typeParam T - The type of the class to create a proxy for.
|
|
86
|
+
* @param class_ - The class constructor to create a proxy for.
|
|
87
|
+
* @param requestFn - A higher-order function that takes a method name and returns a function
|
|
88
|
+
* with the same signature as the original method, which wraps the actual
|
|
89
|
+
* invocation in a custom logic (e.g., sending a message to another thread).
|
|
90
|
+
* @returns An object whose methods match those of the original class, but whose execution is
|
|
91
|
+
* delegated to the provided request function.
|
|
92
|
+
*/
|
|
93
|
+
export function createDispatchProxyFromFn<T>(
|
|
94
|
+
class_: { new (...args: any[]): T },
|
|
95
|
+
requestFn: (fn: string) => (...args: any[]) => Promise<any>,
|
|
96
|
+
): Proxify<T> {
|
|
97
|
+
const proxy: any = class_.prototype instanceof EventEmitter ? new EventEmitter() : {};
|
|
98
|
+
for (const fn of Object.getOwnPropertyNames(class_.prototype)) {
|
|
99
|
+
if (fn === 'constructor') {
|
|
100
|
+
continue;
|
|
101
|
+
}
|
|
102
|
+
proxy[fn] = requestFn(fn);
|
|
103
|
+
}
|
|
104
|
+
return proxy;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Creates a proxy for the given class that transparently dispatches method calls over a transport client.
|
|
109
|
+
* The proxy allows calling methods on remote instances of the class through the provided transport client
|
|
110
|
+
* while maintaining the correct return types and handling promises. If the class inherits from EventEmitter,
|
|
111
|
+
* it also handles event emissions through the transport client.
|
|
112
|
+
*
|
|
113
|
+
* @param class_ - The constructor function of the class to create the proxy for.
|
|
114
|
+
* @param transportClient - The TransportClient instance used to handle communication between proxies.
|
|
115
|
+
* @returns A proxified version of the given class with methods dispatched over the transport client.
|
|
116
|
+
*/
|
|
117
|
+
export function createDispatchProxy<T>(
|
|
118
|
+
class_: { new (...args: any[]): T },
|
|
119
|
+
transportClient: TransportClient<DispatchMsg>,
|
|
120
|
+
): Proxify<T> {
|
|
121
|
+
// Create a proxy of class_ that passes along methods over our transportClient
|
|
122
|
+
const proxy = createDispatchProxyFromFn(class_, (fn: string) => (...args: any[]) => {
|
|
123
|
+
// Pass our proxied function name and arguments over our transport client
|
|
124
|
+
const transfer: Transferable[] = args.reduce(
|
|
125
|
+
(acc, a) => (isTransferDescriptor(a) ? [...acc, ...a.transferables] : acc),
|
|
126
|
+
[] as Transferable[],
|
|
127
|
+
);
|
|
128
|
+
args = args.map(a => (isTransferDescriptor(a) ? a.send : a));
|
|
129
|
+
return transportClient.request({ fn, args }, transfer);
|
|
130
|
+
});
|
|
131
|
+
if (proxy instanceof EventEmitter) {
|
|
132
|
+
// Handle proxied 'emit' calls if our proxy object is an EventEmitter
|
|
133
|
+
transportClient.on('event_msg', ({ fn, args }) => {
|
|
134
|
+
if (fn === 'emit') {
|
|
135
|
+
const [eventName, ...restArgs] = args;
|
|
136
|
+
proxy.emit(eventName, ...restArgs);
|
|
137
|
+
}
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
return proxy;
|
|
141
|
+
}
|