lambda_lw_http_router_core/
route_context.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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
use lambda_runtime::tracing::Span;
use opentelemetry::{Key as OtelKey, Value as OtelValue};
use std::collections::HashMap;
use std::sync::Arc;
use tracing_opentelemetry::OpenTelemetrySpanExt;

/// Context passed to route handlers containing request information and application state.
///
/// This struct provides access to request details, path parameters, application state,
/// and Lambda execution context. It is passed to every route handler and provides
/// methods for accessing OpenTelemetry span attributes.
///
/// # Examples
///
/// ```rust
/// use aws_lambda_events::apigw::ApiGatewayV2httpRequest;
/// use lambda_lw_http_router_core::{RouteContext, Router};
/// use serde_json::Value;
/// use lambda_runtime::Error;
/// use serde_json::json;
///
/// async fn handle_user(ctx: RouteContext<(), ApiGatewayV2httpRequest>) -> Result<Value, Error> {
///     // Get path parameters
///     let user_id = ctx.get_param("id").unwrap_or_else(||"default".to_string());
///     
///     // Access request details
///     let method = ctx.method();
///     let path = ctx.path();
///     
///     // Set span attributes
///     ctx.set_otel_attribute("user.id", user_id.clone());
///     
///     Ok(json!({ "id": user_id }))
/// }
/// ```
#[derive(Debug, Clone)]
pub struct RouteContext<State: Clone, E> {
    /// The full request path
    pub path: String,
    /// The HTTP method (GET, POST, etc.)
    pub method: String,
    /// Path parameters extracted from the URL (e.g., {id} -> "123")
    pub params: HashMap<String, String>,
    /// Application state shared across all requests
    pub state: Arc<State>,
    /// The original Lambda event
    pub event: E,
    /// Lambda execution context
    pub lambda_context: lambda_runtime::Context,
    /// The route template pattern (e.g., "/quote/{id}")
    pub route_pattern: String,
}

impl<State: Clone, E> RouteContext<State, E> {
    /// Returns the full request path of the current request.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use lambda_lw_http_router_core::{RouteContext, Router};
    /// # use aws_lambda_events::apigw::ApiGatewayV2httpRequest;
    /// # #[derive(Clone)]
    /// # struct AppState {}
    /// async fn handler(ctx: RouteContext<AppState, ApiGatewayV2httpRequest>) {
    ///     let path = ctx.path();
    ///     assert_eq!(path, "/users/123/profile");
    /// }
    /// ```
    pub fn path(&self) -> &str {
        &self.path
    }

    /// Returns the HTTP method of the current request (e.g., "GET", "POST").
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use lambda_lw_http_router_core::{RouteContext, Router};
    /// # use aws_lambda_events::apigw::ApiGatewayV2httpRequest;
    /// # #[derive(Clone)]
    /// # struct AppState {}
    /// async fn handler(ctx: RouteContext<AppState, ApiGatewayV2httpRequest>) {
    ///     let method = ctx.method();
    ///     assert_eq!(method, "POST");
    /// }
    /// ```
    pub fn method(&self) -> &str {
        &self.method
    }

    /// Returns a reference to the shared application state.
    ///
    /// The state is shared across all request handlers and can be used to store
    /// application-wide data like database connections or configuration.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use lambda_lw_http_router_core::{RouteContext, Router};
    /// # use aws_lambda_events::apigw::ApiGatewayV2httpRequest;
    /// #[derive(Clone)]
    /// struct AppState {
    ///     api_key: String,
    /// }
    ///
    /// async fn handler(ctx: RouteContext<AppState, ApiGatewayV2httpRequest>) {
    ///     let api_key = &ctx.state().api_key;
    ///     // Use the API key for authentication
    /// }
    /// ```
    pub fn state(&self) -> &State {
        &self.state
    }

    /// Returns a reference to the original Lambda event.
    ///
    /// This provides access to the raw event data from AWS Lambda, which can be useful
    /// for accessing event-specific fields not exposed through the router interface.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use lambda_lw_http_router_core::{RouteContext, Router};
    /// # use aws_lambda_events::apigw::ApiGatewayV2httpRequest;
    /// # #[derive(Clone)]
    /// # struct AppState {}
    /// async fn handler(ctx: RouteContext<AppState, ApiGatewayV2httpRequest>) {
    ///     let raw_event = ctx.event();
    ///     if let Some(body) = &raw_event.body {
    ///         // Process the raw request body
    ///     }
    /// }
    /// ```
    pub fn event(&self) -> &E {
        &self.event
    }

    /// Returns a reference to the Lambda execution context.
    ///
    /// The Lambda context contains metadata about the current execution environment,
    /// such as the request ID, function name, and remaining execution time.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use lambda_lw_http_router_core::{RouteContext, Router};
    /// # use aws_lambda_events::apigw::ApiGatewayV2httpRequest;
    /// # #[derive(Clone)]
    /// # struct AppState {}
    /// async fn handler(ctx: RouteContext<AppState, ApiGatewayV2httpRequest>) {
    ///     let request_id = &ctx.lambda_context().request_id;
    ///     let deadline = ctx.lambda_context().deadline;
    /// }
    /// ```
    pub fn lambda_context(&self) -> &lambda_runtime::Context {
        &self.lambda_context
    }

    /// Returns the route pattern that matched this request.
    ///
    /// The route pattern is the original path template with parameter placeholders,
    /// such as "/users/{id}/profile".
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use lambda_lw_http_router_core::{RouteContext, Router};
    /// # use aws_lambda_events::apigw::ApiGatewayV2httpRequest;
    /// # #[derive(Clone)]
    /// # struct AppState {}
    /// async fn handler(ctx: RouteContext<AppState, ApiGatewayV2httpRequest>) {
    ///     let pattern = ctx.route_pattern();
    ///     assert_eq!(pattern, "/users/{id}/profile");
    /// }
    /// ```
    pub fn route_pattern(&self) -> &str {
        &self.route_pattern
    }

