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
324 lines (266 loc) · 10.3 KB
/
ProxyWasm.java
File metadata and controls
324 lines (266 loc) · 10.3 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
package io.roastedroot.proxywasm;
import static io.roastedroot.proxywasm.Helpers.len;
import com.dylibso.chicory.runtime.ByteArrayMemory;
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.WasmModule;
import com.dylibso.chicory.wasm.types.MemoryLimits;
import com.dylibso.chicory.wasm.types.ValueType;
import java.io.Closeable;
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 ABI abi;
private final WasiPreview1 wasi;
private final AtomicInteger nextContextID = new AtomicInteger(1);
private Context pluginContext;
private Context activeContext;
private HashMap<Integer, Context> contexts = new HashMap<>();
private ProxyMap httpCallResponseHeaders;
private ProxyMap httpCallResponseTrailers;
private byte[] httpCallResponseBody;
private Handler pluginHandler;
private ProxyWasm(Builder other) throws StartException {
this.pluginHandler = Objects.requireNonNullElse(other.pluginHandler, new Handler() {});
this.wasi = other.wasi;
this.abi = other.abi;
this.abi.setHandler(createImportsHandler());
// initialize/start the vm
if (this.abi.initialize()) {
this.abi.main(0, 0);
} else {
this.abi.start();
}
if (other.start) {
start();
}
}
public Handler getPluginHandler() {
return pluginHandler;
}
public void setPluginHandler(Handler pluginHandler) {
this.pluginHandler = pluginHandler;
}
public void start() throws StartException {
if (pluginContext != null) {
return;
}
this.pluginContext = new PluginContext(this, pluginHandler);
registerContext(pluginContext, 0);
byte[] vmConfig = this.pluginHandler.getVmConfig();
if (!this.abi.proxyOnVmStart(pluginContext.id(), len(vmConfig))) {
throw new StartException("proxy_on_vm_start failed");
}
byte[] pluginConfig = this.pluginHandler.getPluginConfig();
if (!this.abi.proxyOnConfigure(pluginContext.id(), len(pluginConfig))) {
throw new StartException("proxy_on_configure failed");
}
}
private void registerContext(Context context, int parentContextID) {
contexts.put(context.id(), context);
activeContext = context;
this.abi.proxyOnContextCreate(context.id(), parentContextID);
}
// 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 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 ProxyMap getHttpCallResponseHeaders() {
return httpCallResponseHeaders;
}
@Override
public ProxyMap getHttpCallResponseTrailers() {
return httpCallResponseTrailers;
}
@Override
public byte[] getHttpCallResponseBody() {
return httpCallResponseBody;
}
};
}
HashMap<Integer, Context> contexts() {
return contexts;
}
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;
}
public NetworkContext createNetworkContext(Handler handler) {
NetworkContext context = new NetworkContext(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() {
this.abi.proxyOnTick(pluginContext.id());
}
@Override
public void close() {
if (this.pluginContext == null) {
return;
}
this.pluginContext.close();
if (wasi != null) {
wasi.close();
}
}
public static ProxyWasm.Builder builder() {
return new ProxyWasm.Builder();
}
public void sendHttpCallResponse(
int calloutID, Map<String, String> headers, Map<String, String> trailers, byte[] body) {
this.sendHttpCallResponse(
calloutID, ProxyMap.copyOf(headers), ProxyMap.copyOf(trailers), body);
}
public void sendHttpCallResponse(
int calloutID, ProxyMap headers, ProxyMap trailers, byte[] body) {
this.httpCallResponseHeaders = headers;
this.httpCallResponseTrailers = trailers;
this.httpCallResponseBody = body;
this.abi.proxyOnHttpCallResponse(
pluginContext.id(), calloutID, len(headers), len(body), len(trailers));
this.httpCallResponseHeaders = null;
this.httpCallResponseTrailers = null;
this.httpCallResponseBody = null;
}
public void sendOnQueueReady(int queueId) {
this.abi.proxyOnQueueReady(pluginContext.id(), queueId);
}
public int contextId() {
return pluginContext.id();
}
ABI abi() {
return abi;
}
public static class Builder implements Cloneable {
private final ABI abi = new ABI();
private WasiPreview1 wasi;
private Handler pluginHandler;
private ImportMemory memory;
private WasiOptions wasiOptions;
private boolean start = true;
@Override
@SuppressWarnings("NoClone")
protected Builder clone() {
try {
return (Builder) super.clone();
} catch (CloneNotSupportedException e) {
throw new RuntimeException(e);
}
}
public HostFunction[] toHostFunctions() {
return ABI_ModuleFactory.toHostFunctions(abi);
}
public Builder withStart(boolean start) {
this.start = start;
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 {
abi.setInstance(instance);
return new ProxyWasm(this.clone());
}
public ProxyWasm build(WasmModule module) throws StartException {
return this.build(Instance.builder(module));
}
public ProxyWasm build(Instance.Builder instanceBuilder) 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,
() ->
WasiOptions.builder()
.inheritSystem()
.withArguments(List.of())
.build()))
.build();
imports.addFunction(wasi.toHostFunctions());
imports.addFunction(Helpers.withModuleName(wasi.toHostFunctions(), "wasi_unstable"));
var instance =
instanceBuilder
.withStart(false) // we will start it manually
.withImportValues(imports.build())
.build();
return build(instance);
}
ImportMemory defaultImportMemory() {
return new ImportMemory(
"env",
"memory",
new ByteArrayMemory(new MemoryLimits(2, MemoryLimits.MAX_PAGES)));
}
WasiOptions defaultWasiOptions() {
return WasiOptions.builder().inheritSystem().build();
}
}
}