-
Notifications
You must be signed in to change notification settings - Fork 69
/
proxy_wasm_api.h
2096 lines (1847 loc) · 86.6 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 <optional>
#include <string>
#include <tuple>
#include <unordered_map>
#include <utility>
#include <vector>
// Macro to log a message and abort the plugin if the given value is not
// `WasmResult::Ok`.
#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
// Functions to log messages at various log levels.
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());
}
// Logs a message at `LogLevel::critical` and aborts plugin execution.
inline void logAbort(std::string_view logMessage) {
logCritical(logMessage);
abort();
}
// Macro to log a message at the given log level with source file, line number,
// and function name included in the log message.
#define LOG(_level, ...) \
log##_level(std::string("[") + __FILE__ + ":" + std::to_string(__LINE__) + \
"]::" + __FUNCTION__ + "() " + __VA_ARGS__)
// Macros to log messages at various log levels with source file, line number,
// and function name included in the log message.
#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:
// Constructs a buffer that owns `size` bytes starting at `data`.
WasmData(const char *data, size_t size) : data_(data), size_(size) {}
// Frees buffer data.
~WasmData() { ::free(const_cast<char *>(data_)); }
// Returns pointer to the start of the buffer;
const char *data() { return data_; }
// Returns the size of the buffer in bytes.
size_t size() { return size_; }
// Returns buffer data in the form of a string_view.
std::string_view view() { return {data_, size_}; }
// Returns a string copy of buffer data.
std::string toString() { return std::string(view()); }
// Returns a series of string pairs decoded from and backed by the buffer.
std::vector<std::pair<std::string_view, std::string_view>> pairs();
// Returns a protobuf of type T parsed from buffer contents.
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;
}
// Returns the number of bytes used by the marshalled representation of
// `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;
}
// Marshals `pairs` to the memory buffer `buffer`. `Pairs` is a map-like type
// that provides a `size` method and iteration over elements that are
// `std::pair`s of `std::string` or `std::string_view`s.
template <typename Pairs> void marshalPairs(const Pairs &pairs, char *buffer) {
char *b = buffer;
*reinterpret_cast<uint32_t *>(b) = pairs.size();
b += sizeof(uint32_t);
for (auto &p : pairs) {
*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 : pairs) {
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;
}
}
// Marshals `pairs` to a newly allocated memory buffer, returning the address of
// the buffer and its size in bytes via the `ptr` and `size_ptr` out-params.
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;
}
// Hasher for pairs.
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);
}
};
// Hasher for three-element tuples.
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));
}
};
// Type for representing HTTP headers or metadata as string pairs.
using HeaderStringPairs = std::vector<std::pair<std::string, std::string>>;
// Superclass for handlers that receive events for unary gRPC callouts initiated
// by `RootContext::grpcCallHandler`.
class GrpcCallHandlerBase {
public:
GrpcCallHandlerBase() {}
virtual ~GrpcCallHandlerBase() {}
// Returns the `RootContext` associated with the gRPC call.
RootContext *context() { return context_; }
// Cancels the gRPC call.
void cancel();
// Returns the token used to identify the gRPC call.
uint32_t token() { return token_; }
// Callback invoked on gRPC call success. `body_size` indicates the size in
// bytes of the gRPC response body.
virtual void onSuccess(size_t body_size) = 0;
// Callback invoked on gRPC call failure. `status` conveys gRPC call status.
virtual void onFailure(GrpcStatus status) = 0;
private:
friend class RootContext;
RootContext *context_{nullptr};
uint32_t token_;
};
// Superclass for handlers that receive events for unary gRPC callouts initiated
// by `RootContext::grpcCallHandler`, templated on protobuf message type.
template <typename Message> class GrpcCallHandler : public GrpcCallHandlerBase {
public:
GrpcCallHandler() : GrpcCallHandlerBase() {}
virtual ~GrpcCallHandler() {}
// Callback invoked on gRPC call success. `body_size` indicates the size in
// bytes of the gRPC response body.
virtual void onSuccess(size_t body_size) = 0;
};
// Superclass for handlers that receive events for streaming gRPC callouts
// initiated by `RootContext::grpcStreamHandler`.
class GrpcStreamHandlerBase {
public:
GrpcStreamHandlerBase() {}
virtual ~GrpcStreamHandlerBase() {}
// Returns the `RootContext` associated with the gRPC call.
RootContext *context() { return context_; }
// Sends `message` over the gRPC stream. `end_of_stream` indicates whether
// this is the last message to be written on the stream.
//
// Note that even with `end_of_stream == true`, callbacks can still
// occur. Call `reset` to prevent further callbacks.
WasmResult send(std::string_view message, bool end_of_stream);
// Closes the gRPC stream.
//
// Note that callbacks can still occur after this method is called. Call
// `reset` to prevent further callbacks.
void close();
// Resets the handler and prevents further callbacks.
void reset();
// Returns the token used to identify the gRPC call.
uint32_t token() { return token_; }
// Callback invoked when gRPC initial metadata is received.
virtual void onReceiveInitialMetadata(uint32_t /* headers */) {}
// Callback invoked when gRPC trailing metadata is recevied.
virtual void onReceiveTrailingMetadata(uint32_t /* trailers */) {}
// Callback invoked when gRPC stream data is received. `body_size` gives the
// number of bytes received. The actual bytes can be retrieved by calling
// `getBufferBytes` with `WasmBufferType::GrpcReceiveBuffer`.
virtual void onReceive(size_t body_size) = 0;
// Callback invoked when the remote peer closed the gRPC stream. `status`
// gives the gRPC call status.
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_;
};
// Superclass for handlers that receive events for streaming gRPC callouts
// initiated by `RootContext::grpcStreamHandler`, templated on protobuf message
// types.
template <typename Request, typename Response>
class GrpcStreamHandler : public GrpcStreamHandlerBase {
public:
GrpcStreamHandler() : GrpcStreamHandlerBase() {}
virtual ~GrpcStreamHandler() {}
// Sends `message` over the gRPC stream. `end_of_stream` indicates whether
// this is the last message to be written on the stream.
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;
}
// Callback invoked when gRPC stream data is received. `body_size` gives the
// number of bytes received. The actual bytes can be retrieved by calling
// `getBufferBytes` with `WasmBufferType::GrpcReceiveBuffer`.
virtual void onReceive(size_t body_size) = 0;
};
// Behavior supported by all contexts.
class ContextBase {
public:
// Constructs a context identified by `id` in underlying ABI calls.
explicit ContextBase(uint32_t id) : id_(id) {}
virtual ~ContextBase() {}
// Returns numeric ID that identifies this context in ABI calls.
uint32_t id() { return id_; }
// Makes this context the effective context for calls out of the VM.
WasmResult setEffectiveContext();
// If this context is a root context, return it as a `RootContext`, else
// return nullptr.
virtual RootContext *asRoot() { return nullptr; }
// If this context is a stream context, return it as a `Context`, else return
// nullptr.
virtual Context *asContext() { return nullptr; }
// Callback invoked when the context is created.
virtual void onCreate() {}
// Callback invoked when the host is done with a context. Returning true
// indicates that the host can proceed to delete the context and perform other
// cleanup. Returning false indicates that the context is still being used,
// and the plugin will call `RootContext::done` later to inform the host that
// the context can be deleted.
virtual bool onDoneBase() = 0;
// Callback invoked after the host is done with a context, but before deleting
// it, when either `onDoneBase` has returned true, or `the plugin has called
// RootContext::done`. This callback can be used for generating log entries.
virtual void onLog() {}
// Callback invoked when the host is releasing its state associated with the
// context. No further callbacks will be invoked on the context after this
// callback.
virtual void onDelete() {} // Called when the stream or VM is being deleted.
// Callback invoked when a foreign function event
// arrives. `foreign_function_id` indicates the event type, which is some
// value agreed upon out-of-band by host and plugin. `data_size` gives the
// size of argument data for the call, in bytes. This argument data can be
// retrieved by calling `getBufferBytes` with `WasmBufferType::CallData`.
virtual void onForeignFunction(uint32_t /* foreign_function_id */, uint32_t /* data_size */) {}
// Returns the host's currently configured log level via the `level`
// out-param.
WasmResult getLogLevel(LogLevel *level) { return proxy_get_log_level(level); }
// Type alias for callbacks that are invoked when an outbound HTTP call
// initiated via `RootContext::httpCall` completes. `num_headers` gives the
// number of response header fields, `body_size` gives the size of the
// response body in bytes, and `num_trailers` gives the number of response
// trailer fields.
using HttpCallCallback =
std::function<void(uint32_t num_headers, size_t body_size, uint32_t num_trailers)>;
// Type alias for callbacks that are invoked when an outbound gRPC call
// initiated via `RootContext::grpcSimpleCall` completes. `status` gives the
// gRPC call status, and `body_size` gives the size of the gRPC response body
// in bytes.
using GrpcSimpleCallCallback = std::function<void(GrpcStatus status, size_t body_size)>;
private:
uint32_t id_;
};
// Behavior and operations supported by root contexts.
class RootContext : public ContextBase {
public:
// Constructs a root context identified by `id` in underlying ABI
// calls. `root_id` is a name that can be used to distinguish between
// different root contexts used by a plugin, if there are multiple.
RootContext(uint32_t id, std::string_view root_id) : ContextBase(id), root_id_(root_id) {}
~RootContext() {}
// Returns ID that distinguishes this root context from others in use.
std::string_view root_id() { return root_id_; }
RootContext *asRoot() override { return this; }
Context *asContext() override { return nullptr; }
// Callback that may be invoked (e.g. by the control plane) to validate plugin
// configuration. `configuration_size` gives the size of configuration data in
// bytes, which can be retrieved by calling `getBufferBytes` with
// `WasmBufferType::PluginConfiguration`. Returns true if the configuration is
// valid, or false if invalid.
virtual bool validateConfiguration(size_t /* configuration_size */) { return true; }
// Callback invoked when the plugin is initially loaded, as well as whenever
// configuration changes. `configuration_size` gives the size of configuration
// data in bytes, which can be retrieved by calling `getBufferBytes` with
// `WasmBufferType::PluginConfiguration`. Returns true if the configuration is
// valid, or false if invalid.
virtual bool onConfigure(size_t /* configuration_size */) { return true; }
// Callback invoked when the plugin is started. `vm_configuration_size` gives
// the size of VM configuration data in bytes, which can be retrieved by
// calling `getBufferBytes` with `WasmBufferType::VmConfiguration`. Returns
// true if the configuration is valid, or false if invalid.
virtual bool onStart(size_t /* vm_configuration_size */) { return true; }
// Callback invoked the timer configured by a previous call to
// `proxy_set_tick_period_milliseconds` goes off.
virtual void onTick() {}
// Callback invoked when data arrives on a shared queue. `token` is a value
// that identifies the shared queue, previously established in a call to
// `registerSharedQueue` or `resolveSharedQueue`. Shared queue data can be
// retrieved by calling `dequeueSharedQueue` with the given `token` value.
virtual void onQueueReady(uint32_t /* token */) {}
// Callback invoked when the plugin is being stopped. Returning true indicates
// that the host can proceed to delete the context and perform other
// cleanup. Returning false indicates that the context is still being used,
// and the plugin will call `RootContext::done` later to inform the host that
// the context can be deleted.
virtual bool onDone() { return true; }
// Informs the host that it is safe to delete this context, following an
// earlier `onDone` callback on it that had returned false.
void done();
// Low-level callback invoked when the response for an outbound HTTP call
// initiated via `makeHttpCall` is received, or the HTTP call times
// out. Plugins that use the high-level `RootContext::httpCall` API to perform
// outbound HTTP calls should not override this method, as doing so
// effectively disables the response callback for that method.
//
// `token` associates the response with the corresponding `makeHttpCall`
// call. `headers` is the number of HTTP header fields, or 0 if the request
// timed out. `body_size` is the size of the response body in bytes, and
// `trailers` is the number of HTTP trailer fields.
//
// Header and trailer values can be fetched by calling `getHeaderMapValue`
// with `WasmHeaderMapType::HttpCallResponseHeaders` and
// `WasmHeaderMapType::HttpCallResponseTrailers`, respectively. Response body
// bytes can be fetched by calling `getBufferBytes` with
// `WasmBufferType::HttpCallResponseBody`.
virtual void onHttpCallResponse(uint32_t token, uint32_t headers, size_t body_size,
uint32_t trailers);
// Low-level callback invoked when initial metadata for an outbound gRPC call
// initiated via `grpcCall` or `grpcStream` is received. Plugins that use the
// the high-level `RootContext::grpcSimpleCall` or
// `RootContext::grpcCallHandler` API to perform outbound gRPC calls should
// not override this method, as doing so effectively disables the response
// callbacks for those methods.
//
// `token` associates the received metadata with the corresponding `grpcCall`
// or `grpcStream` call. `headers` is the number of metadata fields received,
// which can be retrieved by calling `getHeaderMapValue` with
// `WasmHeaderMapType::GrpcReceiveInitialMetadata`.
virtual void onGrpcReceiveInitialMetadata(uint32_t token, uint32_t headers);
// Low-level callback invoked when trailing metadata for an outbound gRPC call
// initiated via `grpcCall` or `grpcStream` is received. Plugins that use the
// the high-level `RootContext::grpcSimpleCall` or
// `RootContext::grpcCallHandler` API to perform outbound gRPC calls should
// not override this method, as doing so effectively disables the response
// callbacks for those methods.
//
// `token` associates the received metadata with the corresponding `grpcCall`
// or `grpcStream` call. `trailers` is the number of metadata fields received,
// which can be retrieved by calling `getHeaderMapValue` with
// `WasmHeaderMapType::GrpcReceiveTrailingMetadata`.
virtual void onGrpcReceiveTrailingMetadata(uint32_t token, uint32_t trailers);
// Low-level callback invoked when response data for an outbound gRPC call
// initiated via `grpcCall` or `grpcStream` is received. Plugins that use the
// the high-level `RootContext::grpcSimpleCall` or
// `RootContext::grpcCallHandler` API to perform outbound gRPC calls should
// not override this method, as doing so effectively disables the response
// callbacks for those methods.
//
// `token` associates the received metadata with the corresponding `grpcCall`
// or `grpcStream` call. `body_size` is the number of response body bytes
// received, which can be retrieved by calling `getBuffer` with
// `WasmHeaderMapType::GrpcReceiveBuffer`.
virtual void onGrpcReceive(uint32_t token, size_t body_size);
// Low-level callback invoked when an outbound gRPC call initiated via
// `grpcCall` or `grpcStream` terminates. Plugins that use the the high-level
// `RootContext::grpcSimpleCall` or `RootContext::grpcCallHandler` API to
// perform outbound gRPC calls should not override this method, as doing so
// effectively disables the response callbacks for those methods.
//
// `token` associates the received metadata with the corresponding `grpcCall`
// or `grpcStream` call. `status` gives the gRPC status code for the call.
virtual void onGrpcClose(uint32_t token, GrpcStatus status);
// Initiates an outbound HTTP call to URI `uri`, sending `request_headers`,
// `request_body`, and `request_trailers` as the request headers, body, and
// trailers. `callback` is a callback that is invoked when the HTTP response
// is received, or the request times out. Returns `WasmResult::Ok` if the
// request is successfully sent.
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);
// Initiates an outbound unary gRPC call to the service named by `service` and
// `service_name`, invoking method `method_name`. `initial_metadata` and
// `request` specify the initial metadata and request body for the
// call. `callback` is a callback that is invoked when the gRPC response is
// received, or the request times out. Returns `WasmResult::Ok` if the call is
// successfully sent.
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);
// Initiates an outbound unary gRPC call to the service named by `service` and
// `service_name`, invoking method `method_name`. `initial_metadata` and
// `request` specify the initial metadata and request body for the
// call. `success_callback` is a callback that is invoked when a successful
// gRPC response is received. `failure_callback` is a callback that is invoked
// if the gRPC call fails. Returns `WasmResult::Ok` if the call is
// successfully sent.
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);
}
// Initiates an outbound unary gRPC call to the service named by `service` and
// `service_name`, invoking method `method_name`. `initial_metadata` and
// `request` specify the initial metadata and request body for the
// call. `handler` is a handler object that receives callbacks for gRPC call
// events such as success or failure. Returns `WasmResult::Ok` if the call is
// successfully sent.
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
// Initiates an outbound unary gRPC call to the service named by `service` and
// `service_name`, invoking method `method_name`. `initial_metadata` and
// `request` specify the initial metadata and request protobuf for the
// call. `callback` is a callback that is invoked when the gRPC response is
// received, or the request times out. Returns `WasmResult::Ok` if the call is successfully sent.
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);
}
// Initiates an outbound unary gRPC call to the service named by `service` and
// `service_name`, invoking method `method_name`. `initial_metadata` and
// `request` specify the initial metadata and request protobuf for the
// call. `success_callback` is a callback that is invoked when a successful
// gRPC response is received. `failure_callback` is a callback that is invoked
// if the gRPC call fails. Returns `WasmResult::Ok` if the call is
// successfully sent.
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);
}
// Initiates an outbound unary gRPC call to the service named by `service` and
// `service_name`, invoking method `method_name`. `initial_metadata` and
// `request` specify the initial metadata and request protobuf for the
// call. `handler` is a handler object that receives callbacks for gRPC call
// events such as success or failure. Returns `WasmResult::Ok` if the call is
// successfully sent.
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
// Initiates an outbound streaming gRPC call to the service named by `service`
// and `service_name`, invoking method `method_name`. `initial_metadata`
// specifies the initial metadata for the call. `handler` is a handler object
// that can be used to send messages over the gRPC stream, and receives
// callbacks for gRPC call events such as receiving metadata and response
// messages. Returns `WasmResult::Ok` if the call is successfully sent.
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_;
};
// Returns `RootContext` object for the root context named by `root_id`, or
// nullptr if none is found.
RootContext *getRoot(std::string_view root_id);
// Behavior and operations supported by stream contexts.
class Context : public ContextBase {
public:
// Constructs a stream context identified by `id` in underlying ABI calls,
// associated with root context `root`.
Context(uint32_t id, RootContext *root) : ContextBase(id), root_(root) {}
virtual ~Context() {}
// Returns the root context associated with this stream context.
RootContext *root() { return root_; }
RootContext *asRoot() override { return nullptr; }
Context *asContext() override { return this; }
// Callback invoked when a new TCP(-like) connection is established. Returns
// `FilterStatus` indicating whether processing of the connection should
// continue or pause until a later call to `continueDownstream`.
virtual FilterStatus onNewConnection() { return FilterStatus::Continue; }
// Callback invoked when new data is received from downstream on a TCP(-like)
// connection. `data_size` gives the number of bytes received, and
// `end_of_stream` indicates whether this is the last data from
// downstream. Data can be retrieved by calling `getBufferBytes` with
// `WasmBufferType::NetworkDownstreamData`.
//
// Returns `FilterStatus` indicating whether processing of the connection
// should continue or pause until a later call to `continueDownstream`.
virtual FilterStatus onDownstreamData(size_t /* data_size */, bool /* end_of_stream */) {
return FilterStatus::Continue;
}
// Callback invoked when new data is received from upstream on a TCP(-like)
// connection. `data_size` gives the number of bytes received, and
// `end_of_stream` indicates whether this is the last data from
// downstream. Data can be retrieved by calling `getBufferBytes` with
// `WasmBufferType::NetworkUpstreamData`.
//
// Returns `FilterStatus` indicating whether processing of the connection
// should continue or pause until a later call to `continueUpstream`.
virtual FilterStatus onUpstreamData(size_t /* data_size */, bool /* end_of_stream */) {
return FilterStatus::Continue;
}
// Callback invoked when the downstream direction of a TCP(-like) connection
// is closed. `close_type` indicates whether the connection was closed by the
// proxy or the remote peer.
virtual void onDownstreamConnectionClose(CloseType /* close_type */) {}
// Callback invoked when the upstream direction of a TCP(-like) connection is
// closed. `close_type` indicates whether the connection was closed by the
// proxy or the remote peer.
virtual void onUpstreamConnectionClose(CloseType /* close_type */) {}
// Callback invoked when HTTP request headers are received. `headers` is the
// number of header fields. `end_of_stream` indicates whether the request ends
// immediately after the headers. Request header values can be accessed and
// manipulated via `*RequestHeader*` hostcalls, or by specifying
// `WasmHeaderMapType::RequestHeaders` in `*HeaderMap*` hostcalls.
//
// Returns `FilterHeadersStatus` indicating whether processing of the
// connection should continue or pause until a later call to
// `continueRequest`.
virtual FilterHeadersStatus onRequestHeaders(uint32_t /* headers */, bool /* end_of_stream */) {
return FilterHeadersStatus::Continue;
}
// Callback invoked when request metadata is received. `elements` is the
// number of metadata entries. Metadata values are not currently accessible.
virtual FilterMetadataStatus onRequestMetadata(uint32_t /* elements */) {
return FilterMetadataStatus::Continue;
}
// Callback invoked when HTTP request body data is
// received. `body_buffer_length` is the size of body data in
// bytes. `end_of_stream` indicates whether the request ends immediately after
// the request body data. Request body bytes can be retrieved by calling
// `getBufferBytes` with `WasmBufferType::HttpRequestBody`.
//
// Returns `FilterDataStatus` indicating whether processing of the connection
// should continue or pause until a later call to `continueRequest`.
virtual FilterDataStatus onRequestBody(size_t /* body_buffer_length */,
bool /* end_of_stream */) {
return FilterDataStatus::Continue;
}
// Callback invoked when HTTP request trailers are received. `trailers` is the
// number of trailer fields. Request trailer values can be accessed and
// manipulated via `*RequestTrailer*` hostcalls, or by specifying
// `WasmHeaderMapType::RequestTrailers` in `*HeaderMap*` hostcalls.
//
// Returns `FilterTrailersStatus` indicating whether processing of the
// connection should continue or pause until a later call to
// `continueRequest`.
virtual FilterTrailersStatus onRequestTrailers(uint32_t /* trailers */) {
return FilterTrailersStatus::Continue;
}
// Callback invoked when HTTP response headers are received. `headers` is the
// number of header fields. `end_of_stream` indicates whether the response
// ends immediately after the headers. Response header values can be accessed
// and manipulated via `*ResponseHeader*` hostcalls, or by specifying
// `WasmHeaderMapType::ResponseHeaders` in `*HeaderMap*` hostcalls.
//
// Returns `FilterHeadersStatus` indicating whether processing of the
// connection should continue or pause until a later call to
// `continueResponse`.
virtual FilterHeadersStatus onResponseHeaders(uint32_t /* headers */, bool /* end_of_stream */) {
return FilterHeadersStatus::Continue;
}
// Callback invoked when response metadata is received. `elements` is the
// number of metadata entries. Metadata values are not currently accessible.
virtual FilterMetadataStatus onResponseMetadata(uint32_t /* elements */) {
return FilterMetadataStatus::Continue;
}
// Callback invoked when HTTP response body data is
// received. `body_buffer_length` is the size of body data in
// bytes. `end_of_stream` indicates whether the response ends immediately
// after the response body data. Response body bytes can be retrieved by
// calling `getBufferBytes` with `WasmBufferType::HttpResponseBody`.
//
// Returns `FilterDataStatus` indicating whether processing of the connection
// should continue or pause until a later call to `continueResponse`.
virtual FilterDataStatus onResponseBody(size_t /* body_buffer_length */,
bool /* end_of_stream */) {
return FilterDataStatus::Continue;
}
// Callback invoked when HTTP response trailers are received. `trailers` is
// the number of trailer fields. Response trailer values can be accessed and
// manipulated via `*ResponseTrailer*` hostcalls, or by specifying
// `WasmHeaderMapType::ResponseTrailers` in `*HeaderMap*` hostcalls.
//
// Returns `FilterTrailersStatus` indicating whether processing of the
// connection should continue or pause until a later call to
// `continueResponse`.
virtual FilterTrailersStatus onResponseTrailers(uint32_t /* trailers */) {
return FilterTrailersStatus::Continue;
}
// Callback invoked when the stream has completed.
virtual void onDone() {}
private:
// For stream contexts, onDone always returns true.
bool onDoneBase() override {
onDone();
return true;
}
RootContext *root_{};
};
// Returns stream context object associated with `context_id`, or nullptr if
// none exists (e.g. the stream has been destroyed, or the context associated
// with `context_id` is not a stream context).
Context *getContext(uint32_t context_id);
// Returns root context object associated with `context_id`, or nullptr if none
// exists (e.g. the context associated with `context_id` is not a root context).
RootContext *getRootContext(uint32_t context_id);
// Returns stream or root context object associated with `context_id`, or
// nullptr if none exists.
ContextBase *getContextBase(uint32_t context_id);
// Factory function type for root contexts.
using RootFactory =
std::function<std::unique_ptr<RootContext>(uint32_t id, std::string_view root_id)>;
// Factory function type for stream contexts.
using ContextFactory = std::function<std::unique_ptr<Context>(uint32_t id, RootContext *root)>;
// Convenience macro to create a root context factory for the `RootContext`
// subclass named by `_c`.
#define ROOT_FACTORY(_c) \
[](uint32_t id, std::string_view root_id) -> std::unique_ptr<RootContext> { \
return std::make_unique<_c>(id, root_id); \
}
// Convenience macro to create a stream context factory for the `RootContext`
// subclass named by `_c`.
#define CONTEXT_FACTORY(_c) \
[](uint32_t id, RootContext *root) -> std::unique_ptr<Context> { \
return std::make_unique<_c>(id, root); \
}
// Struct to instantiate in order to register root context and/or stream context
// factory functions.
struct RegisterContextFactory {
// Registers `context_factory` for creating stream contexts and `root_factory`
// for creating a root context for the plugin indicated by `root_id`.
RegisterContextFactory(ContextFactory context_factory, RootFactory root_factory,
std::string_view root_id = "");
// Registers `root_factory` for creating a root context for the plugin
// indicated by `root_id`.
explicit RegisterContextFactory(RootFactory root_factory, std::string_view root_id = "")
: RegisterContextFactory(nullptr, root_factory, root_id) {}
// Registers `context_factory` for creating stream contexts for the plugin
// indicated by `root_id`.
explicit RegisterContextFactory(ContextFactory context_factory, std::string_view root_id = "")
: RegisterContextFactory(context_factory, nullptr, root_id) {}
};
// Returns the status code and status message of the response to an outbound
// HTTP or gRPC call. Can be called from the `RootContext::onHttpCallResponse`
// or `RootContext::onGrpcClose` callbacks.
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));
}
// Returns value of the property named by the concatenation of `parts`, or
// nullopt if no property value is found.
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);
}
// Returns value of the property named by the concatenation of `parts`, or
// nullopt if no property value is found.
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);
}
// Returns value of the property named by the concatenation of `parts` in
// out-param `out`, which can be of type int64, uint64, double, or bool. Returns
// true if the property was successfully fetched and stored in `out`, or false
// otherwise.
//
// Durations are represented as int64 nanoseconds. Timestamps are represented as
// int64 Unix nanoseconds.
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;
}
// Returns value of the property named by the concatenation of `parts` in string
// out-param `out`. Returns true if the property was successfully fetched and
// stored in `out`, or false otherwise.
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;
}
// Returns value of the property named by the concatenation of `parts` in
// out-param `out`, which can be of type int64, uint64, double, or bool. Returns
// true if the property was successfully fetched and stored in `out`, or false
// otherwise.
//
// Durations are represented as int64 nanoseconds. Timestamps are represented as
// int64 Unix nanoseconds.
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;
}