1
#pragma once
2

            
3
#include <cstdint>
4
#include <functional>
5
#include <memory>
6
#include <string>
7

            
8
#include "envoy/access_log/access_log.h"
9
#include "envoy/buffer/buffer.h"
10
#include "envoy/common/scope_tracker.h"
11
#include "envoy/event/dispatcher.h"
12
#include "envoy/grpc/status.h"
13
#include "envoy/http/codec.h"
14
#include "envoy/http/filter_factory.h"
15
#include "envoy/http/header_map.h"
16
#include "envoy/matcher/matcher.h"
17
#include "envoy/router/router.h"
18
#include "envoy/router/scopes.h"
19
#include "envoy/ssl/connection.h"
20
#include "envoy/tracing/tracer.h"
21
#include "envoy/upstream/load_balancer.h"
22
#include "envoy/upstream/upstream.h"
23

            
24
#include "source/common/common/scope_tracked_object_stack.h"
25

            
26
#include "absl/types/optional.h"
27

            
28
namespace Envoy {
29
namespace Router {
30
class RouteConfigProvider;
31
}
32
namespace Http {
33

            
34
/**
35
 * Return codes for encode/decode headers filter invocations. The connection manager bases further
36
 * filter invocations on the return code of the previous filter.
37
 */
38
enum class FilterHeadersStatus {
39
  // Continue filter chain iteration.
40
  Continue,
41
  // Do not iterate for headers on any of the remaining filters in the chain.
42
  //
43
  // Returning FilterDataStatus::Continue from decodeData()/encodeData() or calling
44
  // continueDecoding()/continueEncoding() MUST be called if continued filter iteration is desired.
45
  //
46
  // Note that if a local reply was sent, no further iteration for headers as well as data and
47
  // trailers for the current filter and the filters following will happen. A local reply can be
48
  // triggered via sendLocalReply() or encodeHeaders().
49
  StopIteration,
50
  // Continue headers iteration to remaining filters, but delay ending the stream. This status MUST
51
  // NOT be returned when end_stream is already set to false.
52
  //
53
  // Used when a filter wants to add a body to a headers-only request/response, but this body is not
54
  // readily available. Delaying end_stream allows the filter to add the body once it's available
55
  // without stopping headers iteration.
56
  //
57
  // The filter is responsible to continue the stream by providing a body through calling
58
  // injectDecodedDataToFilterChain()/injectEncodedDataToFilterChain(), possibly multiple times
59
  // if the body needs to be divided into several chunks. The filter may need to handle
60
  // watermark events when injecting a body, see:
61
  // https://github.com/envoyproxy/envoy/blob/main/source/docs/flow_control.md.
62
  //
63
  // The last call to inject data MUST have end_stream set to true to conclude the stream.
64
  // If the filter cannot provide a body the stream should be reset.
65
  //
66
  // Adding a body through calling addDecodedData()/addEncodedData() then
67
  // continueDecoding()/continueEncoding() is currently NOT supported and causes an assert failure.
68
  //
69
  // Adding trailers in this scenario is currently NOT supported.
70
  //
71
  // The filter MUST NOT attempt to continue the stream without providing a body using
72
  // continueDecoding()/continueEncoding().
73
  //
74
  // TODO(yosrym93): Support adding a body in this case by calling addDecodedData()/addEncodedData()
75
  // then continueDecoding()/continueEncoding(). To support this a new FilterManager::IterationState
76
  // needs to be added and set when a filter returns this status in
77
  // FilterManager::decodeHeaders/FilterManager::encodeHeaders()
78
  // Currently, when a filter returns this, the IterationState is Continue. This causes ASSERTs in
79
  // FilterManager::commonContinue() to fail when continueDecoding()/continueEncoding() is called;
80
  // due to trying to continue iteration when the IterationState is already Continue.
81
  // In this case, a different ASSERT will be needed to make sure the filter does not try to
82
  // continue without adding a body first.
83
  //
84
  // TODO(yosrym93): Support adding trailers in this case by implementing new functions to inject
85
  // trailers, similar to the inject data functions.
86
  ContinueAndDontEndStream,
87
  // Do not iterate for headers as well as data and trailers for the current filter and the filters
88
  // following, and buffer body data for later dispatching. ContinueDecoding() MUST
89
  // be called if continued filter iteration is desired.
90
  //
91
  // Used when a filter wants to stop iteration on data and trailers while waiting for headers'
92
  // iteration to resume.
93
  //
94
  // If buffering the request causes buffered data to exceed the configured buffer limit, a 413 will
95
  // be sent to the user. On the response path exceeding buffer limits will result in a 500.
96
  //
97
  // TODO(soya3129): stop metadata parsing when StopAllIterationAndBuffer is set.
98
  StopAllIterationAndBuffer,
99
  // Do not iterate for headers as well as data and trailers for the current filter and the filters
100
  // following, and buffer body data for later dispatching. continueDecoding() MUST
101
  // be called if continued filter iteration is desired.
102
  //
103
  // Used when a filter wants to stop iteration on data and trailers while waiting for headers'
104
  // iteration to resume.
105
  //
106
  // This will cause the flow of incoming data to cease until continueDecoding() function is called.
107
  //
108
  // TODO(soya3129): stop metadata parsing when StopAllIterationAndWatermark is set.
109
  StopAllIterationAndWatermark,
110
};
111

            
112
/**
113
 * Return codes for encode on informative headers filter invocations.
114
 */
115
enum class Filter1xxHeadersStatus {
116
  // Continue filter chain iteration.
117
  Continue,
118
  // Do not iterate for informative headers on any of the remaining filters in the chain.
119
  //
120
  // Returning FilterDataStatus::Continue from encodeData() or calling
121
  // continueEncoding() MUST be called if continued filter iteration is desired.
122
  StopIteration
123
};
124

            
125
/**
126
 * Return codes for encode/decode data filter invocations. The connection manager bases further
127
 * filter invocations on the return code of the previous filter.
128
 */
129
enum class FilterDataStatus {
130
  // Continue filter chain iteration. If headers have not yet been sent to the next filter, they
131
  // will be sent first via decodeHeaders()/encodeHeaders(). If data has previously been buffered,
132
  // the data in this callback will be added to the buffer before the entirety is sent to the next
133
  // filter.
134
  Continue,
135
  // Do not iterate to any of the remaining filters in the chain, and buffer body data for later
136
  // dispatching. Returning FilterDataStatus::Continue from decodeData()/encodeData() or calling
137
  // continueDecoding()/continueEncoding() MUST be called if continued filter iteration is desired.
138
  //
139
  // This should be called by filters which must parse a larger block of the incoming data before
140
  // continuing processing and so can not push back on streaming data via watermarks.
141
  //
142
  // If buffering the request causes buffered data to exceed the configured buffer limit, a 413 will
143
  // be sent to the user. On the response path exceeding buffer limits will result in a 500.
144
  StopIterationAndBuffer,
145
  // Do not iterate to any of the remaining filters in the chain, and buffer body data for later
146
  // dispatching. Returning FilterDataStatus::Continue from decodeData()/encodeData() or calling
147
  // continueDecoding()/continueEncoding() MUST be called if continued filter iteration is desired.
148
  //
149
  // This will cause the flow of incoming data to cease until one of the continue.*() functions is
150
  // called.
151
  //
152
  // This should be returned by filters which can nominally stream data but have a transient back-up
153
  // such as the configured delay of the fault filter, or if the router filter is still fetching an
154
  // upstream connection.
155
  StopIterationAndWatermark,
156
  // Do not iterate to any of the remaining filters in the chain, but do not buffer any of the
157
  // body data for later dispatching. Returning FilterDataStatus::Continue from
158
  // decodeData()/encodeData() or calling continueDecoding()/continueEncoding() MUST be called if
159
  // continued filter iteration is desired.
160
  //
161
  // Note that if a local reply was sent, no further iteration for either data or trailers
162
  // for the current filter and the filters following will happen. A local reply can be
163
  // triggered via sendLocalReply() or encodeHeaders().
164
  StopIterationNoBuffer
165
};
166

            
167
/**
168
 * Return codes for encode/decode trailers filter invocations. The connection manager bases further
169
 * filter invocations on the return code of the previous filter.
170
 */
171
enum class FilterTrailersStatus {
172
  // Continue filter chain iteration.
173
  Continue,
174
  // Do not iterate to any of the remaining filters in the chain. Calling
175
  // continueDecoding()/continueEncoding() MUST be called if continued filter iteration is desired.
176
  StopIteration
177
};
178

            
179
/**
180
 * Return codes for encode metadata filter invocations. Metadata currently can not stop filter
181
 * iteration except in the case of local replies.
182
 */
183
enum class FilterMetadataStatus {
184
  // Continue filter chain iteration for metadata only. Does not unblock returns of StopIteration*
185
  // from (decode|encode)(Headers|Data).
186
  Continue,
187

            
188
  // Continue filter chain iteration. If headers have not yet been sent to the next filter, they
189
  // will be sent first via (decode|encode)Headers().
190
  ContinueAll,
191

            
192
  // Stops iteration of the entire filter chain. Only to be used in the case of sending a local
193
  // reply from (decode|encode)Metadata.
194
  StopIterationForLocalReply,
195
};
196

            
197
/**
198
 * Return codes for onLocalReply filter invocations.
199
 */
200
enum class LocalErrorStatus {
201
  // Continue sending the local reply after onLocalReply has been sent to all filters.
202
  Continue,
203

            
204
  // Continue sending onLocalReply to all filters, but reset the stream once all filters have been
205
  // informed rather than sending the local reply.
206
  ContinueAndResetStream,
207
};
208

            
209
// These are events that upstream HTTP filters can register for, via the addUpstreamCallbacks
210
// function.
211
class UpstreamCallbacks {
212
public:
213
47611
  virtual ~UpstreamCallbacks() = default;
214

            
215
  // Called when the upstream connection is established and
216
  // UpstreamStreamFilterCallbacks::upstream should be available.
217
  //
218
  // This indicates that data may begin flowing upstream.
219
  virtual void onUpstreamConnectionEstablished() PURE;
220
};
221

            
222
// These are filter callbacks specific to upstream HTTP filters, accessible via
223
// StreamFilterCallbacks::upstreamCallbacks()
224
class UpstreamStreamFilterCallbacks {
225
public:
226
47497
  virtual ~UpstreamStreamFilterCallbacks() = default;
227

            
228
  // Returns a handle to the upstream stream's stream info.
229
  virtual StreamInfo::StreamInfo& upstreamStreamInfo() PURE;
230

            
231
  // Returns a handle to the generic upstream.
232
  virtual OptRef<Router::GenericUpstream> upstream() PURE;
233

            
234
  // Dumps state for the upstream request.
235
  virtual void dumpState(std::ostream& os, int indent_level = 0) const PURE;
236

            
237
  // Setters and getters to determine if sending body payload is paused on
238
  // confirmation of a CONNECT upgrade. These should only be used by the upstream codec filter.
239
  // TODO(alyssawilk) after deprecating the classic path, move this logic to the
240
  // upstream codec filter and remove these APIs
241
  virtual bool pausedForConnect() const PURE;
242
  virtual void setPausedForConnect(bool value) PURE;
243

            
244
  // Setters and getters to determine if sending body payload is paused on
245
  // confirmation of a WebSocket upgrade. These should only be used by the upstream codec filter.
246
  virtual bool pausedForWebsocketUpgrade() const PURE;
247
  virtual void setPausedForWebsocketUpgrade(bool value) PURE;
248

            
249
  // Disable the route timeout after websocket upgrade completes successfully.
250
  // This should only be used by the upstream codec filter.
251
  virtual void disableRouteTimeoutForWebsocketUpgrade() PURE;
252

            
253
  // Disable per-try timeouts after websocket upgrade completes successfully.
254
  // This should only be used by the upstream codec filter.
255
  virtual void disablePerTryTimeoutForWebsocketUpgrade() PURE;
256

            
257
  // Return the upstreamStreamOptions for this stream.
258
  virtual const Http::ConnectionPool::Instance::StreamOptions& upstreamStreamOptions() const PURE;
259

            
260
  // Adds the supplied UpstreamCallbacks to the list of callbacks to be called
261
  // as various upstream events occur. Callbacks should persist for the lifetime
262
  // of the upstream stream.
263
  virtual void addUpstreamCallbacks(UpstreamCallbacks& callbacks) PURE;
264

            
265
  // This should only be called by the UpstreamCodecFilter, and is used to let the
266
  // UpstreamCodecFilter supply the interface used by the GenericUpstream to receive
267
  // response data from the upstream stream once it is established.
268
  virtual void
269
  setUpstreamToDownstream(Router::UpstreamToDownstream& upstream_to_downstream_interface) PURE;
270
};
271

            
272
/**
273
 * RouteConfigUpdatedCallback is used to notify an OnDemandRouteUpdate filter about completion of a
274
 * RouteConfig update. The filter (and the associated ActiveStream) where the original on-demand
275
 * request was originated can be destroyed before a response to an on-demand update request is
276
 * received and updates are propagated. To handle this:
277
 *
278
 * OnDemandRouteUpdate filter instance holds a RouteConfigUpdatedCallbackSharedPtr to a callback.
279
 * Envoy::Router::RdsRouteConfigProviderImpl holds a weak pointer to the RouteConfigUpdatedCallback
280
 * above in an Envoy::Router::UpdateOnDemandCallback struct
281
 *
282
 * In RdsRouteConfigProviderImpl::onConfigUpdate(), before invoking the callback, a check is made to
283
 * verify if the callback is still available.
284
 */
285
using RouteConfigUpdatedCallback = std::function<void(bool)>;
286
using RouteConfigUpdatedCallbackSharedPtr = std::shared_ptr<RouteConfigUpdatedCallback>;
287

            
288
// This class allows entities caching a route (e.g.) ActiveStream to delegate route clearing to xDS
289
// components.
290
class RouteCache {
291
public:
292
94065
  virtual ~RouteCache() = default;
293

            
294
  // Returns true if the route cache currently has a cached route.
295
  virtual bool hasCachedRoute() const PURE;
296
  // Forces the route cache to refresh the cached route.
297
  virtual void refreshCachedRoute() PURE;
298
};
299

            
300
class RouteConfigUpdateRequester {
301
public:
302
93624
  virtual ~RouteConfigUpdateRequester() = default;
303

            
304
  virtual void
305
  requestRouteConfigUpdate(RouteCache& route_cache,
306
                           Http::RouteConfigUpdatedCallbackSharedPtr route_config_updated_cb,
307
                           absl::optional<Router::ConfigConstSharedPtr> route_config,
308
                           Event::Dispatcher& dispatcher, RequestHeaderMap& request_headers) PURE;
309
  virtual void
310
  requestVhdsUpdate(const std::string& host_header, Event::Dispatcher& thread_local_dispatcher,
311
                    Http::RouteConfigUpdatedCallbackSharedPtr route_config_updated_cb) PURE;
312
  virtual void
313
  requestSrdsUpdate(RouteCache& route_cache, Router::ScopeKeyPtr scope_key,
314
                    Event::Dispatcher& thread_local_dispatcher,
315
                    Http::RouteConfigUpdatedCallbackSharedPtr route_config_updated_cb) PURE;
316
};
317

            
318
class RouteConfigUpdateRequesterFactory : public Config::UntypedFactory {
319
public:
320
  // UntypedFactory
321
1006
  std::string category() const override { return "envoy.route_config_update_requester"; }
322

            
323
  virtual std::unique_ptr<RouteConfigUpdateRequester>
324
  createRouteConfigUpdateRequester(Router::RouteConfigProvider* route_config_provider) PURE;
325
  virtual std::unique_ptr<RouteConfigUpdateRequester>
326
  createRouteConfigUpdateRequester(Config::ConfigProvider* scoped_route_config_provider,
327
                                   OptRef<const Router::ScopeKeyBuilder> scope_key_builder) PURE;
328
};
329

            
330
class DownstreamStreamFilterCallbacks {
331
public:
332
101077
  virtual ~DownstreamStreamFilterCallbacks() = default;
333

            
334
  /**
335
   * Sets the cached route for the current request to the passed-in RouteConstSharedPtr parameter.
336
   *
337
   * Similar to route(const Router::RouteCallback& cb), this route that is set will be
338
   * overridden by clearRouteCache() in subsequent filters. Usage is intended for filters at the end
339
   * of the filter chain.
340
   *
341
   * NOTE: Passing nullptr in as the route parameter is equivalent to route resolution being
342
   * attempted and failing to find a route. An example of when this happens is when
343
   * RouteConstSharedPtr route(const RouteCallback& cb, const Http::RequestHeaderMap& headers, const
344
   * StreamInfo::StreamInfo& stream_info, uint64_t random_value) returns nullptr during a
345
   * refreshCachedRoute. It is important to note that setRoute(nullptr) is different from a
346
   * clearRouteCache(), because clearRouteCache() wants route resolution to be attempted again.
347
   * clearRouteCache() achieves this by setting cached_route_ and cached_cluster_info_ to
348
   * absl::optional ptrs instead of null ptrs.
349
   */
350
  virtual void setRoute(Router::RouteConstSharedPtr route) PURE;
351

            
352
  /**
353
   * Invokes callback with a matched route, callback can choose to accept this route by returning
354
   * Router::RouteMatchStatus::Accept or continue route match from last matched route by returning
355
   * Router::RouteMatchStatus::Continue, if there are more routes available.
356
   *
357
   * Returns route accepted by the callback or nullptr if no match found or none of route is
358
   * accepted by the callback.
359
   *
360
   * NOTE: clearRouteCache() must be called before invoking this method otherwise cached route will
361
   * be returned directly to the caller and the callback will not be invoked.
362
   *
363
   * Currently a route callback's decision is overridden by clearRouteCache() / route() call in the
364
   * subsequent filters. We may want to persist callbacks so they always participate in later route
365
   * resolution or make it an independent entity like filters that gets called on route resolution.
366
   */
367
  virtual Router::RouteConstSharedPtr route(const Router::RouteCallback& cb) PURE;
368

            
369
  /**
370
   * Clears the route cache for the current request. This must be called when a filter has modified
371
   * the headers in a way that would affect routing.
372
   */
373
  virtual void clearRouteCache() PURE;
374

            
375
  /**
376
   * Refresh the target cluster but not the route cache. This is used when we want to change the
377
   * target cluster after modifying the request attributes.
378
   *
379
   * NOTE: this is suggested to replace clearRouteCache() if you only want to determine the target
380
   * cluster based on the latest request attributes that have been updated by the filters and do
381
   * not want to configure multiple similar routes at the route table.
382
   *
383
   * NOTE: this depends on the route cluster specifier to support the refreshRouteCluster()
384
   * method.
385
   */
386
  virtual void refreshRouteCluster() PURE;
387

            
388
  /**
389
   * Schedules a request for a RouteConfiguration update from the management server.
390
   * @param route_config_updated_cb callback to be called when the configuration update has been
391
   * propagated to the worker thread.
392
   */
393
  virtual void
394
  requestRouteConfigUpdate(RouteConfigUpdatedCallbackSharedPtr route_config_updated_cb) PURE;
395
};
396

            
397
/**
398
 * The stream filter callbacks are passed to all filters to use for writing response data and
399
 * interacting with the underlying stream in general.
400
 */
401
class StreamFilterCallbacks {
402
public:
403
172898
  virtual ~StreamFilterCallbacks() = default;
404

            
405
  /**
406
   * @return OptRef<const Network::Connection> the downstream connection, or nullptr if there is
407
   * none.
408
   */
409
  virtual OptRef<const Network::Connection> connection() PURE;
410

            
411
  /**
412
   * @return Event::Dispatcher& the thread local dispatcher for allocating timers, etc.
413
   */
414
  virtual Event::Dispatcher& dispatcher() PURE;
415

            
416
  /**
417
   * Reset the underlying stream.
418
   */
419
  virtual void
420
  resetStream(Http::StreamResetReason reset_reason = Http::StreamResetReason::LocalReset,
421
              absl::string_view transport_failure_reason = "") PURE;
422

            
423
  /**
424
   * Returns the route for the current request. The assumption is that the implementation can do
425
   * caching where applicable to avoid multiple lookups. If a filter has modified the headers in
426
   * a way that affects routing, clearRouteCache() must be called to clear the cache.
427
   */
428
  virtual Router::RouteConstSharedPtr route() PURE;
429

            
430
  /**
431
   * Returns the clusterInfo for the cached route.
432
   * This method is to avoid multiple look ups in the filter chain, it also provides a consistent
433
   * view of clusterInfo after a route is picked/repicked.
434
   * NOTE: Cached clusterInfo and route will be updated the same time.
435
   */
436
  virtual Upstream::ClusterInfoConstSharedPtr clusterInfo() PURE;
437

            
438
  /**
439
   * @return uint64_t the ID of the originating stream for logging purposes.
440
   */
441
  virtual uint64_t streamId() const PURE;
442

            
443
  /**
444
   * @return streamInfo for logging purposes. Individual filter may add specific information to be
445
   * put into the access log.
446
   */
447
  virtual StreamInfo::StreamInfo& streamInfo() PURE;
448

            
449
  /**
450
   * @return span context used for tracing purposes. Individual filters may add or modify
451
   *              information in the span context.
452
   */
453
  virtual Tracing::Span& activeSpan() PURE;
454

            
455
  /**
456
   * @return tracing configuration if present.
457
   */
458
  virtual OptRef<const Tracing::Config> tracingConfig() const PURE;
459

            
460
  /**
461
   * @return the ScopeTrackedObject for this stream.
462
   */
463
  virtual const ScopeTrackedObject& scope() PURE;
464

            
465
  /**
466
   * Should be used when we continue processing a request or response by invoking a filter directly
467
   * from an asynchronous callback to restore crash context. If not explicitly used by the filter
468
   * itself, this gets invoked in ActiveStreamFilterBase::commonContinue().
469
   *
470
   * @param tracked_object_stack ScopeTrackedObjectStack where relevant ScopeTrackedObjects will be
471
   * added to.
472
   */
473
  virtual void restoreContextOnContinue(ScopeTrackedObjectStack& tracked_object_stack) PURE;
474

            
475
  /**
476
   * Called when filter activity indicates that the stream idle timeout should be reset.
477
   */
478
  virtual void resetIdleTimer() PURE;
479

            
480
  /**
481
   * This is a helper to get the route's per-filter config if it exists, otherwise the virtual
482
   * host's. Or nullptr if none of them exist.
483
   */
484
  virtual const Router::RouteSpecificFilterConfig* mostSpecificPerFilterConfig() const PURE;
485

            
486
  /**
487
   * Return all the available per route filter configs. The configs is in order of specificity.
488
   * That means that the config from a route configuration will be first, then the config from a
489
   * virtual host, then the config from a route.
490
   */
491
  virtual Router::RouteSpecificFilterConfigs perFilterConfigs() const PURE;
492

            
493
  /**
494
   * Return the HTTP/1 stream encoder options if applicable. If the stream is not HTTP/1 returns
495
   * absl::nullopt.
496
   */
497
  virtual Http1StreamEncoderOptionsOptRef http1StreamEncoderOptions() PURE;
498

            
499
  /**
500
   * Return a handle to the upstream callbacks. This is valid for upstream HTTP filters, and nullopt
501
   * for downstream HTTP filters.
502
   */
503
  virtual OptRef<UpstreamStreamFilterCallbacks> upstreamCallbacks() PURE;
504

            
505
  /**
506
   * Return a handle to the downstream callbacks. This is valid for downstream HTTP filters, and
507
   * nullopt for upstream HTTP filters.
508
   */
509
  virtual OptRef<DownstreamStreamFilterCallbacks> downstreamCallbacks() PURE;
510

            
511
  /**
512
   * @return absl::string_view the name of the filter as configured in the filter chain.
513
   */
514
  virtual absl::string_view filterConfigName() const PURE;
515

            
516
  /**
517
   * The downstream request headers if present.
518
   */
519
  virtual RequestHeaderMapOptRef requestHeaders() PURE;
520

            
521
  /**
522
   * The downstream request trailers if present.
523
   */
524
  virtual RequestTrailerMapOptRef requestTrailers() PURE;
525

            
526
  /**
527
   * Retrieves a pointer to the continue headers if present.
528
   */
529
  virtual ResponseHeaderMapOptRef informationalHeaders() PURE;
530

            
531
  /**
532
   * Retrieves a pointer to the response headers if present.
533
   * Note that response headers might be set multiple times (e.g. if a local reply is issued after
534
   * headers have been received but before headers have been encoded), so it is not safe in general
535
   * to assume that any set of headers will be valid for the duration of the stream.
536
   */
537
  virtual ResponseHeaderMapOptRef responseHeaders() PURE;
538

            
539
  /**
540
   * Retrieves a pointer to the last response trailers if present.
541
   * Note that response headers might be set multiple times (e.g. if a local reply is issued after
542
   * headers have been received but before headers have been encoded), so it is not safe in general
543
   * to assume that any set of headers will be valid for the duration of the stream.
544
   */
545
  virtual ResponseTrailerMapOptRef responseTrailers() PURE;
546

            
547
  /**
548
   * This routine may be called to change the buffer limit for filters.
549
   *
550
   * It is recommended (but not required) that filters calling this function should
551
   * generally only perform increases to the buffer limit, to avoid potentially
552
   * conflicting with the buffer requirements of other filters in the chain, i.e.
553
   *
554
   * if (desired_limit > bufferLimit()) {setBufferLimit(desired_limit);}
555
   *
556
   * @param limit supplies the desired buffer limit.
557
   */
558
  virtual void setBufferLimit(uint64_t limit) PURE;
559

            
560
  /**
561
   * This routine returns the current buffer limit for filters. Filters should abide by
562
   * this limit or change it via setBufferLimit.
563
   * A buffer limit of 0 bytes indicates no limits are applied.
564
   *
565
   * @return the buffer limit the filter should apply.
566
   */
567
  virtual uint64_t bufferLimit() PURE;
568
};
569

            
570
/**
571
 * Stream decoder filter callbacks add additional callbacks that allow a
572
 * decoding filter to restart decoding if they decide to hold data (e.g. for
573
 * buffering or rate limiting).
574
 */
575
class StreamDecoderFilterCallbacks : public virtual StreamFilterCallbacks {
576
public:
577
  /**
578
   * Continue iterating through the filter chain with buffered headers and body data. This routine
579
   * can only be called if the filter has previously returned StopIteration from decodeHeaders()
580
   * AND one of StopIterationAndBuffer, StopIterationAndWatermark, or StopIterationNoBuffer
581
   * from each previous call to decodeData().
582
   *
583
   * The connection manager will dispatch headers and any buffered body data to the
584
   * next filter in the chain. Further note that if the request is not complete, this filter will
585
   * still receive decodeData() calls and must return an appropriate status code depending on what
586
   * the filter needs to do.
587
   */
588
  virtual void continueDecoding() PURE;
589

            
590
  /**
591
   * @return const Buffer::Instance* the currently buffered data as buffered by this filter or
592
   *         previous ones in the filter chain. May be nullptr if nothing has been buffered yet.
593
   */
594
  virtual const Buffer::Instance* decodingBuffer() PURE;
595

            
596
  /**
597
   * Allows modifying the decoding buffer. May only be called before any data has been continued
598
   * past the calling filter.
599
   */
600
  virtual void modifyDecodingBuffer(std::function<void(Buffer::Instance&)> callback) PURE;
601

            
602
  /**
603
   * Add buffered body data. This method is used in advanced cases where returning
604
   * StopIterationAndBuffer from decodeData() is not sufficient.
605
   *
606
   * 1) If a headers only request needs to be turned into a request with a body, this method can
607
   * be called to add body in the decodeHeaders() callback. Subsequent filters will receive
608
   * decodeHeaders(..., false) followed by decodeData(..., true). This works both in the direct
609
   * iteration as well as the continuation case.
610
   *
611
   * 2) If a filter is going to look at all buffered data from within a data callback with end
612
   * stream set, this method can be called to immediately buffer the data. This avoids having
613
   * to deal with the existing buffered data and the data from the current callback.
614
   *
615
   * 3) If additional buffered body data needs to be added by a filter before continuation of data
616
   * to further filters (outside of callback context).
617
   *
618
   * 4) If additional data needs to be added in the decodeTrailers() callback, this method can be
619
   * called in the context of the callback. All further filters will receive decodeData(..., false)
620
   * followed by decodeTrailers(). However if the iteration is stopped, the added data will
621
   * buffered, so that the further filters will not receive decodeData() before decodeHeaders().
622
   *
623
   * It is an error to call this method in any other case.
624
   *
625
   * See also injectDecodedDataToFilterChain() for a different way of passing data to further
626
   * filters and also how the two methods are different.
627
   *
628
   * @param data Buffer::Instance supplies the data to be decoded.
629
   * @param streaming_filter boolean supplies if this filter streams data or buffers the full body.
630
   */
631
  virtual void addDecodedData(Buffer::Instance& data, bool streaming_filter) PURE;
632

            
633
  /**
634
   * Decode data directly to subsequent filters in the filter chain. This method is used in
635
   * advanced cases in which a filter needs full control over how subsequent filters view data,
636
   * and does not want to make use of HTTP connection manager buffering. Using this method allows
637
   * a filter to buffer data (or not) and then periodically inject data to subsequent filters,
638
   * indicating end_stream at an appropriate time. This can be used to implement rate limiting,
639
   * periodic data emission, etc.
640
   *
641
   * This method should only be called outside of callback context. I.e., do not call this method
642
   * from within a filter's decodeData() call.
643
   *
644
   * When using this callback, filters should generally only return
645
   * FilterDataStatus::StopIterationNoBuffer from their decodeData() call, since use of this method
646
   * indicates that a filter does not wish to participate in standard HTTP connection manager
647
   * buffering and continuation and will perform any necessary buffering and continuation on its
648
   * own.
649
   *
650
   * This callback is different from addDecodedData() in that the specified data and end_stream
651
   * status will be propagated directly to further filters in the filter chain. This is different
652
   * from addDecodedData() where data is added to the HTTP connection manager's buffered data with
653
   * the assumption that standard HTTP connection manager buffering and continuation are being used.
654
   *
655
   * @param data Buffer::Instance supplies the data to be injected.
656
   * @param end_stream boolean supplies whether this is the last data frame, and no trailers behind.
657
   */
658
  virtual void injectDecodedDataToFilterChain(Buffer::Instance& data, bool end_stream) PURE;
659

            
660
  /**
661
   * Adds decoded trailers. May only be called in decodeData when end_stream is set to true.
662
   * If called in any other context, an assertion will be triggered.
663
   *
664
   * When called in decodeData, the trailers map will be initialized to an empty map and returned by
665
   * reference. Calling this function more than once is invalid.
666
   *
667
   * @return a reference to the newly created trailers map.
668
   */
669
  virtual RequestTrailerMap& addDecodedTrailers() PURE;
670

            
671
  /**
672
   * Attempts to create a locally generated response using the provided response_code and body_text
673
   * parameters. If the request was a gRPC request the local reply will be encoded as a gRPC
674
   * response with a 200 HTTP response code and grpc-status and grpc-message headers mapped from the
675
   * provided parameters.
676
   *
677
   * If a response has already started (e.g. if the router calls sendLocalReply after encoding
678
   * headers) this will either ship the reply directly to the downstream codec, or reset the stream.
679
   *
680
   * @param response_code supplies the HTTP response code.
681
   * @param body_text supplies the optional body text which is sent using the text/plain content
682
   *                  type, or encoded in the grpc-message header.
683
   * @param modify_headers supplies an optional callback function that can modify the
684
   *                       response headers.
685
   * @param grpc_status the gRPC status code to override the httpToGrpcStatus mapping with.
686
   * @param details a string detailing why this local reply was sent.
687
   */
688
  virtual void sendLocalReply(Code response_code, absl::string_view body_text,
689
                              std::function<void(ResponseHeaderMap& headers)> modify_headers,
690
                              const absl::optional<Grpc::Status::GrpcStatus> grpc_status,
691
                              absl::string_view details) PURE;
692

            
693
  /**
694
   * Attempt to send GOAWAY and close the connection, and no filter chain will move forward.
695
   */
696
  virtual void sendGoAwayAndClose(bool graceful = false) PURE;
697

            
698
  /**
699
   * Adds decoded metadata. This function can only be called in
700
   * StreamDecoderFilter::decodeHeaders/Data/Trailers(). Do not call in
701
   * StreamDecoderFilter::decodeMetadata().
702
   *
703
   * @return a reference to metadata map vector, where new metadata map can be added.
704
   */
705
  virtual MetadataMapVector& addDecodedMetadata() PURE;
706

            
707
  /**
708
   * Called with 1xx headers to be encoded.
709
   *
710
   * Currently supported codes for this function include 100.
711
   *
712
   * This is not folded into encodeHeaders because most Envoy users and filters will not be proxying
713
   * 1xx headers and with it split out, can ignore the complexity of multiple encodeHeaders calls.
714
   *
715
   * This is currently only called once per request but implementations should
716
   * handle multiple calls as multiple 1xx headers are legal.
717
   *
718
   * @param headers supplies the headers to be encoded.
719
   */
720
  virtual void encode1xxHeaders(ResponseHeaderMapPtr&& headers) PURE;
721

            
722
  /**
723
   * Called with headers to be encoded, optionally indicating end of stream.
724
   *
725
   * The connection manager inspects certain pseudo headers that are not actually sent downstream.
726
   * - See source/common/http/headers.h
727
   *
728
   * The only 1xx that may be provided to encodeHeaders() is a 101 upgrade, which will be the final
729
   * encodeHeaders() for a response.
730
   *
731
   * @param headers supplies the headers to be encoded.
732
   * @param end_stream supplies whether this is a header only request/response.
733
   * @param details supplies the details of why this response was sent.
734
   */
735
  virtual void encodeHeaders(ResponseHeaderMapPtr&& headers, bool end_stream,
736
                             absl::string_view details) PURE;
737

            
738
  /**
739
   * Called with data to be encoded, optionally indicating end of stream.
740
   * @param data supplies the data to be encoded.
741
   * @param end_stream supplies whether this is the last data frame.
742
   */
743
  virtual void encodeData(Buffer::Instance& data, bool end_stream) PURE;
744

            
745
  /**
746
   * Called with trailers to be encoded. This implicitly ends the stream.
747
   * @param trailers supplies the trailers to encode.
748
   */
749
  virtual void encodeTrailers(ResponseTrailerMapPtr&& trailers) PURE;
750

            
751
  /**
752
   * Called with metadata to be encoded.
753
   *
754
   * @param metadata_map supplies the unique_ptr of the metadata to be encoded.
755
   */
756
  virtual void encodeMetadata(MetadataMapPtr&& metadata_map) PURE;
757

            
758
  /**
759
   * Called when the buffer for a decoder filter or any buffers the filter sends data to go over
760
   * their high watermark.
761
   *
762
   * In the case of a filter such as the router filter, which spills into multiple buffers (codec,
763
   * connection etc.) this may be called multiple times. Any such filter is responsible for calling
764
   * the low watermark callbacks an equal number of times as the respective buffers are drained.
765
   */
766
  virtual void onDecoderFilterAboveWriteBufferHighWatermark() PURE;
767

            
768
  /**
769
   * Called when a decoder filter or any buffers the filter sends data to go from over its high
770
   * watermark to under its low watermark.
771
   */
772
  virtual void onDecoderFilterBelowWriteBufferLowWatermark() PURE;
773

            
774
  /**
775
   * This routine can be called by a filter to subscribe to watermark events on the downstream
776
   * stream and downstream connection.
777
   *
778
   * Immediately after subscribing, the filter will get a high watermark callback for each
779
   * outstanding backed up buffer.
780
   */
781
  virtual void addDownstreamWatermarkCallbacks(DownstreamWatermarkCallbacks& callbacks) PURE;
782

            
783
  /**
784
   * This routine can be called by a filter to stop subscribing to watermark events on the
785
   * downstream stream and downstream connection.
786
   *
787
   * It is not safe to call this from under the stack of a DownstreamWatermarkCallbacks callback.
788
   */
789
  virtual void removeDownstreamWatermarkCallbacks(DownstreamWatermarkCallbacks& callbacks) PURE;
790

            
791
  /**
792
   * @return the account, if any, used by this stream.
793
   */
794
  virtual Buffer::BufferMemoryAccountSharedPtr account() const PURE;
795

            
796
  /**
797
   * Takes a stream, and acts as if the headers are newly arrived.
798
   * On success, this will result in a creating a new filter chain and likely
799
   * upstream request associated with the original downstream stream. On
800
   * failure, if the preconditions outlined below are not met, the caller is
801
   * responsible for handling or terminating the original stream.
802
   *
803
   * This is currently limited to
804
   *   - streams which are completely read
805
   *   - streams which do not have a request body.
806
   *
807
   * Note that HttpConnectionManager sanitization will *not* be performed on the
808
   * recreated stream, as it is assumed that sanitization has already been done.
809
   *
810
   * @param original_response_headers Headers used for logging in the access logs and for charging
811
   * stats. Ignored if null.
812
   */
813
  virtual bool recreateStream(const ResponseHeaderMap* original_response_headers) PURE;
814

            
815
  /**
816
   * Adds socket options to be applied to any connections used for upstream requests. Note that
817
   * unique values for the options will likely lead to many connection pools being created. The
818
   * added options are appended to any previously added.
819
   *
820
   * @param options The options to be added.
821
   */
822
  virtual void addUpstreamSocketOptions(const Network::Socket::OptionsSharedPtr& options) PURE;
823

            
824
  /**
825
   * @return The socket options to be applied to the upstream request.
826
   */
827
  virtual Network::Socket::OptionsSharedPtr getUpstreamSocketOptions() const PURE;
828

            
829
  /**
830
   * Set override host to be used by the upstream load balancing. If the target host exists in the
831
   * host list of the routed cluster, the host should be selected first.
832
   * @param host The override host address.
833
   */
834
  virtual void setUpstreamOverrideHost(Upstream::LoadBalancerContext::OverrideHost) PURE;
835

            
836
  /**
837
   * @return absl::optional<absl::string_view> optional override host for the upstream
838
   * load balancing.
839
   */
840
  virtual absl::optional<Upstream::LoadBalancerContext::OverrideHost>
841
  upstreamOverrideHost() const PURE;
842

            
843
  /**
844
   * @return true if the filter should shed load based on the system pressure, typically memory.
845
   */
846
  virtual bool shouldLoadShed() const PURE;
847

            
848
  /**
849
   * Deprecated methods for decoder buffer limit accessors. Use setBufferLimit and bufferLimit
850
   * instead. This is kept for backward compatibility and will be removed in next few releases.
851
   */
852
25
  void setDecoderBufferLimit(uint64_t limit) { setBufferLimit(limit); }
853
  uint64_t decoderBufferLimit() { return bufferLimit(); }
854
};
855

            
856
/**
857
 * Common base class for both decoder and encoder filters. Functions here are related to the
858
 * lifecycle of a filter. Currently the life cycle is as follows:
859
 * - All filters receive onStreamComplete()
860
 * - All log handlers receive final log()
861
 * - All filters receive onDestroy()
862
 *
863
 * This means:
864
 * - onStreamComplete can be used to make state changes that are intended to appear in the final
865
 * access logs (like streamInfo().dynamicMetadata() or streamInfo().filterState()).
866
 * - onDestroy is used to cleanup all pending filter resources like pending http requests and
867
 * timers.
868
 */
869
class StreamFilterBase {
870
public:
871
162774
  virtual ~StreamFilterBase() = default;
872

            
873
  /**
874
   * This routine is called before the access log handlers' final log() is called. Filters can use
875
   * this callback to enrich the data passed in to the log handlers.
876
   */
877
101147
  virtual void onStreamComplete() {}
878

            
879
  /**
880
   * This routine is called prior to a filter being destroyed. This may happen after normal stream
881
   * finish (both downstream and upstream) or due to reset. Every filter is responsible for making
882
   * sure that any async events are cleaned up in the context of this routine. This includes timers,
883
   * network calls, etc. The reason there is an onDestroy() method vs. doing this type of cleanup
884
   * in the destructor is due to the deferred deletion model that Envoy uses to avoid stack unwind
885
   * complications. Filters must not invoke either encoder or decoder filter callbacks after having
886
   * onDestroy() invoked. Filters that cross-register as access log handlers receive log() before
887
   * onDestroy().
888
   */
889
  virtual void onDestroy() PURE;
890

            
891
  /**
892
   * Called when a match result occurs that isn't handled by the filter manager.
893
   * @param action the resulting match action
894
   */
895
  virtual void onMatchCallback(const Matcher::Action&) {}
896

            
897
  struct LocalReplyData {
898
    // The error code which (barring reset) will be sent to the client.
899
    Http::Code code_;
900
    // The gRPC status set in local reply.
901
    absl::optional<Grpc::Status::GrpcStatus> grpc_status_;
902
    // The details of why a local reply is being sent.
903
    absl::string_view details_;
904
    // True if a reset will occur rather than the local reply (some prior filter
905
    // has returned ContinueAndResetStream)
906
    bool reset_imminent_;
907
  };
908

            
909
  /**
910
   * Called after sendLocalReply is called, and before any local reply is
911
   * serialized either to filters, or downstream.
912
   * This will be called on both encoder and decoder filters starting at the
913
   * terminal filter (generally the router filter) and working towards the first filter configured.
914
   *
915
   * Note that in some circumstances, onLocalReply may be called more than once
916
   * for a given stream, because it is possible that a filter call
917
   * sendLocalReply while processing the original local reply response.
918
   *
919
   * Filters implementing onLocalReply are responsible for never calling sendLocalReply
920
   * from onLocalReply, as that has the potential for looping.
921
   *
922
   * @param data data associated with the sendLocalReply call.
923
   * @param LocalErrorStatus the action to take after onLocalReply completes.
924
   */
925
3383
  virtual LocalErrorStatus onLocalReply(const LocalReplyData&) {
926
3383
    return LocalErrorStatus::Continue;
927
3383
  }
928
};
929

            
930
/**
931
 * Stream decoder filter interface.
932
 */
933
class StreamDecoderFilter : public virtual StreamFilterBase {
934
public:
935
  /**
936
   * Called with decoded headers, optionally indicating end of stream.
937
   * @param headers supplies the decoded headers map.
938
   * @param end_stream supplies whether this is a header only request/response.
939
   * @return FilterHeadersStatus determines how filter chain iteration proceeds.
940
   */
941
  virtual FilterHeadersStatus decodeHeaders(RequestHeaderMap& headers, bool end_stream) PURE;
942

            
943
  /**
944
   * Called with a decoded data frame.
945
   * @param data supplies the decoded data.
946
   * @param end_stream supplies whether this is the last data frame.
947
   * Further note that end_stream is only true if there are no trailers.
948
   * @return FilterDataStatus determines how filter chain iteration proceeds.
949
   */
950
  virtual FilterDataStatus decodeData(Buffer::Instance& data, bool end_stream) PURE;
951

            
952
  /**
953
   * Called with decoded trailers, implicitly ending the stream.
954
   * @param trailers supplies the decoded trailers.
955
   */
956
  virtual FilterTrailersStatus decodeTrailers(RequestTrailerMap& trailers) PURE;
957

            
958
  /**
959
   * Called with decoded metadata. Add new metadata to metadata_map directly. Do not call
960
   * StreamDecoderFilterCallbacks::addDecodedMetadata() to add new metadata.
961
   *
962
   * Note: decodeMetadata() currently cannot stop the filter iteration, and always returns Continue.
963
   * That means metadata will go through the complete filter chain at once, even if the other frame
964
   * types return StopIteration. If metadata should not pass through all filters at once, users
965
   * should consider using StopAllIterationAndBuffer or StopAllIterationAndWatermark in
966
   * decodeHeaders() to prevent metadata passing to the following filters.
967
   *
968
   * @param metadata_map supplies the decoded metadata.
969
   */
970
37
  virtual FilterMetadataStatus decodeMetadata(MetadataMap& /* metadata_map */) {
971
37
    return Http::FilterMetadataStatus::Continue;
972
37
  }
973

            
974
  /**
975
   * Called by the filter manager once to initialize the filter decoder callbacks that the
976
   * filter should use. Callbacks will not be invoked by the filter after onDestroy() is called.
977
   */
978
  virtual void setDecoderFilterCallbacks(StreamDecoderFilterCallbacks& callbacks) PURE;
979

            
980
  /**
981
   * Called at the end of the stream, when all data has been decoded.
982
   */
983
90274
  virtual void decodeComplete() {}
984
};
985

            
986
using StreamDecoderFilterSharedPtr = std::shared_ptr<StreamDecoderFilter>;
987

            
988
/**
989
 * Stream encoder filter callbacks add additional callbacks that allow a encoding filter to restart
990
 * encoding if they decide to hold data (e.g. for buffering or rate limiting).
991
 */
992
class StreamEncoderFilterCallbacks : public virtual StreamFilterCallbacks {
993
public:
994
  /**
995
   * Continue iterating through the filter chain with buffered headers and body data. This routine
996
   * can only be called if the filter has previously returned StopIteration from encodeHeaders() AND
997
   * one of StopIterationAndBuffer, StopIterationAndWatermark, or StopIterationNoBuffer
998
   * from each previous call to encodeData().
999
   *
   * The connection manager will dispatch headers and any buffered body data to the next filter in
   * the chain. Further note that if the response is not complete, this filter will still receive
   * encodeData() calls and must return an appropriate status code depending on what the filter
   * needs to do.
   */
  virtual void continueEncoding() PURE;
  /**
   * @return const Buffer::Instance* the currently buffered data as buffered by this filter or
   *         previous ones in the filter chain. May be nullptr if nothing has been buffered yet.
   */
  virtual const Buffer::Instance* encodingBuffer() PURE;
  /**
   * Allows modifying the encoding buffer. May only be called before any data has been continued
   * past the calling filter.
   */
  virtual void modifyEncodingBuffer(std::function<void(Buffer::Instance&)> callback) PURE;
  /**
   * Add buffered body data. This method is used in advanced cases where returning
   * StopIterationAndBuffer from encodeData() is not sufficient.
   *
   * 1) If a headers only response needs to be turned into a response with a body, this method can
   * be called to add body in the encodeHeaders() callback. Subsequent filters will receive
   * encodeHeaders(..., false) followed by encodeData(..., true). This works both in the direct
   * iteration as well as the continuation case.
   *
   * 2) If a filter is going to look at all buffered data from within a data callback with end
   * stream set, this method can be called to immediately buffer the data. This avoids having
   * to deal with the existing buffered data and the data from the current callback.
   *
   * 3) If additional buffered body data needs to be added by a filter before continuation of data
   * to further filters (outside of callback context).
   *
   * 4) If additional data needs to be added in the encodeTrailers() callback, this method can be
   * called in the context of the callback. All further filters will receive encodeData(..., false)
   * followed by encodeTrailers(). However if the iteration is stopped, the added data will
   * buffered, so that the further filters will not receive encodeData() before encodeHeaders().
   *
   * It is an error to call this method in any other case.
   *
   * See also injectEncodedDataToFilterChain() for a different way of passing data to further
   * filters and also how the two methods are different.
   *
   * @param data Buffer::Instance supplies the data to be encoded.
   * @param streaming_filter boolean supplies if this filter streams data or buffers the full body.
   */
  virtual void addEncodedData(Buffer::Instance& data, bool streaming_filter) PURE;
  /**
   * Encode data directly to subsequent filters in the filter chain. This method is used in
   * advanced cases in which a filter needs full control over how subsequent filters view data,
   * and does not want to make use of HTTP connection manager buffering. Using this method allows
   * a filter to buffer data (or not) and then periodically inject data to subsequent filters,
   * indicating end_stream at an appropriate time. This can be used to implement rate limiting,
   * periodic data emission, etc.
   *
   * This method should only be called outside of callback context. I.e., do not call this method
   * from within a filter's encodeData() call.
   *
   * When using this callback, filters should generally only return
   * FilterDataStatus::StopIterationNoBuffer from their encodeData() call, since use of this method
   * indicates that a filter does not wish to participate in standard HTTP connection manager
   * buffering and continuation and will perform any necessary buffering and continuation on its
   * own.
   *
   * This callback is different from addEncodedData() in that the specified data and end_stream
   * status will be propagated directly to further filters in the filter chain. This is different
   * from addEncodedData() where data is added to the HTTP connection manager's buffered data with
   * the assumption that standard HTTP connection manager buffering and continuation are being used.
   *
   * @param data Buffer::Instance supplies the data to be injected.
   * @param end_stream boolean supplies whether this is the last data frame, and no trailers behind.
   */
  virtual void injectEncodedDataToFilterChain(Buffer::Instance& data, bool end_stream) PURE;
  /**
   * Adds encoded trailers. May only be called in encodeData when end_stream is set to true.
   * If called in any other context, an assertion will be triggered.
   *
   * When called in encodeData, the trailers map will be initialized to an empty map and returned by
   * reference. Calling this function more than once is invalid.
   *
   * @return a reference to the newly created trailers map.
   */
  virtual ResponseTrailerMap& addEncodedTrailers() PURE;
  /**
   * Attempts to create a locally generated response using the provided response_code and body_text
   * parameters. If the request was a gRPC request the local reply will be encoded as a gRPC
   * response with a 200 HTTP response code and grpc-status and grpc-message headers mapped from the
   * provided parameters.
   *
   * If a response has already started (e.g. if the router calls sendLocalReply after encoding
   * headers) this will either ship the reply directly to the downstream codec, or reset the stream.
   *
   * @param response_code supplies the HTTP response code.
   * @param body_text supplies the optional body text which is sent using the text/plain content
   *                  type, or encoded in the grpc-message header.
   * @param modify_headers supplies an optional callback function that can modify the
   *                       response headers.
   * @param grpc_status the gRPC status code to override the httpToGrpcStatus mapping with.
   * @param details a string detailing why this local reply was sent.
   */
  virtual void sendLocalReply(Code response_code, absl::string_view body_text,
                              std::function<void(ResponseHeaderMap& headers)> modify_headers,
                              const absl::optional<Grpc::Status::GrpcStatus> grpc_status,
                              absl::string_view details) PURE;
  /**
   * Adds new metadata to be encoded.
   *
   * @param metadata_map supplies the unique_ptr of the metadata to be encoded.
   */
  virtual void addEncodedMetadata(MetadataMapPtr&& metadata_map) PURE;
  /**
   * Called when an encoder filter goes over its high watermark.
   */
  virtual void onEncoderFilterAboveWriteBufferHighWatermark() PURE;
  /**
   * Called when a encoder filter goes from over its high watermark to under its low watermark.
   */
  virtual void onEncoderFilterBelowWriteBufferLowWatermark() PURE;
  /**
   * Deprecated methods for encoder buffer limit accessors. Use setBufferLimit and bufferLimit
   * instead. This is kept for backward compatibility and will be removed in next few releases.
   */
  void setEncoderBufferLimit(uint64_t limit) { setBufferLimit(limit); }
  uint64_t encoderBufferLimit() { return bufferLimit(); }
};
/**
 * Stream encoder filter interface.
 */
class StreamEncoderFilter : public virtual StreamFilterBase {
public:
  /**
   * Called with supported 1xx headers.
   *
   * This is not folded into encodeHeaders because most Envoy users and filters
   * will not be proxying 1xxs and with it split out, can ignore the
   * complexity of multiple encodeHeaders calls.
   *
   * This will only be invoked once per request.
   *
   * @param headers supplies the 1xx response headers to be encoded.
   * @return Filter1xxHeadersStatus determines how filter chain iteration proceeds.
   *
   */
  virtual Filter1xxHeadersStatus encode1xxHeaders(ResponseHeaderMap& headers) PURE;
  /**
   * Called with headers to be encoded, optionally indicating end of stream.
   *
   * The only 1xx that may be provided to encodeHeaders() is a 101 upgrade, which will be the final
   * encodeHeaders() for a response.
   *
   * @param headers supplies the headers to be encoded.
   * @param end_stream supplies whether this is a header only request/response.
   * @return FilterHeadersStatus determines how filter chain iteration proceeds.
   */
  virtual FilterHeadersStatus encodeHeaders(ResponseHeaderMap& headers, bool end_stream) PURE;
  /**
   * Called with data to be encoded, optionally indicating end of stream.
   * @param data supplies the data to be encoded.
   * @param end_stream supplies whether this is the last data frame.
   * Further note that end_stream is only true if there are no trailers.
   * @return FilterDataStatus determines how filter chain iteration proceeds.
   */
  virtual FilterDataStatus encodeData(Buffer::Instance& data, bool end_stream) PURE;
  /**
   * Called with trailers to be encoded, implicitly ending the stream.
   * @param trailers supplies the trailers to be encoded.
   */
  virtual FilterTrailersStatus encodeTrailers(ResponseTrailerMap& trailers) PURE;
  /**
   * Called with metadata to be encoded. New metadata should be added directly to metadata_map. DO
   * NOT call StreamDecoderFilterCallbacks::encodeMetadata() interface to add new metadata.
   *
   * @param metadata_map supplies the metadata to be encoded.
   * @return FilterMetadataStatus, which currently is always FilterMetadataStatus::Continue;
   */
  virtual FilterMetadataStatus encodeMetadata(MetadataMap& metadata_map) PURE;
  /**
   * Called by the filter manager once to initialize the filter callbacks that the filter should
   * use. Callbacks will not be invoked by the filter after onDestroy() is called.
   */
  virtual void setEncoderFilterCallbacks(StreamEncoderFilterCallbacks& callbacks) PURE;
  /**
   * Called at the end of the stream, when all data has been encoded.
   */
7157
  virtual void encodeComplete() {}
};
using StreamEncoderFilterSharedPtr = std::shared_ptr<StreamEncoderFilter>;
/**
 * A filter that handles both encoding and decoding.
 */
class StreamFilter : public virtual StreamDecoderFilter, public virtual StreamEncoderFilter {};
using StreamFilterSharedPtr = std::shared_ptr<StreamFilter>;
class HttpMatchingData {
public:
19870
  static absl::string_view name() { return "http"; }
619
  virtual ~HttpMatchingData() = default;
  virtual RequestHeaderMapOptConstRef requestHeaders() const PURE;
  virtual RequestTrailerMapOptConstRef requestTrailers() const PURE;
  virtual ResponseHeaderMapOptConstRef responseHeaders() const PURE;
  virtual ResponseTrailerMapOptConstRef responseTrailers() const PURE;
  virtual const StreamInfo::StreamInfo& streamInfo() const PURE;
  virtual const Network::ConnectionInfoProvider& connectionInfoProvider() const PURE;
12
  const StreamInfo::FilterState& filterState() const { return streamInfo().filterState(); }
27
  const envoy::config::core::v3::Metadata& metadata() const {
27
    return streamInfo().dynamicMetadata();
27
  }
40
  const Network::Address::Instance& localAddress() const {
40
    return *connectionInfoProvider().localAddress();
40
  }
10
  const Network::Address::Instance& remoteAddress() const {
10
    return *connectionInfoProvider().remoteAddress();
10
  }
14
  Ssl::ConnectionInfoConstSharedPtr ssl() const { return connectionInfoProvider().sslConnection(); }
};
/**
 * These callbacks are provided by the connection manager to the factory so that the factory can
 * build the filter chain in an application specific way.
 */
class FilterChainFactoryCallbacks {
public:
233033
  virtual ~FilterChainFactoryCallbacks() = default;
  /**
   * Add a decoder filter that is used when reading stream data.
   * @param filter supplies the filter to add.
   */
  virtual void addStreamDecoderFilter(Http::StreamDecoderFilterSharedPtr filter) PURE;
  /**
   * Add an encoder filter that is used when writing stream data.
   * @param filter supplies the filter to add.
   */
  virtual void addStreamEncoderFilter(Http::StreamEncoderFilterSharedPtr filter) PURE;
  /**
   * Add a decoder/encoder filter that is used both when reading and writing stream data.
   * @param filter supplies the filter to add.
   */
  virtual void addStreamFilter(Http::StreamFilterSharedPtr filter) PURE;
  /**
   * Add an access log handler that is called when the stream is destroyed.
   * @param handler supplies the handler to add.
   */
  virtual void addAccessLogHandler(AccessLog::InstanceSharedPtr handler) PURE;
  /**
   * Allows filters to access the thread local dispatcher.
   * @param return the worker thread's dispatcher.
   */
  virtual Event::Dispatcher& dispatcher() PURE;
  /**
   * @return absl::string_view the filter config name that used to create the filter. This
   * will return the latest set name by the setFilterConfigName() method.
   */
  virtual absl::string_view filterConfigName() const PURE;
  /**
   * Set the configured name of the filter in the filter chain. This name is used to identify
   * the filter self and look up filter-specific configuration in various places (e.g., route
   * configuration).
   *
   * NOTE: This method should be called for each filter before adding the filter to the filter
   * chain via addStreamDecoderFilter(), addStreamEncoderFilter(), or addStreamFilter().
   * NOTE: By default, the FilterChainFactory will call this method to set the config name
   * from configuration and the per filter factory does not need to care this method except
   * it wants to override the config name.
   *
   * @param name the name to be used for looking up filter-specific configuration.
   */
  virtual void setFilterConfigName(absl::string_view name) PURE;
  /**
   * @return OptRef<const Router::Route> the route selected for this stream, if any.
   */
  virtual OptRef<const Router::Route> route() const PURE;
  /**
   * Check whether the filter chain is disabled for this stream.
   * @param name the name of the filter chain to check.
   *
   * @return absl::optional<bool> whether the filter chain is disabled for this stream.
   */
  virtual absl::optional<bool> filterDisabled(absl::string_view name) const PURE;
  /**
   * @return const StreamInfo::StreamInfo& the stream info for this stream.
   */
  virtual const StreamInfo::StreamInfo& streamInfo() const PURE;
  /**
   * @return RequestHeaderMapOptRef the request headers for this stream.
   */
  virtual RequestHeaderMapOptRef requestHeaders() const PURE;
};
} // namespace Http
} // namespace Envoy