forked from roastedroot/proxy-wasm-java-host
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathImports.java
More file actions
1005 lines (862 loc) · 34.6 KB
/
Imports.java
File metadata and controls
1005 lines (862 loc) · 34.6 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
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package io.roastedroot.proxywasm.impl;
import static io.roastedroot.proxywasm.v1.Helpers.string;
import com.dylibso.chicory.experimental.hostmodule.annotations.HostModule;
import com.dylibso.chicory.experimental.hostmodule.annotations.WasmExport;
import com.dylibso.chicory.runtime.Instance;
import com.dylibso.chicory.runtime.WasmRuntimeException;
import io.roastedroot.proxywasm.v1.Action;
import io.roastedroot.proxywasm.v1.BufferType;
import io.roastedroot.proxywasm.v1.Handler;
import io.roastedroot.proxywasm.v1.LogLevel;
import io.roastedroot.proxywasm.v1.MapType;
import io.roastedroot.proxywasm.v1.MetricType;
import io.roastedroot.proxywasm.v1.StreamType;
import io.roastedroot.proxywasm.v1.WasmException;
import io.roastedroot.proxywasm.v1.WasmResult;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Map;
@HostModule("env")
public class Imports extends Common {
private Handler handler;
Exports exports;
public Exports getExports() {
return exports;
}
public void setExports(Exports exports) {
this.exports = exports;
}
public Handler getHandler() {
return handler;
}
public void setHandler(Handler handler) {
this.handler = handler;
}
@Override
int malloc(int length) throws WasmException {
return exports.malloc(length);
}
@WasmExport
public int proxyLog(int logLevel, int messageData, int messageSize) {
try {
var msg = instance.memory().readBytes(messageData, messageSize);
handler.log(LogLevel.fromInt(logLevel), new String(msg));
return WasmResult.OK.getValue();
} catch (WasmException e) {
return e.result().getValue();
}
}
/**
* Get a header map based on the map type.
*
* @param instance The WebAssembly instance
* @param mapType The type of map to get
* @return The header map
*/
public Map<String, String> getMap(Instance instance, int mapType) {
var knownType = MapType.fromInt(mapType);
if (knownType == null) {
return handler.getCustomHeaders(mapType);
}
switch (knownType) {
case HTTP_REQUEST_HEADERS:
return handler.getHttpRequestHeaders();
case HTTP_REQUEST_TRAILERS:
return handler.getHttpRequestTrailers();
case HTTP_RESPONSE_HEADERS:
return handler.getHttpResponseHeaders();
case HTTP_RESPONSE_TRAILERS:
return handler.getHttpResponseTrailers();
case HTTP_CALL_RESPONSE_HEADERS:
return handler.getHttpCallResponseHeaders();
case HTTP_CALL_RESPONSE_TRAILERS:
return handler.getHttpCallResponseTrailers();
case GRPC_RECEIVE_INITIAL_METADATA:
return handler.getGrpcReceiveInitialMetaData();
case GRPC_RECEIVE_TRAILING_METADATA:
return handler.getGrpcReceiveTrailerMetaData();
}
return null;
}
/**
* Set a header map based on the map type.
*
* @param instance The WebAssembly instance
* @param mapType The type of map to set
* @param map The header map to set
* @return WasmResult indicating success or failure
*/
private WasmResult setMap(Instance instance, int mapType, Map<String, String> map) {
var knownType = MapType.fromInt(mapType);
if (knownType == null) {
return handler.setCustomHeaders(mapType, map);
}
switch (knownType) {
case HTTP_REQUEST_HEADERS:
return handler.setHttpRequestHeaders(map);
case HTTP_REQUEST_TRAILERS:
return handler.setHttpRequestTrailers(map);
case HTTP_RESPONSE_HEADERS:
return handler.setHttpResponseHeaders(map);
case HTTP_RESPONSE_TRAILERS:
return handler.setHttpResponseTrailers(map);
case HTTP_CALL_RESPONSE_HEADERS:
return handler.setHttpCallResponseHeaders(map);
case HTTP_CALL_RESPONSE_TRAILERS:
return handler.setHttpCallResponseTrailers(map);
case GRPC_RECEIVE_INITIAL_METADATA:
return handler.setGrpcReceiveInitialMetaData(map);
case GRPC_RECEIVE_TRAILING_METADATA:
return handler.setGrpcReceiveTrailerMetaData(map);
}
return WasmResult.NOT_FOUND;
}
/**
* Get a buffer based on the buffer type.
*
* @param instance The WebAssembly instance
* @param bufferType The type of buffer to get
* @return The buffer, or null if not found
*/
private byte[] getBuffer(Instance instance, int bufferType) {
// Return the appropriate buffer based on the buffer type
var knownType = BufferType.fromInt(bufferType);
if (knownType == null) {
return handler.getCustomBuffer(bufferType);
}
switch (knownType) {
case HTTP_REQUEST_BODY:
return handler.getHttpRequestBody();
case HTTP_RESPONSE_BODY:
return handler.getHttpResponseBody();
case DOWNSTREAM_DATA:
return handler.getDownStreamData();
case UPSTREAM_DATA:
return handler.getUpstreamData();
case HTTP_CALL_RESPONSE_BODY:
return handler.getHttpCallResponseBody();
case GRPC_RECEIVE_BUFFER:
return handler.getGrpcReceiveBuffer();
case PLUGIN_CONFIGURATION:
return handler.getPluginConfig();
case VM_CONFIGURATION:
return handler.getVmConfig();
case CALL_DATA:
return handler.getFuncCallData();
}
return null;
}
/**
* Set a buffer based on the buffer type.
*
* @param instance The WebAssembly instance
* @param bufferType The type of buffer to set
* @param buffer The buffer to set
* @return WasmResult indicating success or failure
*/
private WasmResult setBuffer(Instance instance, int bufferType, byte[] buffer) {
// Set the appropriate buffer based on the buffer type
var knownType = BufferType.fromInt(bufferType);
if (knownType == null) {
return handler.setCustomBuffer(bufferType, buffer);
}
// TODO: check if the buffers that can be set may depend on the ABI version.
switch (knownType) {
case HTTP_REQUEST_BODY:
return handler.setHttpRequestBody(buffer);
case HTTP_RESPONSE_BODY:
return handler.setHttpResponseBody(buffer);
case DOWNSTREAM_DATA:
return handler.setDownStreamData(buffer);
case UPSTREAM_DATA:
return handler.setUpstreamData(buffer);
case HTTP_CALL_RESPONSE_BODY:
return handler.setHttpCallResponseBody(buffer);
case GRPC_RECEIVE_BUFFER:
return handler.setGrpcReceiveBuffer(buffer);
case CALL_DATA:
return handler.setFuncCallData(buffer);
}
return WasmResult.NOT_FOUND;
}
/**
* Get header map pairs and format them for WebAssembly memory.
*
* @param mapType The type of map to get
* @param returnDataPtr Pointer to where the data address should be stored
* @param returnDataSize Pointer to where the data size should be stored
* @return WasmResult status code
*/
@WasmExport
public int proxyGetHeaderMapPairs(int mapType, int returnDataPtr, int returnDataSize) {
try {
// Get the header map based on the map type
Map<String, String> header = getMap(instance, mapType);
if (header == null) {
return WasmResult.NOT_FOUND.getValue();
}
// to clone the headers so that they don't change on while we process them in the loop
final Map<String, String> cloneMap = new HashMap<>();
int totalBytesLen = U32_LEN; // Start with space for the count
for (Map.Entry<String, String> entry : header.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
cloneMap.put(key, value);
totalBytesLen += U32_LEN + U32_LEN; // keyLen + valueLen
totalBytesLen += key.length() + 1 + value.length() + 1; // key + \0 + value + \0
}
// Allocate memory in the WebAssembly instance
int addr = malloc(totalBytesLen);
// Write the number of entries to the allocated memory
putUint32(addr, cloneMap.size());
// Calculate pointers for lengths and data
int lenPtr = addr + U32_LEN;
int dataPtr = lenPtr + ((U32_LEN + U32_LEN) * cloneMap.size());
// Write each key-value pair to memory
for (Map.Entry<String, String> entry : cloneMap.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
// Write key length
putUint32(lenPtr, key.length());
lenPtr += U32_LEN;
// Write value length
putUint32(lenPtr, value.length());
lenPtr += U32_LEN;
// Write key bytes
putMemory(dataPtr, key.getBytes());
dataPtr += key.length();
// Write null terminator for key
putByte(dataPtr, (byte) 0);
dataPtr++;
// Write value bytes
putMemory(dataPtr, value.getBytes());
dataPtr += value.length();
// Write null terminator for value
putByte(dataPtr, (byte) 0);
dataPtr++;
}
// Write the address to the return pointer
putUint32(returnDataPtr, addr);
// Write the total size to the return size pointer
putUint32(returnDataSize, totalBytesLen);
return WasmResult.OK.getValue();
} catch (WasmException e) {
return e.result().getValue();
}
}
/**
* Set header map pairs from WebAssembly memory.
*
* @param mapType The type of map to set
* @param ptr Pointer to the map data in WebAssembly memory
* @param size Size of the map data
* @return WasmResult status code
*/
@WasmExport
public int proxySetHeaderMapPairs(int mapType, int ptr, int size) {
try {
// Get the header map based on the map type
Map<String, String> headerMap = getMap(instance, mapType);
if (headerMap == null) {
return WasmResult.BAD_ARGUMENT.getValue();
}
// Decode the map content and set each key-value pair
Map<String, String> newMap = decodeMap(ptr, size);
for (Map.Entry<String, String> entry : newMap.entrySet()) {
headerMap.put(entry.getKey(), entry.getValue());
}
return WasmResult.OK.getValue();
} catch (WasmRuntimeException e) {
return WasmResult.INVALID_MEMORY_ACCESS.getValue();
} catch (WasmException e) {
return e.result().getValue();
}
}
/**
* Retrieves serialized size of all key-value pairs from the map mapType
*
* @param mapType The type of map to set
* @param returnSize Pointer to ruturn the size of the map data
* @return WasmResult status code
*/
@WasmExport
public int proxyGetHeaderMapSize(int mapType, int returnSize) {
try {
// Get the header map based on the map type
Map<String, String> header = getMap(instance, mapType);
if (header == null) {
return WasmResult.BAD_ARGUMENT.getValue();
}
// to clone the headers so that they don't change on while we process them in the loop
final Map<String, String> cloneMap = new HashMap<>();
int totalBytesLen = U32_LEN; // Start with space for the count
for (Map.Entry<String, String> entry : header.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
cloneMap.put(key, value);
totalBytesLen += U32_LEN + U32_LEN; // keyLen + valueLen
totalBytesLen += key.length() + 1 + value.length() + 1; // key + \0 + value + \0
}
// Write the total size to the return size pointer
putUint32(returnSize, totalBytesLen);
return WasmResult.OK.getValue();
} catch (WasmException e) {
return e.result().getValue();
}
}
/**
* Get a value from a header map by key.
*
* @param mapType The type of map to get from
* @param keyDataPtr Pointer to the key data in WebAssembly memory
* @param keySize Size of the key data
* @param valueDataPtr Pointer to where the value data should be stored
* @param valueSize Size of the value data buffer
* @return WasmResult status code
*/
@WasmExport
public int proxyGetHeaderMapValue(
int mapType, int keyDataPtr, int keySize, int valueDataPtr, int valueSize) {
try {
// Get the header map based on the map type
Map<String, String> headerMap = getMap(instance, mapType);
if (headerMap == null) {
return WasmResult.BAD_ARGUMENT.getValue();
}
// Get key from memory
String key = readString(keyDataPtr, keySize);
// Get value from map
String value = headerMap.get(key);
if (value == null) {
return WasmResult.NOT_FOUND.getValue();
}
// Copy value into WebAssembly memory
copyIntoInstance(value, valueDataPtr, valueSize);
return WasmResult.OK.getValue();
} catch (WasmRuntimeException e) {
return WasmResult.INVALID_MEMORY_ACCESS.getValue();
} catch (WasmException e) {
return e.result().getValue();
}
}
/**
* Replace a value in a header map.
*
* @param mapType The type of map to modify
* @param keyDataPtr Pointer to the key data in WebAssembly memory
* @param keySize Size of the key data
* @param valueDataPtr Pointer to the value data in WebAssembly memory
* @param valueSize Size of the value data
* @return WasmResult status code
*/
@WasmExport
public int proxyReplaceHeaderMapValue(
int mapType, int keyDataPtr, int keySize, int valueDataPtr, int valueSize) {
try {
// Get the header map based on the map type
Map<String, String> headerMap = getMap(instance, mapType);
if (headerMap == null) {
return WasmResult.BAD_ARGUMENT.getValue();
}
// Get key from memory
String key = readString(keyDataPtr, keySize);
// Get value from memory
String value = readString(valueDataPtr, valueSize);
// Replace value in map
var copy = new HashMap<>(headerMap);
copy.put(key, value);
setMap(instance, mapType, copy);
return WasmResult.OK.getValue();
} catch (WasmRuntimeException e) {
return WasmResult.INVALID_MEMORY_ACCESS.getValue();
} catch (WasmException e) {
return e.result().getValue();
}
}
/**
* Add a value to a header map.
*
* @param mapType The type of map to modify
* @param keyDataPtr Pointer to the key data in WebAssembly memory
* @param keySize Size of the key data
* @param valueDataPtr Pointer to the value data in WebAssembly memory
* @param valueSize Size of the value data
* @return WasmResult status code
*/
@WasmExport
public int proxyAddHeaderMapValue(
int mapType, int keyDataPtr, int keySize, int valueDataPtr, int valueSize) {
return proxyReplaceHeaderMapValue(mapType, keyDataPtr, keySize, valueDataPtr, valueSize);
}
/**
* Remove a value from a header map.
*
* @param mapType The type of map to modify
* @param keyDataPtr Pointer to the key data in WebAssembly memory
* @param keySize Size of the key data
* @return WasmResult status code
*/
@WasmExport
public int proxyRemoveHeaderMapValue(int mapType, int keyDataPtr, int keySize) {
try {
// Get the header map based on the map type
Map<String, String> headerMap = getMap(instance, mapType);
if (headerMap == null) {
return WasmResult.NOT_FOUND.getValue();
}
// Get key from memory
String key = readString(keyDataPtr, keySize);
if (key.isEmpty()) {
return WasmResult.BAD_ARGUMENT.getValue();
}
// Remove key from map
var copy = new HashMap<>(headerMap);
copy.remove(key);
setMap(instance, mapType, copy);
return WasmResult.OK.getValue();
} catch (WasmRuntimeException e) {
return WasmResult.INVALID_MEMORY_ACCESS.getValue();
} catch (WasmException e) {
return e.result().getValue();
}
}
/**
* Decodes a byte array containing map data into a Map of String key-value pairs.
* <p>
* The format is:
* - First 4 bytes: number of entries (headerSize) in little endian
* - For each entry:
* - 4 bytes: key size in little endian
* - 4 bytes: value size in little endian
* - Then the actual data:
* - key bytes (null terminated)
* - value bytes (null terminated)
*
* @param addr The memory address to read from
* @param mem_size The size of memory to read
* @return The decoded map containing string keys and values
* @throws WasmException if there is an error accessing memory
*/
private HashMap<String, String> decodeMap(int addr, int mem_size) throws WasmException {
if (mem_size < U32_LEN) {
return new HashMap<>();
}
// Read header size (number of entries)
var mapSize = getUint32(addr);
// Calculate start of data section
// mapSize + (key1_size + value1_size) * mapSize
long dataOffset = U32_LEN + (U32_LEN + U32_LEN) * mapSize;
if (dataOffset >= mem_size) {
return new HashMap<>();
}
// Create result map with initial capacity
var result = new HashMap<String, String>((int) mapSize);
// Process each entry
for (int i = 0; i < mapSize; i++) {
// Calculate index for length values
int keySizeOffset = U32_LEN + (U32_LEN + U32_LEN) * i;
int valueSizeOffset = keySizeOffset + U32_LEN;
// Read key and value sizes
long keySize = getUint32(addr + keySizeOffset);
long valueSize = getUint32(addr + valueSizeOffset);
// Check if we have enough data for the key/value
if (dataOffset >= mem_size || dataOffset + keySize + valueSize + 2 > mem_size) {
break;
}
// Extract key
String key = readString((int) (addr + dataOffset), (int) keySize);
dataOffset += keySize + 1; // Skip null terminator
// Extract value
String value = readString((int) (addr + dataOffset), (int) valueSize);
dataOffset += valueSize + 1;
// Add to result map
result.put(key, value);
}
return result;
}
@WasmExport
public int proxyGetProperty(int keyPtr, int keySize, int returnValueData, int returnValueSize) {
try {
// Get key from memory
byte[] keyBytes = readMemory(keyPtr, keySize);
if (keyBytes.length == 0) {
return WasmResult.BAD_ARGUMENT.getValue();
}
String key = new String(keyBytes);
// Get property value using handler
String value = handler.getProperty(key);
if (value == null) {
return WasmResult.NOT_FOUND.getValue();
}
copyIntoInstance(value, returnValueData, returnValueSize);
return WasmResult.OK.getValue();
} catch (WasmException e) {
return e.result().getValue();
}
}
/**
* Get bytes from a buffer and make them available to WebAssembly.
*
* @param bufferType The type of buffer to get
* @param start The start index in the buffer
* @param length The number of bytes to get
* @param returnBufferData Pointer to where the buffer data address should be stored
* @param returnBufferSize Pointer to where the buffer size should be stored
* @return WasmResult status code
*/
@WasmExport
public int proxyGetBufferBytes(
int bufferType, int start, int length, int returnBufferData, int returnBufferSize) {
try {
// Get the buffer based on the buffer type
byte[] b = getBuffer(instance, bufferType);
if (b == null || b.length == 0) {
return WasmResult.NOT_FOUND.getValue();
}
if (start > start + length) {
return WasmResult.BAD_ARGUMENT.getValue();
}
ByteBuffer buffer = ByteBuffer.wrap(b);
if (start + length > buffer.capacity()) {
length = buffer.capacity() - start;
}
try {
buffer.position(start);
buffer.limit(start + length);
} catch (IllegalArgumentException e) {
return WasmResult.BAD_ARGUMENT.getValue();
}
// Allocate memory in the WebAssembly instance
int addr = malloc(length);
putMemory(addr, buffer);
// Write the address to the return pointer
putUint32(returnBufferData, addr);
// Write the length to the return size pointer
putUint32(returnBufferSize, length);
return WasmResult.OK.getValue();
} catch (WasmException e) {
return e.result().getValue();
}
}
/**
* Set bytes in a buffer.
*
* @param bufferType The type of buffer to modify
* @param start The start index in the buffer
* @param length The number of bytes to set
* @param dataPtr Pointer to the data in WebAssembly memory
* @param dataSize Size of the data
* @return WasmResult status code
*/
@WasmExport
public int proxySetBufferBytes(
int bufferType, int start, int length, int dataPtr, int dataSize) {
try {
// Get the buffer based on the buffer type
var buf = getBuffer(instance, bufferType);
if (buf == null) {
return WasmResult.NOT_FOUND.getValue();
}
// Get content from WebAssembly memory
byte[] content = instance.memory().readBytes(dataPtr, dataSize);
content = replaceBytes(buf, content, start, length);
// Set the buffer using the appropriate handler method
WasmResult result = setBuffer(instance, bufferType, content);
return result.getValue();
} catch (WasmRuntimeException e) {
return WasmResult.INVALID_MEMORY_ACCESS.getValue();
}
}
public static byte[] replaceBytes(
byte[] existing, byte[] change, int replaceStart, int replaceLength) {
if (replaceStart > existing.length) {
replaceStart = existing.length;
}
if (replaceLength > existing.length) {
replaceLength = existing.length;
}
// when we are replacing the whole buffer
if (replaceStart == 0 && replaceLength == existing.length) {
return change;
}
int newLength = change.length + (existing.length - replaceLength);
byte[] result = new byte[newLength];
// Copy the unchanged part before the start position
System.arraycopy(existing, 0, result, 0, Math.min(replaceStart, existing.length));
// Copy the new change bytes
System.arraycopy(change, 0, result, replaceStart, change.length);
// Copy the remaining unchanged part after replacement
if (replaceStart + replaceLength < existing.length) {
System.arraycopy(
existing,
replaceStart + replaceLength,
result,
replaceStart + change.length,
existing.length - (replaceStart + replaceLength));
}
return result;
}
/**
* Send an HTTP response.
*
* @param responseCode The HTTP response code
* @param responseCodeDetailsData Pointer to response code details in WebAssembly memory
* @param responseCodeDetailsSize Size of response code details
* @param responseBodyData Pointer to response body in WebAssembly memory
* @param responseBodySize Size of response body
* @param additionalHeadersMapData Pointer to additional headers map in WebAssembly memory
* @param additionalHeadersSize Size of additional headers map
* @param grpcStatus The gRPC status code (-1 for non-gRPC responses)
* @return WasmResult status code
*/
@WasmExport
public int proxySendLocalResponse(
int responseCode,
int responseCodeDetailsData,
int responseCodeDetailsSize,
int responseBodyData,
int responseBodySize,
int additionalHeadersMapData,
int additionalHeadersSize,
int grpcStatus) {
try {
// Get response code details from memory
byte[] responseCodeDetails = null;
if (responseCodeDetailsSize > 0) {
responseCodeDetails =
instance.memory()
.readBytes(responseCodeDetailsData, responseCodeDetailsSize);
}
// Get response body from memory
byte[] responseBody = new byte[0];
if (responseBodySize > 0) {
responseBody = instance.memory().readBytes(responseBodyData, responseBodySize);
}
// Get and decode additional headers from memory
HashMap<String, String> additionalHeaders =
decodeMap(additionalHeadersMapData, additionalHeadersSize);
// Send the response through the handler
WasmResult result =
handler.sendHttpResponse(
responseCode,
responseCodeDetails,
responseBody,
additionalHeaders,
grpcStatus);
return result.getValue();
} catch (WasmRuntimeException e) {
return WasmResult.INVALID_MEMORY_ACCESS.getValue();
} catch (WasmException e) {
return e.result().getValue();
}
}
@WasmExport
int proxySetEffectiveContext(int contextId) {
return handler.setEffectiveContextID(contextId).getValue();
}
@WasmExport
int proxyDone() {
return handler.done().getValue();
}
@WasmExport
int proxySetTickPeriodMilliseconds(int tick_period) {
return handler.setTickPeriodMilliseconds(tick_period).getValue();
}
@WasmExport
int proxyGetCurrentTimeNanoseconds(int returnTime) {
try {
int currentTimeNanoseconds = handler.getCurrentTimeNanoseconds();
putUint32(returnTime, currentTimeNanoseconds);
return WasmResult.OK.getValue();
} catch (WasmException e) {
return e.result().getValue();
}
}
/**
* Resumes processing of paused stream_type.
*
* see: https://github.com/proxy-wasm/spec/tree/main/abi-versions/v0.2.1#proxy_continue_stream
*/
@WasmExport
int proxyContinueStream(int arg) {
var streamType = StreamType.fromInt(arg);
if (streamType == null) {
return WasmResult.BAD_ARGUMENT.getValue();
}
WasmResult result = handler.setAction(streamType, Action.CONTINUE);
return result.getValue();
}
/**
* Resumes processing of paused HTTP request.
*
* see: https://github.com/proxy-wasm/spec/blob/main/abi-versions/v0.1.0/README.md#proxy_continue_request
*/
@WasmExport
void proxyContinueRequest() {
handler.setAction(StreamType.REQUEST, Action.CONTINUE);
}
/**
* Resumes processing of paused HTTP response.
*
* see: https://github.com/proxy-wasm/spec/blob/main/abi-versions/v0.1.0/README.md#proxy_continue_response
*/
@WasmExport
void proxyContinueResponse() {
handler.setAction(StreamType.RESPONSE, Action.CONTINUE);
}
/**
* Clears cached HTTP route.
*
* see: https://github.com/proxy-wasm/spec/blob/main/abi-versions/v0.1.0/README.md#proxy_clear_route_cache
*/
@WasmExport
void proxyClearRouteCache() {
handler.clearRouteCache();
}
@WasmExport
int proxyHttpCall(
int uriData,
int uriSize,
int headersData,
int headersSize,
int bodyData,
int bodySize,
int trailersData,
int trailersSize,
int timeout,
int returnCalloutID) {
try {
var uri = string(readMemory(uriData, uriSize));
var headers = decodeMap(headersData, headersSize);
var body = readMemory(bodyData, bodySize);
var trailers = decodeMap(trailersData, trailersSize);
int calloutId = handler.httpCall(uri, headers, body, trailers, timeout);
putUint32(returnCalloutID, calloutId);
return WasmResult.OK.getValue();
} catch (WasmException e) {
return e.result().getValue();
}
}
@WasmExport
int proxyDispatchHttpCall(
int upstreamNameData,
int upstreamNameSize,
int headersData,
int headersSize,
int bodyData,
int bodySize,
int trailersData,
int trailersSize,
int timeoutMilliseconds,
int returnCalloutID) {
try {
var upstreamName = string(readMemory(upstreamNameData, upstreamNameSize));
var headers = decodeMap(headersData, headersSize);
var body = readMemory(bodyData, bodySize);
var trailers = decodeMap(trailersData, trailersSize);
int calloutId =
handler.dispatchHttpCall(
upstreamName, headers, body, trailers, timeoutMilliseconds);
putUint32(returnCalloutID, calloutId);
return WasmResult.OK.getValue();
} catch (WasmException e) {
return e.result().getValue();
}
}
@WasmExport
int proxyCallForeignFunction(
int nameDataPtr,
int nameSize,
int argumentDataPtr,
int argumentSize,
int returnResultsPtr,
int returnResultsSizePtr) {
try {
var name = string(readMemory(nameDataPtr, nameSize));
var argument = readMemory(argumentDataPtr, argumentSize);
var result = handler.callForeignFunction(name, argument);
// Allocate memory in the WebAssembly instance
int addr = malloc(result.length);
putMemory(addr, result);
// Write the address to the return pointer
putUint32(returnResultsPtr, addr);
// Write the length to the return size pointer
putUint32(returnResultsSizePtr, result.length);
return WasmResult.OK.getValue();
} catch (WasmException e) {
return e.result().getValue();
}
}
@WasmExport
int proxyDefineMetric(int metricType, int nameDataPtr, int nameSize, int returnMetricId) {
try {
MetricType type = MetricType.fromInt(metricType);
if (type == null) {
return WasmResult.BAD_ARGUMENT.getValue();
}
var name = string(readMemory(nameDataPtr, nameSize));
int metricId = handler.defineMetric(type, name);
putUint32(returnMetricId, metricId);
return WasmResult.OK.getValue();
} catch (WasmException e) {
return e.result().getValue();
}
}
@WasmExport
int proxyRecordMetric(int metricId, long value) {
WasmResult result = handler.recordMetric(metricId, value);
return result.getValue();
}
@WasmExport
int proxyRemoveMetric(int metricId) {
WasmResult result = handler.removeMetric(metricId);
return result.getValue();
}
@WasmExport
int proxyIncrementMetric(int metricId, long value) {
WasmResult result = handler.incrementMetric(metricId, value);
return result.getValue();
}
@WasmExport
int proxyGetMetric(int metricId, int returnValuePtr) {
try {
var result = handler.getMetric(metricId);
putUint32(returnValuePtr, (int) result);
return WasmResult.OK.getValue();
} catch (WasmException e) {
return e.result().getValue();
}
}
@WasmExport
int proxyGetSharedData(
int keyDataPtr, int keySize, int returnValueData, int returnValueSize, int returnCas) {
try {
// Get key from memory
String key = string(readMemory(keyDataPtr, keySize));
// Get shared data value using handler
Handler.SharedData value = handler.getSharedData(key);
if (value == null) {
return WasmResult.NOT_FOUND.getValue();
}
copyIntoInstance(value.data, returnValueData, returnValueSize);
putUint32(returnCas, value.cas);
return WasmResult.OK.getValue();
} catch (WasmException e) {
return e.result().getValue();
}
}
@WasmExport
int proxySetSharedData(int keyDataPtr, int keySize, int valueDataPtr, int valueSize, int cas) {
try {
// Get key from memory
String key = string(readMemory(keyDataPtr, keySize));
// Get value from memory
byte[] value = readMemory(valueDataPtr, valueSize);
// Set shared data value using handler
WasmResult result = handler.setSharedData(key, value, cas);
return result.getValue();