forked from proxy-wasm/proxy-wasm-cpp-sdk
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathproxy_wasm_api.h
1621 lines (1411 loc) · 59.2 KB
/
proxy_wasm_api.h
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
/*
* Copyright 2016-2019 Envoy Project Authors
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Intrinsic high-level support functions available to WASM modules.
*/
// NOLINT(namespace-envoy)
#pragma once
#ifdef PROXY_WASM_PROTOBUF
#include "google/protobuf/message_lite.h"
#endif
#include <cstring>
#include <functional>
#include <memory>
#include <string>
#include <tuple>
#include <unordered_map>
#include <utility>
#include <vector>
#define CHECK_RESULT(_c) \
do { \
if ((_c) != WasmResult::Ok) { \
proxy_log(LogLevel::critical, #_c, sizeof(#_c) - 1); \
abort(); \
} \
} while (0)
//
// High Level C++ API.
//
class ContextBase;
class RootContext;
class Context;
// Note: exceptions are currently not supported.
#define WASM_EXCEPTIONS 0
#if WASM_EXCEPTIONS
class ProxyException : std::runtime_error {
public:
ProxyException(const std::string &message) : std::runtime_error(message) {}
};
#endif
inline WasmResult logTrace(std::string_view logMessage) {
return proxy_log(LogLevel::trace, logMessage.data(), logMessage.size());
}
inline WasmResult logDebug(std::string_view logMessage) {
return proxy_log(LogLevel::debug, logMessage.data(), logMessage.size());
}
inline WasmResult logInfo(std::string_view logMessage) {
return proxy_log(LogLevel::info, logMessage.data(), logMessage.size());
}
inline WasmResult logWarn(std::string_view logMessage) {
return proxy_log(LogLevel::warn, logMessage.data(), logMessage.size());
}
inline WasmResult logError(std::string_view logMessage) {
return proxy_log(LogLevel::error, logMessage.data(), logMessage.size());
}
inline WasmResult logCritical(std::string_view logMessage) {
return proxy_log(LogLevel::critical, logMessage.data(), logMessage.size());
}
inline void logAbort(std::string_view logMessag) {
logCritical(logMessag);
abort();
}
#define LOG(_level, ...) \
log##_level(std::string("[") + __FILE__ + ":" + std::to_string(__LINE__) + \
"]::" + __FUNCTION__ + "() " + __VA_ARGS__)
#define LOG_TRACE(...) LOG(Trace, __VA_ARGS__)
#define LOG_DEBUG(...) LOG(Debug, __VA_ARGS__)
#define LOG_INFO(...) LOG(Info, __VA_ARGS__)
#define LOG_WARN(...) LOG(Warn, __VA_ARGS__)
#define LOG_ERROR(...) LOG(Error, __VA_ARGS__)
#define LOG_CRITICAL(...) LOG(Critical, __VA_ARGS__)
// Buffers coming into the WASM filter.
class WasmData {
public:
WasmData(const char *data, size_t size) : data_(data), size_(size) {}
~WasmData() { ::free(const_cast<char *>(data_)); }
const char *data() { return data_; }
size_t size() { return size_; }
std::string_view view() { return {data_, size_}; }
std::string toString() { return std::string(view()); }
std::vector<std::pair<std::string_view, std::string_view>> pairs();
template <typename T> T proto() {
T p;
p.ParseFromArray(data_, size_);
return p;
}
WasmData &operator=(const WasmData &) = delete;
WasmData(const WasmData &) = delete;
private:
const char *data_;
size_t size_;
};
typedef std::unique_ptr<WasmData> WasmDataPtr;
inline std::vector<std::pair<std::string_view, std::string_view>> WasmData::pairs() {
std::vector<std::pair<std::string_view, std::string_view>> result;
if (!data())
return result;
auto p = data();
int n = *reinterpret_cast<const int *>(p);
p += sizeof(int);
result.resize(n);
auto s = p + n * 8;
for (int i = 0; i < n; i++) {
int size = *reinterpret_cast<const int *>(p);
p += sizeof(int);
result[i].first = std::string_view(s, size);
s += size + 1;
size = *reinterpret_cast<const int *>(p);
p += sizeof(int);
result[i].second = std::string_view(s, size);
s += size + 1;
}
return result;
}
template <typename Pairs> size_t pairsSize(const Pairs &result) {
size_t size = 4; // number of headers
for (auto &p : result) {
size += 8; // size of key, size of value
size += p.first.size() + 1; // null terminated key
size += p.second.size() + 1; // null terminated value
}
return size;
}
template <typename Pairs> void marshalPairs(const Pairs &result, char *buffer) {
char *b = buffer;
*reinterpret_cast<uint32_t *>(b) = result.size();
b += sizeof(uint32_t);
for (auto &p : result) {
*reinterpret_cast<uint32_t *>(b) = p.first.size();
b += sizeof(uint32_t);
*reinterpret_cast<uint32_t *>(b) = p.second.size();
b += sizeof(uint32_t);
}
for (auto &p : result) {
memcpy(b, p.first.data(), p.first.size());
b += p.first.size();
*b++ = 0;
memcpy(b, p.second.data(), p.second.size());
b += p.second.size();
*b++ = 0;
}
}
template <typename Pairs> void exportPairs(const Pairs &pairs, const char **ptr, size_t *size_ptr) {
if (pairs.empty()) {
*ptr = nullptr;
*size_ptr = 0;
return;
}
size_t size = pairsSize(pairs);
char *buffer = static_cast<char *>(::malloc(size));
marshalPairs(pairs, buffer);
*size_ptr = size;
*ptr = buffer;
}
struct PairHash {
template <typename T, typename U> std::size_t operator()(const std::pair<T, U> &x) const {
return std::hash<T>()(x.first) + std::hash<U>()(x.second);
}
};
struct Tuple3Hash {
template <typename T, typename U, typename V>
std::size_t operator()(const std::tuple<T, U, V> &x) const {
return std::hash<T>()(std::get<0>(x)) + std::hash<U>()(std::get<1>(x)) +
std::hash<V>()(std::get<2>(x));
}
};
using HeaderStringPairs = std::vector<std::pair<std::string, std::string>>;
class GrpcCallHandlerBase {
public:
GrpcCallHandlerBase() {}
virtual ~GrpcCallHandlerBase() {}
RootContext *context() { return context_; }
void cancel();
uint32_t token() { return token_; }
virtual void onSuccess(size_t body_size) = 0;
virtual void onFailure(GrpcStatus status) = 0;
private:
friend class RootContext;
RootContext *context_{nullptr};
uint32_t token_;
};
template <typename Message> class GrpcCallHandler : public GrpcCallHandlerBase {
public:
GrpcCallHandler() : GrpcCallHandlerBase() {}
virtual ~GrpcCallHandler() {}
virtual void onSuccess(size_t body_size) = 0;
};
class GrpcStreamHandlerBase {
public:
GrpcStreamHandlerBase() {}
virtual ~GrpcStreamHandlerBase() {}
RootContext *context() { return context_; }
// NB: with end_of_stream == true, callbacks can still occur: reset() to
// prevent further callbacks.
WasmResult send(std::string_view message, bool end_of_stream);
void close(); // NB: callbacks can still occur: reset() to prevent further
// callbacks.
void reset();
uint32_t token() { return token_; }
virtual void onReceiveInitialMetadata(uint32_t /* headers */) {}
virtual void onReceiveTrailingMetadata(uint32_t /* trailers */) {}
virtual void onReceive(size_t body_size) = 0;
virtual void onRemoteClose(GrpcStatus status) = 0;
protected:
friend class RootContext;
void doRemoteClose(GrpcStatus status);
bool local_close_{false};
bool remote_close_{false};
RootContext *context_{nullptr};
uint32_t token_;
};
template <typename Request, typename Response>
class GrpcStreamHandler : public GrpcStreamHandlerBase {
public:
GrpcStreamHandler() : GrpcStreamHandlerBase() {}
virtual ~GrpcStreamHandler() {}
WasmResult send(const Request &message, bool end_of_stream) {
std::string output;
if (!message.SerializeToString(&output)) {
return WasmResult::SerializationFailure;
}
GrpcStreamHandlerBase::send(output, end_of_stream);
local_close_ = local_close_ || end_of_stream;
return WasmResult::Ok;
}
virtual void onReceive(size_t body_size) = 0;
};
// Behavior supported by all contexts.
class ContextBase {
public:
explicit ContextBase(uint32_t id) : id_(id) {}
virtual ~ContextBase() {}
uint32_t id() { return id_; }
// Make this context the effective context for calls out of the VM.
WasmResult setEffectiveContext();
virtual RootContext *asRoot() { return nullptr; }
virtual Context *asContext() { return nullptr; }
virtual void onCreate() {}
virtual bool onDoneBase() = 0;
// Called on Stream Context after onDone when logging is requested or called on Root Context
// if so requested.
virtual void onLog() {}
// Called to indicate that no more calls will come and this context is being
// deleted.
virtual void onDelete() {} // Called when the stream or VM is being deleted.
// Called when a foreign function event arrives.
virtual void onForeignFunction(uint32_t /* foreign_function_id */, uint32_t /* data_size */) {}
// Return the log level configured for the "wasm" logger in the host
WasmResult getLogLevel(LogLevel *level) { return proxy_get_log_level(level); }
using HttpCallCallback =
std::function<void(uint32_t, size_t, uint32_t)>; // headers, body_size, trailers
using GrpcSimpleCallCallback = std::function<void(GrpcStatus status, size_t body_size)>;
using RedisCallCallback = std::function<void(RedisStatus status, size_t result_size)>;
private:
uint32_t id_;
};
// A context unique for each root_id for a use-case (e.g. filter) compiled into
// module.
class RootContext : public ContextBase {
public:
RootContext(uint32_t id, std::string_view root_id) : ContextBase(id), root_id_(root_id) {}
~RootContext() {}
std::string_view root_id() { return root_id_; }
RootContext *asRoot() override { return this; }
Context *asContext() override { return nullptr; }
// Can be used to validate the configuration (e.g. in the control plane).
// Returns false if the configuration is invalid.
virtual bool validateConfiguration(size_t /* configuration_size */) { return true; }
// Called once when the VM loads and once when each hook loads and whenever
// configuration changes. Returns false if the configuration is invalid.
virtual bool onConfigure(size_t /* configuration_size */) { return true; }
// Called when each hook loads. Returns false if the configuration is
// invalid.
virtual bool onStart(size_t /* vm_configuration_size */) { return true; }
// Called when the timer goes off.
virtual void onTick() {}
// Called when data arrives on a SharedQueue.
virtual void onQueueReady(uint32_t /* token */) {}
virtual bool onDone() { return true; } // Called when the VM is being torn down.
void done(); // Report that we are now done following returning false from onDone.
// Low level HTTP/gRPC interface.
virtual void onHttpCallResponse(uint32_t token, uint32_t headers, size_t body_size,
uint32_t trailers);
virtual void onGrpcReceiveInitialMetadata(uint32_t token, uint32_t headers);
virtual void onGrpcReceiveTrailingMetadata(uint32_t token, uint32_t trailers);
virtual void onGrpcReceive(uint32_t token, size_t body_size);
virtual void onGrpcClose(uint32_t token, GrpcStatus status);
virtual void onRedisCallResponse(uint32_t token, RedisStatus status, size_t response_size);
WasmResult redisInit(std::string_view service, std::string_view username,
std::string_view password, uint32_t timeout_milliseconds);
WasmResult redisCall(std::string_view service, std::string_view query,
RedisCallCallback callback);
// Default high level HTTP/gRPC interface. NB: overriding the low level
// interface will disable this interface. Returns false on setup error.
WasmResult httpCall(std::string_view uri, const HeaderStringPairs &request_headers,
std::string_view request_body, const HeaderStringPairs &request_trailers,
uint32_t timeout_milliseconds, HttpCallCallback callback);
// NB: the message is the response if status == OK and an error message
// otherwise. Returns false on setup error.
WasmResult grpcSimpleCall(std::string_view service, std::string_view service_name,
std::string_view method_name, const HeaderStringPairs &initial_metadata,
std::string_view request, uint32_t timeout_milliseconds,
GrpcSimpleCallCallback callback);
WasmResult grpcSimpleCall(std::string_view service, std::string_view service_name,
std::string_view method_name, const HeaderStringPairs &initial_metadata,
std::string_view request, uint32_t timeout_milliseconds,
std::function<void(size_t body_size)> success_callback,
std::function<void(GrpcStatus status)> failure_callback) {
auto callback = [success_callback, failure_callback](GrpcStatus status, size_t body_size) {
if (status == GrpcStatus::Ok) {
success_callback(body_size);
} else {
failure_callback(status);
}
};
return grpcSimpleCall(service, service_name, method_name, initial_metadata, request,
timeout_milliseconds, callback);
}
WasmResult grpcCallHandler(std::string_view service, std::string_view service_name,
std::string_view method_name,
const HeaderStringPairs &initial_metadata, std::string_view request,
uint32_t timeout_milliseconds,
std::unique_ptr<GrpcCallHandlerBase> handler);
#ifdef PROXY_WASM_PROTOBUF
WasmResult grpcSimpleCall(std::string_view service, std::string_view service_name,
std::string_view method_name, const HeaderStringPairs &initial_metadata,
const google::protobuf::MessageLite &request,
uint32_t timeout_milliseconds, GrpcSimpleCallCallback callback) {
std::string serialized_request;
if (!request.SerializeToString(&serialized_request)) {
return WasmResult::SerializationFailure;
}
return grpcSimpleCall(service, service_name, method_name, initial_metadata, serialized_request,
timeout_milliseconds, callback);
}
WasmResult grpcSimpleCall(std::string_view service, std::string_view service_name,
std::string_view method_name, const HeaderStringPairs &initial_metadata,
const google::protobuf::MessageLite &request,
uint32_t timeout_milliseconds,
std::function<void(size_t body_size)> success_callback,
std::function<void(GrpcStatus status)> failure_callback) {
std::string serialized_request;
if (!request.SerializeToString(&serialized_request)) {
return WasmResult::SerializationFailure;
}
return grpcSimpleCall(service, service_name, method_name, initial_metadata, serialized_request,
timeout_milliseconds, success_callback, failure_callback);
}
// Returns false on setup error.
WasmResult grpcCallHandler(std::string_view service, std::string_view service_name,
std::string_view method_name,
const HeaderStringPairs &initial_metadata,
const google::protobuf::MessageLite &request,
uint32_t timeout_milliseconds,
std::unique_ptr<GrpcCallHandlerBase> handler) {
std::string serialized_request;
if (!request.SerializeToString(&serialized_request)) {
return WasmResult::SerializationFailure;
}
return grpcCallHandler(service, service_name, method_name, initial_metadata, serialized_request,
timeout_milliseconds, std::move(handler));
}
#endif
// Returns false on setup error.
WasmResult grpcStreamHandler(std::string_view service, std::string_view service_name,
std::string_view method_name,
const HeaderStringPairs &initial_metadata,
std::unique_ptr<GrpcStreamHandlerBase> handler);
private:
friend class GrpcCallHandlerBase;
friend class GrpcStreamHandlerBase;
bool onDoneBase() override { return onDone(); }
const std::string root_id_;
std::unordered_map<uint32_t, HttpCallCallback> http_calls_;
std::unordered_map<uint32_t, GrpcSimpleCallCallback> simple_grpc_calls_;
std::unordered_map<uint32_t, std::unique_ptr<GrpcCallHandlerBase>> grpc_calls_;
std::unordered_map<uint32_t, std::unique_ptr<GrpcStreamHandlerBase>> grpc_streams_;
std::unordered_map<uint32_t, RedisCallCallback> redis_calls_;
};
RootContext *getRoot(std::string_view root_id);
// Context for a stream. The distinguished context id == 0 is used for
// non-stream calls.
class Context : public ContextBase {
public:
Context(uint32_t id, RootContext *root) : ContextBase(id), root_(root) {}
virtual ~Context() {}
RootContext *root() { return root_; }
RootContext *asRoot() override { return nullptr; }
Context *asContext() override { return this; }
virtual FilterStatus onNewConnection() { return FilterStatus::Continue; }
virtual FilterStatus onDownstreamData(size_t, bool) { return FilterStatus::Continue; }
virtual FilterStatus onUpstreamData(size_t, bool) { return FilterStatus::Continue; }
virtual void onDownstreamConnectionClose(CloseType) {}
virtual void onUpstreamConnectionClose(CloseType) {}
virtual FilterHeadersStatus onRequestHeaders(uint32_t, bool) {
return FilterHeadersStatus::Continue;
}
virtual FilterMetadataStatus onRequestMetadata(uint32_t) {
return FilterMetadataStatus::Continue;
}
virtual FilterDataStatus onRequestBody(size_t /* body_buffer_length */,
bool /* end_of_stream */) {
return FilterDataStatus::Continue;
}
virtual FilterTrailersStatus onRequestTrailers(uint32_t) {
return FilterTrailersStatus::Continue;
}
virtual FilterHeadersStatus onResponseHeaders(uint32_t, bool) {
return FilterHeadersStatus::Continue;
}
virtual FilterMetadataStatus onResponseMetadata(uint32_t) {
return FilterMetadataStatus::Continue;
}
virtual FilterDataStatus onResponseBody(size_t /* body_buffer_length */,
bool /* end_of_stream */) {
return FilterDataStatus::Continue;
}
virtual FilterTrailersStatus onResponseTrailers(uint32_t) {
return FilterTrailersStatus::Continue;
}
virtual void onDone() {} // Called when the stream has completed.
private:
// For stream Contexts, onDone always returns true.
bool onDoneBase() override {
onDone();
return true;
}
RootContext *root_{};
};
// Returns nullptr if the Context no longer exists (i.e. the stream has been
// destroyed).
Context *getContext(uint32_t context_id);
RootContext *getRootContext(uint32_t context_id);
ContextBase *getContextBase(uint32_t context_id);
using RootFactory =
std::function<std::unique_ptr<RootContext>(uint32_t id, std::string_view root_id)>;
using ContextFactory = std::function<std::unique_ptr<Context>(uint32_t id, RootContext *root)>;
// Create a factory from a class name.
#define ROOT_FACTORY(_c) \
[](uint32_t id, std::string_view root_id) -> std::unique_ptr<RootContext> { \
return std::make_unique<_c>(id, root_id); \
}
#define CONTEXT_FACTORY(_c) \
[](uint32_t id, RootContext *root) -> std::unique_ptr<Context> { \
return std::make_unique<_c>(id, root); \
}
// Register Context factory.
// e.g. static RegisterContextFactory
// register_MyContext(CONTEXT_FACTORY(MyContext));
struct RegisterContextFactory {
RegisterContextFactory(ContextFactory context_factory, RootFactory root_factory,
std::string_view root_id = "");
explicit RegisterContextFactory(RootFactory root_factory, std::string_view root_id = "")
: RegisterContextFactory(nullptr, root_factory, root_id) {}
explicit RegisterContextFactory(ContextFactory context_factory, std::string_view root_id = "")
: RegisterContextFactory(context_factory, nullptr, root_id) {}
};
inline std::pair<uint32_t, WasmDataPtr> getStatus() {
uint32_t code = 0;
const char *value_ptr = nullptr;
size_t value_size = 0;
CHECK_RESULT(proxy_get_status(&code, &value_ptr, &value_size));
return std::make_pair(code, std::make_unique<WasmData>(value_ptr, value_size));
}
// Generic selector
inline std::optional<WasmDataPtr>
getProperty(const std::initializer_list<std::string_view> &parts) {
size_t size = 0;
for (auto part : parts) {
size += part.size() + 1; // null terminated string value
}
char *buffer = static_cast<char *>(::malloc(size));
char *b = buffer;
for (auto part : parts) {
memcpy(b, part.data(), part.size());
b += part.size();
*b++ = 0;
}
const char *value_ptr = nullptr;
size_t value_size = 0;
auto result = proxy_get_property(buffer, size, &value_ptr, &value_size);
::free(buffer);
if (result != WasmResult::Ok) {
return {};
}
return std::make_unique<WasmData>(value_ptr, value_size);
}
template <typename S> inline std::optional<WasmDataPtr> getProperty(const std::vector<S> &parts) {
size_t size = 0;
for (auto part : parts) {
size += part.size() + 1; // null terminated string value
}
char *buffer = static_cast<char *>(::malloc(size));
char *b = buffer;
for (auto part : parts) {
memcpy(b, part.data(), part.size());
b += part.size();
*b++ = 0;
}
const char *value_ptr = nullptr;
size_t value_size = 0;
auto result = proxy_get_property(buffer, size, &value_ptr, &value_size);
::free(buffer);
if (result != WasmResult::Ok) {
return {};
}
return std::make_unique<WasmData>(value_ptr, value_size);
}
// Generic property reader for basic types: int64, uint64, double, bool
// Durations are represented as int64 nanoseconds.
// Timestamps are represented as int64 Unix nanoseconds.
// Strings and bytes are represented as std::string.
template <typename T>
inline bool getValue(const std::initializer_list<std::string_view> &parts, T *out) {
auto buf = getProperty(parts);
if (!buf.has_value() || buf.value()->size() != sizeof(T)) {
return false;
}
*out = *reinterpret_cast<const T *>(buf.value()->data());
return true;
}
// Specialization for bytes and string values
template <>
inline bool getValue<std::string>(const std::initializer_list<std::string_view> &parts,
std::string *out) {
auto buf = getProperty(parts);
if (!buf.has_value()) {
return false;
}
out->assign(buf.value()->data(), buf.value()->size());
return true;
}
template <typename S, typename T> inline bool getValue(const std::vector<S> &parts, T *out) {
auto buf = getProperty(parts);
if (!buf.has_value() || buf.value()->size() != sizeof(T)) {
return false;
}
*out = *reinterpret_cast<const T *>(buf.value()->data());
return true;
}
template <>
inline bool getValue<std::string, std::string>(const std::vector<std::string> &parts,
std::string *out) {
auto buf = getProperty(parts);
if (!buf.has_value()) {
return false;
}
out->assign(buf.value()->data(), buf.value()->size());
return true;
}
template <>
inline bool getValue<std::string_view, std::string>(const std::vector<std::string_view> &parts,
std::string *out) {
auto buf = getProperty(parts);
if (!buf.has_value()) {
return false;
}
out->assign(buf.value()->data(), buf.value()->size());
return true;
}
// Specialization for message types (including struct value for lists and maps)
template <typename T>
inline bool getMessageValue(const std::initializer_list<std::string_view> &parts, T *value_ptr) {
auto buf = getProperty(parts);
if (!buf.has_value()) {
return false;
}
if (buf.value()->size() == 0) {
value_ptr = nullptr;
return true;
}
return value_ptr->ParseFromArray(buf.value()->data(), buf.value()->size());
}
template <typename S, typename T>
inline bool getMessageValue(const std::vector<S> &parts, T *value_ptr) {
auto buf = getProperty(parts);
if (!buf.has_value()) {
return false;
}
if (buf.value()->size() == 0) {
value_ptr = nullptr;
return true;
}
return value_ptr->ParseFromArray(buf.value()->data(), buf.value()->size());
}
inline WasmResult setFilterState(std::string_view key, std::string_view value) {
return static_cast<WasmResult>(
proxy_set_property(key.data(), key.size(), value.data(), value.size()));
}
inline WasmResult setFilterStateStringValue(std::string_view key, std::string_view s) {
return setFilterState(key, s);
}
// Continue/Respond/Route
inline WasmResult continueDownstream() { return proxy_continue_stream(WasmStreamType::Downstream); }
inline WasmResult continueUpstream() { return proxy_continue_stream(WasmStreamType::Upstream); }
inline WasmResult closeDownstream() { return proxy_close_stream(WasmStreamType::Downstream); }
inline WasmResult closeUpstream() { return proxy_close_stream(WasmStreamType::Upstream); }
inline WasmResult continueRequest() { return proxy_continue_stream(WasmStreamType::Request); }
inline WasmResult continueResponse() { return proxy_continue_stream(WasmStreamType::Response); }
inline WasmResult closeRequest() { return proxy_close_stream(WasmStreamType::Request); }
inline WasmResult closeResponse() { return proxy_close_stream(WasmStreamType::Response); }
inline WasmResult sendLocalResponse(uint32_t response_code, std::string_view response_code_details,
std::string_view body,
const HeaderStringPairs &additional_response_headers,
GrpcStatus grpc_status = GrpcStatus::InvalidCode) {
const char *ptr = nullptr;
size_t size = 0;
exportPairs(additional_response_headers, &ptr, &size);
WasmResult result = proxy_send_local_response(
response_code, response_code_details.data(), response_code_details.size(), body.data(),
body.size(), ptr, size, static_cast<uint32_t>(grpc_status));
::free(const_cast<char *>(ptr));
return result;
}
// SharedData
inline WasmResult getSharedData(std::string_view key, WasmDataPtr *value, uint32_t *cas = nullptr) {
uint32_t dummy_cas;
const char *value_ptr = nullptr;
size_t value_size = 0;
if (!cas)
cas = &dummy_cas;
auto result = proxy_get_shared_data(key.data(), key.size(), &value_ptr, &value_size, cas);
if (result != WasmResult::Ok) {
return result;
}
*value = std::make_unique<WasmData>(value_ptr, value_size);
return WasmResult::Ok;
}
inline WasmResult setSharedData(std::string_view key, std::string_view value, uint32_t cas = 0) {
return proxy_set_shared_data(key.data(), key.size(), value.data(), value.size(), cas);
}
inline WasmDataPtr getSharedDataValue(std::string_view key, uint32_t *cas = nullptr) {
WasmDataPtr data;
auto result = getSharedData(key, &data, cas);
if (result != WasmResult::Ok) {
logAbort("getSharedData returned WasmError: " + toString(result));
}
return data;
}
// SharedQueue
inline WasmResult registerSharedQueue(std::string_view queue_name, uint32_t *token) {
return proxy_register_shared_queue(queue_name.data(), queue_name.size(), token);
}
inline WasmResult resolveSharedQueue(std::string_view vm_id, std::string_view queue_name,
uint32_t *token) {
return proxy_resolve_shared_queue(vm_id.data(), vm_id.size(), queue_name.data(),
queue_name.size(), token);
}
inline WasmResult enqueueSharedQueue(uint32_t token, std::string_view data) {
return proxy_enqueue_shared_queue(token, data.data(), data.size());
}
inline WasmResult dequeueSharedQueue(uint32_t token, WasmDataPtr *data) {
const char *data_ptr = nullptr;
size_t data_size = 0;
auto result = proxy_dequeue_shared_queue(token, &data_ptr, &data_size);
*data = std::make_unique<WasmData>(data_ptr, data_size);
return result;
}
// Headers/Trailers
inline WasmResult addHeaderMapValue(WasmHeaderMapType type, std::string_view key,
std::string_view value) {
return proxy_add_header_map_value(type, key.data(), key.size(), value.data(), value.size());
}
inline WasmDataPtr getHeaderMapValue(WasmHeaderMapType type, std::string_view key) {
const char *value_ptr = nullptr;
size_t value_size = 0;
proxy_get_header_map_value(type, key.data(), key.size(), &value_ptr, &value_size);
return std::make_unique<WasmData>(value_ptr, value_size);
}
inline WasmResult replaceHeaderMapValue(WasmHeaderMapType type, std::string_view key,
std::string_view value) {
return proxy_replace_header_map_value(type, key.data(), key.size(), value.data(), value.size());
}
inline WasmResult removeHeaderMapValue(WasmHeaderMapType type, std::string_view key) {
return proxy_remove_header_map_value(type, key.data(), key.size());
}
inline WasmDataPtr getHeaderMapPairs(WasmHeaderMapType type) {
const char *ptr = nullptr;
size_t size = 0;
proxy_get_header_map_pairs(type, &ptr, &size);
return std::make_unique<WasmData>(ptr, size);
}
inline WasmResult setHeaderMapPairs(WasmHeaderMapType type, const HeaderStringPairs &pairs) {
const char *ptr = nullptr;
size_t size = 0;
exportPairs(pairs, &ptr, &size);
auto result = proxy_set_header_map_pairs(type, ptr, size);
::free(const_cast<char *>(ptr));
return result;
}
inline WasmResult getHeaderMapSize(WasmHeaderMapType type, size_t *size) {
return proxy_get_header_map_size(type, size);
}
inline WasmResult addRequestHeader(std::string_view key, std::string_view value) {
return addHeaderMapValue(WasmHeaderMapType::RequestHeaders, key, value);
}
inline WasmDataPtr getRequestHeader(std::string_view key) {
return getHeaderMapValue(WasmHeaderMapType::RequestHeaders, key);
}
inline WasmResult replaceRequestHeader(std::string_view key, std::string_view value) {
return replaceHeaderMapValue(WasmHeaderMapType::RequestHeaders, key, value);
}
inline WasmResult removeRequestHeader(std::string_view key) {
return removeHeaderMapValue(WasmHeaderMapType::RequestHeaders, key);
}
inline WasmDataPtr getRequestHeaderPairs() {
return getHeaderMapPairs(WasmHeaderMapType::RequestHeaders);
}
inline WasmResult setRequestHeaderPairs(const HeaderStringPairs &pairs) {
return setHeaderMapPairs(WasmHeaderMapType::RequestHeaders, pairs);
}
inline WasmResult getRequestHeaderSize(size_t *size) {
return getHeaderMapSize(WasmHeaderMapType::RequestHeaders, size);
}
inline WasmResult addRequestTrailer(std::string_view key, std::string_view value) {
return addHeaderMapValue(WasmHeaderMapType::RequestTrailers, key, value);
}
inline WasmDataPtr getRequestTrailer(std::string_view key) {
return getHeaderMapValue(WasmHeaderMapType::RequestTrailers, key);
}
inline WasmResult replaceRequestTrailer(std::string_view key, std::string_view value) {
return replaceHeaderMapValue(WasmHeaderMapType::RequestTrailers, key, value);
}
inline WasmResult removeRequestTrailer(std::string_view key) {
return removeHeaderMapValue(WasmHeaderMapType::RequestTrailers, key);
}
inline WasmDataPtr getRequestTrailerPairs() {
return getHeaderMapPairs(WasmHeaderMapType::RequestTrailers);
}
inline WasmResult setRequestTrailerPairs(const HeaderStringPairs &pairs) {
return setHeaderMapPairs(WasmHeaderMapType::RequestTrailers, pairs);
}
inline WasmResult getRequestTrailerSize(size_t *size) {
return getHeaderMapSize(WasmHeaderMapType::RequestTrailers, size);
}
inline WasmResult addResponseHeader(std::string_view key, std::string_view value) {
return addHeaderMapValue(WasmHeaderMapType::ResponseHeaders, key, value);
}
inline WasmDataPtr getResponseHeader(std::string_view key) {
return getHeaderMapValue(WasmHeaderMapType::ResponseHeaders, key);
}
inline WasmResult replaceResponseHeader(std::string_view key, std::string_view value) {
return replaceHeaderMapValue(WasmHeaderMapType::ResponseHeaders, key, value);
}
inline WasmResult removeResponseHeader(std::string_view key) {
return removeHeaderMapValue(WasmHeaderMapType::ResponseHeaders, key);
}
inline WasmDataPtr getResponseHeaderPairs() {
return getHeaderMapPairs(WasmHeaderMapType::ResponseHeaders);
}
inline WasmResult setResponseHeaderPairs(const HeaderStringPairs &pairs) {
return setHeaderMapPairs(WasmHeaderMapType::ResponseHeaders, pairs);
}
inline WasmResult getResponseHeaderSize(size_t *size) {
return getHeaderMapSize(WasmHeaderMapType::ResponseHeaders, size);
}
inline WasmResult addResponseTrailer(std::string_view key, std::string_view value) {
return addHeaderMapValue(WasmHeaderMapType::ResponseTrailers, key, value);
}
inline WasmDataPtr getResponseTrailer(std::string_view key) {
return getHeaderMapValue(WasmHeaderMapType::ResponseTrailers, key);
}
inline WasmResult replaceResponseTrailer(std::string_view key, std::string_view value) {
return replaceHeaderMapValue(WasmHeaderMapType::ResponseTrailers, key, value);
}
inline WasmResult removeResponseTrailer(std::string_view key) {
return removeHeaderMapValue(WasmHeaderMapType::ResponseTrailers, key);
}
inline WasmDataPtr getResponseTrailerPairs() {
return getHeaderMapPairs(WasmHeaderMapType::ResponseTrailers);
}
inline WasmResult setResponseTrailerPairs(const HeaderStringPairs &pairs) {
return setHeaderMapPairs(WasmHeaderMapType::ResponseTrailers, pairs);
}
inline WasmResult getResponseTrailerSize(size_t *size) {
return getHeaderMapSize(WasmHeaderMapType::ResponseTrailers, size);
}
// Buffer
inline WasmDataPtr getBufferBytes(WasmBufferType type, size_t start, size_t length) {
const char *ptr = nullptr;
size_t size = 0;
proxy_get_buffer_bytes(type, start, length, &ptr, &size);
return std::make_unique<WasmData>(ptr, size);
}
inline WasmResult getBufferStatus(WasmBufferType type, size_t *size, uint32_t *flags) {
return proxy_get_buffer_status(type, size, flags);
}
inline WasmResult setBuffer(WasmBufferType type, size_t start, size_t length, std::string_view data,
size_t *new_size = nullptr) {
auto result = proxy_set_buffer_bytes(type, start, length, data.data(), data.size());
if (result == WasmResult::Ok && new_size)
*new_size = *new_size - length + data.size();
return result;
}
// HTTP
inline void MakeHeaderStringPairsBuffer(const HeaderStringPairs &headers, void **buffer_ptr,
size_t *size_ptr) {
if (headers.empty()) {
*buffer_ptr = nullptr;
*size_ptr = 0;
return;
}
int size = 4; // number of headers
for (auto &p : headers) {
size += 8; // size of key, size of value
size += p.first.size() + 1; // null terminated key
size += p.second.size() + 1; // null terminated value
}
char *buffer = static_cast<char *>(::malloc(size));
char *b = buffer;
*reinterpret_cast<int32_t *>(b) = headers.size();
b += sizeof(int32_t);
for (auto &p : headers) {
*reinterpret_cast<int32_t *>(b) = p.first.size();
b += sizeof(int32_t);
*reinterpret_cast<int32_t *>(b) = p.second.size();
b += sizeof(int32_t);
}
for (auto &p : headers) {
memcpy(b, p.first.data(), p.first.size());
b += p.first.size();
*b++ = 0;
memcpy(b, p.second.data(), p.second.size());
b += p.second.size();
*b++ = 0;
}
*buffer_ptr = buffer;
*size_ptr = size;
}
inline WasmResult makeHttpCall(std::string_view uri, const HeaderStringPairs &request_headers,
std::string_view request_body,
const HeaderStringPairs &request_trailers,
uint32_t timeout_milliseconds, uint32_t *token_ptr) {
void *headers_ptr = nullptr, *trailers_ptr = nullptr;
size_t headers_size = 0, trailers_size = 0;
MakeHeaderStringPairsBuffer(request_headers, &headers_ptr, &headers_size);
MakeHeaderStringPairsBuffer(request_trailers, &trailers_ptr, &trailers_size);
WasmResult result = proxy_http_call(uri.data(), uri.size(), headers_ptr, headers_size,
request_body.data(), request_body.size(), trailers_ptr,
trailers_size, timeout_milliseconds, token_ptr);
::free(headers_ptr);
::free(trailers_ptr);
return result;
}
// Low level metrics interface.
inline WasmResult defineMetric(MetricType type, std::string_view name, uint32_t *metric_id) {
return proxy_define_metric(type, name.data(), name.size(), metric_id);
}
inline WasmResult incrementMetric(uint32_t metric_id, int64_t offset) {
return proxy_increment_metric(metric_id, offset);
}
inline WasmResult recordMetric(uint32_t metric_id, uint64_t value) {
return proxy_record_metric(metric_id, value);
}
inline WasmResult getMetric(uint32_t metric_id, uint64_t *value) {
return proxy_get_metric(metric_id, value);
}
// Higher level metrics interface.
struct MetricTag {
enum class TagType : uint32_t {
String = 0,
Int = 1,
Bool = 2,
};
std::string name;
TagType tagType;