|
| 1 | +/* |
| 2 | + * Licensed to the Apache Software Foundation (ASF) under one |
| 3 | + * or more contributor license agreements. See the NOTICE file |
| 4 | + * distributed with this work for additional information |
| 5 | + * regarding copyright ownership. The ASF licenses this file |
| 6 | + * to you under the Apache License, Version 2.0 (the |
| 7 | + * "License"); you may not use this file except in compliance |
| 8 | + * with the License. You may obtain a copy of the License at |
| 9 | + * |
| 10 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 11 | + * |
| 12 | + * Unless required by applicable law or agreed to in writing, |
| 13 | + * software distributed under the License is distributed on an |
| 14 | + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 15 | + * KIND, either express or implied. See the License for the |
| 16 | + * specific language governing permissions and limitations |
| 17 | + * under the License. |
| 18 | + */ |
| 19 | +// Helper tools to enable asynctify handling |
| 20 | +// Thie following code is used to support wrapping of |
| 21 | +// functins that can have async await calls in the backend runtime |
| 22 | +// reference |
| 23 | +// - https://kripken.github.io/blog/wasm/2019/07/16/asyncify.html |
| 24 | +// - https://github.com/GoogleChromeLabs/asyncify |
| 25 | +import { assert, isPromise } from "./support"; |
| 26 | + |
| 27 | +/** |
| 28 | + * enums to check the current state of asynctify |
| 29 | + */ |
| 30 | +const enum AsyncifyStateKind { |
| 31 | + None = 0, |
| 32 | + Unwinding = 1, |
| 33 | + Rewinding = 2 |
| 34 | +} |
| 35 | + |
| 36 | +/** The start location of asynctify stack data */ |
| 37 | +const ASYNCIFY_DATA_ADDR = 16; |
| 38 | +/** The data start of stack rewind/unwind */ |
| 39 | +const ASYNCIFY_DATA_START = ASYNCIFY_DATA_ADDR + 8; |
| 40 | +/** The data end of stack rewind/unwind */ |
| 41 | +const ASYNCIFY_DATA_END = 1024; |
| 42 | + |
| 43 | +/** Hold asynctify handler instance that runtime can use */ |
| 44 | +export class AsyncifyHandler { |
| 45 | + /** exports from wasm */ |
| 46 | + private exports: Record<string, Function>; |
| 47 | + /** current state kind */ |
| 48 | + private state: AsyncifyStateKind = AsyncifyStateKind.None; |
| 49 | + /** The stored value before unwind */ |
| 50 | + private storedPromiseBeforeUnwind : Promise<any> = null; |
| 51 | + // NOTE: asynctify do not work with exceptions |
| 52 | + // this implementation here is mainly for possible future compact |
| 53 | + /** The stored value that is resolved */ |
| 54 | + private storedValueBeforeRewind: any = null; |
| 55 | + /** The stored exception */ |
| 56 | + private storedExceptionBeforeRewind: any = null; |
| 57 | + |
| 58 | + constructor(exports: Record<string, Function>, memory: WebAssembly.Memory) { |
| 59 | + this.exports = exports; |
| 60 | + this.initMemory(memory); |
| 61 | + } |
| 62 | + |
| 63 | + // NOTE: wrapImport and wrapExport are closely related to each other |
| 64 | + // We mark the logical jump pt in comments to increase the readability |
| 65 | + /** |
| 66 | + * Whether the wasm enables asynctify |
| 67 | + * @returns Whether the wasm enables asynctify |
| 68 | + */ |
| 69 | + enabled(): boolean { |
| 70 | + return this.exports.asyncify_stop_rewind !== undefined; |
| 71 | + } |
| 72 | + |
| 73 | + /** |
| 74 | + * Get the current asynctify state |
| 75 | + * |
| 76 | + * @returns The current asynctify state |
| 77 | + */ |
| 78 | + getState(): AsyncifyStateKind { |
| 79 | + return this.state; |
| 80 | + } |
| 81 | + |
| 82 | + /** |
| 83 | + * Wrap a function that can be used as import of the wasm asynctify layer |
| 84 | + * |
| 85 | + * @param func The input import function |
| 86 | + * @returns The wrapped function that can be registered to the system |
| 87 | + */ |
| 88 | + wrapImport(func: (...args: Array<any>) => any): (...args: Array<any>) => any { |
| 89 | + return (...args: any) => { |
| 90 | + // this is being called second time |
| 91 | + // where we are rewinding the stack |
| 92 | + if (this.getState() == AsyncifyStateKind.Rewinding) { |
| 93 | + // JUMP-PT-REWIND: rewind will jump to this pt |
| 94 | + // while rewinding the stack |
| 95 | + this.stopRewind(); |
| 96 | + // the value has been resolved |
| 97 | + if (this.storedValueBeforeRewind !== null) { |
| 98 | + assert(this.storedExceptionBeforeRewind === null); |
| 99 | + const result = this.storedValueBeforeRewind; |
| 100 | + this.storedValueBeforeRewind = null; |
| 101 | + return result; |
| 102 | + } else { |
| 103 | + assert(this.storedValueBeforeRewind === null); |
| 104 | + const error = this.storedExceptionBeforeRewind; |
| 105 | + this.storedExceptionBeforeRewind = null; |
| 106 | + throw error; |
| 107 | + } |
| 108 | + } |
| 109 | + // this function is being called for the first time |
| 110 | + assert(this.getState() == AsyncifyStateKind.None); |
| 111 | + |
| 112 | + // call the function |
| 113 | + const value = func(...args); |
| 114 | + // if the value is promise |
| 115 | + // we need to unwind the stack |
| 116 | + // so the caller will be able to evaluate the promise |
| 117 | + if (isPromise(value)) { |
| 118 | + // The next code step is JUMP-PT-UNWIND in wrapExport |
| 119 | + // The value will be passed to that pt through storedPromiseBeforeUnwind |
| 120 | + // getState() == Unwinding and we will enter the while loop in wrapExport |
| 121 | + this.startUnwind(); |
| 122 | + assert(this.storedPromiseBeforeUnwind == null); |
| 123 | + this.storedPromiseBeforeUnwind = value; |
| 124 | + return undefined; |
| 125 | + } else { |
| 126 | + // The next code step is JUMP-PT-UNWIND in wrapExport |
| 127 | + // normal value, we don't have to do anything |
| 128 | + // getState() == None and we will exit while loop there |
| 129 | + return value; |
| 130 | + } |
| 131 | + }; |
| 132 | + } |
| 133 | + |
| 134 | + /** |
| 135 | + * Warp an exported asynctify function so it can return promise |
| 136 | + * |
| 137 | + * @param func The input function |
| 138 | + * @returns The wrapped async function |
| 139 | + */ |
| 140 | + wrapExport(func: (...args: Array<any>) => any): (...args: Array<any>) => Promise<any> { |
| 141 | + return async (...args: Array<any>) => { |
| 142 | + assert(this.getState() == AsyncifyStateKind.None); |
| 143 | + |
| 144 | + // call the original function |
| 145 | + let result = func(...args); |
| 146 | + |
| 147 | + // JUMP-PT-UNWIND |
| 148 | + // after calling the function |
| 149 | + // the caller may hit a unwinding point depending on |
| 150 | + // the if (isPromise(value)) condition in wrapImport |
| 151 | + while (this.getState() == AsyncifyStateKind.Unwinding) { |
| 152 | + this.stopUnwind(); |
| 153 | + // try to resolve the promise that the internal requested |
| 154 | + // we then store it into the temp value in storedValueBeforeRewind |
| 155 | + // which then get passed onto the function(see wrapImport) |
| 156 | + // that can return the value |
| 157 | + const storedPromiseBeforeUnwind = this.storedPromiseBeforeUnwind; |
| 158 | + this.storedPromiseBeforeUnwind = null; |
| 159 | + assert(this.storedExceptionBeforeRewind === null); |
| 160 | + assert(this.storedValueBeforeRewind == null); |
| 161 | + |
| 162 | + try { |
| 163 | + this.storedValueBeforeRewind = await storedPromiseBeforeUnwind; |
| 164 | + } catch (error) { |
| 165 | + // the store exception |
| 166 | + this.storedExceptionBeforeRewind = error; |
| 167 | + } |
| 168 | + assert(!isPromise(this.storedValueBeforeRewind)); |
| 169 | + // because we called asynctify_stop_unwind,the state is now none |
| 170 | + assert(this.getState() == AsyncifyStateKind.None); |
| 171 | + |
| 172 | + // re-enter the function, jump to JUMP-PT-REWIND in wrapImport |
| 173 | + // the value will be passed to that point via storedValueBeforeRewind |
| 174 | + // |
| 175 | + // NOTE: we guarantee that if exception is throw the asynctify state |
| 176 | + // will already be at None, this is because we will goto JUMP-PT-REWIND |
| 177 | + // which will call aynctify_stop_rewind |
| 178 | + this.startRewind(); |
| 179 | + result = func(...args); |
| 180 | + } |
| 181 | + return result; |
| 182 | + }; |
| 183 | + } |
| 184 | + |
| 185 | + private startRewind() : void { |
| 186 | + if (this.exports.asyncify_start_rewind === undefined) { |
| 187 | + throw Error("Asynctify is not enabled, please compile with -s ASYNCIFY=1 in emcc"); |
| 188 | + } |
| 189 | + this.exports.asyncify_start_rewind(ASYNCIFY_DATA_ADDR); |
| 190 | + this.state = AsyncifyStateKind.Rewinding; |
| 191 | + } |
| 192 | + |
| 193 | + private stopRewind() : void { |
| 194 | + if (this.exports.asyncify_stop_rewind === undefined) { |
| 195 | + throw Error("Asynctify is not enabled, please compile with -s ASYNCIFY=1 in emcc"); |
| 196 | + } |
| 197 | + this.exports.asyncify_stop_rewind(); |
| 198 | + this.state = AsyncifyStateKind.None; |
| 199 | + } |
| 200 | + |
| 201 | + private startUnwind() : void { |
| 202 | + if (this.exports.asyncify_start_unwind === undefined) { |
| 203 | + throw Error("Asynctify is not enabled, please compile with -s ASYNCIFY=1 in emcc"); |
| 204 | + } |
| 205 | + this.exports.asyncify_start_unwind(ASYNCIFY_DATA_ADDR); |
| 206 | + this.state = AsyncifyStateKind.Unwinding; |
| 207 | + } |
| 208 | + |
| 209 | + private stopUnwind() : void { |
| 210 | + if (this.exports.asyncify_stop_unwind === undefined) { |
| 211 | + throw Error("Asynctify is not enabled, please compile with -s ASYNCIFY=1 in emcc"); |
| 212 | + } |
| 213 | + this.exports.asyncify_stop_unwind(); |
| 214 | + this.state = AsyncifyStateKind.None; |
| 215 | + } |
| 216 | + /** |
| 217 | + * Initialize the wasm memory to setup necessary meta-data |
| 218 | + * for asynctify handling |
| 219 | + * @param memory The memory ti |
| 220 | + */ |
| 221 | + private initMemory(memory: WebAssembly.Memory): void { |
| 222 | + // Set the meta-data at address ASYNCTIFY_DATA_ADDR |
| 223 | + new Int32Array(memory.buffer, ASYNCIFY_DATA_ADDR, 2).set( |
| 224 | + [ASYNCIFY_DATA_START, ASYNCIFY_DATA_END] |
| 225 | + ); |
| 226 | + } |
| 227 | +} |
0 commit comments