    /// Returns a path parameter by name, if it exists.
    ///
    /// Path parameters are extracted from the URL based on the route pattern.
    /// For example, if the route pattern is "/users/{id}" and the URL is "/users/123",
    /// then `get_param("id")` will return `Some("123")`.
    ///
    /// # Arguments
    ///
    /// * `name` - The name of the path parameter to retrieve
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use lambda_lw_http_router_core::{RouteContext, Router};
    /// # use aws_lambda_events::apigw::ApiGatewayV2httpRequest;
    /// # use serde_json::json;
    /// # #[derive(Clone)]
    /// # struct AppState {}
    /// async fn get_user(ctx: RouteContext<AppState, ApiGatewayV2httpRequest>) -> serde_json::Value {
    ///     let user_id = ctx.get_param("id").unwrap_or_default();
    ///     json!({ "id": user_id })
    /// }
    /// ```
    pub fn get_param(&self, name: &str) -> Option<String> {
        self.params.get(name).cloned()
    }

    /// Returns a path parameter by name, or a default value if it doesn't exist.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use lambda_lw_http_router_core::{RouteContext, Router};
    /// # use aws_lambda_events::apigw::ApiGatewayV2httpRequest;
    /// # use serde_json::json;
    /// # #[derive(Clone)]
    /// # struct AppState {}
    /// async fn get_user(ctx: RouteContext<AppState, ApiGatewayV2httpRequest>) -> serde_json::Value {
    ///     let user_id = ctx.get_param_or("id", "default");
    ///     json!({ "id": user_id })
    /// }
    /// ```
    pub fn get_param_or(&self, name: &str, default: &str) -> String {
        self.get_param(name).unwrap_or_else(|| default.to_string())
    }

    /// Returns a path parameter by name, or an empty string if it doesn't exist.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use lambda_lw_http_router_core::{RouteContext, Router};
    /// # use aws_lambda_events::apigw::ApiGatewayV2httpRequest;
    /// # use serde_json::json;
    /// # #[derive(Clone)]
    /// # struct AppState {}
    /// async fn get_user(ctx: RouteContext<AppState, ApiGatewayV2httpRequest>) -> serde_json::Value {
    ///     let user_id = ctx.get_param_or_empty("id");
    ///     json!({ "id": user_id })
    /// }
    /// ```
    pub fn get_param_or_empty(&self, name: &str) -> String {
        self.get_param_or(name, "")
    }

    /// Returns a reference to all path parameters.
    ///
    /// This method returns a HashMap containing all path parameters extracted from
    /// the URL based on the route pattern.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use lambda_lw_http_router_core::{RouteContext, Router};
    /// # use aws_lambda_events::apigw::ApiGatewayV2httpRequest;
    /// # use serde_json::json;
    /// # #[derive(Clone)]
    /// # struct AppState {}
    /// async fn handler(ctx: RouteContext<AppState, ApiGatewayV2httpRequest>) -> serde_json::Value {
    ///     let params = ctx.params();
    ///     json!({
    ///         "user_id": params.get("user_id"),
    ///         "post_id": params.get("post_id")
    ///     })
    /// }
    /// ```
    pub fn params(&self) -> &HashMap<String, String> {
        &self.params
    }

    /// Sets a single attribute on the current OpenTelemetry span.
    ///
    /// This method allows you to add custom attributes to the current span for
    /// better observability and tracing.
    ///
    /// # Arguments
    ///
    /// * `key` - The attribute key
    /// * `value` - The attribute value (supports strings, numbers, and booleans)
    ///
    /// # Returns
    ///
    /// Returns a reference to self for method chaining
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use lambda_lw_http_router_core::{RouteContext, Router};
    /// # use aws_lambda_events::apigw::ApiGatewayV2httpRequest;
    /// # #[derive(Clone)]
    /// # struct AppState {}
    /// async fn handler(ctx: RouteContext<AppState, ApiGatewayV2httpRequest>) {
    ///     ctx.set_otel_attribute("user.id", "123")
    ///        .set_otel_attribute("request.size", 1024)
    ///        .set_otel_attribute("cache.hit", true);
    /// }
    /// ```
    pub fn set_otel_attribute(
        &self,
        key: impl Into<OtelKey>,
        value: impl Into<OtelValue>,
    ) -> &Self {
        let span = Span::current();
        span.set_attribute(key, value);
        self
    }

    /// Sets the OpenTelemetry span kind for the current span.
    ///
    /// The span kind describes the relationship between the span and its parent.
    /// Common values include:
    /// - "SERVER" for server-side request handling
    /// - "CLIENT" for outbound requests
    /// - "PRODUCER" for message publishing
    /// - "CONSUMER" for message processing
    /// - "INTERNAL" for internal operations
    ///
    /// # Arguments
    ///
    /// * `kind` - The span kind to set
    ///
    /// # Returns
    ///
    /// Returns a reference to self for method chaining
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use lambda_lw_http_router_core::{RouteContext, Router};
    /// # use aws_lambda_events::apigw::ApiGatewayV2httpRequest;
    /// # #[derive(Clone)]
    /// # struct AppState {}
    /// async fn handler(ctx: RouteContext<AppState, ApiGatewayV2httpRequest>) {
    ///     ctx.set_otel_span_kind("SERVER")
    ///        .set_otel_attribute("request.id", "abc-123");
    /// }
    /// ```
    pub fn set_otel_span_kind(&self, kind: &str) -> &Self {
        let span = Span::current();
        span.record("otel.kind", kind);
        self
    }
}