forked from roastedroot/proxy-wasm-java-host
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProxyWasm.java
More file actions
401 lines (336 loc) · 13.2 KB
/
ProxyWasm.java
File metadata and controls
401 lines (336 loc) · 13.2 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
package io.roastedroot.proxywasm.v1;
import static io.roastedroot.proxywasm.v1.Helpers.len;
import com.dylibso.chicory.runtime.ByteBufferMemory;
import com.dylibso.chicory.runtime.HostFunction;
import com.dylibso.chicory.runtime.ImportMemory;
import com.dylibso.chicory.runtime.ImportValues;
import com.dylibso.chicory.runtime.Instance;
import com.dylibso.chicory.wasi.WasiOptions;
import com.dylibso.chicory.wasi.WasiPreview1;
import com.dylibso.chicory.wasm.InvalidException;
import com.dylibso.chicory.wasm.WasmModule;
import com.dylibso.chicory.wasm.types.MemoryLimits;
import com.dylibso.chicory.wasm.types.ValueType;
import io.roastedroot.proxywasm.impl.Exports;
import io.roastedroot.proxywasm.impl.Imports;
import io.roastedroot.proxywasm.impl.Imports_ModuleFactory;
import java.io.Closeable;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
public final class ProxyWasm implements Closeable {
private final Exports exports;
private final Imports imports;
private final Handler pluginHandler;
private final byte[] pluginConfig;
private final byte[] vmConfig;
private final HashMap<String, String> properties;
private final WasiPreview1 wasi;
private final AtomicInteger nextContextID = new AtomicInteger(1);
private final ABIVersion abiVersion;
private Context pluginContext;
private Context activeContext;
private HashMap<Integer, Context> contexts = new HashMap<>();
private Map<String, String> httpCallResponseHeaders;
private Map<String, String> httpCallResponseTrailers;
private byte[] httpCallResponseBody;
private HashMap<String, ForeignFunction> foreignFunctions = new HashMap<>();
private ProxyWasm(Builder other) throws StartException {
this.vmConfig = other.vmConfig;
this.pluginConfig = other.pluginConfig;
this.properties = Objects.requireNonNullElse(other.properties, new HashMap<>());
this.pluginHandler = Objects.requireNonNullElse(other.pluginHandler, new Handler() {});
this.wasi = other.wasi;
this.exports = other.exports;
this.imports = other.imports;
this.imports.setHandler(createImportsHandler());
this.abiVersion = findAbiVersion();
// Since 0_2_0, prefer proxy_on_memory_allocate over malloc
if (instanceExportsFunction("proxy_on_memory_allocate")) {
this.exports.setMallocFunctionName("proxy_on_memory_allocate");
}
// initialize/start the vm
if (instanceExportsFunction("_initialize")) {
this.exports.initialize();
if (instanceExportsFunction("main")) {
this.exports.main(0, 0);
}
} else {
if (instanceExportsFunction("_start")) {
this.exports.start();
}
}
// start the vm with the vmHandler, it will receive stuff like log messages.
this.pluginContext = new PluginContext(this, pluginHandler);
registerContext(pluginContext, 0);
if (!exports.proxyOnVmStart(pluginContext.id(), vmConfig.length)) {
throw new StartException("proxy_on_vm_start failed");
}
if (!exports.proxyOnConfigure(pluginContext.id(), pluginConfig.length)) {
throw new StartException("proxy_on_configure failed");
}
}
private void registerContext(Context context, int parentContextID) {
contexts.put(context.id(), context);
activeContext = context;
exports.proxyOnContextCreate(context.id(), parentContextID);
}
private ABIVersion findAbiVersion() throws StartException {
for (var version : ABIVersion.values()) {
if (instanceExportsFunction(version.getAbiMarkerFunction())) {
return version;
}
}
throw new StartException("wasm module does nto contain a supported proxy-wasm abi version");
}
private boolean instanceExportsFunction(String name) {
try {
this.imports.getInstance().exports().function(name);
return true;
} catch (InvalidException e) {
return false;
}
}
// Let's implement some of the handler functions to make life easier for the user.
// The user's handler will be the last handler in the chain.
private ChainedHandler createImportsHandler() {
return new ChainedHandler() {
@Override
protected Handler next() {
return activeContext.handler();
}
@Override
public byte[] getVmConfig() {
return vmConfig;
}
@Override
public byte[] getPluginConfig() {
return pluginConfig;
}
@Override
public String getProperty(String key) throws WasmException {
if (properties.containsKey(key)) {
return properties.get(key);
}
var handler = activeContext.handler();
if (handler != null) {
return handler.getProperty(key);
}
return null;
}
@Override
public WasmResult setEffectiveContextID(int contextID) {
Context context = contexts.get(contextID);
if (context == null) {
return WasmResult.BAD_ARGUMENT;
}
activeContext = context;
return WasmResult.OK;
}
@Override
public WasmResult done() {
return activeContext.done();
}
@Override
public Map<String, String> getHttpCallResponseHeaders() {
return httpCallResponseHeaders;
}
@Override
public Map<String, String> getHttpCallResponseTrailers() {
return httpCallResponseTrailers;
}
@Override
public byte[] getHttpCallResponseBody() {
return httpCallResponseBody;
}
@Override
public byte[] callForeignFunction(String name, byte[] bytes) throws WasmException {
ForeignFunction func = foreignFunctions.get(name);
if (func == null) {
throw new WasmException(WasmResult.NOT_FOUND);
}
return func.apply(bytes);
}
};
}
HashMap<Integer, Context> contexts() {
return contexts;
}
Exports exports() {
return exports;
}
Context getActiveContext() {
return activeContext;
}
void setActiveContext(Context activeContext) {
if (activeContext == null) {
// this happens when a context is finishes closing...
// assuming the current context should be the plugin context after that,
// but maybe it would be better to error out if a new context is not set.
activeContext = this.pluginContext;
}
this.activeContext = activeContext;
}
int nextContextID() {
return nextContextID.getAndIncrement();
}
public HttpContext createHttpContext(Handler handler) {
HttpContext context = new HttpContext(this, handler);
registerContext(context, this.pluginContext.id());
return context;
}
/**
* Delivers a tick event to the plugin.
* <p>
* tick() should be called in response to a Handler.setTickPeriodMilliseconds(int tick_period) callback.
*/
public void tick() {
exports.proxyOnTick(pluginContext.id());
}
public ABIVersion abiVersion() {
return abiVersion;
}
public void setProperty(String[] path, String data) {
if (len(path) == 0) {
throw new IllegalArgumentException("path must not be empty");
}
if (len(data) == 0) {
throw new IllegalArgumentException("data must not be empty");
}
this.properties.put(String.join("\u0000", path), data);
}
public String getProperty(String[] path) {
if (len(path) == 0) {
throw new IllegalArgumentException("path must not be empty");
}
return this.properties.get(String.join("\u0000", path));
}
@Override
public void close() {
this.pluginContext.close();
if (wasi != null) {
wasi.close();
}
}
public static ProxyWasm.Builder builder() {
return new ProxyWasm.Builder();
}
public void callOnHttpCallResponse(
int calloutID, Map<String, String> headers, Map<String, String> trailers, byte[] body) {
this.httpCallResponseHeaders = headers;
this.httpCallResponseTrailers = trailers;
this.httpCallResponseBody = body;
this.exports.proxyOnHttpCallResponse(
pluginContext.id(), calloutID, len(headers), len(body), len(trailers));
this.httpCallResponseHeaders = null;
this.httpCallResponseTrailers = null;
this.httpCallResponseBody = null;
}
public int contextId() {
return pluginContext.id();
}
public void registerForeignFunction(String name, ForeignFunction func) {
foreignFunctions.put(name, func);
}
public static class Builder implements Cloneable {
private Exports exports;
private final Imports imports = new Imports();
private WasiPreview1 wasi;
private byte[] vmConfig = new byte[0];
private byte[] pluginConfig = new byte[0];
private HashMap<String, String> properties;
private Handler pluginHandler;
private ImportMemory memory;
private WasiOptions wasiOptions;
@Override
@SuppressWarnings("NoClone")
protected Builder clone() {
try {
return (Builder) super.clone();
} catch (CloneNotSupportedException e) {
throw new RuntimeException(e);
}
}
public HostFunction[] toHostFunctions() {
return Imports_ModuleFactory.toHostFunctions(imports);
}
public ProxyWasm.Builder withVmConfig(String vmConfig) {
this.vmConfig = vmConfig.getBytes(StandardCharsets.UTF_8);
return this;
}
public ProxyWasm.Builder withPluginConfig(String pluginConfig) {
this.pluginConfig = pluginConfig.getBytes(StandardCharsets.UTF_8);
return this;
}
public ProxyWasm.Builder withProperties(Map<String, String> properties) {
if (properties != null) {
this.properties = new HashMap<>(properties);
} else {
this.properties = null;
}
return this;
}
public ProxyWasm.Builder withPluginHandler(Handler vmHandler) {
this.pluginHandler = vmHandler;
return this;
}
public ProxyWasm.Builder withImportMemory(ImportMemory memory) {
this.memory = memory;
return this;
}
public ProxyWasm.Builder withWasiOptions(WasiOptions options) {
this.wasiOptions = options;
return this;
}
Builder() {}
public ProxyWasm build(Instance instance) throws StartException {
exports = new Exports(instance.exports());
imports.setInstance(instance);
imports.setExports(exports);
return new ProxyWasm(this.clone());
}
public ProxyWasm build(WasmModule module) throws StartException {
var imports = ImportValues.builder();
imports.addMemory(Objects.requireNonNullElseGet(memory, this::defaultImportMemory));
imports.addFunction(toHostFunctions());
imports.addFunction(
new HostFunction(
"env",
"emscripten_notify_memory_growth",
List.of(ValueType.I32),
List.of(),
(inst, args) -> {
return null;
}));
wasi =
WasiPreview1.builder()
.withOptions(
Objects.requireNonNullElseGet(
wasiOptions, this::defaultWasiOptions))
.build();
imports.addFunction(wasi.toHostFunctions());
imports.addFunction(Helpers.withModuleName(wasi.toHostFunctions(), "wasi_unstable"));
var instance =
Instance.builder(module)
.withStart(false) // we will start it manually
.withImportValues(imports.build())
.build();
return build(instance);
}
ImportMemory defaultImportMemory() {
return new ImportMemory(
"env",
"memory",
new ByteBufferMemory(new MemoryLimits(2, MemoryLimits.MAX_PAGES)));
}
WasiOptions defaultWasiOptions() {
return WasiOptions.builder().inheritSystem().build();
}
}
public static void start(int abi_version_ignored) {
// ... existing code ...
}
}