1
#pragma once
2

            
3
#include <cassert>
4
#include <cstddef>
5
#include <format>
6
#include <functional>
7
#include <map>
8
#include <memory>
9
#include <optional>
10
#include <span>
11
#include <string>
12
#include <string_view>
13
#include <vector>
14

            
15
namespace Envoy {
16
namespace DynamicModules {
17

            
18
/** Interface definitions for the dynamic module SDK. */
19

            
20
/**
21
 * BufferView should have the same layout as envoy_dynamic_module_type_module_buffer
22
 * and envoy_dynamic_module_type_envoy_buffer.
23
 */
24
class BufferView {
25
public:
26
  /**
27
   * Constructs a BufferView from a string_view.
28
   * @param data The string view to construct from.
29
   */
30
  BufferView(std::string_view data) : data_(data.data()), length_(data.size()) {}
31
  BufferView(const char* data, size_t length) : data_(data), length_(length) {}
32
  /**
33
   * Default constructor.
34
   */
35
  BufferView() = default;
36

            
37
  /**
38
   * Returns the buffer as a string_view.
39
   * @return The buffer contents as a string_view.
40
   */
41
  std::string_view toStringView() const { return {data_, length_}; }
42

            
43
  size_t size() const { return length_; }
44
  const char* data() const { return data_; }
45

            
46
private:
47
  const char* data_{};
48
  size_t length_{};
49
};
50

            
51
/**
52
 * HeaderView should have the same layout as envoy_dynamic_module_type_module_http_header
53
 * and envoy_dynamic_module_type_envoy_http_header.
54
 */
55
class HeaderView {
56
public:
57
  /**
58
   * Constructs a HeaderView from key and value string_views.
59
   * @param key The header key.
60
   * @param value The header value.
61
   */
62
  HeaderView(std::string_view key, std::string_view value)
63
      : key_data_(key.data()), key_length_(key.size()), value_data_(value.data()),
64
        value_length_(value.size()) {}
65
  HeaderView(const char* key_data, size_t key_length, const char* value_data, size_t value_length)
66
      : key_data_(key_data), key_length_(key_length), value_data_(value_data),
67
        value_length_(value_length) {}
68
  /**
69
   * Default constructor.
70
   */
71
  HeaderView() = default;
72

            
73
  /**
74
   * Returns the header key as a string_view.
75
   * @return The header key.
76
   */
77
  std::string_view key() const { return {key_data_, key_length_}; }
78

            
79
  /**
80
   * Returns the header value as a string_view.
81
   * @return The header value.
82
   */
83
  std::string_view value() const { return {value_data_, value_length_}; }
84

            
85
  const char* keyData() const { return key_data_; }
86
  size_t keyLength() const { return key_length_; }
87
  const char* valueData() const { return value_data_; }
88
  size_t valueLength() const { return value_length_; }
89

            
90
private:
91
  const char* key_data_{};
92
  size_t key_length_{};
93
  const char* value_data_{};
94
  size_t value_length_{};
95
};
96

            
97
/** BodyBuffer interface */
98
class BodyBuffer {
99
public:
100
  virtual ~BodyBuffer();
101

            
102
  /**
103
   * Returns all data chunks in the buffer.
104
   * @return Vector of buffer views containing all chunks.
105
   */
106
  virtual std::vector<BufferView> getChunks() const = 0;
107

            
108
  /**
109
   * Returns the total size of the buffer.
110
   * @return The total size in bytes.
111
   */
112
  virtual size_t getSize() const = 0;
113

            
114
  /**
115
   * Removes size from the front of the buffer.
116
   * @param size Number of bytes to remove.
117
   */
118
  virtual void drain(size_t size) = 0;
119

            
120
  /**
121
   * Appends data to the buffer.
122
   * @param data The data to append.
123
   */
124
  virtual void append(std::string_view data) = 0;
125
};
126

            
127
/** HeaderMap interface */
128
class HeaderMap {
129
public:
130
  virtual ~HeaderMap();
131

            
132
  /**
133
   * Returns all values for a given header key.
134
   * @param key The header key to look up.
135
   * @return Vector of string views containing all values for the key.
136
   */
137
  virtual std::vector<std::string_view> get(std::string_view key) const = 0;
138

            
139
  /**
140
   * Returns the first value for a given header key.
141
   * @param key The header key to look up.
142
   * @return The first header value, or empty if not found.
143
   */
144
  virtual std::string_view getOne(std::string_view key) const = 0;
145

            
146
  /**
147
   * Returns all headers.
148
   * @return Vector of HeaderView containing all headers.
149
   */
150
  virtual std::vector<HeaderView> getAll() const = 0;
151

            
152
  /**
153
   * Return size of the header map.
154
   * @return The number of headers in the map.
155
   */
156
  virtual size_t size() const = 0;
157

            
158
  /**
159
   * Sets a header key-value pair (replaces existing).
160
   * @param key The header key.
161
   * @param value The header value.
162
   */
163
  virtual void set(std::string_view key, std::string_view value) = 0;
164

            
165
  /**
166
   * Adds a header key-value pair (appends to existing).
167
   * @param key The header key.
168
   * @param value The header value.
169
   */
170
  virtual void add(std::string_view key, std::string_view value) = 0;
171

            
172
  /**
173
   * Removes all headers with the given key.
174
   * @param key The header key to remove.
175
   */
176
  virtual void remove(std::string_view key) = 0;
177
};
178

            
179
/** Attribute IDs */
180
enum class AttributeID : uint32_t {
181
  RequestPath = 0,
182
  RequestUrlPath,
183
  RequestHost,
184
  RequestScheme,
185
  RequestMethod,
186
  RequestHeaders,
187
  RequestReferer,
188
  RequestUserAgent,
189
  RequestTime,
190
  RequestId,
191
  RequestProtocol,
192
  RequestQuery,
193
  RequestDuration,
194
  RequestSize,
195
  RequestTotalSize,
196
  ResponseCode,
197
  ResponseCodeDetails,
198
  ResponseFlags,
199
  ResponseGrpcStatus,
200
  ResponseHeaders,
201
  ResponseTrailers,
202
  ResponseSize,
203
  ResponseTotalSize,
204
  ResponseBackendLatency,
205
  SourceAddress,
206
  SourcePort,
207
  DestinationAddress,
208
  DestinationPort,
209
  ConnectionId,
210
  ConnectionMtls,
211
  ConnectionRequestedServerName,
212
  ConnectionTlsVersion,
213
  ConnectionSubjectLocalCertificate,
214
  ConnectionSubjectPeerCertificate,
215
  ConnectionDnsSanLocalCertificate,
216
  ConnectionDnsSanPeerCertificate,
217
  ConnectionUriSanLocalCertificate,
218
  ConnectionUriSanPeerCertificate,
219
  ConnectionSha256PeerCertificateDigest,
220
  ConnectionTransportFailureReason,
221
  ConnectionTerminationDetails,
222
  UpstreamAddress,
223
  UpstreamPort,
224
  UpstreamTlsVersion,
225
  UpstreamSubjectLocalCertificate,
226
  UpstreamSubjectPeerCertificate,
227
  UpstreamDnsSanLocalCertificate,
228
  UpstreamDnsSanPeerCertificate,
229
  UpstreamUriSanLocalCertificate,
230
  UpstreamUriSanPeerCertificate,
231
  UpstreamSha256PeerCertificateDigest,
232
  UpstreamLocalAddress,
233
  UpstreamTransportFailureReason,
234
  UpstreamRequestAttemptCount,
235
  UpstreamCxPoolReadyDuration,
236
  UpstreamLocality,
237
  XdsNode,
238
  XdsClusterName,
239
  XdsClusterMetadata,
240
  XdsListenerDirection,
241
  XdsListenerMetadata,
242
  XdsRouteName,
243
  XdsRouteMetadata,
244
  XdsVirtualHostName,
245
  XdsVirtualHostMetadata,
246
  XdsUpstreamHostMetadata,
247
  XdsFilterChainName
248
};
249

            
250
enum class LogLevel : uint32_t { Trace, Debug, Info, Warn, Error, Critical, Off };
251

            
252
enum class HttpCalloutInitResult : uint32_t {
253
  Success,
254
  MissingRequiredHeaders,
255
  ClusterNotFound,
256
  DuplicateCalloutId,
257
  CannotCreateRequest
258
};
259

            
260
enum class HttpCalloutResult : uint32_t { Success, Reset, ExceedResponseBufferLimit };
261

            
262
class HttpCalloutCallback {
263
public:
264
  virtual ~HttpCalloutCallback();
265

            
266
  /**
267
   * Invokes the callback with the HTTP callout result, headers, and body chunks.
268
   * @param result The HTTP callout result status.
269
   * @param headers Span of response headers.
270
   * @param body_chunks Span of response body chunks.
271
   */
272
  virtual void onHttpCalloutDone(HttpCalloutResult result, std::span<const HeaderView> headers,
273
                                 std::span<const BufferView> body_chunks) = 0;
274
};
275

            
276
enum class HttpStreamResetReason : uint32_t {
277
  ConnectionFailure,
278
  ConnectionTermination,
279
  LocalReset,
280
  LocalRefusedStreamReset,
281
  Overflow,
282
  RemoteReset,
283
  RemoteRefusedStreamReset,
284
  ProtocolError,
285
};
286

            
287
class HttpStreamCallback {
288
public:
289
  virtual ~HttpStreamCallback();
290

            
291
  /**
292
   * Called when response headers are received.
293
   * @param stream_id The ID of the stream.
294
   * @param headers The response headers.
295
   * @param end_stream Indicates if this is the end of the stream.
296
   */
297
  virtual void onHttpStreamHeaders(uint64_t stream_id, std::span<const HeaderView> headers,
298
                                   bool end_stream) = 0;
299

            
300
  /**
301
   * Called when response data is received.
302
   * @param stream_id The ID of the stream.
303
   * @param body The response body chunks.
304
   * @param end_stream Indicates if this is the end of the stream.
305
   */
306
  virtual void onHttpStreamData(uint64_t stream_id, std::span<const BufferView> body,
307
                                bool end_stream) = 0;
308

            
309
  /**
310
   * Called when response trailers are received.
311
   * @param stream_id The ID of the stream.
312
   * @param trailers The response trailers.
313
   */
314
  virtual void onHttpStreamTrailers(uint64_t stream_id, std::span<const HeaderView> trailers) = 0;
315

            
316
  /**
317
   * Called when the stream is complete.
318
   * @param stream_id The ID of the stream.
319
   */
320
  virtual void onHttpStreamComplete(uint64_t stream_id) = 0;
321

            
322
  /**
323
   * Called when the stream is reset.
324
   * @param stream_id The ID of the stream.
325
   * @param reason The reason for the reset.
326
   */
327
  virtual void onHttpStreamReset(uint64_t stream_id, HttpStreamResetReason reason) = 0;
328
};
329

            
330
class RouteSpecificConfig {
331
public:
332
  virtual ~RouteSpecificConfig();
333
};
334

            
335
class Scheduler {
336
public:
337
  virtual ~Scheduler();
338

            
339
  /**
340
   * Schedules a function for deferred execution.
341
   * @param func The function to schedule.
342
   */
343
  virtual void schedule(std::function<void()> func) = 0;
344
};
345

            
346
class DownstreamWatermarkCallbacks {
347
public:
348
  virtual ~DownstreamWatermarkCallbacks();
349

            
350
  /**
351
   * Called when the downstream write buffer exceeds the high watermark.
352
   */
353
  virtual void onAboveWriteBufferHighWatermark() = 0;
354

            
355
  /**
356
   * Called when the downstream write buffer drops below the low watermark.
357
   */
358
  virtual void onBelowWriteBufferLowWatermark() = 0;
359
};
360

            
361
using MetricID = uint64_t;
362
enum class MetricsResult : uint32_t { Success, NotFound, InvalidTags, Frozen };
363

            
364
class HttpFilterHandle {
365
public:
366
  virtual ~HttpFilterHandle();
367

            
368
  /**
369
   * Retrieves a string metadata value by namespace and key.
370
   * @param ns The metadata namespace.
371
   * @param key The metadata key.
372
   * @return Pair of string view and bool indicating if value was found.
373
   */
374
  virtual std::optional<std::string_view> getMetadataString(std::string_view ns,
375
                                                            std::string_view key) = 0;
376

            
377
  /**
378
   * Retrieves a numeric metadata value by namespace and key.
379
   * @param ns The metadata namespace.
380
   * @param key The metadata key.
381
   * @return Pair of double and bool indicating if value was found.
382
   */
383
  virtual std::optional<double> getMetadataNumber(std::string_view ns, std::string_view key) = 0;
384

            
385
  /**
386
   * Retrieves a bool metadata value by namespace and key.
387
   * @param ns The metadata namespace.
388
   * @param key The metadata key.
389
   * @return The bool value if found, otherwise nullopt.
390
   */
391
  virtual std::optional<bool> getMetadataBool(std::string_view ns, std::string_view key) = 0;
392

            
393
  /**
394
   * Retrieves all keys in a metadata namespace.
395
   * @param ns The metadata namespace.
396
   * @return Vector of key strings.
397
   */
398
  virtual std::vector<std::string_view> getMetadataKeys(std::string_view ns) = 0;
399

            
400
  /**
401
   * Retrieves all namespace names in the metadata.
402
   * @return Vector of namespace name strings.
403
   */
404
  virtual std::vector<std::string_view> getMetadataNamespaces() = 0;
405

            
406
  /**
407
   * Sets a string metadata value.
408
   * @param ns The metadata namespace.
409
   * @param key The metadata key.
410
   * @param value The string value to set.
411
   */
412
  virtual void setMetadata(std::string_view ns, std::string_view key, std::string_view value) = 0;
413

            
414
  /**
415
   * Sets a numeric metadata value.
416
   * @param ns The metadata namespace.
417
   * @param key The metadata key.
418
   * @param value The numeric value to set.
419
   */
420
  virtual void setMetadata(std::string_view ns, std::string_view key, double value) = 0;
421

            
422
  /**
423
   * Sets a bool metadata value.
424
   * @param ns The metadata namespace.
425
   * @param key The metadata key.
426
   * @param value The bool value to set.
427
   */
428
  virtual void setMetadata(std::string_view ns, std::string_view key, bool value) = 0;
429

            
430
  // Prevent const char* from implicitly converting to bool instead of string_view.
431
  void setMetadata(std::string_view ns, std::string_view key, const char* value) {
432
    setMetadata(ns, key, std::string_view(value));
433
  }
434

            
435
  /**
436
   * Appends a numeric value to the dynamic metadata list stored under the given namespace and key.
437
   * If the key does not exist, a new list is created. Returns false if the key exists but is not a
438
   * list, or if the metadata is not accessible.
439
   * @param ns The metadata namespace.
440
   * @param key The metadata key.
441
   * @param value The number to append.
442
   * @return true if the operation is successful, false otherwise.
443
   */
444
  virtual bool addMetadataList(std::string_view ns, std::string_view key, double value) = 0;
445

            
446
  /**
447
   * Appends a string value to the dynamic metadata list stored under the given namespace and key.
448
   * If the key does not exist, a new list is created. Returns false if the key exists but is not a
449
   * list, or if the metadata is not accessible.
450
   * @param ns The metadata namespace.
451
   * @param key The metadata key.
452
   * @param value The string to append.
453
   * @return true if the operation is successful, false otherwise.
454
   */
455
  virtual bool addMetadataList(std::string_view ns, std::string_view key,
456
                               std::string_view value) = 0;
457

            
458
  // Prevent const char* from implicitly converting to bool instead of string_view.
459
  bool addMetadataList(std::string_view ns, std::string_view key, const char* value) {
460
    return addMetadataList(ns, key, std::string_view(value));
461
  }
462

            
463
  /**
464
   * Appends a bool value to the dynamic metadata list stored under the given namespace and key.
465
   * If the key does not exist, a new list is created. Returns false if the key exists but is not a
466
   * list, or if the metadata is not accessible.
467
   * @param ns The metadata namespace.
468
   * @param key The metadata key.
469
   * @param value The bool to append.
470
   * @return true if the operation is successful, false otherwise.
471
   */
472
  virtual bool addMetadataList(std::string_view ns, std::string_view key, bool value) = 0;
473

            
474
  /**
475
   * Returns the number of elements in the metadata list stored under the given namespace and key.
476
   * Returns nullopt if the metadata is not accessible, the namespace or key does not exist, or the
477
   * value is not a list.
478
   * @param ns The metadata namespace.
479
   * @param key The metadata key.
480
   */
481
  virtual std::optional<size_t> getMetadataListSize(std::string_view ns, std::string_view key) = 0;
482

            
483
  /**
484
   * Returns the number element at the given index in the metadata list stored under the given
485
   * namespace and key. Returns nullopt if the metadata is not accessible, the namespace or key does
486
   * not exist, the value is not a list, the index is out of range, or the element is not a number.
487
   * @param ns The metadata namespace.
488
   * @param key The metadata key.
489
   * @param index The zero-based index.
490
   */
491
  virtual std::optional<double> getMetadataListNumber(std::string_view ns, std::string_view key,
492
                                                      size_t index) = 0;
493

            
494
  /**
495
   * Returns the string element at the given index in the metadata list stored under the given
496
   * namespace and key. Returns nullopt if the metadata is not accessible, the namespace or key does
497
   * not exist, the value is not a list, the index is out of range, or the element is not a string.
498
   * @param ns The metadata namespace.
499
   * @param key The metadata key.
500
   * @param index The zero-based index.
501
   */
502
  virtual std::optional<std::string_view>
503
  getMetadataListString(std::string_view ns, std::string_view key, size_t index) = 0;
504

            
505
  /**
506
   * Returns the bool element at the given index in the metadata list stored under the given
507
   * namespace and key. Returns nullopt if the metadata is not accessible, the namespace or key does
508
   * not exist, the value is not a list, the index is out of range, or the element is not a bool.
509
   * @param ns The metadata namespace.
510
   * @param key The metadata key.
511
   * @param index The zero-based index.
512
   */
513
  virtual std::optional<bool> getMetadataListBool(std::string_view ns, std::string_view key,
514
                                                  size_t index) = 0;
515

            
516
  /**
517
   * Retrieves the serialized filter state value of the stream.
518
   * @param key The filter state key.
519
   * @return The filter state value if found, otherwise empty.
520
   */
521
  virtual std::optional<std::string_view> getFilterState(std::string_view key) = 0;
522

            
523
  /**
524
   * Sets the serialized filter state value of the stream.
525
   * @param key The filter state key.
526
   * @param value The filter state value.
527
   */
528
  virtual void setFilterState(std::string_view key, std::string_view value) = 0;
529

            
530
  /**
531
   * Retrieves a string attribute value.
532
   * @param id The attribute ID.
533
   * @return Pair of string view and bool indicating if attribute was found.
534
   */
535
  virtual std::optional<std::string_view> getAttributeString(AttributeID id) = 0;
536

            
537
  /**
538
   * Retrieves a numeric attribute value.
539
   * @param id The attribute ID.
540
   * @return Pair of double and bool indicating if attribute was found.
541
   */
542
  virtual std::optional<uint64_t> getAttributeNumber(AttributeID id) = 0;
543

            
544
  /**
545
   * Retrieves a boolean attribute value.
546
   * @param id The attribute ID.
547
   * @return The bool value if found, otherwise nullopt.
548
   */
549
  virtual std::optional<bool> getAttributeBool(AttributeID id) = 0;
550

            
551
  /**
552
   * Sends a local response with status code, body, and detail.
553
   * @param status The HTTP status code.
554
   * @param body The response body.
555
   * @param detail The response detail.
556
   */
557
  virtual void sendLocalResponse(uint32_t status, std::span<const HeaderView> headers,
558
                                 std::string_view body, std::string_view detail) = 0;
559

            
560
  /**
561
   * Sends response headers. This is used for streaming local replies.
562
   * @param headers The response headers.
563
   * @param end_stream Indicates if this is the end of the stream.
564
   */
565
  virtual void sendResponseHeaders(std::span<const HeaderView> headers, bool end_stream) = 0;
566

            
567
  /**
568
   * Sends response data. This is used for streaming local replies.
569
   * @param body The response body data.
570
   * @param end_stream Indicates if this is the end of the stream.
571
   */
572
  virtual void sendResponseData(std::string_view body, bool end_stream) = 0;
573

            
574
  /**
575
   * Sends response trailers. This is used for streaming local replies.
576
   * @param trailers The response trailers.
577
   */
578
  virtual void sendResponseTrailers(std::span<const HeaderView> trailers) = 0;
579

            
580
  /**
581
   * Adds a custom flag to the current request context.
582
   * @param flag The custom flag to add.
583
   */
584
  virtual void addCustomFlag(std::string_view flag) = 0;
585

            
586
  /**
587
   * Continues processing the current request.
588
   */
589
  virtual void continueRequest() = 0;
590

            
591
  /**
592
   * Continues processing the current response.
593
   */
594
  virtual void continueResponse() = 0;
595

            
596
  /**
597
   * Clear route cache to force re-evaluation of route.
598
   */
599
  virtual void clearRouteCache() = 0;
600

            
601
  /**
602
   * Returns reference to request headers.
603
   * @return Reference to StreamHeaderMap containing request headers.
604
   */
605
  virtual HeaderMap& requestHeaders() = 0;
606

            
607
  /**
608
   * Returns reference to buffered request body.
609
   * @return Reference to BodyBuffer containing request body.
610
   */
611
  virtual BodyBuffer& bufferedRequestBody() = 0;
612

            
613
  /**
614
   * Returns reference to the latest received request body chunk.
615
   * NOTE: This is only valid in the onRequestBody callback, and it retrieves the latest received
616
   * body chunk that triggers the callback. For other callbacks or outside of the callbacks, you
617
   * should use bufferedRequestBody() to get the currently buffered body in the chain.
618
   * @return Reference to BodyBuffer containing the latest received request body chunk.
619
   */
620
  virtual BodyBuffer& receivedRequestBody() = 0;
621

            
622
  /**
623
   * Returns reference to request trailers.
624
   * @return Reference to StreamHeaderMap containing request trailers.
625
   */
626
  virtual HeaderMap& requestTrailers() = 0;
627

            
628
  /**
629
   * Returns reference to response headers.
630
   * @return Reference to StreamHeaderMap containing response headers.
631
   */
632
  virtual HeaderMap& responseHeaders() = 0;
633

            
634
  /**
635
   * Returns reference to buffered response body.
636
   * @return Reference to BodyBuffer containing response body.
637
   */
638
  virtual BodyBuffer& bufferedResponseBody() = 0;
639

            
640
  /**
641
   * Returns reference to the latest received response body chunk.
642
   * NOTE: This is only valid in the onResponseBody callback, and it retrieves the latest received
643
   * body chunk that triggers the callback. For other callbacks or outside of the callbacks, you
644
   * should use bufferedResponseBody() to get the currently buffered body in the chain.
645
   * @return Reference to BodyBuffer containing the latest received response body chunk.
646
   */
647
  virtual BodyBuffer& receivedResponseBody() = 0;
648

            
649
  /**
650
   * Returns true if the latest received request body is the previously buffered request body.
651
   * This is true when a previous filter in the chain stopped and buffered the request body, then
652
   * resumed, and this filter is now receiving that buffered body.
653
   * NOTE: This is only meaningful inside the onRequestBody callback.
654
   * @return true if the received request body is the previously buffered request body.
655
   */
656
  virtual bool receivedBufferedRequestBody() = 0;
657

            
658
  /**
659
   * Returns true if the latest received response body is the previously buffered response body.
660
   * This is true when a previous filter in the chain stopped and buffered the response body, then
661
   * resumed, and this filter is now receiving that buffered body.
662
   * NOTE: This is only meaningful inside the onResponseBody callback.
663
   * @return true if the received response body is the previously buffered response body.
664
   */
665
  virtual bool receivedBufferedResponseBody() = 0;
666

            
667
  /**
668
   * Returns reference to response trailers.
669
   * @return Reference to StreamHeaderMap containing response trailers.
670
   */
671
  virtual HeaderMap& responseTrailers() = 0;
672

            
673
  /**
674
   * Returns the most specific route configuration for the stream.
675
   * @return Pointer to RouteSpecificConfig, or nullptr if not available.
676
   */
677
  virtual const RouteSpecificConfig* getMostSpecificConfig() = 0;
678

            
679
  /**
680
   * Returns a scheduler for deferred task execution.
681
   * @return Unique pointer to Scheduler instance.
682
   */
683
  virtual std::shared_ptr<Scheduler> getScheduler() = 0;
684

            
685
  /**
686
   * Initiates an HTTP callout to a cluster with headers, body, and callback.
687
   * @param cluster The cluster name.
688
   * @param headers Span of request headers.
689
   * @param body The request body.
690
   * @param timeoutMs The timeout in milliseconds.
691
   * @param cb Callback invoked when the callout completes. The cb must remain valid
692
   * for the lifetime of the callout.
693
   * @return HttpCalloutInitResult and callout ID pair.
694
   */
695
  virtual std::pair<HttpCalloutInitResult, uint64_t>
696
  httpCallout(std::string_view cluster, std::span<const HeaderView> headers, std::string_view body,
697
              uint64_t timeout_ms, HttpCalloutCallback& cb) = 0;
698

            
699
  /**
700
   * Starts a new HTTP stream to an external service.
701
   * @param cluster The cluster name.
702
   * @param headers Span of request headers.
703
   * @param body The initial request body.
704
   * @param end_of_stream Whether this is the end of the stream.
705
   * @param timeout_ms The timeout in milliseconds.
706
   * @param cb Callback invoked for stream events. The cb must remain valid for the lifetime
707
   * of the stream.
708
   * @return HttpCalloutInitResult and stream ID pair.
709
   */
710
  virtual std::pair<HttpCalloutInitResult, uint64_t>
711
  startHttpStream(std::string_view cluster, std::span<const HeaderView> headers,
712
                  std::string_view body, bool end_of_stream, uint64_t timeout_ms,
713
                  HttpStreamCallback& cb) = 0;
714

            
715
  /**
716
   * Sends data on an existing HTTP stream.
717
   * @param stream_id The ID of the stream.
718
   * @param body The body data to send.
719
   * @param end_of_stream Whether this is the end of the stream.
720
   * @return True if successful, false otherwise.
721
   */
722
  virtual bool sendHttpStreamData(uint64_t stream_id, std::string_view body,
723
                                  bool end_of_stream) = 0;
724

            
725
  /**
726
   * Sends trailers on an existing HTTP stream.
727
   * @param stream_id The ID of the stream.
728
   * @param trailers The trailers to send.
729
   * @return True if successful, false otherwise.
730
   */
731
  virtual bool sendHttpStreamTrailers(uint64_t stream_id, std::span<const HeaderView> trailers) = 0;
732

            
733
  /**
734
   * Resets an existing HTTP stream.
735
   * @param stream_id The ID of the stream.
736
   */
737
  virtual void resetHttpStream(uint64_t stream_id) = 0;
738

            
739
  /**
740
   * Sets the downstream watermark callbacks for the stream.
741
   * @param callbacks The downstream watermark callbacks.
742
   */
743
  virtual void setDownstreamWatermarkCallbacks(DownstreamWatermarkCallbacks& callbacks) = 0;
744

            
745
  /**
746
   * Unsets the downstream watermark callbacks for the stream.
747
   */
748
  virtual void clearDownstreamWatermarkCallbacks() = 0;
749

            
750
  /**
751
   * Records a histogram value with optional tags.
752
   * @param id The metric ID.
753
   * @param value The value to record.
754
   * @param tags_values Optional span of tag values.
755
   * @return MetricsResult indicating success or failure.
756
   */
757
  virtual MetricsResult recordHistogramValue(MetricID id, uint64_t value,
758
                                             std::span<const BufferView> tags_values = {}) = 0;
759

            
760
  /**
761
   * Sets a gauge value with optional tags.
762
   * @param id The metric ID.
763
   * @param value The gauge value.
764
   * @param tags_values Optional span of tag values.
765
   * @return MetricsResult indicating success or failure.
766
   */
767
  virtual MetricsResult setGaugeValue(MetricID id, uint64_t value,
768
                                      std::span<const BufferView> tags_values = {}) = 0;
769

            
770
  /**
771
   * Increments a gauge value with optional tags.
772
   * @param id The metric ID.
773
   * @param value The increment amount.
774
   * @param tags_values Optional span of tag values.
775
   * @return MetricsResult indicating success or failure.
776
   */
777
  virtual MetricsResult incrementGaugeValue(MetricID id, uint64_t value,
778
                                            std::span<const BufferView> tags_values = {}) = 0;
779

            
780
  /**
781
   * Decrements a gauge value with optional tags.
782
   * @param id The metric ID.
783
   * @param value The decrement amount.
784
   * @param tags_values Optional span of tag values.
785
   * @return MetricsResult indicating success or failure.
786
   */
787
  virtual MetricsResult decrementGaugeValue(MetricID id, uint64_t value,
788
                                            std::span<const BufferView> tags_values = {}) = 0;
789

            
790
  /**
791
   * Increments a counter value with optional tags.
792
   * @param id The metric ID.
793
   * @param value The increment amount.
794
   * @param tags_values Optional span of tag values.
795
   * @return MetricsResult indicating success or failure.
796
   */
797
  virtual MetricsResult incrementCounterValue(MetricID id, uint64_t value,
798
                                              std::span<const BufferView> tags_values = {}) = 0;
799

            
800
  /**
801
   * Checks if logging is enabled for the given log level.
802
   * @param level The log level to check.
803
   * @return True if logging is enabled, false otherwise.
804
   */
805
  virtual bool logEnabled(LogLevel level) = 0;
806

            
807
  /**
808
   * Logs a message at the specified log level.
809
   * @param level The log level.
810
   * @param message The message to log.
811
   */
812
  virtual void log(LogLevel level, std::string_view message) = 0;
813
};
814

            
815
class HttpFilterConfigHandle {
816
public:
817
  virtual ~HttpFilterConfigHandle();
818

            
819
  /**
820
   * Defines a histogram metric with a name and optional tag keys.
821
   * @param name The metric name.
822
   * @param tags_keys Optional span of tag keys.
823
   * @return Pair of MetricID and MetricsResult indicating success or failure.
824
   */
825
  virtual std::pair<MetricID, MetricsResult>
826
  defineHistogram(std::string_view name, std::span<const BufferView> tags_keys = {}) = 0;
827

            
828
  /**
829
   * Defines a gauge metric with a name and optional tag keys.
830
   * @param name The metric name.
831
   * @param tags_keys Optional span of tag keys.
832
   * @return Pair of MetricID and MetricsResult indicating success or failure.
833
   */
834
  virtual std::pair<MetricID, MetricsResult>
835
  defineGauge(std::string_view name, std::span<const BufferView> tags_keys = {}) = 0;
836

            
837
  /**
838
   * Defines a counter metric with a name and optional tag keys.
839
   * @param name The metric name.
840
   * @param tags_keys Optional span of tag keys.
841
   * @return Pair of MetricID and MetricsResult indicating success or failure.
842
   */
843
  virtual std::pair<MetricID, MetricsResult>
844
  defineCounter(std::string_view name, std::span<const BufferView> tags_keys = {}) = 0;
845

            
846
  /**
847
   * Checks if logging is enabled for the given log level.
848
   * @param level The log level to check.
849
   * @return True if logging is enabled, false otherwise.
850
   */
851
  virtual bool logEnabled(LogLevel level) = 0;
852

            
853
  /**
854
   * Logs a message at the specified log level.
855
   * @param level The log level.
856
   * @param message The message to log.
857
   */
858
  virtual void log(LogLevel level, std::string_view message) = 0;
859

            
860
  /**
861
   * Initiates a one-shot HTTP callout to a cluster. The response will be delivered via
862
   * HttpFilterConfigFactory::onHttpCalloutDone.
863
   * @param cluster The cluster name.
864
   * @param headers The request headers. Must include :method, :path, and host headers.
865
   * @param body The request body.
866
   * @param timeout_ms The timeout in milliseconds.
867
   * @param cb The callback to invoke when the callout completes.
868
   * @return HttpCalloutInitResult and callout ID pair.
869
   */
870
  virtual std::pair<HttpCalloutInitResult, uint64_t>
871
  httpCallout(std::string_view cluster, std::span<const HeaderView> headers, std::string_view body,
872
              uint64_t timeout_ms, HttpCalloutCallback& cb) = 0;
873

            
874
  /**
875
   * Starts a streamable HTTP callout to a cluster. Stream events will be delivered via
876
   * HttpFilterConfigFactory::onHttpStream* methods.
877
   * @param cluster The cluster name.
878
   * @param headers The request headers. Must include :method, :path, and host headers.
879
   * @param body The initial request body (may be empty).
880
   * @param end_of_stream If true, the stream ends after sending the initial headers/body.
881
   * @param timeout_ms The timeout in milliseconds (0 for no timeout).
882
   * @param cb The callback to invoke for stream events.
883
   * @return HttpCalloutInitResult and stream ID pair.
884
   */
885
  virtual std::pair<HttpCalloutInitResult, uint64_t>
886
  startHttpStream(std::string_view cluster, std::span<const HeaderView> headers,
887
                  std::string_view body, bool end_of_stream, uint64_t timeout_ms,
888
                  HttpStreamCallback& cb) = 0;
889

            
890
  /**
891
   * Sends data on an active stream started via startHttpStream.
892
   * @param stream_id The stream handle returned from startHttpStream.
893
   * @param body The data to send.
894
   * @param end_of_stream If true, this is the last data chunk.
895
   * @return True if successful, false if the stream is not found.
896
   */
897
  virtual bool sendHttpStreamData(uint64_t stream_id, std::string_view body,
898
                                  bool end_of_stream) = 0;
899

            
900
  /**
901
   * Sends trailers on an active stream, implicitly ending the stream.
902
   * @param stream_id The stream handle returned from startHttpStream.
903
   * @param trailers The trailers to send.
904
   * @return True if successful, false if the stream is not found.
905
   */
906
  virtual bool sendHttpStreamTrailers(uint64_t stream_id, std::span<const HeaderView> trailers) = 0;
907

            
908
  /**
909
   * Resets an active stream started via startHttpStream.
910
   * @param stream_id The stream handle returned from startHttpStream.
911
   */
912
  virtual void resetHttpStream(uint64_t stream_id) = 0;
913

            
914
  /**
915
   * Returns a scheduler for deferred task execution. This can only be called on config loading
916
   * event and then the returned Scheduler can be used in other threads.
917
   * @return Unique pointer to Scheduler instance.
918
   */
919
  virtual std::shared_ptr<Scheduler> getScheduler() = 0;
920
};
921

            
922
/**
923
 * Interface definitions that plugin developers to implement
924
 */
925
enum class HeadersStatus : uint32_t {
926
  Continue = 0,
927
  Stop = 1,
928
  StopAllAndBuffer = 3,
929
  StopAllAndWatermark = 4,
930
};
931

            
932
enum class BodyStatus : uint32_t {
933
  Continue = 0,
934
  StopAndBuffer = 1,
935
  StopAndWatermark = 2,
936
  StopNoBuffer = 3,
937
};
938

            
939
enum class TrailersStatus : uint32_t {
940
  Continue = 0,
941
  Stop = 1,
942
};
943

            
944
class HttpFilter {
945
public:
946
  virtual ~HttpFilter();
947

            
948
  /**
949
   * Processes request headers. Returns status indicating how to proceed.
950
   * @param headers The request headers.
951
   * @param end_stream Indicates if this is the end of the stream.
952
   * @return HeadersStatus indicating how to proceed.
953
   */
954
  virtual HeadersStatus onRequestHeaders(HeaderMap& headers, bool end_stream) = 0;
955

            
956
  /**
957
   * Processes request body. Returns status indicating how to proceed.
958
   * @param body The request body buffer.
959
   * @param end_stream Indicates if this is the end of the stream.
960
   * @return BodyStatus indicating how to proceed.
961
   */
962
  virtual BodyStatus onRequestBody(BodyBuffer& body, bool end_stream) = 0;
963

            
964
  /**
965
   * Processes request trailers. Returns status indicating how to proceed.
966
   * @param trailers The request trailers.
967
   * @return TrailersStatus indicating how to proceed.
968
   */
969
  virtual TrailersStatus onRequestTrailers(HeaderMap& trailers) = 0;
970

            
971
  /**
972
   * Processes response headers. Returns status indicating how to proceed.
973
   * @param headers The response headers.
974
   * @param end_stream Indicates if this is the end of the stream.
975
   * @return HeadersStatus indicating how to proceed.
976
   */
977
  virtual HeadersStatus onResponseHeaders(HeaderMap& headers, bool end_stream) = 0;
978

            
979
  /**
980
   * Processes response body. Returns status indicating how to proceed.
981
   * @param body The response body buffer.
982
   * @param end_stream Indicates if this is the end of the stream.
983
   * @return BodyStatus indicating how to proceed.
984
   */
985
  virtual BodyStatus onResponseBody(BodyBuffer& body, bool end_stream) = 0;
986

            
987
  /**
988
   * Processes response trailers. Returns status indicating how to proceed.
989
   * @param trailers The response trailers.
990
   * @return TrailersStatus indicating how to proceed.
991
   */
992
  virtual TrailersStatus onResponseTrailers(HeaderMap& trailers) = 0;
993

            
994
  /**
995
   * Called when the stream processing is complete and before access logs are flushed.
996
   * This is a good place to do any final processing or cleanup before the request is fully
997
   * completed.
998
   */
999
  virtual void onStreamComplete() = 0;
  /**
   * Called when the HTTP filter instance is being destroyed. This is called
   * after onStreamComplete and access logs are flushed. This is a good place to release
   * any per-stream resources.
   */
  virtual void onDestroy() = 0;
};
class HttpFilterFactory {
public:
  virtual ~HttpFilterFactory();
  /**
   * Creates a StreamPlugin instance for a given stream handle.
   * @param handle The stream plugin handle.
   * @return Unique pointer to a new StreamPlugin instance.
   */
  virtual std::unique_ptr<HttpFilter> create(HttpFilterHandle& handle) = 0;
};
class HttpFilterConfigFactory {
public:
  virtual ~HttpFilterConfigFactory();
  /**
   * Creates a HttpFilterFactory from configuration data.
   * @param handle The stream config handle.
   * @param config_view The unparsed configuration string.
   * @return Unique pointer to a new HttpFilterFactory instance.
   */
  virtual std::unique_ptr<HttpFilterFactory> create(HttpFilterConfigHandle& handle,
                                                    std::string_view config_view) = 0;
  /**
   * Creates route-specific configuration from unparsed config data.
   * @param handle The stream config handle.
   * @param config_view The unparsed configuration string.
   * @return Unique pointer to a new RouteSpecificConfig instance.
   */
  virtual std::unique_ptr<RouteSpecificConfig>
  createPerRoute([[maybe_unused]] std::string_view config_view) {
    return nullptr;
  }
};
using HttpFilterConfigFactoryPtr = std::unique_ptr<HttpFilterConfigFactory>;
namespace Utility {
/**
 * Reads the whole request body by combining the buffered body and the latest received body.
 * This will copy all request body content into a module owned string.
 *
 * This should only be called after we see the end of the request, which means the end_of_stream
 * flag is true in the onRequestBody callback or we are in the onRequestTrailers callback.
 * @param handle The HTTP filter handle.
 * @return The combined request body as a string.
 */
std::string readWholeRequestBody(HttpFilterHandle& handle);
/**
 * Reads the whole response body by combining the buffered body and the latest received body.
 * This will copy all response body content into a module owned string.
 *
 * This should only be called after we see the end of the response, which means the end_of_stream
 * flag is true in the onResponseBody callback or we are in the onResponseTrailers callback.
 * @param handle The HTTP filter handle.
 * @return The combined response body as a string.
 */
std::string readWholeResponseBody(HttpFilterHandle& handle);
} // namespace Utility
class HttpFilterConfigFactoryRegistry {
public:
  static const std::map<std::string_view, HttpFilterConfigFactoryPtr>& getRegistry();
private:
  static std::map<std::string_view, HttpFilterConfigFactoryPtr>& getMutableRegistry();
  friend class HttpFilterConfigFactoryRegister;
};
class HttpFilterConfigFactoryRegister {
public:
  HttpFilterConfigFactoryRegister(std::string_view name, HttpFilterConfigFactoryPtr factory);
  ~HttpFilterConfigFactoryRegister();
private:
  const std::string name_;
};
// Macro to register a HttpFilterConfigFactory
#define REGISTER_HTTP_FILTER_CONFIG_FACTORY(FACTORY_CLASS, NAME)                                   \
  static Envoy::DynamicModules::HttpFilterConfigFactoryRegister                                    \
      HttpFilterConfigFactoryRegister_##FACTORY_CLASS##_register_NAME(                             \
          NAME,                                                                                    \
          std::unique_ptr<Envoy::DynamicModules::HttpFilterConfigFactory>(new FACTORY_CLASS()));
// Macro to log messages
#define DYM_LOG(HANDLE, LEVEL, FORMAT_STRING, ...)                                                 \
  do {                                                                                             \
    if (HANDLE.logEnabled(LEVEL)) {                                                                \
      HANDLE.log(LEVEL, std::format(FORMAT_STRING, ##__VA_ARGS__));                                \
    }                                                                                              \
  } while (0)
} // namespace DynamicModules
} // namespace Envoy