1
#pragma once
2

            
3
#include <chrono>
4
#include <cstdint>
5
#include <functional>
6
#include <map>
7
#include <memory>
8
#include <string>
9

            
10
#include "envoy/access_log/access_log.h"
11
#include "envoy/common/conn_pool.h"
12
#include "envoy/common/matchers.h"
13
#include "envoy/config/core/v3/base.pb.h"
14
#include "envoy/config/route/v3/route_components.pb.h"
15
#include "envoy/config/typed_metadata.h"
16
#include "envoy/http/codec.h"
17
#include "envoy/http/codes.h"
18
#include "envoy/http/conn_pool.h"
19
#include "envoy/http/hash_policy.h"
20
#include "envoy/http/header_evaluator.h"
21
#include "envoy/rds/config.h"
22
#include "envoy/router/internal_redirect.h"
23
#include "envoy/router/path_matcher.h"
24
#include "envoy/router/path_rewriter.h"
25
#include "envoy/stream_info/stream_info.h"
26
#include "envoy/tcp/conn_pool.h"
27
#include "envoy/tracing/tracer.h"
28
#include "envoy/type/v3/percent.pb.h"
29
#include "envoy/upstream/resource_manager.h"
30
#include "envoy/upstream/retry.h"
31

            
32
#include "source/common/protobuf/protobuf.h"
33
#include "source/common/protobuf/utility.h"
34

            
35
#include "absl/types/optional.h"
36

            
37
namespace Envoy {
38
namespace Formatter {
39
class Formatter;
40
}
41
namespace Upstream {
42
class ClusterManager;
43
class LoadBalancerContext;
44
class ThreadLocalCluster;
45
} // namespace Upstream
46

            
47
namespace Router {
48

            
49
/**
50
 * Functionality common among routing primitives, such as DirectResponseEntry and RouteEntry.
51
 */
52
class ResponseEntry {
53
public:
54
46720
  virtual ~ResponseEntry() = default;
55

            
56
  /**
57
   * Do potentially destructive header transforms on response headers prior to forwarding. For
58
   * example, adding or removing headers. This should only be called ONCE immediately after
59
   * obtaining the initial response headers.
60
   * @param headers supplies the response headers, which may be modified during this call.
61
   * @param stream_info holds additional information about the request.
62
   */
63
  virtual void finalizeResponseHeaders(Http::ResponseHeaderMap& headers,
64
                                       const Formatter::Context& context,
65
                                       const StreamInfo::StreamInfo& stream_info) const PURE;
66

            
67
  /**
68
   * Returns the response header transforms that would be applied if finalizeResponseHeaders were
69
   * called now. This is useful if you want to obtain response header transforms at request time and
70
   * process them later. Note: do not use unless you are sure that there will be no route
71
   * modifications later in the filter chain.
72
   * @param stream_info holds additional information about the request.
73
   * @param do_formatting whether or not to evaluate configured transformations; if false, returns
74
   * original values instead.
75
   */
76
  virtual Http::HeaderTransforms responseHeaderTransforms(const StreamInfo::StreamInfo& stream_info,
77
                                                          bool do_formatting = true) const PURE;
78
};
79

            
80
/**
81
 * A routing primitive that specifies a direct (non-proxied) HTTP response.
82
 */
83
class DirectResponseEntry : public ResponseEntry {
84
public:
85
12873
  ~DirectResponseEntry() override = default;
86

            
87
  /**
88
   * Returns the HTTP status code to return.
89
   * @return Http::Code the response Code.
90
   */
91
  virtual Http::Code responseCode() const PURE;
92

            
93
  /**
94
   * Returns the redirect URI based on the request headers.
95
   * @param headers supplies the request headers.
96
   * @return std::string the redirect URL if this DirectResponseEntry is a redirect,
97
   *         or an empty string otherwise.
98
   */
99
  virtual std::string newUri(const Http::RequestHeaderMap& headers) const PURE;
100

            
101
  /**
102
   * Format the response body for direct responses. Users should pass
103
   * a string reference to populate, `body`, and the return value may
104
   * or may not be the same reference based on if a formatter is applied.
105
   * If a formatter is applied, the return value will be the same reference.
106
   * If no formatter is applied, the return value will be the configured body.
107
   * @param request_headers supplies the request headers.
108
   * @param response_headers supplies the response headers.
109
   * @param stream_info holds additional information about the request.
110
   * @param body_out a string in which a formatted body may be stored.
111
   * @return std::string& the response body.
112
   */
113
  virtual absl::string_view formatBody(const Http::RequestHeaderMap& request_headers,
114
                                       const Http::ResponseHeaderMap& response_headers,
115
                                       const StreamInfo::StreamInfo& stream_info,
116
                                       std::string& body_out) const PURE;
117

            
118
  /**
119
   * @return the content type to use for the direct response body, or empty string if not
120
   * configured (in which case the default "text/plain" will be used).
121
   */
122
  virtual absl::string_view responseContentType() const PURE;
123

            
124
  /**
125
   * Do potentially destructive header transforms on Path header prior to redirection. For
126
   * example prefix rewriting for redirects etc. This should only be called ONCE
127
   * immediately prior to redirecting.
128
   * @param headers supplies the request headers, which may be modified during this call.
129
   * @param insert_envoy_original_path insert x-envoy-original-path header?
130
   */
131
  virtual void rewritePathHeader(Http::RequestHeaderMap& headers,
132
                                 bool insert_envoy_original_path) const PURE;
133
};
134

            
135
/**
136
 * All route specific config returned by the method at
137
 *   NamedHttpFilterConfigFactory::createRouteSpecificFilterConfig
138
 * should be derived from this class.
139
 */
140
class RouteSpecificFilterConfig {
141
public:
142
19912
  virtual ~RouteSpecificFilterConfig() = default;
143
};
144
using RouteSpecificFilterConfigConstSharedPtr = std::shared_ptr<const RouteSpecificFilterConfig>;
145
using RouteSpecificFilterConfigs = absl::InlinedVector<const RouteSpecificFilterConfig*, 4>;
146

            
147
/**
148
 * CorsPolicy for Route and VirtualHost.
149
 */
150
class CorsPolicy : public RouteSpecificFilterConfig {
151
public:
152
  /**
153
   * @return std::vector<StringMatcherPtr>& access-control-allow-origin matchers.
154
   */
155
  virtual const std::vector<Matchers::StringMatcherPtr>& allowOrigins() const PURE;
156

            
157
  /**
158
   * @return std::string access-control-allow-methods value.
159
   */
160
  virtual const std::string& allowMethods() const PURE;
161

            
162
  /**
163
   * @return std::string access-control-allow-headers value.
164
   */
165
  virtual const std::string& allowHeaders() const PURE;
166

            
167
  /**
168
   * @return std::string access-control-expose-headers value.
169
   */
170
  virtual const std::string& exposeHeaders() const PURE;
171

            
172
  /**
173
   * @return std::string access-control-max-age value.
174
   */
175
  virtual const std::string& maxAge() const PURE;
176

            
177
  /**
178
   * @return const absl::optional<bool>& Whether access-control-allow-credentials should be true.
179
   */
180
  virtual const absl::optional<bool>& allowCredentials() const PURE;
181

            
182
  /**
183
   * @return const absl::optional<bool>& How to handle access-control-request-private-network.
184
   */
185
  virtual const absl::optional<bool>& allowPrivateNetworkAccess() const PURE;
186

            
187
  /**
188
   * @return bool Whether CORS is enabled for the route or virtual host.
189
   */
190
  virtual bool enabled() const PURE;
191

            
192
  /**
193
   * @return bool Whether CORS policies are evaluated when filter is off.
194
   */
195
  virtual bool shadowEnabled() const PURE;
196

            
197
  /**
198
   * @return bool whether preflight requests with origin not matching
199
   * configured allowed origins should be forwarded upstream.
200
   */
201
  virtual const absl::optional<bool>& forwardNotMatchingPreflights() const PURE;
202
};
203

            
204
/**
205
 * An interface to be implemented by rate limited reset header parsers.
206
 */
207
class ResetHeaderParser {
208
public:
209
20
  virtual ~ResetHeaderParser() = default;
210

            
211
  /**
212
   * Iterate over the headers, choose the first one that matches by name, and try to parse its
213
   * value.
214
   */
215
  virtual absl::optional<std::chrono::milliseconds>
216
  parseInterval(TimeSource& time_source, const Http::HeaderMap& headers) const PURE;
217
};
218

            
219
using ResetHeaderParserSharedPtr = std::shared_ptr<ResetHeaderParser>;
220

            
221
class RetryPolicy;
222
using RetryPolicyConstSharedPtr = std::shared_ptr<const RetryPolicy>;
223

            
224
/**
225
 * Route level retry policy.
226
 */
227
class RetryPolicy {
228
public:
229
  // clang-format off
230
  static constexpr uint32_t RETRY_ON_5XX                                = 0x1;
231
  static constexpr uint32_t RETRY_ON_GATEWAY_ERROR                      = 0x2;
232
  static constexpr uint32_t RETRY_ON_CONNECT_FAILURE                    = 0x4;
233
  static constexpr uint32_t RETRY_ON_RETRIABLE_4XX                      = 0x8;
234
  static constexpr uint32_t RETRY_ON_REFUSED_STREAM                     = 0x10;
235
  static constexpr uint32_t RETRY_ON_GRPC_CANCELLED                     = 0x20;
236
  static constexpr uint32_t RETRY_ON_GRPC_DEADLINE_EXCEEDED             = 0x40;
237
  static constexpr uint32_t RETRY_ON_GRPC_RESOURCE_EXHAUSTED            = 0x80;
238
  static constexpr uint32_t RETRY_ON_GRPC_UNAVAILABLE                   = 0x100;
239
  static constexpr uint32_t RETRY_ON_GRPC_INTERNAL                      = 0x200;
240
  static constexpr uint32_t RETRY_ON_RETRIABLE_STATUS_CODES             = 0x400;
241
  static constexpr uint32_t RETRY_ON_RESET                              = 0x800;
242
  static constexpr uint32_t RETRY_ON_RETRIABLE_HEADERS                  = 0x1000;
243
  static constexpr uint32_t RETRY_ON_ENVOY_RATE_LIMITED                 = 0x2000;
244
  static constexpr uint32_t RETRY_ON_HTTP3_POST_CONNECT_FAILURE         = 0x4000;
245
  static constexpr uint32_t RETRY_ON_RESET_BEFORE_REQUEST               = 0x8000;
246
  // clang-format on
247

            
248
8809
  virtual ~RetryPolicy() = default;
249

            
250
  /**
251
   * @return std::chrono::milliseconds timeout per retry attempt. 0 is disabled.
252
   */
253
  virtual std::chrono::milliseconds perTryTimeout() const PURE;
254

            
255
  /**
256
   * @return std::chrono::milliseconds the optional per try idle timeout. 0 is disabled.
257
   */
258
  virtual std::chrono::milliseconds perTryIdleTimeout() const PURE;
259

            
260
  /**
261
   * @return uint32_t the number of retries to allow against the route.
262
   */
263
  virtual uint32_t numRetries() const PURE;
264

            
265
  /**
266
   * @return uint32_t a local OR of RETRY_ON values above.
267
   */
268
  virtual uint32_t retryOn() const PURE;
269

            
270
  /**
271
   * Initializes a new set of RetryHostPredicates to be used when retrying with this retry policy.
272
   * @return list of RetryHostPredicates to use
273
   */
274
  virtual std::vector<Upstream::RetryHostPredicateSharedPtr> retryHostPredicates() const PURE;
275

            
276
  /**
277
   * Initializes a RetryPriority to be used when retrying with this retry policy.
278
   * @return the RetryPriority to use when determining priority load for retries, or nullptr
279
   * if none should be used.
280
   */
281
  virtual Upstream::RetryPrioritySharedPtr retryPriority() const PURE;
282

            
283
  /**
284
   * @return the retry options predicates for this policy. Each policy will be applied prior
285
   * to retrying a request, allowing for request behavior to be customized.
286
   */
287
  virtual absl::Span<const Upstream::RetryOptionsPredicateConstSharedPtr>
288
  retryOptionsPredicates() const PURE;
289

            
290
  /**
291
   * Number of times host selection should be reattempted when selecting a host
292
   * for a retry attempt.
293
   */
294
  virtual uint32_t hostSelectionMaxAttempts() const PURE;
295

            
296
  /**
297
   * List of status codes that should trigger a retry when the retriable-status-codes retry
298
   * policy is enabled.
299
   */
300
  virtual const std::vector<uint32_t>& retriableStatusCodes() const PURE;
301

            
302
  /**
303
   * @return std::vector<Http::HeaderMatcherSharedPtr>& list of response header matchers that
304
   * will be checked when the 'retriable-headers' retry policy is enabled.
305
   */
306
  virtual const std::vector<Http::HeaderMatcherSharedPtr>& retriableHeaders() const PURE;
307

            
308
  /**
309
   * @return std::vector<Http::HeaderMatcherSharedPt>& list of request header
310
   * matchers that will be checked before enabling retries.
311
   */
312
  virtual const std::vector<Http::HeaderMatcherSharedPtr>& retriableRequestHeaders() const PURE;
313

            
314
  /**
315
   * @return absl::optional<std::chrono::milliseconds> base retry interval
316
   */
317
  virtual absl::optional<std::chrono::milliseconds> baseInterval() const PURE;
318

            
319
  /**
320
   * @return absl::optional<std::chrono::milliseconds> maximum retry interval
321
   */
322
  virtual absl::optional<std::chrono::milliseconds> maxInterval() const PURE;
323

            
324
  /**
325
   * @return std::vector<Http::ResetHeaderParserSharedPtr>& list of reset header
326
   * parsers that will be used to extract a retry back-off interval from response headers.
327
   */
328
  virtual const std::vector<ResetHeaderParserSharedPtr>& resetHeaders() const PURE;
329

            
330
  /**
331
   * @return std::chrono::milliseconds upper limit placed on a retry
332
   * back-off interval parsed from response headers.
333
   */
334
  virtual std::chrono::milliseconds resetMaxInterval() const PURE;
335
};
336

            
337
/**
338
 * RetryStatus whether request should be retried or not.
339
 */
340
enum class RetryStatus { No, NoOverflow, NoRetryLimitExceeded, Yes };
341

            
342
/**
343
 * InternalRedirectPolicy from the route configuration.
344
 */
345
class InternalRedirectPolicy {
346
public:
347
8940
  virtual ~InternalRedirectPolicy() = default;
348

            
349
  /**
350
   * @return whether internal redirect is enabled on this route.
351
   */
352
  virtual bool enabled() const PURE;
353

            
354
  /**
355
   * @param response_code the response code from the upstream.
356
   * @return whether the given response_code should trigger an internal redirect on this route.
357
   */
358
  virtual bool shouldRedirectForResponseCode(const Http::Code& response_code) const PURE;
359

            
360
  /**
361
   * Creates the target route predicates. This should really be called only once for each upstream
362
   * redirect response. Creating the predicates lazily to avoid wasting CPU cycles on non-redirect
363
   * responses, which should be the most common case.
364
   * @return a vector of newly constructed InternalRedirectPredicate instances.
365
   */
366
  virtual std::vector<InternalRedirectPredicateSharedPtr> predicates() const PURE;
367

            
368
  /**
369
   * @return a vector of response header names to preserve in the redirected request.
370
   */
371
  virtual const std::vector<Http::LowerCaseString>& responseHeadersToCopy() const PURE;
372

            
373
  /**
374
   * @return the maximum number of allowed internal redirects on this route.
375
   */
376
  virtual uint32_t maxInternalRedirects() const PURE;
377

            
378
  /**
379
   * @return if it is allowed to follow the redirect with a different scheme in
380
   *         the target URI than the downstream request.
381
   */
382
  virtual bool isCrossSchemeRedirectAllowed() const PURE;
383
};
384

            
385
/**
386
 * Wraps retry state for an active routed request.
387
 */
388
class RetryState {
389
public:
390
  enum class RetryDecision {
391
    // Retry the request immediately.
392
    RetryImmediately,
393
    // Retry the request with timed backoff delay.
394
    RetryWithBackoff,
395
    // Do not retry.
396
    NoRetry,
397
  };
398

            
399
  enum class Http3Used {
400
    Unknown,
401
    Yes,
402
    No,
403
  };
404

            
405
  using DoRetryCallback = std::function<void()>;
406
  /**
407
   * @param disabled_http3 indicates whether the retry should disable http3 or not.
408
   */
409
  using DoRetryResetCallback = std::function<void(bool disable_http3)>;
410
  /**
411
   * @param disable_early_data indicates whether the retry should disable early data or not.
412
   */
413
  using DoRetryHeaderCallback = std::function<void(bool disable_early_data)>;
414

            
415
3475
  virtual ~RetryState() = default;
416

            
417
  /**
418
   * @return true if a policy is in place for the active request that allows retries.
419
   */
420
  virtual bool enabled() PURE;
421

            
422
  /**
423
   * Attempts to parse any matching rate limited reset headers (RFC 7231), either in the form of an
424
   * interval directly, or in the form of a unix timestamp relative to the current system time.
425
   * @return the interval if parsing was successful.
426
   */
427
  virtual absl::optional<std::chrono::milliseconds>
428
  parseResetInterval(const Http::ResponseHeaderMap& response_headers) const PURE;
429

            
430
  /**
431
   * Determine whether a request should be retried based on the response headers.
432
   * @param response_headers supplies the response headers.
433
   * @param original_request supplies the original request headers.
434
   * @param callback supplies the callback that will be invoked when the retry should take place.
435
   *                 This is used to add timed backoff, etc. The callback will never be called
436
   *                 inline.
437
   * @return RetryStatus if a retry should take place. @param callback will be called at some point
438
   *         in the future. Otherwise a retry should not take place and the callback will never be
439
   *         called. Calling code should proceed with error handling.
440
   */
441
  virtual RetryStatus shouldRetryHeaders(const Http::ResponseHeaderMap& response_headers,
442
                                         const Http::RequestHeaderMap& original_request,
443
                                         DoRetryHeaderCallback callback) PURE;
444

            
445
  /**
446
   * Determines whether given response headers would be retried by the retry policy, assuming
447
   * sufficient retry budget and circuit breaker headroom. This is useful in cases where
448
   * the information about whether a response is "good" or not is useful, but a retry should
449
   * not be attempted for other reasons.
450
   * @param response_headers supplies the response headers.
451
   * @param original_request supplies the original request headers.
452
   * @param retry_as_early_data output argument to tell the caller if a retry should be sent as
453
   *        early data if it is warranted.
454
   * @return RetryDecision if a retry would be warranted based on the retry policy and if it would
455
   *         be warranted with timed backoff.
456
   */
457
  virtual RetryDecision wouldRetryFromHeaders(const Http::ResponseHeaderMap& response_headers,
458
                                              const Http::RequestHeaderMap& original_request,
459
                                              bool& retry_as_early_data) PURE;
460

            
461
  /**
462
   * Determine whether a request should be retried after a reset based on the reason for the reset.
463
   * @param reset_reason supplies the reset reason.
464
   * @param http3_used whether the reset request was sent over http3 as alternate protocol or
465
   *                   not. nullopt means it wasn't sent at all before getting reset.
466
   * @param callback supplies the callback that will be invoked when the retry should take place.
467
   *                 This is used to add timed backoff, etc. The callback will never be called
468
   *                 inline.
469
   * @param upstream_request_started indicates whether the first byte has been transmitted to the
470
   *                                 upstream server.
471
   *
472
   * @return RetryStatus if a retry should take place. @param callback will be called at some point
473
   *         in the future. Otherwise a retry should not take place and the callback will never be
474
   *         called. Calling code should proceed with error handling.
475
   */
476
  virtual RetryStatus shouldRetryReset(Http::StreamResetReason reset_reason, Http3Used http3_used,
477
                                       DoRetryResetCallback callback,
478
                                       bool upstream_request_started) PURE;
479

            
480
  /**
481
   * Determine whether a "hedged" retry should be sent after the per try
482
   * timeout expires. This means the original request is not canceled, but a
483
   * new one is sent to hedge against the original request taking even longer.
484
   * @param callback supplies the callback that will be invoked when the retry should take place.
485
   *                 This is used to add timed backoff, etc. The callback will never be called
486
   * inline.
487
   * @return RetryStatus if a retry should take place. @param callback will be called at some point
488
   *         in the future. Otherwise a retry should not take place and the callback will never be
489
   *         called. Calling code should proceed with error handling.
490
   */
491
  virtual RetryStatus shouldHedgeRetryPerTryTimeout(DoRetryCallback callback) PURE;
492

            
493
  /**
494
   * Called when a host was attempted but the request failed and is eligible for another retry.
495
   * Should be used to update whatever internal state depends on previously attempted hosts.
496
   * @param host the previously attempted host.
497
   */
498
  virtual void onHostAttempted(Upstream::HostDescriptionConstSharedPtr host) PURE;
499

            
500
  /**
501
   * Determine whether host selection should be reattempted. Applies to host selection during
502
   * retries, and is used to provide configurable host selection for retries.
503
   * @param host the host under consideration
504
   * @return whether host selection should be reattempted
505
   */
506
  virtual bool shouldSelectAnotherHost(const Upstream::Host& host) PURE;
507

            
508
  /**
509
   * Returns a reference to the PriorityLoad that should be used for the next retry.
510
   * @param stream_info request stream information.
511
   * @param priority_set current priority set.
512
   * @param original_priority_load original priority load.
513
   * @param priority_mapping_func see @Upstream::RetryPriority::PriorityMappingFunc.
514
   * @return HealthyAndDegradedLoad that should be used to select a priority for the next retry.
515
   */
516
  virtual const Upstream::HealthyAndDegradedLoad& priorityLoadForRetry(
517
      StreamInfo::StreamInfo* stream_info, const Upstream::PrioritySet& priority_set,
518
      const Upstream::HealthyAndDegradedLoad& original_priority_load,
519
      const Upstream::RetryPriority::PriorityMappingFunc& priority_mapping_func) PURE;
520
  /**
521
   * return how many times host selection should be reattempted during host selection.
522
   */
523
  virtual uint32_t hostSelectionMaxAttempts() const PURE;
524
};
525

            
526
using RetryStatePtr = std::unique_ptr<RetryState>;
527

            
528
/**
529
 * Per route policy for request shadowing.
530
 */
531
class ShadowPolicy {
532
public:
533
109
  virtual ~ShadowPolicy() = default;
534

            
535
  /**
536
   * @return the name of the cluster that a matching request should be shadowed to.
537
   *         Only one of *cluster* and *cluster_header* can be specified. Returns empty
538
   *         string if no shadowing should take place.
539
   */
540
  virtual const std::string& cluster() const PURE;
541

            
542
  /**
543
   * @return the cluster header name that router can get the cluster name from request headers.
544
   *         Only one of *cluster* and *cluster_header* can be specified. Returns empty
545
   *         string if no shadowing should take place.
546
   */
547
  virtual const Http::LowerCaseString& clusterHeader() const PURE;
548

            
549
  /**
550
   * @return the runtime key that will be used to determine whether an individual request should
551
   *         be shadowed. The lack of a key means that all requests will be shadowed. If a key is
552
   *         present it will be used to drive random selection in the range 0-10000 for 0.01%
553
   *         increments.
554
   */
555
  virtual const std::string& runtimeKey() const PURE;
556

            
557
  /**
558
   * @return the default fraction of traffic the should be shadowed, if the runtime key is not
559
   *         present.
560
   */
561
  virtual const envoy::type::v3::FractionalPercent& defaultValue() const PURE;
562

            
563
  /**
564
   * @return true if the trace span should be sampled.
565
   */
566
  virtual absl::optional<bool> traceSampled() const PURE;
567

            
568
  /**
569
   * @return true if host name should be suffixed with "-shadow".
570
   */
571
  virtual bool disableShadowHostSuffixAppend() const PURE;
572

            
573
  /**
574
   * @return the header evaluator for manipulating headers in mirrored requests.
575
   */
576
  virtual const Http::HeaderEvaluator& headerEvaluator() const PURE;
577

            
578
  /**
579
   * @return the literal value to rewrite the host header with, or empty if no rewrite.
580
   */
581
  virtual absl::string_view hostRewriteLiteral() const PURE;
582
};
583

            
584
using ShadowPolicyPtr = std::shared_ptr<ShadowPolicy>;
585

            
586
/**
587
 * All virtual cluster stats. @see stats_macro.h
588
 */
589
#define ALL_VIRTUAL_CLUSTER_STATS(COUNTER, GAUGE, HISTOGRAM, TEXT_READOUT, STATNAME)               \
590
  COUNTER(upstream_rq_retry)                                                                       \
591
  COUNTER(upstream_rq_retry_limit_exceeded)                                                        \
592
  COUNTER(upstream_rq_retry_overflow)                                                              \
593
  COUNTER(upstream_rq_retry_success)                                                               \
594
  COUNTER(upstream_rq_timeout)                                                                     \
595
  COUNTER(upstream_rq_total)                                                                       \
596
  STATNAME(other)                                                                                  \
597
  STATNAME(vcluster)                                                                               \
598
  STATNAME(vhost)
599

            
600
/**
601
 * All route level stats. @see stats_macro.h
602
 */
603
#define ALL_ROUTE_STATS(COUNTER, GAUGE, HISTOGRAM, TEXT_READOUT, STATNAME)                         \
604
  COUNTER(upstream_rq_retry)                                                                       \
605
  COUNTER(upstream_rq_retry_limit_exceeded)                                                        \
606
  COUNTER(upstream_rq_retry_overflow)                                                              \
607
  COUNTER(upstream_rq_retry_success)                                                               \
608
  COUNTER(upstream_rq_timeout)                                                                     \
609
  COUNTER(upstream_rq_total)                                                                       \
610
  STATNAME(route)                                                                                  \
611
  STATNAME(vhost)
612

            
613
/**
614
 * Struct definition for all virtual cluster stats. @see stats_macro.h
615
 */
616
MAKE_STAT_NAMES_STRUCT(VirtualClusterStatNames, ALL_VIRTUAL_CLUSTER_STATS);
617
MAKE_STATS_STRUCT(VirtualClusterStats, VirtualClusterStatNames, ALL_VIRTUAL_CLUSTER_STATS);
618

            
619
/**
620
 * Struct definition for all route level stats. @see stats_macro.h
621
 */
622
MAKE_STAT_NAMES_STRUCT(RouteStatNames, ALL_ROUTE_STATS);
623
MAKE_STATS_STRUCT(RouteStats, RouteStatNames, ALL_ROUTE_STATS);
624

            
625
/**
626
 * RouteStatsContext defines config needed to generate all route level stats.
627
 */
628
class RouteStatsContext;
629

            
630
using RouteStatsContextPtr = std::unique_ptr<RouteStatsContext>;
631
using RouteStatsContextOptRef = OptRef<RouteStatsContext>;
632

            
633
/**
634
 * Virtual cluster definition (allows splitting a virtual host into virtual clusters orthogonal to
635
 * routes for stat tracking and priority purposes).
636
 */
637
class VirtualCluster {
638
public:
639
8601
  virtual ~VirtualCluster() = default;
640

            
641
  /**
642
   * @return the string name of the virtual cluster.
643
   */
644
  virtual const absl::optional<std::string>& name() const PURE;
645

            
646
  /**
647
   * @return the stat-name of the virtual cluster.
648
   */
649
  virtual Stats::StatName statName() const PURE;
650

            
651
  /**
652
   * @return VirtualClusterStats& strongly named stats for this virtual cluster.
653
   */
654
  virtual VirtualClusterStats& stats() const PURE;
655

            
656
  static VirtualClusterStats generateStats(Stats::Scope& scope,
657
8601
                                           const VirtualClusterStatNames& stat_names) {
658
8601
    return {stat_names, scope};
659
8601
  }
660
};
661

            
662
class RateLimitPolicy;
663
class Config;
664
class CommonConfig;
665

            
666
/**
667
 * Virtual host definition.
668
 */
669
class VirtualHost {
670
public:
671
20103
  virtual ~VirtualHost() = default;
672

            
673
  /**
674
   * @return const CorsPolicy* the CORS policy for this virtual host.
675
   */
676
  virtual const CorsPolicy* corsPolicy() const PURE;
677

            
678
  /**
679
   * @return const std::string& the name of the virtual host.
680
   */
681
  virtual const std::string& name() const PURE;
682

            
683
  /**
684
   * @return the stat-name of the virtual host.
685
   */
686
  virtual Stats::StatName statName() const PURE;
687

            
688
  /**
689
   * @return const RateLimitPolicy& the rate limit policy for the virtual host.
690
   */
691
  virtual const RateLimitPolicy& rateLimitPolicy() const PURE;
692

            
693
  /**
694
   * @return const Config& the RouteConfiguration that owns this virtual host.
695
   */
696
  virtual const CommonConfig& routeConfig() const PURE;
697

            
698
  /**
699
   * @return bool whether to include the request count header in upstream requests.
700
   */
701
  virtual bool includeAttemptCountInRequest() const PURE;
702

            
703
  /**
704
   * @return bool whether to include the request count header in the downstream response.
705
   */
706
  virtual bool includeAttemptCountInResponse() const PURE;
707

            
708
  /**
709
   * @return bool whether to include the header in the upstream request to indicate it is a retry
710
   * initiated by a timeout.
711
   */
712
  virtual bool includeIsTimeoutRetryHeader() const PURE;
713

            
714
  /**
715
   * This is a helper to get the route's per-filter config if it exists, up along the config
716
   * hierarchy (Route --> VirtualHost --> RouteConfiguration). Or nullptr if none of them exist.
717
   */
718
  virtual const RouteSpecificFilterConfig*
719
  mostSpecificPerFilterConfig(absl::string_view name) const PURE;
720

            
721
  /**
722
   * Return all the available per route filter configs. The configs is in order of specificity.
723
   * That means that the config from a route configuration will be first, then the config from a
724
   * virtual host, then the config from a route.
725
   */
726
  virtual Router::RouteSpecificFilterConfigs perFilterConfigs(absl::string_view name) const PURE;
727

            
728
  /**
729
   * @return const envoy::config::core::v3::Metadata& return the metadata provided in the config for
730
   * this virtual host.
731
   */
732
  virtual const envoy::config::core::v3::Metadata& metadata() const PURE;
733

            
734
  /**
735
   * @return const Envoy::Config::TypedMetadata& return the typed metadata provided in the config
736
   * for this virtual host.
737
   */
738
  virtual const Envoy::Config::TypedMetadata& typedMetadata() const PURE;
739

            
740
  /**
741
   * Determine whether a specific request path belongs to a virtual cluster for use in stats, etc.
742
   * @param headers supplies the request headers.
743
   * @return the virtual cluster or nullptr if there is no match.
744
   */
745
  virtual const VirtualCluster* virtualCluster(const Http::HeaderMap& headers) const PURE;
746
};
747

            
748
using VirtualHostConstSharedPtr = std::shared_ptr<const VirtualHost>;
749

            
750
/**
751
 * Route level hedging policy.
752
 */
753
class HedgePolicy {
754
public:
755
8527
  virtual ~HedgePolicy() = default;
756

            
757
  /**
758
   * @return number of upstream requests that should be sent initially.
759
   */
760
  virtual uint32_t initialRequests() const PURE;
761

            
762
  /**
763
   * @return percent chance that an additional upstream request should be sent
764
   * on top of the value from initialRequests().
765
   */
766
  virtual const envoy::type::v3::FractionalPercent& additionalRequestChance() const PURE;
767

            
768
  /**
769
   * @return bool indicating whether request hedging should occur when a request
770
   * is retried due to a per try timeout. The alternative is the original request
771
   * will be canceled immediately.
772
   */
773
  virtual bool hedgeOnPerTryTimeout() const PURE;
774
};
775

            
776
class MetadataMatchCriterion {
777
public:
778
593
  virtual ~MetadataMatchCriterion() = default;
779

            
780
  /*
781
   * @return const std::string& the name of the metadata key
782
   */
783
  virtual const std::string& name() const PURE;
784

            
785
  /*
786
   * @return const Envoy::HashedValue& the value for the metadata key
787
   */
788
  virtual const HashedValue& value() const PURE;
789
};
790

            
791
using MetadataMatchCriterionConstSharedPtr = std::shared_ptr<const MetadataMatchCriterion>;
792

            
793
class MetadataMatchCriteria;
794
using MetadataMatchCriteriaConstPtr = std::unique_ptr<const MetadataMatchCriteria>;
795

            
796
class MetadataMatchCriteria {
797
public:
798
9028
  virtual ~MetadataMatchCriteria() = default;
799

            
800
  /*
801
   * @return std::vector<MetadataMatchCriterionConstSharedPtr>& a vector of
802
   * metadata to be matched against upstream endpoints when load
803
   * balancing, sorted lexically by name.
804
   */
805
  virtual const std::vector<MetadataMatchCriterionConstSharedPtr>&
806
  metadataMatchCriteria() const PURE;
807

            
808
  /**
809
   * Creates a new MetadataMatchCriteria, merging existing
810
   * metadata criteria with the provided criteria. The result criteria is the
811
   * combination of both sets of criteria, with those from the metadata_matches
812
   * Protobuf::Struct taking precedence.
813
   * @param metadata_matches supplies the new criteria.
814
   * @return MetadataMatchCriteriaConstPtr the result criteria.
815
   */
816
  virtual MetadataMatchCriteriaConstPtr
817
  mergeMatchCriteria(const Protobuf::Struct& metadata_matches) const PURE;
818

            
819
  /**
820
   * Creates a new MetadataMatchCriteria with criteria vector reduced to given names
821
   * @param names names of metadata keys to preserve
822
   * @return MetadataMatchCriteriaConstPtr the result criteria. Returns nullptr if the result
823
   * criteria are empty.
824
   */
825
  virtual MetadataMatchCriteriaConstPtr
826
  filterMatchCriteria(const std::set<std::string>& names) const PURE;
827
};
828

            
829
/**
830
 * Criterion that a route entry uses for matching TLS connection context.
831
 */
832
class TlsContextMatchCriteria {
833
public:
834
8532
  virtual ~TlsContextMatchCriteria() = default;
835

            
836
  /**
837
   * @return bool indicating whether the client presented credentials.
838
   */
839
  virtual const absl::optional<bool>& presented() const PURE;
840

            
841
  /**
842
   * @return bool indicating whether the client credentials successfully validated against the TLS
843
   * context validation context.
844
   */
845
  virtual const absl::optional<bool>& validated() const PURE;
846
};
847

            
848
using TlsContextMatchCriteriaConstPtr = std::unique_ptr<const TlsContextMatchCriteria>;
849

            
850
/**
851
 * Type of path matching that a route entry uses.
852
 */
853
enum class PathMatchType {
854
  None,
855
  Prefix,
856
  Exact,
857
  Regex,
858
  PathSeparatedPrefix,
859
  Template,
860
};
861

            
862
/**
863
 * Criterion that a route entry uses for matching a particular path.
864
 * Extensions can use this to gain better insights of chosen route paths,
865
 * see: https://github.com/envoyproxy/envoy/pull/2531.
866
 */
867
class PathMatchCriterion {
868
public:
869
21322
  virtual ~PathMatchCriterion() = default;
870

            
871
  /**
872
   * @return PathMatchType type of path match.
873
   */
874
  virtual PathMatchType matchType() const PURE;
875

            
876
  /**
877
   * @return const std::string& the string with which to compare paths.
878
   */
879
  virtual const std::string& matcher() const PURE;
880
};
881

            
882
/**
883
 * Base class for all route typed metadata factories.
884
 */
885
class HttpRouteTypedMetadataFactory : public Envoy::Config::TypedMetadataFactory {};
886

            
887
/**
888
 * Base class for all early data option extensions.
889
 */
890
class EarlyDataPolicy {
891
public:
892
24924
  virtual ~EarlyDataPolicy() = default;
893

            
894
  /**
895
   * @return bool whether the given request may be sent over early data.
896
   */
897
  virtual bool allowsEarlyDataForRequest(const Http::RequestHeaderMap& request_headers) const PURE;
898
};
899

            
900
using EarlyDataPolicyPtr = std::unique_ptr<EarlyDataPolicy>;
901

            
902
/**
903
 * Base class for all early data option factories.
904
 */
905
class EarlyDataPolicyFactory : public Envoy::Config::TypedFactory {
906
public:
907
  ~EarlyDataPolicyFactory() override = default;
908

            
909
  /**
910
   * @param config the typed config for early data option.
911
   * @return EarlyDataIOptionPtr an instance of EarlyDataPolicy.
912
   */
913
  virtual EarlyDataPolicyPtr createEarlyDataPolicy(const Protobuf::Message& config) PURE;
914

            
915
  // Config::UntypedFactory
916
2628
  std::string category() const override { return "envoy.route.early_data_policy"; }
917
};
918

            
919
/**
920
 * An individual resolved route entry.
921
 */
922
class RouteEntry : public ResponseEntry {
923
public:
924
33847
  ~RouteEntry() override = default;
925

            
926
  /**
927
   * @return const std::string& the upstream cluster that owns the route.
928
   */
929
  virtual const std::string& clusterName() const PURE;
930

            
931
  /**
932
   * Returns the HTTP status code to use when configured cluster is not found.
933
   * @return Http::Code to use when configured cluster is not found.
934
   */
935
  virtual Http::Code clusterNotFoundResponseCode() const PURE;
936

            
937
  /**
938
   * @return const CorsPolicy* the CORS policy for this virtual host.
939
   */
940
  virtual const CorsPolicy* corsPolicy() const PURE;
941

            
942
  /**
943
   * Returns the URL path as it will be calculated by finalizeRequestHeaders
944
   * using current values of headers. Note that final path may be different if
945
   * headers change before finalization.
946
   * @param headers supplies the request headers.
947
   * @param context supplies the formatter context for path generation.
948
   * @param stream_info holds additional information about the request.
949
   * @return std::string the value of the URL path after rewrite or empty string
950
   *         if rewrite is not configured or rewrite failed.
951
   */
952
  virtual std::string
953
  currentUrlPathAfterRewrite(const Http::RequestHeaderMap& headers,
954
                             const Formatter::Context& context,
955
                             const StreamInfo::StreamInfo& stream_info) const PURE;
956

            
957
  /**
958
   * Do potentially destructive header transforms on request headers prior to forwarding. For
959
   * example URL prefix rewriting, adding headers, etc. This should only be called ONCE
960
   * immediately prior to forwarding. It is done this way vs. copying for performance reasons.
961
   * @param headers supplies the request headers, which may be modified during this call.
962
   * @param stream_info holds additional information about the request.
963
   * @param keep_original_host_or_path insert x-envoy-original-path header if path rewritten,
964
   *        or x-envoy-original-host header if host rewritten.
965
   */
966
  virtual void finalizeRequestHeaders(Http::RequestHeaderMap& headers,
967
                                      const Formatter::Context& context,
968
                                      const StreamInfo::StreamInfo& stream_info,
969
                                      bool keep_original_host_or_path) const PURE;
970

            
971
  /**
972
   * Returns the request header transforms that would be applied if finalizeRequestHeaders were
973
   * called now. This is useful if you want to obtain request header transforms which was or will be
974
   * applied through finalizeRequestHeaders call. Note: do not use unless you are sure that there
975
   * will be no route modifications later in the filter chain.
976
   * @param stream_info holds additional information about the request.
977
   * @param do_formatting whether or not to evaluate configured transformations; if false, returns
978
   * original values instead.
979
   */
980
  virtual Http::HeaderTransforms requestHeaderTransforms(const StreamInfo::StreamInfo& stream_info,
981
                                                         bool do_formatting = true) const PURE;
982

            
983
  /**
984
   * @return const HashPolicy* the optional hash policy for the route.
985
   */
986
  virtual const Http::HashPolicy* hashPolicy() const PURE;
987

            
988
  /**
989
   * @return const HedgePolicy& the hedge policy for the route. All routes have a hedge policy even
990
   *         if it is empty and does not allow for hedged requests.
991
   */
992
  virtual const HedgePolicy& hedgePolicy() const PURE;
993

            
994
  /**
995
   * @return the priority of the route.
996
   */
997
  virtual Upstream::ResourcePriority priority() const PURE;
998

            
999
  /**
   * @return const RateLimitPolicy& the rate limit policy for the route.
   */
  virtual const RateLimitPolicy& rateLimitPolicy() const PURE;
  /**
   * @return const RetryPolicy& the retry policy for the route. All routes have a retry policy even
   *         if it is empty and does not allow retries.
   */
  virtual const RetryPolicyConstSharedPtr& retryPolicy() const PURE;
  /**
   * @return const InternalRedirectPolicy& the internal redirect policy for the route. All routes
   *         have a internal redirect policy even if it is not enabled, which means redirects are
   *         simply proxied as normal responses.
   */
  virtual const InternalRedirectPolicy& internalRedirectPolicy() const PURE;
  /**
   * @return const PathMatcherSharedPtr& the path match policy for the route.
   */
  virtual const PathMatcherSharedPtr& pathMatcher() const PURE;
  /**
   * @return const PathRewriterSharedPtr& the path match rewrite for the route.
   */
  virtual const PathRewriterSharedPtr& pathRewriter() const PURE;
  /**
   * @return uint64_t the maximum bytes which should be buffered for request bodies. This enables
   *         buffering larger request bodies beyond the connection buffer limit for use cases
   *         with large payloads, shadowing, or retries.
   *
   *         This method consolidates the functionality of the previous
   *         per_request_buffer_limit_bytes and request_body_buffer_limit fields. It supports both
   *         legacy configurations using per_request_buffer_limit_bytes and new configurations using
   *         request_body_buffer_limit.
   *
   *         If neither is set, falls back to connection buffer limits. Unlike some other buffer
   *         limits, 0 here indicates buffering should not be performed rather than no limit
   * applies.
   */
  virtual uint64_t requestBodyBufferLimit() const PURE;
  /**
   * @return const std::vector<ShadowPolicy>& the shadow policies for the route. The vector is empty
   *         if no shadowing takes place.
   */
  virtual const std::vector<ShadowPolicyPtr>& shadowPolicies() const PURE;
  /**
   * @return std::chrono::milliseconds the route's timeout.
   */
  virtual std::chrono::milliseconds timeout() const PURE;
  /**
   * @return optional<std::chrono::milliseconds> the route's idle timeout. Zero indicates a
   *         disabled idle timeout, while nullopt indicates deference to the global timeout.
   */
  virtual absl::optional<std::chrono::milliseconds> idleTimeout() const PURE;
  /**
   * @return optional<std::chrono::milliseconds> the route's flush timeout. Zero indicates a
   *         disabled idle timeout, while nullopt indicates deference to the global timeout.
   */
  virtual absl::optional<std::chrono::milliseconds> flushTimeout() const PURE;
  /**
   * @return true if new style max_stream_duration config should be used over the old style.
   */
  virtual bool usingNewTimeouts() const PURE;
  /**
   * @return optional<std::chrono::milliseconds> the route's maximum stream duration.
   */
  virtual absl::optional<std::chrono::milliseconds> maxStreamDuration() const PURE;
  /**
   * @return optional<std::chrono::milliseconds> the max grpc-timeout this route will allow.
   */
  virtual absl::optional<std::chrono::milliseconds> grpcTimeoutHeaderMax() const PURE;
  /**
   * @return optional<std::chrono::milliseconds> the delta between grpc-timeout and enforced grpc
   *         timeout.
   */
  virtual absl::optional<std::chrono::milliseconds> grpcTimeoutHeaderOffset() const PURE;
  /**
   * @return absl::optional<std::chrono::milliseconds> the maximum allowed timeout value derived
   * from 'grpc-timeout' header of a gRPC request. Non-present value disables use of 'grpc-timeout'
   * header, while 0 represents infinity.
   */
  virtual absl::optional<std::chrono::milliseconds> maxGrpcTimeout() const PURE;
  /**
   * @return absl::optional<std::chrono::milliseconds> the timeout offset to apply to the timeout
   * provided by the 'grpc-timeout' header of a gRPC request. This value will be positive and should
   * be subtracted from the value provided by the header.
   */
  virtual absl::optional<std::chrono::milliseconds> grpcTimeoutOffset() const PURE;
  /**
   * @return bool true if the :authority header should be overwritten with the upstream hostname.
   */
  virtual bool autoHostRewrite() const PURE;
  /**
   * @return bool true if the x-forwarded-host header should be updated.
   */
  virtual bool appendXfh() const PURE;
  /**
   * @return MetadataMatchCriteria* the metadata that a subset load balancer should match when
   * selecting an upstream host
   */
  virtual const MetadataMatchCriteria* metadataMatchCriteria() const PURE;
  /**
   * @return const std::multimap<std::string, std::string> the opaque configuration associated
   *         with the route
   */
  virtual const std::multimap<std::string, std::string>& opaqueConfig() const PURE;
  /**
   * @return bool true if the virtual host rate limits should be included.
   */
  virtual bool includeVirtualHostRateLimits() const PURE;
  /**
   * @return TlsContextMatchCriteria* the tls context match criterion for this route. If there is no
   * tls context match criteria, nullptr is returned.
   */
  virtual const TlsContextMatchCriteria* tlsContextMatchCriteria() const PURE;
  /**
   * @return const PathMatchCriterion& the match criterion for this route.
   */
  virtual const PathMatchCriterion& pathMatchCriterion() const PURE;
  /**
   * True if the virtual host this RouteEntry belongs to is configured to include the attempt
   * count header.
   * @return bool whether x-envoy-attempt-count should be included on the upstream request.
   */
  virtual bool includeAttemptCountInRequest() const PURE;
  /**
   * True if the virtual host this RouteEntry belongs to is configured to include the attempt
   * count header.
   * @return bool whether x-envoy-attempt-count should be included on the downstream response.
   */
  virtual bool includeAttemptCountInResponse() const PURE;
  using UpgradeMap = std::map<std::string, bool>;
  /**
   * @return a map of route-specific upgrades to their enabled/disabled status.
   */
  virtual const UpgradeMap& upgradeMap() const PURE;
  using ConnectConfig = envoy::config::route::v3::RouteAction::UpgradeConfig::ConnectConfig;
  using ConnectConfigOptRef = OptRef<ConnectConfig>;
  /**
   * If present, informs how to handle proxying CONNECT requests on this route.
   */
  virtual const ConnectConfigOptRef connectConfig() const PURE;
  /**
   * @return RouteStatsContextOptRef the config needed to generate route level stats.
   */
  virtual const RouteStatsContextOptRef routeStatsContext() const PURE;
  /**
   * @return EarlyDataPolicy& the configured early data option.
   */
  virtual const EarlyDataPolicy& earlyDataPolicy() const PURE;
  /**
   * Refresh the target cluster of the route with the request attributes if possible.
   */
  virtual void refreshRouteCluster(const Http::RequestHeaderMap& headers,
                                   const StreamInfo::StreamInfo& stream_info) const PURE;
};
/**
 * An interface representing the Decorator.
 */
class Decorator {
public:
8476
  virtual ~Decorator() = default;
  /**
   * This method decorates the supplied span.
   * @param Tracing::Span& the span.
   */
  virtual void apply(Tracing::Span& span) const PURE;
  /**
   * This method returns the operation name.
   * @return the operation name
   */
  virtual const std::string& getOperation() const PURE;
  /**
   * This method returns whether the decorator information
   * should be propagated to other services.
   * @return whether to propagate
   */
  virtual bool propagate() const PURE;
};
using DecoratorConstPtr = std::unique_ptr<const Decorator>;
/**
 * An interface representing the Tracing for the route configuration.
 */
class RouteTracing {
public:
8478
  virtual ~RouteTracing() = default;
  /**
   * This method returns the client sampling percentage.
   * @return the client sampling percentage
   */
  virtual const envoy::type::v3::FractionalPercent& getClientSampling() const PURE;
  /**
   * This method returns the random sampling percentage.
   * @return the random sampling percentage
   */
  virtual const envoy::type::v3::FractionalPercent& getRandomSampling() const PURE;
  /**
   * This method returns the overall sampling percentage.
   * @return the overall sampling percentage
   */
  virtual const envoy::type::v3::FractionalPercent& getOverallSampling() const PURE;
  /**
   * This method returns the route level tracing custom tags.
   * @return the tracing custom tags.
   */
  virtual const Tracing::CustomTagMap& getCustomTags() const PURE;
  /**
   * This method returns operation name formatter of span for the route.
   * @return the operation formatter.
   */
  virtual OptRef<const Formatter::Formatter> operation() const PURE;
  /**
   * This method returns operation name formatter of upstream span for the route.
   * @return the operation name formatter.
   */
  virtual OptRef<const Formatter::Formatter> upstreamOperation() const PURE;
};
using RouteTracingConstPtr = std::unique_ptr<const RouteTracing>;
/**
 * An interface that holds a DirectResponseEntry or RouteEntry for a request.
 */
class Route {
public:
36914
  virtual ~Route() = default;
  /**
   * @return the direct response entry or nullptr if there is no direct response for the request.
   */
  virtual const DirectResponseEntry* directResponseEntry() const PURE;
  /**
   * @return the route entry or nullptr if there is no matching route for the request.
   */
  virtual const RouteEntry* routeEntry() const PURE;
  /**
   * @return the decorator or nullptr if not defined for the request.
   */
  virtual const Decorator* decorator() const PURE;
  /**
   * @return the tracing config or nullptr if not defined for the request.
   */
  virtual const RouteTracing* tracingConfig() const PURE;
  /**
   * Check if the filter is disabled for this route.
   * @param config_name supplies the name of the filter config in the HTTP filter chain. This name
   * may be different from the filter extension qualified name.
   * @return true if the filter is disabled for this route, false if the filter is enabled.
   *         nullopt if no decision can be made explicitly for the filter.
   */
  virtual absl::optional<bool> filterDisabled(absl::string_view config_name) const PURE;
  /**
   * This is a helper to get the route's per-filter config if it exists, up along the config
   * hierarchy(Route --> VirtualHost --> RouteConfiguration). Or nullptr if none of them exist.
   */
  virtual const RouteSpecificFilterConfig*
  mostSpecificPerFilterConfig(absl::string_view name) const PURE;
  /**
   * Return all the available per route filter configs. The configs is in order of specificity.
   * That means that the config from a route configuration will be first, then the config from a
   * virtual host, then the config from a route.
   */
  virtual Router::RouteSpecificFilterConfigs perFilterConfigs(absl::string_view name) const PURE;
  /**
   * @return const envoy::config::core::v3::Metadata& return the metadata provided in the config for
   * this route.
   */
  virtual const envoy::config::core::v3::Metadata& metadata() const PURE;
  /**
   * @return const Envoy::Config::TypedMetadata& return the typed metadata provided in the config
   * for this route.
   */
  virtual const Envoy::Config::TypedMetadata& typedMetadata() const PURE;
  /**
   * @return std::string& the name of the route.
   */
  virtual const std::string& routeName() const PURE;
  /**
   * @return const VirtualHostConstSharedPtr& the virtual host that owns the route.
   *
   * NOTE: This MUST not be null.
   */
  virtual const VirtualHostConstSharedPtr& virtualHost() const PURE;
};
using RouteConstSharedPtr = std::shared_ptr<const Route>;
class RouteEntryAndRoute : public RouteEntry, public Route {};
using RouteEntryAndRouteConstSharedPtr = std::shared_ptr<const RouteEntryAndRoute>;
/**
 * RouteCallback, returns one of these enums to the route matcher to indicate
 * if the matched route has been accepted or it wants the route matching to
 * continue.
 */
enum class RouteMatchStatus {
  // Continue matching route
  Continue,
  // Accept matched route
  Accept
};
/**
 * RouteCallback is passed this enum to indicate if more routes are available for evaluation.
 */
enum class RouteEvalStatus {
  // Has more routes that can be evaluated for match.
  HasMoreRoutes,
  // All routes have been evaluated for match.
  NoMoreRoutes
};
/**
 * RouteCallback can be used to override routing decision made by the Route::Config::route,
 * this callback is passed the RouteConstSharedPtr, when a matching route is found, and
 * RouteEvalStatus indicating whether there are more routes available for evaluation.
 *
 * RouteCallback will be called back only when at least one matching route is found, if no matching
 * routes are found RouteCallback will not be invoked. RouteCallback can return one of the
 * RouteMatchStatus enum to indicate if the match has been accepted or should the route match
 * evaluation continue.
 *
 * Returning RouteMatchStatus::Continue, when no more routes available for evaluation will result in
 * no further callbacks and no route is deemed to be accepted and nullptr is returned to the caller
 * of Route::Config::route.
 */
using RouteCallback = std::function<RouteMatchStatus(RouteConstSharedPtr, RouteEvalStatus)>;
/**
 * Shared part of the route configuration. This class contains interfaces that needn't depend on
 * router matcher. Then every virtualhost could keep a reference to the CommonConfig. When the
 * entire route config is destroyed, the part of CommonConfig will still live until all
 * virtual hosts are destroyed.
 */
class CommonConfig {
public:
32452
  virtual ~CommonConfig() = default;
  /**
   * Return a list of headers that will be cleaned from any requests that are not from an internal
   * (RFC1918) source.
   */
  virtual const std::vector<Http::LowerCaseString>& internalOnlyHeaders() const PURE;
  /**
   * @return const std::string the RouteConfiguration name.
   */
  virtual const std::string& name() const PURE;
  /**
   * @return whether router configuration uses VHDS.
   */
  virtual bool usesVhds() const PURE;
  /**
   * @return bool whether most specific header mutations should take precedence. The default
   * evaluation order is route level, then virtual host level and finally global connection
   * manager level.
   */
  virtual bool mostSpecificHeaderMutationsWins() const PURE;
  /**
   * @return uint32_t The maximum bytes of the response direct response body size. The default value
   * is 4096.
   * TODO(dio): To allow overrides at different levels (e.g. per-route, virtual host, etc).
   */
  virtual uint32_t maxDirectResponseBodySizeBytes() const PURE;
  /**
   * @return const envoy::config::core::v3::Metadata& return the metadata provided in the config for
   * this route configuration.
   */
  virtual const envoy::config::core::v3::Metadata& metadata() const PURE;
  /**
   * @return const Envoy::Config::TypedMetadata& return the typed metadata provided in the config
   * for this route configuration.
   */
  virtual const Envoy::Config::TypedMetadata& typedMetadata() const PURE;
};
struct VirtualHostRoute {
  VirtualHostConstSharedPtr vhost;
  RouteConstSharedPtr route;
  // Override -> operator to access methods of route directly.
562
  const Route* operator->() const { return route.get(); }
  // Convert the VirtualHostRoute to RouteConstSharedPtr.
166
  operator RouteConstSharedPtr() const { return route; }
};
/**
 * The router configuration.
 */
class Config : public Rds::Config, public CommonConfig {
public:
  /**
   * Based on the incoming HTTP request headers, determine the target route (containing either a
   * route entry or a direct response entry) for the request.
   * @param headers supplies the request headers.
   * @param random_value supplies the random seed to use if a runtime choice is required. This
   *        allows stable choices between calls if desired.
   * @return the route result or nullptr if there is no matching route for the request.
   */
  virtual VirtualHostRoute route(const Http::RequestHeaderMap& headers,
                                 const StreamInfo::StreamInfo& stream_info,
                                 uint64_t random_value) const PURE;
  /**
   * Based on the incoming HTTP request headers, determine the target route (containing either a
   * route entry or a direct response entry) for the request.
   *
   * Invokes callback with matched route, callback can choose to accept the route by returning
   * RouteStatus::Stop or continue route match from last matched route by returning
   * RouteMatchStatus::Continue, when more routes are available.
   *
   * @param cb supplies callback to be invoked upon route match.
   * @param headers supplies the request headers.
   * @param random_value supplies the random seed to use if a runtime choice is required. This
   *        allows stable choices between calls if desired.
   * @return the route accepted by the callback or nullptr if no match found or none of route is
   * accepted by the callback.
   */
  virtual VirtualHostRoute route(const RouteCallback& cb, const Http::RequestHeaderMap& headers,
                                 const StreamInfo::StreamInfo& stream_info,
                                 uint64_t random_value) const PURE;
};
using ConfigConstSharedPtr = std::shared_ptr<const Config>;
class GenericConnectionPoolCallbacks;
class GenericUpstream;
/**
 * An API for wrapping either an HTTP, TCP, or UDP connection pool.
 *
 * The GenericConnPool exists to create a GenericUpstream handle via a call to
 * newStream resulting in an eventual call to onPoolReady
 */
class GenericConnPool {
public:
47526
  virtual ~GenericConnPool() = default;
  /**
   * Called to create a new HTTP stream, TCP connection for CONNECT streams, or UDP socket for
   * CONNECT-UDP streams.
   *
   * The implementation of the GenericConnPool will either call
   * GenericConnectionPoolCallbacks::onPoolReady
   * when a stream is available or GenericConnectionPoolCallbacks::onPoolFailure
   * if stream creation fails.
   *
   * The caller is responsible for calling cancelAnyPendingStream() if stream
   * creation is no longer desired. newStream may only be called once per
   * GenericConnPool.
   *
   * @param callbacks callbacks to communicate stream failure or creation on.
   */
  virtual void newStream(GenericConnectionPoolCallbacks* callbacks) PURE;
  /**
   * Called to cancel any pending newStream request,
   */
  virtual bool cancelAnyPendingStream() PURE;
  /**
   * @return optionally returns the host for the connection pool.
   */
  virtual Upstream::HostDescriptionConstSharedPtr host() const PURE;
  /**
   * @return returns if the connection pool was initialized successfully.
   */
  virtual bool valid() const PURE;
};
/**
 * An API for the interactions the upstream stream needs to have with the downstream stream
 * and/or router components
 */
class UpstreamToDownstream : public Http::ResponseDecoder, public Http::StreamCallbacks {
public:
  /**
   * @return return the route for the downstream stream.
   */
  virtual const Route& route() const PURE;
  /**
   * @return return the connection for the downstream stream if it exists.
   */
  virtual OptRef<const Network::Connection> connection() const PURE;
  /**
   * @return returns the options to be consulted with for upstream stream creation.
   */
  virtual const Http::ConnectionPool::Instance::StreamOptions& upstreamStreamOptions() const PURE;
};
/**
 * An API for wrapping callbacks from either an HTTP, TCP, or UDP connection pool.
 *
 * Just like the connection pool callbacks, the GenericConnectionPoolCallbacks
 * will either call onPoolReady when a GenericUpstream is ready, or
 * onPoolFailure if a connection/stream can not be established.
 */
class GenericConnectionPoolCallbacks {
public:
47507
  virtual ~GenericConnectionPoolCallbacks() = default;
  /**
   * Called to indicate a failure for GenericConnPool::newStream to establish a stream.
   *
   * @param reason supplies the failure reason.
   * @param transport_failure_reason supplies the details of the transport failure reason.
   * @param host supplies the description of the host that caused the failure. This may be nullptr
   *             if no host was involved in the failure (for example overflow).
   */
  virtual void onPoolFailure(ConnectionPool::PoolFailureReason reason,
                             absl::string_view transport_failure_reason,
                             Upstream::HostDescriptionConstSharedPtr host) PURE;
  /**
   * Called when GenericConnPool::newStream has established a new stream.
   *
   * @param upstream supplies the generic upstream for the stream.
   * @param host supplies the description of the host that will carry the request. For logical
   *             connection pools the description may be different each time this is called.
   * @param connection_info_provider, supplies the address provider of the upstream connection.
   * @param info supplies the stream info object associated with the upstream connection.
   * @param protocol supplies the protocol associated with the upstream connection.
   */
  virtual void onPoolReady(std::unique_ptr<GenericUpstream>&& upstream,
                           Upstream::HostDescriptionConstSharedPtr host,
                           const Network::ConnectionInfoProvider& connection_info_provider,
                           StreamInfo::StreamInfo& info,
                           absl::optional<Http::Protocol> protocol) PURE;
  // @return the UpstreamToDownstream interface for this stream.
  //
  // This is the interface for all interactions the upstream stream needs to have with the
  // downstream stream. It is in the GenericConnectionPoolCallbacks as the GenericConnectionPool
  // creates the GenericUpstream, and the GenericUpstream will need this interface.
  virtual UpstreamToDownstream& upstreamToDownstream() PURE;
};
/**
 * An API for sending information to either a TCP, UDP, or HTTP upstream.
 *
 * It is similar logically to RequestEncoder, only without the getStream interface.
 */
class GenericUpstream {
public:
46748
  virtual ~GenericUpstream() = default;
  /**
   * Encode a data frame.
   * @param data supplies the data to encode. The data may be moved by the encoder.
   * @param end_stream supplies whether this is the last data frame.
   */
  virtual void encodeData(Buffer::Instance& data, bool end_stream) PURE;
  /**
   * Encode metadata.
   * @param metadata_map_vector is the vector of metadata maps to encode.
   */
  virtual void encodeMetadata(const Http::MetadataMapVector& metadata_map_vector) PURE;
  /**
   * Encode headers, optionally indicating end of stream.
   * @param headers supplies the header map to encode.
   * @param end_stream supplies whether this is a header only request.
   * @return status indicating success. Encoding will fail if headers do not have required HTTP
   * headers.
   */
  virtual Http::Status encodeHeaders(const Http::RequestHeaderMap& headers, bool end_stream) PURE;
  /**
   * Encode trailers. This implicitly ends the stream.
   * @param trailers supplies the trailers to encode.
   */
  virtual void encodeTrailers(const Http::RequestTrailerMap& trailers) PURE;
  // TODO(vikaschoudhary16): Remove this api.
  // This api is only used to enable TCP tunneling semantics in the upstream codec.
  // TCP proxy extension uses this API when proxyingn TCP tunnel via HTTP CONNECT or POST.
  /**
   * Enable TCP tunneling semantics on the upstream codec. Reading a remote half-close
   * will not fully close the connection. This is off by default.
   */
  virtual void enableTcpTunneling() PURE;
  /**
   * Enable/disable further data from this stream.
   */
  virtual void readDisable(bool disable) PURE;
  /**
   * Reset the stream. No events will fire beyond this point.
   */
  virtual void resetStream() PURE;
  /**
   * Sets the upstream to use the following account.
   * @param the account to assign the generic upstream.
   */
  virtual void setAccount(Buffer::BufferMemoryAccountSharedPtr account) PURE;
  /**
   * Get the bytes meter for this stream.
   */
  virtual const StreamInfo::BytesMeterSharedPtr& bytesMeter() PURE;
};
using GenericConnPoolPtr = std::unique_ptr<GenericConnPool>;
/*
 * A factory for creating generic connection pools.
 */
class GenericConnPoolFactory : public Envoy::Config::TypedFactory {
public:
  /*
   * Protocol used by the upstream sockets.
   */
  enum class UpstreamProtocol { HTTP, TCP, UDP };
16
  ~GenericConnPoolFactory() override = default;
  /*
   * @param options for creating the transport socket
   * @return may be null
   */
  virtual GenericConnPoolPtr createGenericConnPool(
      Upstream::HostConstSharedPtr host, Upstream::ThreadLocalCluster& thread_local_cluster,
      GenericConnPoolFactory::UpstreamProtocol upstream_protocol,
      Upstream::ResourcePriority priority, absl::optional<Http::Protocol> downstream_protocol,
      Upstream::LoadBalancerContext* ctx, const Protobuf::Message& config) const PURE;
};
using GenericConnPoolFactoryPtr = std::unique_ptr<GenericConnPoolFactory>;
} // namespace Router
} // namespace Envoy