Line data Source code
1 : #pragma once
2 :
3 : #include <chrono>
4 : #include <cstdint>
5 : #include <functional>
6 : #include <list>
7 : #include <map>
8 : #include <memory>
9 : #include <string>
10 :
11 : #include "envoy/access_log/access_log.h"
12 : #include "envoy/common/conn_pool.h"
13 : #include "envoy/common/matchers.h"
14 : #include "envoy/config/core/v3/base.pb.h"
15 : #include "envoy/config/route/v3/route_components.pb.h"
16 : #include "envoy/config/typed_metadata.h"
17 : #include "envoy/http/codec.h"
18 : #include "envoy/http/codes.h"
19 : #include "envoy/http/conn_pool.h"
20 : #include "envoy/http/hash_policy.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/tcp/conn_pool.h"
26 : #include "envoy/tracing/tracer.h"
27 : #include "envoy/type/v3/percent.pb.h"
28 : #include "envoy/upstream/resource_manager.h"
29 : #include "envoy/upstream/retry.h"
30 :
31 : #include "source/common/protobuf/protobuf.h"
32 : #include "source/common/protobuf/utility.h"
33 :
34 : #include "absl/types/optional.h"
35 :
36 : namespace Envoy {
37 :
38 : namespace Upstream {
39 : class ClusterManager;
40 : class LoadBalancerContext;
41 : class ThreadLocalCluster;
42 : } // namespace Upstream
43 :
44 : namespace Router {
45 :
46 : /**
47 : * Functionality common among routing primitives, such as DirectResponseEntry and RouteEntry.
48 : */
49 : class ResponseEntry {
50 : public:
51 3746 : virtual ~ResponseEntry() = default;
52 :
53 : /**
54 : * Do potentially destructive header transforms on response headers prior to forwarding. For
55 : * example, adding or removing headers. This should only be called ONCE immediately after
56 : * obtaining the initial response headers.
57 : * @param headers supplies the response headers, which may be modified during this call.
58 : * @param stream_info holds additional information about the request.
59 : */
60 : virtual void finalizeResponseHeaders(Http::ResponseHeaderMap& headers,
61 : const StreamInfo::StreamInfo& stream_info) const PURE;
62 :
63 : /**
64 : * Returns the response header transforms that would be applied if finalizeResponseHeaders were
65 : * called now. This is useful if you want to obtain response header transforms at request time and
66 : * process them later. Note: do not use unless you are sure that there will be no route
67 : * modifications later in the filter chain.
68 : * @param stream_info holds additional information about the request.
69 : * @param do_formatting whether or not to evaluate configured transformations; if false, returns
70 : * original values instead.
71 : */
72 : virtual Http::HeaderTransforms responseHeaderTransforms(const StreamInfo::StreamInfo& stream_info,
73 : bool do_formatting = true) const PURE;
74 : };
75 :
76 : /**
77 : * A routing primitive that specifies a direct (non-proxied) HTTP response.
78 : */
79 : class DirectResponseEntry : public ResponseEntry {
80 : public:
81 1684 : ~DirectResponseEntry() override = default;
82 :
83 : /**
84 : * Returns the HTTP status code to return.
85 : * @return Http::Code the response Code.
86 : */
87 : virtual Http::Code responseCode() const PURE;
88 :
89 : /**
90 : * Returns the redirect URI based on the request headers.
91 : * @param headers supplies the request headers.
92 : * @return std::string the redirect URL if this DirectResponseEntry is a redirect,
93 : * or an empty string otherwise.
94 : */
95 : virtual std::string newUri(const Http::RequestHeaderMap& headers) const PURE;
96 :
97 : /**
98 : * Returns the response body to send with direct responses.
99 : * @return std::string& the response body specified in the route configuration,
100 : * or an empty string if no response body is specified.
101 : */
102 : virtual const std::string& responseBody() const PURE;
103 :
104 : /**
105 : * Do potentially destructive header transforms on Path header prior to redirection. For
106 : * example prefix rewriting for redirects etc. This should only be called ONCE
107 : * immediately prior to redirecting.
108 : * @param headers supplies the request headers, which may be modified during this call.
109 : * @param insert_envoy_original_path insert x-envoy-original-path header?
110 : */
111 : virtual void rewritePathHeader(Http::RequestHeaderMap& headers,
112 : bool insert_envoy_original_path) const PURE;
113 : };
114 :
115 : /**
116 : * All route specific config returned by the method at
117 : * NamedHttpFilterConfigFactory::createRouteSpecificFilterConfig
118 : * should be derived from this class.
119 : */
120 : class RouteSpecificFilterConfig {
121 : public:
122 234 : virtual ~RouteSpecificFilterConfig() = default;
123 : };
124 : using RouteSpecificFilterConfigConstSharedPtr = std::shared_ptr<const RouteSpecificFilterConfig>;
125 :
126 : /**
127 : * CorsPolicy for Route and VirtualHost.
128 : */
129 : class CorsPolicy : public RouteSpecificFilterConfig {
130 : public:
131 : /**
132 : * @return std::vector<StringMatcherPtr>& access-control-allow-origin matchers.
133 : */
134 : virtual const std::vector<Matchers::StringMatcherPtr>& allowOrigins() const PURE;
135 :
136 : /**
137 : * @return std::string access-control-allow-methods value.
138 : */
139 : virtual const std::string& allowMethods() const PURE;
140 :
141 : /**
142 : * @return std::string access-control-allow-headers value.
143 : */
144 : virtual const std::string& allowHeaders() const PURE;
145 :
146 : /**
147 : * @return std::string access-control-expose-headers value.
148 : */
149 : virtual const std::string& exposeHeaders() const PURE;
150 :
151 : /**
152 : * @return std::string access-control-max-age value.
153 : */
154 : virtual const std::string& maxAge() const PURE;
155 :
156 : /**
157 : * @return const absl::optional<bool>& Whether access-control-allow-credentials should be true.
158 : */
159 : virtual const absl::optional<bool>& allowCredentials() const PURE;
160 :
161 : /**
162 : * @return const absl::optional<bool>& How to handle access-control-request-private-network.
163 : */
164 : virtual const absl::optional<bool>& allowPrivateNetworkAccess() const PURE;
165 :
166 : /**
167 : * @return bool Whether CORS is enabled for the route or virtual host.
168 : */
169 : virtual bool enabled() const PURE;
170 :
171 : /**
172 : * @return bool Whether CORS policies are evaluated when filter is off.
173 : */
174 : virtual bool shadowEnabled() const PURE;
175 : };
176 :
177 : /**
178 : * An interface to be implemented by rate limited reset header parsers.
179 : */
180 : class ResetHeaderParser {
181 : public:
182 0 : virtual ~ResetHeaderParser() = default;
183 :
184 : /**
185 : * Iterate over the headers, choose the first one that matches by name, and try to parse its
186 : * value.
187 : */
188 : virtual absl::optional<std::chrono::milliseconds>
189 : parseInterval(TimeSource& time_source, const Http::HeaderMap& headers) const PURE;
190 : };
191 :
192 : using ResetHeaderParserSharedPtr = std::shared_ptr<ResetHeaderParser>;
193 :
194 : /**
195 : * Route level retry policy.
196 : */
197 : class RetryPolicy {
198 : public:
199 : // clang-format off
200 : static constexpr uint32_t RETRY_ON_5XX = 0x1;
201 : static constexpr uint32_t RETRY_ON_GATEWAY_ERROR = 0x2;
202 : static constexpr uint32_t RETRY_ON_CONNECT_FAILURE = 0x4;
203 : static constexpr uint32_t RETRY_ON_RETRIABLE_4XX = 0x8;
204 : static constexpr uint32_t RETRY_ON_REFUSED_STREAM = 0x10;
205 : static constexpr uint32_t RETRY_ON_GRPC_CANCELLED = 0x20;
206 : static constexpr uint32_t RETRY_ON_GRPC_DEADLINE_EXCEEDED = 0x40;
207 : static constexpr uint32_t RETRY_ON_GRPC_RESOURCE_EXHAUSTED = 0x80;
208 : static constexpr uint32_t RETRY_ON_GRPC_UNAVAILABLE = 0x100;
209 : static constexpr uint32_t RETRY_ON_GRPC_INTERNAL = 0x200;
210 : static constexpr uint32_t RETRY_ON_RETRIABLE_STATUS_CODES = 0x400;
211 : static constexpr uint32_t RETRY_ON_RESET = 0x800;
212 : static constexpr uint32_t RETRY_ON_RETRIABLE_HEADERS = 0x1000;
213 : static constexpr uint32_t RETRY_ON_ENVOY_RATE_LIMITED = 0x2000;
214 : static constexpr uint32_t RETRY_ON_HTTP3_POST_CONNECT_FAILURE = 0x4000;
215 : // clang-format on
216 :
217 257 : virtual ~RetryPolicy() = default;
218 :
219 : /**
220 : * @return std::chrono::milliseconds timeout per retry attempt. 0 is disabled.
221 : */
222 : virtual std::chrono::milliseconds perTryTimeout() const PURE;
223 :
224 : /**
225 : * @return std::chrono::milliseconds the optional per try idle timeout. 0 is disabled.
226 : */
227 : virtual std::chrono::milliseconds perTryIdleTimeout() const PURE;
228 :
229 : /**
230 : * @return uint32_t the number of retries to allow against the route.
231 : */
232 : virtual uint32_t numRetries() const PURE;
233 :
234 : /**
235 : * @return uint32_t a local OR of RETRY_ON values above.
236 : */
237 : virtual uint32_t retryOn() const PURE;
238 :
239 : /**
240 : * Initializes a new set of RetryHostPredicates to be used when retrying with this retry policy.
241 : * @return list of RetryHostPredicates to use
242 : */
243 : virtual std::vector<Upstream::RetryHostPredicateSharedPtr> retryHostPredicates() const PURE;
244 :
245 : /**
246 : * Initializes a RetryPriority to be used when retrying with this retry policy.
247 : * @return the RetryPriority to use when determining priority load for retries, or nullptr
248 : * if none should be used.
249 : */
250 : virtual Upstream::RetryPrioritySharedPtr retryPriority() const PURE;
251 :
252 : /**
253 : * @return the retry options predicates for this policy. Each policy will be applied prior
254 : * to retrying a request, allowing for request behavior to be customized.
255 : */
256 : virtual absl::Span<const Upstream::RetryOptionsPredicateConstSharedPtr>
257 : retryOptionsPredicates() const PURE;
258 :
259 : /**
260 : * Number of times host selection should be reattempted when selecting a host
261 : * for a retry attempt.
262 : */
263 : virtual uint32_t hostSelectionMaxAttempts() const PURE;
264 :
265 : /**
266 : * List of status codes that should trigger a retry when the retriable-status-codes retry
267 : * policy is enabled.
268 : */
269 : virtual const std::vector<uint32_t>& retriableStatusCodes() const PURE;
270 :
271 : /**
272 : * @return std::vector<Http::HeaderMatcherSharedPtr>& list of response header matchers that
273 : * will be checked when the 'retriable-headers' retry policy is enabled.
274 : */
275 : virtual const std::vector<Http::HeaderMatcherSharedPtr>& retriableHeaders() const PURE;
276 :
277 : /**
278 : * @return std::vector<Http::HeaderMatcherSharedPt>& list of request header
279 : * matchers that will be checked before enabling retries.
280 : */
281 : virtual const std::vector<Http::HeaderMatcherSharedPtr>& retriableRequestHeaders() const PURE;
282 :
283 : /**
284 : * @return absl::optional<std::chrono::milliseconds> base retry interval
285 : */
286 : virtual absl::optional<std::chrono::milliseconds> baseInterval() const PURE;
287 :
288 : /**
289 : * @return absl::optional<std::chrono::milliseconds> maximum retry interval
290 : */
291 : virtual absl::optional<std::chrono::milliseconds> maxInterval() const PURE;
292 :
293 : /**
294 : * @return std::vector<Http::ResetHeaderParserSharedPtr>& list of reset header
295 : * parsers that will be used to extract a retry back-off interval from response headers.
296 : */
297 : virtual const std::vector<ResetHeaderParserSharedPtr>& resetHeaders() const PURE;
298 :
299 : /**
300 : * @return std::chrono::milliseconds upper limit placed on a retry
301 : * back-off interval parsed from response headers.
302 : */
303 : virtual std::chrono::milliseconds resetMaxInterval() const PURE;
304 : };
305 :
306 : /**
307 : * RetryStatus whether request should be retried or not.
308 : */
309 : enum class RetryStatus { No, NoOverflow, NoRetryLimitExceeded, Yes };
310 :
311 : /**
312 : * InternalRedirectPolicy from the route configuration.
313 : */
314 : class InternalRedirectPolicy {
315 : public:
316 110 : virtual ~InternalRedirectPolicy() = default;
317 :
318 : /**
319 : * @return whether internal redirect is enabled on this route.
320 : */
321 : virtual bool enabled() const PURE;
322 :
323 : /**
324 : * @param response_code the response code from the upstream.
325 : * @return whether the given response_code should trigger an internal redirect on this route.
326 : */
327 : virtual bool shouldRedirectForResponseCode(const Http::Code& response_code) const PURE;
328 :
329 : /**
330 : * Creates the target route predicates. This should really be called only once for each upstream
331 : * redirect response. Creating the predicates lazily to avoid wasting CPU cycles on non-redirect
332 : * responses, which should be the most common case.
333 : * @return a vector of newly constructed InternalRedirectPredicate instances.
334 : */
335 : virtual std::vector<InternalRedirectPredicateSharedPtr> predicates() const PURE;
336 :
337 : /**
338 : * @return a vector of response header names to preserve in the redirected request.
339 : */
340 : virtual const std::vector<Http::LowerCaseString>& responseHeadersToCopy() const PURE;
341 :
342 : /**
343 : * @return the maximum number of allowed internal redirects on this route.
344 : */
345 : virtual uint32_t maxInternalRedirects() const PURE;
346 :
347 : /**
348 : * @return if it is allowed to follow the redirect with a different scheme in
349 : * the target URI than the downstream request.
350 : */
351 : virtual bool isCrossSchemeRedirectAllowed() const PURE;
352 : };
353 :
354 : /**
355 : * Wraps retry state for an active routed request.
356 : */
357 : class RetryState {
358 : public:
359 : enum class RetryDecision {
360 : // Retry the request immediately.
361 : RetryImmediately,
362 : // Retry the request with timed backoff delay.
363 : RetryWithBackoff,
364 : // Do not retry.
365 : NoRetry,
366 : };
367 :
368 : enum class Http3Used {
369 : Unknown,
370 : Yes,
371 : No,
372 : };
373 :
374 : using DoRetryCallback = std::function<void()>;
375 : /**
376 : * @param disabled_http3 indicates whether the retry should disable http3 or not.
377 : */
378 : using DoRetryResetCallback = std::function<void(bool disable_http3)>;
379 : /**
380 : * @param disable_early_data indicates whether the retry should disable early data or not.
381 : */
382 : using DoRetryHeaderCallback = std::function<void(bool disable_early_data)>;
383 :
384 0 : virtual ~RetryState() = default;
385 :
386 : /**
387 : * @return true if a policy is in place for the active request that allows retries.
388 : */
389 : virtual bool enabled() PURE;
390 :
391 : /**
392 : * Attempts to parse any matching rate limited reset headers (RFC 7231), either in the form of an
393 : * interval directly, or in the form of a unix timestamp relative to the current system time.
394 : * @return the interval if parsing was successful.
395 : */
396 : virtual absl::optional<std::chrono::milliseconds>
397 : parseResetInterval(const Http::ResponseHeaderMap& response_headers) const PURE;
398 :
399 : /**
400 : * Determine whether a request should be retried based on the response headers.
401 : * @param response_headers supplies the response headers.
402 : * @param original_request supplies the original request headers.
403 : * @param callback supplies the callback that will be invoked when the retry should take place.
404 : * This is used to add timed backoff, etc. The callback will never be called
405 : * inline.
406 : * @return RetryStatus if a retry should take place. @param callback will be called at some point
407 : * in the future. Otherwise a retry should not take place and the callback will never be
408 : * called. Calling code should proceed with error handling.
409 : */
410 : virtual RetryStatus shouldRetryHeaders(const Http::ResponseHeaderMap& response_headers,
411 : const Http::RequestHeaderMap& original_request,
412 : DoRetryHeaderCallback callback) PURE;
413 :
414 : /**
415 : * Determines whether given response headers would be retried by the retry policy, assuming
416 : * sufficient retry budget and circuit breaker headroom. This is useful in cases where
417 : * the information about whether a response is "good" or not is useful, but a retry should
418 : * not be attempted for other reasons.
419 : * @param response_headers supplies the response headers.
420 : * @param original_request supplies the original request headers.
421 : * @param retry_as_early_data output argument to tell the caller if a retry should be sent as
422 : * early data if it is warranted.
423 : * @return RetryDecision if a retry would be warranted based on the retry policy and if it would
424 : * be warranted with timed backoff.
425 : */
426 : virtual RetryDecision wouldRetryFromHeaders(const Http::ResponseHeaderMap& response_headers,
427 : const Http::RequestHeaderMap& original_request,
428 : bool& retry_as_early_data) PURE;
429 :
430 : /**
431 : * Determine whether a request should be retried after a reset based on the reason for the reset.
432 : * @param reset_reason supplies the reset reason.
433 : * @param http3_used whether the reset request was sent over http3 as alternate protocol or
434 : * not. nullopt means it wasn't sent at all before getting reset.
435 : * @param callback supplies the callback that will be invoked when the retry should take place.
436 : * This is used to add timed backoff, etc. The callback will never be called
437 : * inline.
438 : * @return RetryStatus if a retry should take place. @param callback will be called at some point
439 : * in the future. Otherwise a retry should not take place and the callback will never be
440 : * called. Calling code should proceed with error handling.
441 : */
442 : virtual RetryStatus shouldRetryReset(Http::StreamResetReason reset_reason, Http3Used http3_used,
443 : DoRetryResetCallback callback) PURE;
444 :
445 : /**
446 : * Determine whether a "hedged" retry should be sent after the per try
447 : * timeout expires. This means the original request is not canceled, but a
448 : * new one is sent to hedge against the original request taking even longer.
449 : * @param callback supplies the callback that will be invoked when the retry should take place.
450 : * This is used to add timed backoff, etc. The callback will never be called
451 : * inline.
452 : * @return RetryStatus if a retry should take place. @param callback will be called at some point
453 : * in the future. Otherwise a retry should not take place and the callback will never be
454 : * called. Calling code should proceed with error handling.
455 : */
456 : virtual RetryStatus shouldHedgeRetryPerTryTimeout(DoRetryCallback callback) PURE;
457 :
458 : /**
459 : * Called when a host was attempted but the request failed and is eligible for another retry.
460 : * Should be used to update whatever internal state depends on previously attempted hosts.
461 : * @param host the previously attempted host.
462 : */
463 : virtual void onHostAttempted(Upstream::HostDescriptionConstSharedPtr host) PURE;
464 :
465 : /**
466 : * Determine whether host selection should be reattempted. Applies to host selection during
467 : * retries, and is used to provide configurable host selection for retries.
468 : * @param host the host under consideration
469 : * @return whether host selection should be reattempted
470 : */
471 : virtual bool shouldSelectAnotherHost(const Upstream::Host& host) PURE;
472 :
473 : /**
474 : * Returns a reference to the PriorityLoad that should be used for the next retry.
475 : * @param priority_set current priority set.
476 : * @param original_priority_load original priority load.
477 : * @param priority_mapping_func see @Upstream::RetryPriority::PriorityMappingFunc.
478 : * @return HealthyAndDegradedLoad that should be used to select a priority for the next retry.
479 : */
480 : virtual const Upstream::HealthyAndDegradedLoad& priorityLoadForRetry(
481 : const Upstream::PrioritySet& priority_set,
482 : const Upstream::HealthyAndDegradedLoad& original_priority_load,
483 : const Upstream::RetryPriority::PriorityMappingFunc& priority_mapping_func) PURE;
484 : /**
485 : * return how many times host selection should be reattempted during host selection.
486 : */
487 : virtual uint32_t hostSelectionMaxAttempts() const PURE;
488 : };
489 :
490 : using RetryStatePtr = std::unique_ptr<RetryState>;
491 :
492 : /**
493 : * Per route policy for request shadowing.
494 : */
495 : class ShadowPolicy {
496 : public:
497 56 : virtual ~ShadowPolicy() = default;
498 :
499 : /**
500 : * @return the name of the cluster that a matching request should be shadowed to.
501 : * Only one of *cluster* and *cluster_header* can be specified. Returns empty
502 : * string if no shadowing should take place.
503 : */
504 : virtual const std::string& cluster() const PURE;
505 :
506 : /**
507 : * @return the cluster header name that router can get the cluster name from request headers.
508 : * Only one of *cluster* and *cluster_header* can be specified. Returns empty
509 : * string if no shadowing should take place.
510 : */
511 : virtual const Http::LowerCaseString& clusterHeader() const PURE;
512 :
513 : /**
514 : * @return the runtime key that will be used to determine whether an individual request should
515 : * be shadowed. The lack of a key means that all requests will be shadowed. If a key is
516 : * present it will be used to drive random selection in the range 0-10000 for 0.01%
517 : * increments.
518 : */
519 : virtual const std::string& runtimeKey() const PURE;
520 :
521 : /**
522 : * @return the default fraction of traffic the should be shadowed, if the runtime key is not
523 : * present.
524 : */
525 : virtual const envoy::type::v3::FractionalPercent& defaultValue() const PURE;
526 :
527 : /**
528 : * @return true if the trace span should be sampled.
529 : */
530 : virtual bool traceSampled() const PURE;
531 : };
532 :
533 : using ShadowPolicyPtr = std::shared_ptr<ShadowPolicy>;
534 :
535 : /**
536 : * All virtual cluster stats. @see stats_macro.h
537 : */
538 : #define ALL_VIRTUAL_CLUSTER_STATS(COUNTER, GAUGE, HISTOGRAM, TEXT_READOUT, STATNAME) \
539 : COUNTER(upstream_rq_retry) \
540 : COUNTER(upstream_rq_retry_limit_exceeded) \
541 : COUNTER(upstream_rq_retry_overflow) \
542 : COUNTER(upstream_rq_retry_success) \
543 : COUNTER(upstream_rq_timeout) \
544 : COUNTER(upstream_rq_total) \
545 : STATNAME(other) \
546 : STATNAME(vcluster) \
547 : STATNAME(vhost)
548 :
549 : /**
550 : * All route level stats. @see stats_macro.h
551 : */
552 : #define ALL_ROUTE_STATS(COUNTER, GAUGE, HISTOGRAM, TEXT_READOUT, STATNAME) \
553 : COUNTER(upstream_rq_retry) \
554 : COUNTER(upstream_rq_retry_limit_exceeded) \
555 : COUNTER(upstream_rq_retry_overflow) \
556 : COUNTER(upstream_rq_retry_success) \
557 : COUNTER(upstream_rq_timeout) \
558 : COUNTER(upstream_rq_total) \
559 : STATNAME(route) \
560 : STATNAME(vhost)
561 :
562 : /**
563 : * Struct definition for all virtual cluster stats. @see stats_macro.h
564 : */
565 : MAKE_STAT_NAMES_STRUCT(VirtualClusterStatNames, ALL_VIRTUAL_CLUSTER_STATS);
566 : MAKE_STATS_STRUCT(VirtualClusterStats, VirtualClusterStatNames, ALL_VIRTUAL_CLUSTER_STATS);
567 :
568 : /**
569 : * Struct definition for all route level stats. @see stats_macro.h
570 : */
571 : MAKE_STAT_NAMES_STRUCT(RouteStatNames, ALL_ROUTE_STATS);
572 : MAKE_STATS_STRUCT(RouteStats, RouteStatNames, ALL_ROUTE_STATS);
573 :
574 : /**
575 : * RouteStatsContext defines config needed to generate all route level stats.
576 : */
577 : class RouteStatsContext;
578 :
579 : using RouteStatsContextPtr = std::unique_ptr<RouteStatsContext>;
580 : using RouteStatsContextOptRef = OptRef<RouteStatsContext>;
581 :
582 : /**
583 : * Virtual cluster definition (allows splitting a virtual host into virtual clusters orthogonal to
584 : * routes for stat tracking and priority purposes).
585 : */
586 : class VirtualCluster {
587 : public:
588 101 : virtual ~VirtualCluster() = default;
589 :
590 : /**
591 : * @return the string name of the virtual cluster.
592 : */
593 : virtual const absl::optional<std::string>& name() const PURE;
594 :
595 : /**
596 : * @return the stat-name of the virtual cluster.
597 : */
598 : virtual Stats::StatName statName() const PURE;
599 :
600 : /**
601 : * @return VirtualClusterStats& strongly named stats for this virtual cluster.
602 : */
603 : virtual VirtualClusterStats& stats() const PURE;
604 :
605 : static VirtualClusterStats generateStats(Stats::Scope& scope,
606 101 : const VirtualClusterStatNames& stat_names) {
607 101 : return {stat_names, scope};
608 101 : }
609 : };
610 :
611 : class RateLimitPolicy;
612 : class Config;
613 : class CommonConfig;
614 :
615 : /**
616 : * Virtual host definition.
617 : */
618 : class VirtualHost {
619 : public:
620 1373 : virtual ~VirtualHost() = default;
621 :
622 : /**
623 : * @return const CorsPolicy* the CORS policy for this virtual host.
624 : */
625 : virtual const CorsPolicy* corsPolicy() const PURE;
626 :
627 : /**
628 : * @return the stat-name of the virtual host.
629 : */
630 : virtual Stats::StatName statName() const PURE;
631 :
632 : /**
633 : * @return const RateLimitPolicy& the rate limit policy for the virtual host.
634 : */
635 : virtual const RateLimitPolicy& rateLimitPolicy() const PURE;
636 :
637 : /**
638 : * @return const Config& the RouteConfiguration that owns this virtual host.
639 : */
640 : virtual const CommonConfig& routeConfig() const PURE;
641 :
642 : /**
643 : * @return bool whether to include the request count header in upstream requests.
644 : */
645 : virtual bool includeAttemptCountInRequest() const PURE;
646 :
647 : /**
648 : * @return bool whether to include the request count header in the downstream response.
649 : */
650 : virtual bool includeAttemptCountInResponse() const PURE;
651 :
652 : /**
653 : * @return bool whether to include the header in the upstream request to indicate it is a retry
654 : * initiated by a timeout.
655 : */
656 : virtual bool includeIsTimeoutRetryHeader() const PURE;
657 :
658 : /**
659 : * @return uint32_t any route cap on bytes which should be buffered for shadowing or retries.
660 : * This is an upper bound so does not necessarily reflect the bytes which will be buffered
661 : * as other limits may apply.
662 : * If a per route limit exists, it takes precedence over this configuration.
663 : * Unlike some other buffer limits, 0 here indicates buffering should not be performed
664 : * rather than no limit applies.
665 : */
666 : virtual uint32_t retryShadowBufferLimit() const PURE;
667 :
668 : /**
669 : * This is a helper to get the route's per-filter config if it exists, up along the config
670 : * hierarchy (Route --> VirtualHost --> RouteConfiguration). Or nullptr if none of them exist.
671 : */
672 : virtual const RouteSpecificFilterConfig*
673 : mostSpecificPerFilterConfig(const std::string& name) const PURE;
674 :
675 : /**
676 : * Find all the available per route filter configs, invoking the callback with
677 : * each config (if it is present). Iteration of the configs is in order of
678 : * specificity. That means that the callback will be called first for a config on
679 : * a route configuration, virtual host, route, and finally a route entry (weighted cluster). If
680 : * a config is not present, the callback will not be invoked.
681 : */
682 : virtual void traversePerFilterConfig(
683 : const std::string& filter_name,
684 : std::function<void(const Router::RouteSpecificFilterConfig&)> cb) const PURE;
685 :
686 : /**
687 : * @return const envoy::config::core::v3::Metadata& return the metadata provided in the config for
688 : * this virtual host.
689 : */
690 : virtual const envoy::config::core::v3::Metadata& metadata() const PURE;
691 :
692 : /**
693 : * @return const Envoy::Config::TypedMetadata& return the typed metadata provided in the config
694 : * for this virtual host.
695 : */
696 : virtual const Envoy::Config::TypedMetadata& typedMetadata() const PURE;
697 : };
698 :
699 : /**
700 : * Route level hedging policy.
701 : */
702 : class HedgePolicy {
703 : public:
704 137 : virtual ~HedgePolicy() = default;
705 :
706 : /**
707 : * @return number of upstream requests that should be sent initially.
708 : */
709 : virtual uint32_t initialRequests() const PURE;
710 :
711 : /**
712 : * @return percent chance that an additional upstream request should be sent
713 : * on top of the value from initialRequests().
714 : */
715 : virtual const envoy::type::v3::FractionalPercent& additionalRequestChance() const PURE;
716 :
717 : /**
718 : * @return bool indicating whether request hedging should occur when a request
719 : * is retried due to a per try timeout. The alternative is the original request
720 : * will be canceled immediately.
721 : */
722 : virtual bool hedgeOnPerTryTimeout() const PURE;
723 : };
724 :
725 : class MetadataMatchCriterion {
726 : public:
727 32 : virtual ~MetadataMatchCriterion() = default;
728 :
729 : /*
730 : * @return const std::string& the name of the metadata key
731 : */
732 : virtual const std::string& name() const PURE;
733 :
734 : /*
735 : * @return const Envoy::HashedValue& the value for the metadata key
736 : */
737 : virtual const HashedValue& value() const PURE;
738 : };
739 :
740 : using MetadataMatchCriterionConstSharedPtr = std::shared_ptr<const MetadataMatchCriterion>;
741 :
742 : class MetadataMatchCriteria;
743 : using MetadataMatchCriteriaConstPtr = std::unique_ptr<const MetadataMatchCriteria>;
744 :
745 : class MetadataMatchCriteria {
746 : public:
747 133 : virtual ~MetadataMatchCriteria() = default;
748 :
749 : /*
750 : * @return std::vector<MetadataMatchCriterionConstSharedPtr>& a vector of
751 : * metadata to be matched against upstream endpoints when load
752 : * balancing, sorted lexically by name.
753 : */
754 : virtual const std::vector<MetadataMatchCriterionConstSharedPtr>&
755 : metadataMatchCriteria() const PURE;
756 :
757 : /**
758 : * Creates a new MetadataMatchCriteria, merging existing
759 : * metadata criteria with the provided criteria. The result criteria is the
760 : * combination of both sets of criteria, with those from the metadata_matches
761 : * ProtobufWkt::Struct taking precedence.
762 : * @param metadata_matches supplies the new criteria.
763 : * @return MetadataMatchCriteriaConstPtr the result criteria.
764 : */
765 : virtual MetadataMatchCriteriaConstPtr
766 : mergeMatchCriteria(const ProtobufWkt::Struct& metadata_matches) const PURE;
767 :
768 : /**
769 : * Creates a new MetadataMatchCriteria with criteria vector reduced to given names
770 : * @param names names of metadata keys to preserve
771 : * @return MetadataMatchCriteriaConstPtr the result criteria. Returns nullptr if the result
772 : * criteria are empty.
773 : */
774 : virtual MetadataMatchCriteriaConstPtr
775 : filterMatchCriteria(const std::set<std::string>& names) const PURE;
776 : };
777 :
778 : /**
779 : * Criterion that a route entry uses for matching TLS connection context.
780 : */
781 : class TlsContextMatchCriteria {
782 : public:
783 131 : virtual ~TlsContextMatchCriteria() = default;
784 :
785 : /**
786 : * @return bool indicating whether the client presented credentials.
787 : */
788 : virtual const absl::optional<bool>& presented() const PURE;
789 :
790 : /**
791 : * @return bool indicating whether the client credentials successfully validated against the TLS
792 : * context validation context.
793 : */
794 : virtual const absl::optional<bool>& validated() const PURE;
795 : };
796 :
797 : using TlsContextMatchCriteriaConstPtr = std::unique_ptr<const TlsContextMatchCriteria>;
798 :
799 : /**
800 : * Type of path matching that a route entry uses.
801 : */
802 : enum class PathMatchType {
803 : None,
804 : Prefix,
805 : Exact,
806 : Regex,
807 : PathSeparatedPrefix,
808 : Template,
809 : };
810 :
811 : /**
812 : * Criterion that a route entry uses for matching a particular path.
813 : * Extensions can use this to gain better insights of chosen route paths,
814 : * see: https://github.com/envoyproxy/envoy/pull/2531.
815 : */
816 : class PathMatchCriterion {
817 : public:
818 1785 : virtual ~PathMatchCriterion() = default;
819 :
820 : /**
821 : * @return PathMatchType type of path match.
822 : */
823 : virtual PathMatchType matchType() const PURE;
824 :
825 : /**
826 : * @return const std::string& the string with which to compare paths.
827 : */
828 : virtual const std::string& matcher() const PURE;
829 : };
830 :
831 : /**
832 : * Base class for all route typed metadata factories.
833 : */
834 : class HttpRouteTypedMetadataFactory : public Envoy::Config::TypedMetadataFactory {};
835 :
836 : /**
837 : * Base class for all early data option extensions.
838 : */
839 : class EarlyDataPolicy {
840 : public:
841 1812 : virtual ~EarlyDataPolicy() = default;
842 :
843 : /**
844 : * @return bool whether the given request may be sent over early data.
845 : */
846 : virtual bool allowsEarlyDataForRequest(const Http::RequestHeaderMap& request_headers) const PURE;
847 : };
848 :
849 : using EarlyDataPolicyPtr = std::unique_ptr<EarlyDataPolicy>;
850 :
851 : /**
852 : * Base class for all early data option factories.
853 : */
854 : class EarlyDataPolicyFactory : public Envoy::Config::TypedFactory {
855 : public:
856 0 : ~EarlyDataPolicyFactory() override = default;
857 :
858 : /**
859 : * @param config the typed config for early data option.
860 : * @return EarlyDataIOptionPtr an instance of EarlyDataPolicy.
861 : */
862 : virtual EarlyDataPolicyPtr createEarlyDataPolicy(const Protobuf::Message& config) PURE;
863 :
864 : // Config::UntypedFactory
865 112 : std::string category() const override { return "envoy.route.early_data_policy"; }
866 : };
867 :
868 : /**
869 : * An individual resolved route entry.
870 : */
871 : class RouteEntry : public ResponseEntry {
872 : public:
873 2062 : ~RouteEntry() override = default;
874 :
875 : /**
876 : * @return const std::string& the upstream cluster that owns the route.
877 : */
878 : virtual const std::string& clusterName() const PURE;
879 :
880 : /**
881 : * Returns the HTTP status code to use when configured cluster is not found.
882 : * @return Http::Code to use when configured cluster is not found.
883 : */
884 : virtual Http::Code clusterNotFoundResponseCode() const PURE;
885 :
886 : /**
887 : * @return const CorsPolicy* the CORS policy for this virtual host.
888 : */
889 : virtual const CorsPolicy* corsPolicy() const PURE;
890 :
891 : /**
892 : * Returns the URL path as it will be calculated by finalizeRequestHeaders
893 : * using current values of headers. Note that final path may be different if
894 : * headers change before finalization.
895 : * @param headers supplies the request headers.
896 : * @return absl::optional<std::string> the value of the URL path after rewrite or absl::nullopt
897 : * if rewrite is not configured.
898 : */
899 : virtual absl::optional<std::string>
900 : currentUrlPathAfterRewrite(const Http::RequestHeaderMap& headers) const PURE;
901 :
902 : /**
903 : * Do potentially destructive header transforms on request headers prior to forwarding. For
904 : * example URL prefix rewriting, adding headers, etc. This should only be called ONCE
905 : * immediately prior to forwarding. It is done this way vs. copying for performance reasons.
906 : * @param headers supplies the request headers, which may be modified during this call.
907 : * @param stream_info holds additional information about the request.
908 : * @param insert_envoy_original_path insert x-envoy-original-path header if path rewritten?
909 : */
910 : virtual void finalizeRequestHeaders(Http::RequestHeaderMap& headers,
911 : const StreamInfo::StreamInfo& stream_info,
912 : bool insert_envoy_original_path) const PURE;
913 :
914 : /**
915 : * Returns the request header transforms that would be applied if finalizeRequestHeaders were
916 : * called now. This is useful if you want to obtain request header transforms which was or will be
917 : * applied through finalizeRequestHeaders call. Note: do not use unless you are sure that there
918 : * will be no route modifications later in the filter chain.
919 : * @param stream_info holds additional information about the request.
920 : * @param do_formatting whether or not to evaluate configured transformations; if false, returns
921 : * original values instead.
922 : */
923 : virtual Http::HeaderTransforms requestHeaderTransforms(const StreamInfo::StreamInfo& stream_info,
924 : bool do_formatting = true) const PURE;
925 :
926 : /**
927 : * @return const HashPolicy* the optional hash policy for the route.
928 : */
929 : virtual const Http::HashPolicy* hashPolicy() const PURE;
930 :
931 : /**
932 : * @return const HedgePolicy& the hedge policy for the route. All routes have a hedge policy even
933 : * if it is empty and does not allow for hedged requests.
934 : */
935 : virtual const HedgePolicy& hedgePolicy() const PURE;
936 :
937 : /**
938 : * @return the priority of the route.
939 : */
940 : virtual Upstream::ResourcePriority priority() const PURE;
941 :
942 : /**
943 : * @return const RateLimitPolicy& the rate limit policy for the route.
944 : */
945 : virtual const RateLimitPolicy& rateLimitPolicy() const PURE;
946 :
947 : /**
948 : * @return const RetryPolicy& the retry policy for the route. All routes have a retry policy even
949 : * if it is empty and does not allow retries.
950 : */
951 : virtual const RetryPolicy& retryPolicy() const PURE;
952 :
953 : /**
954 : * @return const InternalRedirectPolicy& the internal redirect policy for the route. All routes
955 : * have a internal redirect policy even if it is not enabled, which means redirects are
956 : * simply proxied as normal responses.
957 : */
958 : virtual const InternalRedirectPolicy& internalRedirectPolicy() const PURE;
959 :
960 : /**
961 : * @return const PathMatcherSharedPtr& the path match policy for the route.
962 : */
963 : virtual const PathMatcherSharedPtr& pathMatcher() const PURE;
964 :
965 : /**
966 : * @return const PathRewriterSharedPtr& the path match rewrite for the route.
967 : */
968 : virtual const PathRewriterSharedPtr& pathRewriter() const PURE;
969 :
970 : /**
971 : * @return uint32_t any route cap on bytes which should be buffered for shadowing or retries.
972 : * This is an upper bound so does not necessarily reflect the bytes which will be buffered
973 : * as other limits may apply.
974 : * Unlike some other buffer limits, 0 here indicates buffering should not be performed
975 : * rather than no limit applies.
976 : */
977 : virtual uint32_t retryShadowBufferLimit() const PURE;
978 :
979 : /**
980 : * @return const std::vector<ShadowPolicy>& the shadow policies for the route. The vector is empty
981 : * if no shadowing takes place.
982 : */
983 : virtual const std::vector<ShadowPolicyPtr>& shadowPolicies() const PURE;
984 :
985 : /**
986 : * @return std::chrono::milliseconds the route's timeout.
987 : */
988 : virtual std::chrono::milliseconds timeout() const PURE;
989 :
990 : /**
991 : * @return optional<std::chrono::milliseconds> the route's idle timeout. Zero indicates a
992 : * disabled idle timeout, while nullopt indicates deference to the global timeout.
993 : */
994 : virtual absl::optional<std::chrono::milliseconds> idleTimeout() const PURE;
995 :
996 : /**
997 : * @return true if new style max_stream_duration config should be used over the old style.
998 : */
999 : virtual bool usingNewTimeouts() const PURE;
1000 :
1001 : /**
1002 : * @return optional<std::chrono::milliseconds> the route's maximum stream duration.
1003 : */
1004 : virtual absl::optional<std::chrono::milliseconds> maxStreamDuration() const PURE;
1005 :
1006 : /**
1007 : * @return optional<std::chrono::milliseconds> the max grpc-timeout this route will allow.
1008 : */
1009 : virtual absl::optional<std::chrono::milliseconds> grpcTimeoutHeaderMax() const PURE;
1010 :
1011 : /**
1012 : * @return optional<std::chrono::milliseconds> the delta between grpc-timeout and enforced grpc
1013 : * timeout.
1014 : */
1015 : virtual absl::optional<std::chrono::milliseconds> grpcTimeoutHeaderOffset() const PURE;
1016 :
1017 : /**
1018 : * @return absl::optional<std::chrono::milliseconds> the maximum allowed timeout value derived
1019 : * from 'grpc-timeout' header of a gRPC request. Non-present value disables use of 'grpc-timeout'
1020 : * header, while 0 represents infinity.
1021 : */
1022 : virtual absl::optional<std::chrono::milliseconds> maxGrpcTimeout() const PURE;
1023 :
1024 : /**
1025 : * @return absl::optional<std::chrono::milliseconds> the timeout offset to apply to the timeout
1026 : * provided by the 'grpc-timeout' header of a gRPC request. This value will be positive and should
1027 : * be subtracted from the value provided by the header.
1028 : */
1029 : virtual absl::optional<std::chrono::milliseconds> grpcTimeoutOffset() const PURE;
1030 :
1031 : /**
1032 : * Determine whether a specific request path belongs to a virtual cluster for use in stats, etc.
1033 : * @param headers supplies the request headers.
1034 : * @return the virtual cluster or nullptr if there is no match.
1035 : */
1036 : virtual const VirtualCluster* virtualCluster(const Http::HeaderMap& headers) const PURE;
1037 :
1038 : /**
1039 : * @return const VirtualHost& the virtual host that owns the route.
1040 : */
1041 : virtual const VirtualHost& virtualHost() const PURE;
1042 :
1043 : /**
1044 : * @return bool true if the :authority header should be overwritten with the upstream hostname.
1045 : */
1046 : virtual bool autoHostRewrite() const PURE;
1047 :
1048 : /**
1049 : * @return bool true if the x-forwarded-host header should be updated.
1050 : */
1051 : virtual bool appendXfh() const PURE;
1052 :
1053 : /**
1054 : * @return MetadataMatchCriteria* the metadata that a subset load balancer should match when
1055 : * selecting an upstream host
1056 : */
1057 : virtual const MetadataMatchCriteria* metadataMatchCriteria() const PURE;
1058 :
1059 : /**
1060 : * @return const std::multimap<std::string, std::string> the opaque configuration associated
1061 : * with the route
1062 : */
1063 : virtual const std::multimap<std::string, std::string>& opaqueConfig() const PURE;
1064 :
1065 : /**
1066 : * @return bool true if the virtual host rate limits should be included.
1067 : */
1068 : virtual bool includeVirtualHostRateLimits() const PURE;
1069 :
1070 : /**
1071 : * @return TlsContextMatchCriteria* the tls context match criterion for this route. If there is no
1072 : * tls context match criteria, nullptr is returned.
1073 : */
1074 : virtual const TlsContextMatchCriteria* tlsContextMatchCriteria() const PURE;
1075 :
1076 : /**
1077 : * @return const PathMatchCriterion& the match criterion for this route.
1078 : */
1079 : virtual const PathMatchCriterion& pathMatchCriterion() const PURE;
1080 :
1081 : /**
1082 : * True if the virtual host this RouteEntry belongs to is configured to include the attempt
1083 : * count header.
1084 : * @return bool whether x-envoy-attempt-count should be included on the upstream request.
1085 : */
1086 : virtual bool includeAttemptCountInRequest() const PURE;
1087 :
1088 : /**
1089 : * True if the virtual host this RouteEntry belongs to is configured to include the attempt
1090 : * count header.
1091 : * @return bool whether x-envoy-attempt-count should be included on the downstream response.
1092 : */
1093 : virtual bool includeAttemptCountInResponse() const PURE;
1094 :
1095 : using UpgradeMap = std::map<std::string, bool>;
1096 : /**
1097 : * @return a map of route-specific upgrades to their enabled/disabled status.
1098 : */
1099 : virtual const UpgradeMap& upgradeMap() const PURE;
1100 :
1101 : using ConnectConfig = envoy::config::route::v3::RouteAction::UpgradeConfig::ConnectConfig;
1102 : using ConnectConfigOptRef = OptRef<ConnectConfig>;
1103 : /**
1104 : * If present, informs how to handle proxying CONNECT requests on this route.
1105 : */
1106 : virtual const ConnectConfigOptRef connectConfig() const PURE;
1107 :
1108 : /**
1109 : * @return RouteStatsContextOptRef the config needed to generate route level stats.
1110 : */
1111 : virtual const RouteStatsContextOptRef routeStatsContext() const PURE;
1112 :
1113 : /**
1114 : * @return EarlyDataPolicy& the configured early data option.
1115 : */
1116 : virtual const EarlyDataPolicy& earlyDataPolicy() const PURE;
1117 : };
1118 :
1119 : /**
1120 : * An interface representing the Decorator.
1121 : */
1122 : class Decorator {
1123 : public:
1124 145 : virtual ~Decorator() = default;
1125 :
1126 : /**
1127 : * This method decorates the supplied span.
1128 : * @param Tracing::Span& the span.
1129 : */
1130 : virtual void apply(Tracing::Span& span) const PURE;
1131 :
1132 : /**
1133 : * This method returns the operation name.
1134 : * @return the operation name
1135 : */
1136 : virtual const std::string& getOperation() const PURE;
1137 :
1138 : /**
1139 : * This method returns whether the decorator information
1140 : * should be propagated to other services.
1141 : * @return whether to propagate
1142 : */
1143 : virtual bool propagate() const PURE;
1144 : };
1145 :
1146 : using DecoratorConstPtr = std::unique_ptr<const Decorator>;
1147 :
1148 : /**
1149 : * An interface representing the Tracing for the route configuration.
1150 : */
1151 : class RouteTracing {
1152 : public:
1153 107 : virtual ~RouteTracing() = default;
1154 :
1155 : /**
1156 : * This method returns the client sampling percentage.
1157 : * @return the client sampling percentage
1158 : */
1159 : virtual const envoy::type::v3::FractionalPercent& getClientSampling() const PURE;
1160 :
1161 : /**
1162 : * This method returns the random sampling percentage.
1163 : * @return the random sampling percentage
1164 : */
1165 : virtual const envoy::type::v3::FractionalPercent& getRandomSampling() const PURE;
1166 :
1167 : /**
1168 : * This method returns the overall sampling percentage.
1169 : * @return the overall sampling percentage
1170 : */
1171 : virtual const envoy::type::v3::FractionalPercent& getOverallSampling() const PURE;
1172 :
1173 : /**
1174 : * This method returns the route level tracing custom tags.
1175 : * @return the tracing custom tags.
1176 : */
1177 : virtual const Tracing::CustomTagMap& getCustomTags() const PURE;
1178 : };
1179 :
1180 : using RouteTracingConstPtr = std::unique_ptr<const RouteTracing>;
1181 :
1182 : /**
1183 : * An interface that holds a DirectResponseEntry or RouteEntry for a request.
1184 : */
1185 : class Route {
1186 : public:
1187 2062 : virtual ~Route() = default;
1188 :
1189 : /**
1190 : * @return the direct response entry or nullptr if there is no direct response for the request.
1191 : */
1192 : virtual const DirectResponseEntry* directResponseEntry() const PURE;
1193 :
1194 : /**
1195 : * @return the route entry or nullptr if there is no matching route for the request.
1196 : */
1197 : virtual const RouteEntry* routeEntry() const PURE;
1198 :
1199 : /**
1200 : * @return the decorator or nullptr if not defined for the request.
1201 : */
1202 : virtual const Decorator* decorator() const PURE;
1203 :
1204 : /**
1205 : * @return the tracing config or nullptr if not defined for the request.
1206 : */
1207 : virtual const RouteTracing* tracingConfig() const PURE;
1208 :
1209 : /**
1210 : * Check if the filter is disabled for this route.
1211 : * @param config_name supplies the name of the filter config in the HTTP filter chain. This name
1212 : * may be different from the filter extension qualified name.
1213 : * @return true if the filter is disabled for this route, false if the filter is enabled.
1214 : * nullopt if no decision can be made explicitly for the filter.
1215 : */
1216 : virtual absl::optional<bool> filterDisabled(absl::string_view config_name) const PURE;
1217 :
1218 : /**
1219 : * This is a helper to get the route's per-filter config if it exists, up along the config
1220 : * hierarchy(Route --> VirtualHost --> RouteConfiguration). Or nullptr if none of them exist.
1221 : */
1222 : virtual const RouteSpecificFilterConfig*
1223 : mostSpecificPerFilterConfig(const std::string& name) const PURE;
1224 :
1225 : /**
1226 : * Find all the available per route filter configs, invoking the callback with each config (if
1227 : * it is present). Iteration of the configs is in order of specificity. That means that the
1228 : * callback will be called first for a config on a Virtual host, then a route, and finally a route
1229 : * entry (weighted cluster). If a config is not present, the callback will not be invoked.
1230 : */
1231 : virtual void traversePerFilterConfig(
1232 : const std::string& filter_name,
1233 : std::function<void(const Router::RouteSpecificFilterConfig&)> cb) const PURE;
1234 :
1235 : /**
1236 : * @return const envoy::config::core::v3::Metadata& return the metadata provided in the config for
1237 : * this route.
1238 : */
1239 : virtual const envoy::config::core::v3::Metadata& metadata() const PURE;
1240 :
1241 : /**
1242 : * @return const Envoy::Config::TypedMetadata& return the typed metadata provided in the config
1243 : * for this route.
1244 : */
1245 : virtual const Envoy::Config::TypedMetadata& typedMetadata() const PURE;
1246 :
1247 : /**
1248 : * @return std::string& the name of the route.
1249 : */
1250 : virtual const std::string& routeName() const PURE;
1251 : };
1252 :
1253 : using RouteConstSharedPtr = std::shared_ptr<const Route>;
1254 :
1255 : class RouteEntryAndRoute : public RouteEntry, public Route {};
1256 :
1257 : /**
1258 : * RouteCallback, returns one of these enums to the route matcher to indicate
1259 : * if the matched route has been accepted or it wants the route matching to
1260 : * continue.
1261 : */
1262 : enum class RouteMatchStatus {
1263 : // Continue matching route
1264 : Continue,
1265 : // Accept matched route
1266 : Accept
1267 : };
1268 :
1269 : /**
1270 : * RouteCallback is passed this enum to indicate if more routes are available for evaluation.
1271 : */
1272 : enum class RouteEvalStatus {
1273 : // Has more routes that can be evaluated for match.
1274 : HasMoreRoutes,
1275 : // All routes have been evaluated for match.
1276 : NoMoreRoutes
1277 : };
1278 :
1279 : /**
1280 : * RouteCallback can be used to override routing decision made by the Route::Config::route,
1281 : * this callback is passed the RouteConstSharedPtr, when a matching route is found, and
1282 : * RouteEvalStatus indicating whether there are more routes available for evaluation.
1283 : *
1284 : * RouteCallback will be called back only when at least one matching route is found, if no matching
1285 : * routes are found RouteCallback will not be invoked. RouteCallback can return one of the
1286 : * RouteMatchStatus enum to indicate if the match has been accepted or should the route match
1287 : * evaluation continue.
1288 : *
1289 : * Returning RouteMatchStatus::Continue, when no more routes available for evaluation will result in
1290 : * no further callbacks and no route is deemed to be accepted and nullptr is returned to the caller
1291 : * of Route::Config::route.
1292 : */
1293 : using RouteCallback = std::function<RouteMatchStatus(RouteConstSharedPtr, RouteEvalStatus)>;
1294 :
1295 : /**
1296 : * Shared part of the route configuration. This class contains interfaces that needn't depend on
1297 : * router matcher. Then every virtualhost could keep a reference to the CommonConfig. When the
1298 : * entire route config is destroyed, the part of CommonConfig will still live until all
1299 : * virtualhosts are destroyed.
1300 : */
1301 : class CommonConfig {
1302 : public:
1303 2844 : virtual ~CommonConfig() = default;
1304 :
1305 : /**
1306 : * Return a list of headers that will be cleaned from any requests that are not from an internal
1307 : * (RFC1918) source.
1308 : */
1309 : virtual const std::list<Http::LowerCaseString>& internalOnlyHeaders() const PURE;
1310 :
1311 : /**
1312 : * @return const std::string the RouteConfiguration name.
1313 : */
1314 : virtual const std::string& name() const PURE;
1315 :
1316 : /**
1317 : * @return whether router configuration uses VHDS.
1318 : */
1319 : virtual bool usesVhds() const PURE;
1320 :
1321 : /**
1322 : * @return bool whether most specific header mutations should take precedence. The default
1323 : * evaluation order is route level, then virtual host level and finally global connection
1324 : * manager level.
1325 : */
1326 : virtual bool mostSpecificHeaderMutationsWins() const PURE;
1327 :
1328 : /**
1329 : * @return uint32_t The maximum bytes of the response direct response body size. The default value
1330 : * is 4096.
1331 : * TODO(dio): To allow overrides at different levels (e.g. per-route, virtual host, etc).
1332 : */
1333 : virtual uint32_t maxDirectResponseBodySizeBytes() const PURE;
1334 :
1335 : /**
1336 : * @return const envoy::config::core::v3::Metadata& return the metadata provided in the config for
1337 : * this route configuration.
1338 : */
1339 : virtual const envoy::config::core::v3::Metadata& metadata() const PURE;
1340 :
1341 : /**
1342 : * @return const Envoy::Config::TypedMetadata& return the typed metadata provided in the config
1343 : * for this route configuration.
1344 : */
1345 : virtual const Envoy::Config::TypedMetadata& typedMetadata() const PURE;
1346 : };
1347 :
1348 : /**
1349 : * The router configuration.
1350 : */
1351 : class Config : public Rds::Config, public CommonConfig {
1352 : public:
1353 : /**
1354 : * Based on the incoming HTTP request headers, determine the target route (containing either a
1355 : * route entry or a direct response entry) for the request.
1356 : * @param headers supplies the request headers.
1357 : * @param random_value supplies the random seed to use if a runtime choice is required. This
1358 : * allows stable choices between calls if desired.
1359 : * @return the route or nullptr if there is no matching route for the request.
1360 : */
1361 : virtual RouteConstSharedPtr route(const Http::RequestHeaderMap& headers,
1362 : const StreamInfo::StreamInfo& stream_info,
1363 : uint64_t random_value) const PURE;
1364 :
1365 : /**
1366 : * Based on the incoming HTTP request headers, determine the target route (containing either a
1367 : * route entry or a direct response entry) for the request.
1368 : *
1369 : * Invokes callback with matched route, callback can choose to accept the route by returning
1370 : * RouteStatus::Stop or continue route match from last matched route by returning
1371 : * RouteMatchStatus::Continue, when more routes are available.
1372 : *
1373 : * @param cb supplies callback to be invoked upon route match.
1374 : * @param headers supplies the request headers.
1375 : * @param random_value supplies the random seed to use if a runtime choice is required. This
1376 : * allows stable choices between calls if desired.
1377 : * @return the route accepted by the callback or nullptr if no match found or none of route is
1378 : * accepted by the callback.
1379 : */
1380 : virtual RouteConstSharedPtr route(const RouteCallback& cb, const Http::RequestHeaderMap& headers,
1381 : const StreamInfo::StreamInfo& stream_info,
1382 : uint64_t random_value) const PURE;
1383 : };
1384 :
1385 : using ConfigConstSharedPtr = std::shared_ptr<const Config>;
1386 :
1387 : class GenericConnectionPoolCallbacks;
1388 : class GenericUpstream;
1389 :
1390 : /**
1391 : * An API for wrapping either an HTTP, TCP, or UDP connection pool.
1392 : *
1393 : * The GenericConnPool exists to create a GenericUpstream handle via a call to
1394 : * newStream resulting in an eventual call to onPoolReady
1395 : */
1396 : class GenericConnPool {
1397 : public:
1398 251 : virtual ~GenericConnPool() = default;
1399 :
1400 : /**
1401 : * Called to create a new HTTP stream, TCP connection for CONNECT streams, or UDP socket for
1402 : * CONNECT-UDP streams.
1403 : *
1404 : * The implementation of the GenericConnPool will either call
1405 : * GenericConnectionPoolCallbacks::onPoolReady
1406 : * when a stream is available or GenericConnectionPoolCallbacks::onPoolFailure
1407 : * if stream creation fails.
1408 : *
1409 : * The caller is responsible for calling cancelAnyPendingStream() if stream
1410 : * creation is no longer desired. newStream may only be called once per
1411 : * GenericConnPool.
1412 : *
1413 : * @param callbacks callbacks to communicate stream failure or creation on.
1414 : */
1415 : virtual void newStream(GenericConnectionPoolCallbacks* callbacks) PURE;
1416 : /**
1417 : * Called to cancel any pending newStream request,
1418 : */
1419 : virtual bool cancelAnyPendingStream() PURE;
1420 : /**
1421 : * @return optionally returns the host for the connection pool.
1422 : */
1423 : virtual Upstream::HostDescriptionConstSharedPtr host() const PURE;
1424 :
1425 : /**
1426 : * @return returns if the connection pool was iniitalized successfully.
1427 : */
1428 : virtual bool valid() const PURE;
1429 : };
1430 :
1431 : /**
1432 : * An API for the interactions the upstream stream needs to have with the downstream stream
1433 : * and/or router components
1434 : */
1435 : class UpstreamToDownstream : public Http::ResponseDecoder, public Http::StreamCallbacks {
1436 : public:
1437 : /**
1438 : * @return return the route for the downstream stream.
1439 : */
1440 : virtual const Route& route() const PURE;
1441 : /**
1442 : * @return return the connection for the downstream stream if it exists.
1443 : */
1444 : virtual OptRef<const Network::Connection> connection() const PURE;
1445 : /**
1446 : * @return returns the options to be consulted with for upstream stream creation.
1447 : */
1448 : virtual const Http::ConnectionPool::Instance::StreamOptions& upstreamStreamOptions() const PURE;
1449 : };
1450 :
1451 : /**
1452 : * An API for wrapping callbacks from either an HTTP, TCP, or UDP connection pool.
1453 : *
1454 : * Just like the connection pool callbacks, the GenericConnectionPoolCallbacks
1455 : * will either call onPoolReady when a GenericUpstream is ready, or
1456 : * onPoolFailure if a connection/stream can not be established.
1457 : */
1458 : class GenericConnectionPoolCallbacks {
1459 : public:
1460 251 : virtual ~GenericConnectionPoolCallbacks() = default;
1461 :
1462 : /**
1463 : * Called to indicate a failure for GenericConnPool::newStream to establish a stream.
1464 : *
1465 : * @param reason supplies the failure reason.
1466 : * @param transport_failure_reason supplies the details of the transport failure reason.
1467 : * @param host supplies the description of the host that caused the failure. This may be nullptr
1468 : * if no host was involved in the failure (for example overflow).
1469 : */
1470 : virtual void onPoolFailure(ConnectionPool::PoolFailureReason reason,
1471 : absl::string_view transport_failure_reason,
1472 : Upstream::HostDescriptionConstSharedPtr host) PURE;
1473 : /**
1474 : * Called when GenericConnPool::newStream has established a new stream.
1475 : *
1476 : * @param upstream supplies the generic upstream for the stream.
1477 : * @param host supplies the description of the host that will carry the request. For logical
1478 : * connection pools the description may be different each time this is called.
1479 : * @param connection_info_provider, supplies the address provider of the upstream connection.
1480 : * @param info supplies the stream info object associated with the upstream connection.
1481 : * @param protocol supplies the protocol associated with the upstream connection.
1482 : */
1483 : virtual void onPoolReady(std::unique_ptr<GenericUpstream>&& upstream,
1484 : Upstream::HostDescriptionConstSharedPtr host,
1485 : const Network::ConnectionInfoProvider& connection_info_provider,
1486 : StreamInfo::StreamInfo& info,
1487 : absl::optional<Http::Protocol> protocol) PURE;
1488 :
1489 : // @return the UpstreamToDownstream interface for this stream.
1490 : //
1491 : // This is the interface for all interactions the upstream stream needs to have with the
1492 : // downstream stream. It is in the GenericConnectionPoolCallbacks as the GenericConnectionPool
1493 : // creates the GenericUpstream, and the GenericUpstream will need this interface.
1494 : virtual UpstreamToDownstream& upstreamToDownstream() PURE;
1495 : };
1496 :
1497 : /**
1498 : * An API for sending information to either a TCP, UDP, or HTTP upstream.
1499 : *
1500 : * It is similar logically to RequestEncoder, only without the getStream interface.
1501 : */
1502 : class GenericUpstream {
1503 : public:
1504 202 : virtual ~GenericUpstream() = default;
1505 : /**
1506 : * Encode a data frame.
1507 : * @param data supplies the data to encode. The data may be moved by the encoder.
1508 : * @param end_stream supplies whether this is the last data frame.
1509 : */
1510 : virtual void encodeData(Buffer::Instance& data, bool end_stream) PURE;
1511 : /**
1512 : * Encode metadata.
1513 : * @param metadata_map_vector is the vector of metadata maps to encode.
1514 : */
1515 : virtual void encodeMetadata(const Http::MetadataMapVector& metadata_map_vector) PURE;
1516 : /**
1517 : * Encode headers, optionally indicating end of stream.
1518 : * @param headers supplies the header map to encode.
1519 : * @param end_stream supplies whether this is a header only request.
1520 : * @return status indicating success. Encoding will fail if headers do not have required HTTP
1521 : * headers.
1522 : */
1523 : virtual Http::Status encodeHeaders(const Http::RequestHeaderMap& headers, bool end_stream) PURE;
1524 : /**
1525 : * Encode trailers. This implicitly ends the stream.
1526 : * @param trailers supplies the trailers to encode.
1527 : */
1528 : virtual void encodeTrailers(const Http::RequestTrailerMap& trailers) PURE;
1529 : /**
1530 : * Enable/disable further data from this stream.
1531 : */
1532 : virtual void readDisable(bool disable) PURE;
1533 : /**
1534 : * Reset the stream. No events will fire beyond this point.
1535 : */
1536 : virtual void resetStream() PURE;
1537 :
1538 : /**
1539 : * Sets the upstream to use the following account.
1540 : * @param the account to assign the generic upstream.
1541 : */
1542 : virtual void setAccount(Buffer::BufferMemoryAccountSharedPtr account) PURE;
1543 :
1544 : /**
1545 : * Get the bytes meter for this stream.
1546 : */
1547 : virtual const StreamInfo::BytesMeterSharedPtr& bytesMeter() PURE;
1548 : };
1549 :
1550 : using GenericConnPoolPtr = std::unique_ptr<GenericConnPool>;
1551 :
1552 : /*
1553 : * A factory for creating generic connection pools.
1554 : */
1555 : class GenericConnPoolFactory : public Envoy::Config::TypedFactory {
1556 : public:
1557 : /*
1558 : * Protocol used by the upstream sockets.
1559 : */
1560 : enum class UpstreamProtocol { HTTP, TCP, UDP };
1561 :
1562 0 : ~GenericConnPoolFactory() override = default;
1563 :
1564 : /*
1565 : * @param options for creating the transport socket
1566 : * @return may be null
1567 : */
1568 : virtual GenericConnPoolPtr
1569 : createGenericConnPool(Upstream::ThreadLocalCluster& thread_local_cluster,
1570 : GenericConnPoolFactory::UpstreamProtocol upstream_protocol,
1571 : Upstream::ResourcePriority priority,
1572 : absl::optional<Http::Protocol> downstream_protocol,
1573 : Upstream::LoadBalancerContext* ctx) const PURE;
1574 : };
1575 :
1576 : using GenericConnPoolFactoryPtr = std::unique_ptr<GenericConnPoolFactory>;
1577 :
1578 : } // namespace Router
1579 : } // namespace Envoy
|