-
Notifications
You must be signed in to change notification settings - Fork 1
/
lib.rs
254 lines (224 loc) · 8.55 KB
/
lib.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
// Copyright 2024 Wladimir Palant
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! # Module helpers
//!
//! This crate contains some helpers that are useful when using `static-files-module` or
//! `virtual-hosts-module` crates for example.
mod deserialize;
pub mod pingora;
pub mod router;
pub mod standard_response;
mod trie;
use async_trait::async_trait;
use log::{error, info, trace};
use pingora::{wrap_session, Error, ErrorType, ResponseHeader, Session, SessionWrapper};
use serde::{de::DeserializeSeed, Deserialize};
use std::fmt::Debug;
use std::fs::File;
use std::io::BufReader;
use std::path::Path;
pub use deserialize::{DeserializeMap, MapVisitor, _private};
pub use module_utils_macros::{merge_conf, merge_opt, DeserializeMap, RequestFilter};
// Required for macros
#[doc(hidden)]
pub use serde;
#[doc(hidden)]
pub use serde_yaml;
/// Request filter result indicating how the current request should be processed further
#[derive(Debug, Copy, Clone, PartialEq, Default, Deserialize)]
pub enum RequestFilterResult {
/// Response has been sent, no further processing should happen. Other Pingora phases should
/// not be triggered.
ResponseSent,
/// Request has been handled and further request filters should not run. Response hasn’t been
/// sent however, next Pingora phase should deal with that.
Handled,
/// Request filter could not handle this request, next request filter should run if it exists.
#[default]
Unhandled,
}
/// Trait to be implemented by request filters.
#[async_trait]
pub trait RequestFilter: Sized {
/// Configuration type of this handler.
type Conf;
/// Creates a new instance of the handler from its configuration.
fn new(conf: Self::Conf) -> Result<Self, Box<Error>>
where
Self: Sized,
Self::Conf: TryInto<Self, Error = Box<Error>>,
{
conf.try_into()
}
/// Handles the `request_filter` phase of the current request.
///
/// This will wrap the current session and call `request_filter` methods of the individual
/// handlers then. It will then create a result that can be returned from the `request_filter`
/// phase directly.
async fn handle(&self, session: &mut Session, ctx: &mut Self::CTX) -> Result<bool, Box<Error>>
where
Self::CTX: Send,
{
let mut session = wrap_session(session, self);
let result = self.request_filter(&mut session, ctx).await?;
self.request_filter_done(&mut session, ctx, result);
Ok(result == RequestFilterResult::ResponseSent)
}
/// Handles the `upstream_response_filter` or `response_filter` phase of the current request.
///
/// This will wrap the current session and call `response_filter` methods of the individual
/// handlers then.
fn handle_response(
&self,
session: &mut Session,
response: &mut ResponseHeader,
ctx: &mut Self::CTX,
) where
Self: Sync,
{
let mut session = wrap_session(session, self);
self.response_filter(&mut session, response, Some(ctx))
}
/// Per-request state of this handler, see [`pingora_proxy::ProxyHttp::CTX`]
type CTX;
/// Creates a new sate object, see [`pingora_proxy::ProxyHttp::new_ctx`]
fn new_ctx() -> Self::CTX;
/// Handler to run during Pingora’s `request_filter` state, see
/// [`pingora_proxy::ProxyHttp::request_filter`]. This uses a different return type to account
/// for the existence of multiple request filters.
async fn request_filter(
&self,
session: &mut impl SessionWrapper,
ctx: &mut Self::CTX,
) -> Result<RequestFilterResult, Box<Error>>;
/// Called after `request_filter` was called for all handlers and a result was produced. This
/// allows the handler to perform some post-processing.
fn request_filter_done(
&self,
_session: &mut impl SessionWrapper,
_ctx: &mut Self::CTX,
_result: RequestFilterResult,
) {
}
/// Called when a response header is about to be sent, either from a request filter or an
/// upstream response.
///
/// *Note*: A context will only be available for the latter call.
fn response_filter(
&self,
_session: &mut impl SessionWrapper,
_response: &mut ResponseHeader,
_ctx: Option<&mut Self::CTX>,
) {
}
}
/// Trait for configuration structures that can be loaded from YAML files. This trait has a blanket
/// implementation for any structure implementing [`serde::Deserialize`].
pub trait FromYaml {
/// Loads and merges configuration from a number of YAML files. Glob patterns in file names
/// will be resolved and file names will be sorted before further processing.
fn load_from_files<I>(files: I) -> Result<Self, Box<Error>>
where
Self: Sized,
I: IntoIterator,
I::Item: AsRef<str>;
/// Loads configuration from a YAML file.
fn load_from_yaml(path: impl AsRef<Path>) -> Result<Self, Box<Error>>
where
Self: Sized;
/// Loads configuration from a YAML file, using existing data for missing fields.
fn merge_load_from_yaml(self, path: impl AsRef<Path>) -> Result<Self, Box<Error>>
where
Self: Sized;
/// Loads configuration from a YAML string.
fn from_yaml(yaml_conf: impl AsRef<str>) -> Result<Self, Box<Error>>
where
Self: Sized;
/// Loads configuration from a YAML string, using existing data for missing fields.
fn merge_from_yaml(self, yaml_conf: impl AsRef<str>) -> Result<Self, Box<Error>>
where
Self: Sized;
}
impl<D> FromYaml for D
where
D: Debug + Default,
for<'de> D: DeserializeSeed<'de, Value = D>,
{
fn load_from_files<I>(files: I) -> Result<Self, Box<Error>>
where
I: IntoIterator,
I::Item: AsRef<str>,
{
let mut files = files
.into_iter()
.filter_map(|path| match glob::glob(path.as_ref()) {
Ok(iter) => Some(iter),
Err(err) => {
error!("Ignoring invalid glob pattern `{}`: {err}", path.as_ref());
None
}
})
.flatten()
.filter_map(|path| match path {
Ok(path) => Some(path),
Err(err) => {
error!("Failed resolving glob pattern: {err}");
None
}
})
.collect::<Vec<_>>();
files.sort();
files.into_iter().try_fold(Self::default(), |conf, path| {
info!("Loading configuration file `{}`", path.display());
conf.merge_load_from_yaml(path)
})
}
fn load_from_yaml(path: impl AsRef<Path>) -> Result<Self, Box<Error>> {
Self::default().merge_load_from_yaml(path)
}
fn merge_load_from_yaml(self, path: impl AsRef<Path>) -> Result<Self, Box<Error>> {
let path = path.as_ref();
let file = File::open(path).map_err(|err| {
Error::because(
ErrorType::FileOpenError,
format!("failed opening configuration file `{}`", path.display()),
err,
)
})?;
let reader = BufReader::new(file);
let conf = self
.deserialize(serde_yaml::Deserializer::from_reader(reader))
.map_err(|err| {
Error::because(
ErrorType::FileReadError,
format!("failed reading configuration file `{}`", path.display()),
err,
)
})?;
trace!("Loaded configuration file: {conf:#?}");
Ok(conf)
}
fn from_yaml(yaml_conf: impl AsRef<str>) -> Result<Self, Box<Error>> {
Self::default().merge_from_yaml(yaml_conf)
}
fn merge_from_yaml(self, yaml_conf: impl AsRef<str>) -> Result<Self, Box<Error>> {
let conf = self
.deserialize(serde_yaml::Deserializer::from_str(yaml_conf.as_ref()))
.map_err(|err| {
Error::because(ErrorType::ReadError, "failed reading configuration", err)
})?;
trace!("Loaded configuration: {conf:#?}");
Ok(conf)
}
}