|
3 | 3 | import com.bitgo.wasm.privacycoin.WasmException; |
4 | 4 | import com.bitgo.wasm.privacycoin.proto.Response; |
5 | 5 | import com.bitgo.wasm.privacycoin.proto.WasmError; |
| 6 | +import com.dylibso.chicory.compiler.MachineFactoryCompiler; |
6 | 7 | import com.dylibso.chicory.runtime.ExportFunction; |
7 | 8 | import com.dylibso.chicory.runtime.Instance; |
| 9 | +import com.dylibso.chicory.runtime.Machine; |
8 | 10 | import com.dylibso.chicory.wasm.Parser; |
| 11 | +import com.dylibso.chicory.wasm.WasmModule; |
9 | 12 | import com.google.protobuf.InvalidProtocolBufferException; |
10 | 13 |
|
11 | 14 | import java.io.ByteArrayInputStream; |
12 | 15 | import java.io.IOException; |
13 | 16 | import java.io.InputStream; |
| 17 | +import java.util.concurrent.ConcurrentLinkedDeque; |
| 18 | +import java.util.function.Function; |
14 | 19 |
|
15 | 20 | /** |
16 | 21 | * Low-level bridge to the shielded-tree WASM instance. |
|
22 | 27 | * Each call writes a proto-encoded request into WASM linear memory, invokes the named |
23 | 28 | * export, then reads the {@link Response} proto from the LAST_RESULT buffer. |
24 | 29 | * |
| 30 | + * <p><b>Performance:</b> The parsed {@link WasmModule}, JIT-compiled machine factory, and |
| 31 | + * instantiated {@link Instance} objects are all cached/pooled. The module is parsed once per |
| 32 | + * JVM (it is immutable and safe to share). The WASM functions are JIT-compiled to JVM bytecode |
| 33 | + * once via {@link MachineFactoryCompiler} — this replaces Chicory's default interpreter with |
| 34 | + * native-speed bytecode execution. Instances are pooled: on {@link #close()}, the in-WASM tree |
| 35 | + * is dropped via the {@code drop_tree} export and the Instance is returned to a pool for reuse |
| 36 | + * by the next {@code WasmBridge}. |
| 37 | + * |
25 | 38 | * <p><b>Thread safety:</b> Not thread-safe. One bridge per {@link ShieldedMerkleTree}. |
| 39 | + * The cached module and instance pool are safe for concurrent access. |
26 | 40 | */ |
27 | 41 | final class WasmBridge implements AutoCloseable { |
28 | 42 |
|
| 43 | + /** |
| 44 | + * Lazily-parsed, JVM-wide cached WASM module. {@link WasmModule} is immutable after |
| 45 | + * construction, so it is safe to share across threads and to build multiple independent |
| 46 | + * {@link Instance}s from it. |
| 47 | + */ |
| 48 | + private static volatile WasmModule cachedModule; |
| 49 | + |
| 50 | + /** |
| 51 | + * JIT-compiled machine factory cached alongside the module. The {@link MachineFactoryCompiler} |
| 52 | + * translates WASM functions into JVM bytecode at load time; the resulting factory is reused |
| 53 | + * by every {@link Instance}, so the compilation cost is paid once per JVM. This replaces |
| 54 | + * Chicory's default interpreter with native-speed bytecode execution. |
| 55 | + */ |
| 56 | + private static volatile Function<Instance, Machine> cachedMachineFactory; |
| 57 | + |
| 58 | + /** |
| 59 | + * Pool of previously-used {@link Instance} objects whose in-WASM tree has been dropped. |
| 60 | + * Reusing an Instance avoids the instantiation cost; the {@code from_frontier} / |
| 61 | + * {@code from_state} export re-initializes the tree state in the existing linear memory. |
| 62 | + */ |
| 63 | + private static final ConcurrentLinkedDeque<Instance> instancePool = new ConcurrentLinkedDeque<>(); |
| 64 | + |
29 | 65 | private final Instance instance; |
30 | 66 | private final ExportFunction fnAlloc; |
31 | 67 | private final ExportFunction fnDealloc; |
32 | 68 | private final ExportFunction fnResultPtr; |
33 | 69 | private final ExportFunction fnResultLen; |
34 | 70 |
|
35 | 71 | WasmBridge() { |
36 | | - byte[] wasmBytes; |
| 72 | + Instance inst = instancePool.pollFirst(); |
| 73 | + if (inst == null) { |
| 74 | + try { |
| 75 | + inst = Instance.builder(loadModule()) |
| 76 | + .withMachineFactory(loadMachineFactory()) |
| 77 | + .build(); |
| 78 | + } catch (Exception e) { |
| 79 | + throw new IllegalStateException("Failed to instantiate WASM module", e); |
| 80 | + } |
| 81 | + } |
| 82 | + this.instance = inst; |
| 83 | + |
| 84 | + this.fnAlloc = instance.export("alloc"); |
| 85 | + this.fnDealloc = instance.export("dealloc"); |
| 86 | + this.fnResultPtr = instance.export("last_result_ptr"); |
| 87 | + this.fnResultLen = instance.export("last_result_len"); |
| 88 | + } |
| 89 | + |
| 90 | + /** |
| 91 | + * Returns the cached parsed module, parsing it on first use. Subsequent calls reuse |
| 92 | + * the same immutable {@link WasmModule}, eliminating redundant parse overhead when |
| 93 | + * multiple {@link ShieldedMerkleTree} instances are created in the same JVM (e.g. |
| 94 | + * in tests or when re-initializing after a reorg). |
| 95 | + */ |
| 96 | + private static WasmModule loadModule() { |
| 97 | + WasmModule module = cachedModule; |
| 98 | + if (module != null) { |
| 99 | + return module; |
| 100 | + } |
| 101 | + synchronized (WasmBridge.class) { |
| 102 | + module = cachedModule; |
| 103 | + if (module == null) { |
| 104 | + byte[] wasmBytes = readWasmBytes(); |
| 105 | + module = Parser.parse(new ByteArrayInputStream(wasmBytes)); |
| 106 | + cachedModule = module; |
| 107 | + } |
| 108 | + return module; |
| 109 | + } |
| 110 | + } |
| 111 | + |
| 112 | + /** |
| 113 | + * Returns the cached JIT-compiled machine factory, compiling it on first use. The |
| 114 | + * {@link MachineFactoryCompiler} translates all WASM functions to JVM bytecode once; |
| 115 | + * the resulting {@link Machine} is then used by every {@link Instance} built from |
| 116 | + * the same module, providing native-speed execution instead of interpretation. |
| 117 | + */ |
| 118 | + private static Function<Instance, Machine> loadMachineFactory() { |
| 119 | + Function<Instance, Machine> factory = cachedMachineFactory; |
| 120 | + if (factory != null) { |
| 121 | + return factory; |
| 122 | + } |
| 123 | + synchronized (WasmBridge.class) { |
| 124 | + factory = cachedMachineFactory; |
| 125 | + if (factory == null) { |
| 126 | + factory = MachineFactoryCompiler.compile(loadModule()); |
| 127 | + cachedMachineFactory = factory; |
| 128 | + } |
| 129 | + return factory; |
| 130 | + } |
| 131 | + } |
| 132 | + |
| 133 | + private static byte[] readWasmBytes() { |
37 | 134 | try (InputStream is = WasmBridge.class.getResourceAsStream("/wasm/privacy_coin.wasm")) { |
38 | 135 | if (is == null) { |
39 | 136 | throw new IllegalStateException( |
40 | 137 | "WASM binary not found on classpath: /wasm/privacy_coin.wasm"); |
41 | 138 | } |
42 | | - wasmBytes = is.readAllBytes(); |
| 139 | + return is.readAllBytes(); |
43 | 140 | } catch (IOException e) { |
44 | 141 | throw new IllegalStateException("Failed to load WASM binary", e); |
45 | 142 | } |
46 | | - |
47 | | - try { |
48 | | - var module = Parser.parse(new ByteArrayInputStream(wasmBytes)); |
49 | | - this.instance = Instance.builder(module).build(); |
50 | | - } catch (Exception e) { |
51 | | - throw new IllegalStateException("Failed to instantiate WASM module", e); |
52 | | - } |
53 | | - |
54 | | - this.fnAlloc = instance.export("alloc"); |
55 | | - this.fnDealloc = instance.export("dealloc"); |
56 | | - this.fnResultPtr = instance.export("last_result_ptr"); |
57 | | - this.fnResultLen = instance.export("last_result_len"); |
58 | 143 | } |
59 | 144 |
|
60 | 145 | private final class WasmBuffer implements AutoCloseable { |
@@ -114,8 +199,27 @@ static WasmException toWasmException(WasmError error) { |
114 | 199 | return new WasmException(error.getCode(), error.getMessage()); |
115 | 200 | } |
116 | 201 |
|
| 202 | + /** |
| 203 | + * Drops the in-WASM tree and returns the {@link Instance} to the pool for reuse. |
| 204 | + * If {@code drop_tree} fails (e.g. the tree was never initialized), the Instance is |
| 205 | + * still pooled — the next {@code from_frontier} / {@code from_state} call will |
| 206 | + * re-initialize it regardless. |
| 207 | + */ |
117 | 208 | @Override |
118 | 209 | public void close() { |
119 | | - // Chicory Instance has no explicit close method; nothing to do here. |
| 210 | + try { |
| 211 | + instance.export("drop_tree").apply(); |
| 212 | + } catch (Exception ignored) { |
| 213 | + // Best-effort cleanup; the instance is still reusable. |
| 214 | + } |
| 215 | + instancePool.addFirst(instance); |
| 216 | + } |
| 217 | + |
| 218 | + /** |
| 219 | + * Discards this bridge without returning the {@link Instance} to the pool. Use this |
| 220 | + * when initialization failed and the WASM linear memory may be in an inconsistent state. |
| 221 | + */ |
| 222 | + void discard() { |
| 223 | + // Instance is simply abandoned; Chicory has no explicit close. |
120 | 224 | } |
121 | 225 | } |
0 commit comments