cf-gears-toolkit 0.10.0

Core ToolKit library
Documentation
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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
use axum::extract::{FromRequestParts, Query};
use axum::http::request::Parts;
use serde::Deserialize;
use toolkit_canonical_errors::CanonicalError;
use toolkit_odata::errors::OdataError;
use toolkit_odata::{CursorV1, Error as ODataError, ODataOrderBy, OrderKey, SortDir};

// Re-export types from toolkit-odata for convenience and better DX
pub use toolkit_odata::ODataQuery;
// CursorV1 is available through the private import above for internal use

/// Wire binding for the `OData` query-parameter family.
///
/// This struct is the single place where `OData` query parameters are bound
/// off the URL: `toolkit-odata` operates on already-parsed values and does no
/// HTTP query parsing of its own.
#[derive(Deserialize, Default)]
pub struct ODataParams {
    #[serde(rename = "$filter")]
    pub filter: Option<String>,
    #[serde(rename = "$orderby")]
    pub orderby: Option<String>,
    #[serde(rename = "$select")]
    pub select: Option<String>,
    /// Page size. Accepted as `limit` or as the canonical `OData` spelling
    /// `$top` (OASIS `OData` 4.01 Part 2: URL Conventions, §5.1.6 "System
    /// Query Options $top and $skip") — both spellings fold onto this one
    /// slot, so a gear needs no per-endpoint handling to honor either.
    ///
    /// Sending both in one request is ambiguous and is rejected with
    /// `400 InvalidArgument` (serde reports the second spelling as a
    /// duplicate field).
    #[serde(alias = "$top")]
    pub limit: Option<u64>,
    /// Opaque keyset token from the previous page's `next_cursor`. Accepted
    /// as `cursor` or as `$skiptoken`, `OData`'s opaque continuation token
    /// for server-driven paging; both spellings fold onto this one slot.
    ///
    /// This is the platform's only pagination continuation. `$skip` — offset
    /// paging — is not supported and is rejected; see
    /// [`ACCEPTED_SYSTEM_QUERY_OPTIONS`].
    #[serde(alias = "$skiptoken")]
    pub cursor: Option<String>,
}

/// `OData` system query options this extractor binds, in the exact spelling
/// that binds.
///
/// Any other `$`-prefixed query key is rejected rather than ignored. OASIS
/// `OData` 4.01 Part 1: Protocol, §6.1 "Query Option Extensibility": a
/// service "MUST fail any request that contains unsupported `OData` query
/// options defined in the version of this specification supported by the
/// service", and SHOULD fail any option it does not understand. §6.1 also
/// reserves the `$` prefix for `OData`, so unprefixed keys stay out of
/// scope — those belong to the handler's own params struct, and policing
/// them is each gear's business.
pub const ACCEPTED_SYSTEM_QUERY_OPTIONS: [&str; 5] =
    ["$filter", "$orderby", "$select", "$top", "$skiptoken"];

/// Every system query option `OData` 4.01 defines, whether or not this
/// platform binds it (OASIS `OData` 4.01 Part 2: URL Conventions, §§5.1.2 —
/// 5.1.12).
///
/// Splits the two ways a `$` key can be refused: one of these is
/// *unsupported* and may become supported later, while a `$` key outside
/// this set is *unknown* — which is what a typo like `$filtre` should hear.
const ODATA_SYSTEM_QUERY_OPTIONS: [&str; 12] = [
    "$filter",
    "$expand",
    "$select",
    "$orderby",
    "$top",
    "$skip",
    "$count",
    "$search",
    "$format",
    "$compute",
    "$index",
    "$schemaversion",
];

/// Reason code carried by every unsupported-option violation.
const UNSUPPORTED_QUERY_PARAM: &str = "UNSUPPORTED_QUERY_PARAM";

pub const MAX_FILTER_LEN: usize = 8 * 1024;
pub const MAX_NODES: usize = 2000;
pub const MAX_ORDERBY_LEN: usize = 1024;
pub const MAX_ORDER_FIELDS: usize = 10;
pub const MAX_SELECT_LEN: usize = 2048;
pub const MAX_SELECT_FIELDS: usize = 100;

/// Build a canonical `InvalidArgument` keyed by the `$select` field.
fn select_invalid_arg(detail: impl Into<String>, reason: &'static str) -> CanonicalError {
    OdataError::invalid_argument()
        .with_field_violation("$select", detail, reason)
        .create()
}

/// Parse $select string into a list of field names.
/// Format: "field1, field2, field3, ..."
/// Field names are case-insensitive and whitespace is trimmed.
///
/// # Errors
/// Returns a `CanonicalError` if the select string is invalid. Axum renders it
/// via `IntoResponse for CanonicalError`; the `canonical_error_middleware`
/// fills `instance` / `trace_id` on the way out.
#[allow(clippy::result_large_err)]
pub fn parse_select(raw: &str) -> Result<Vec<String>, CanonicalError> {
    let raw = raw.trim();
    if raw.is_empty() {
        return Err(select_invalid_arg(
            "$select cannot be empty",
            "INVALID_SELECT",
        ));
    }

    if raw.len() > MAX_SELECT_LEN {
        return Err(select_invalid_arg("$select too long", "INVALID_SELECT"));
    }

    let fields: Vec<String> = raw
        .split(',')
        .map(|f| f.trim().to_lowercase())
        .filter(|f| !f.is_empty())
        .collect();

    if fields.is_empty() {
        return Err(select_invalid_arg(
            "$select must contain at least one field",
            "INVALID_SELECT",
        ));
    }

    if fields.len() > MAX_SELECT_FIELDS {
        return Err(select_invalid_arg(
            "$select contains too many fields",
            "INVALID_SELECT",
        ));
    }

    // Check for duplicate fields
    let mut seen = std::collections::HashSet::new();
    for field in &fields {
        if !seen.insert(field.clone()) {
            return Err(select_invalid_arg(
                format!("duplicate field in $select: {field}"),
                "INVALID_SELECT",
            ));
        }
    }

    Ok(fields)
}

/// Parse $orderby string into `ODataOrderBy`.
/// Format: "field1 [asc|desc], field2 [asc|desc], ..."
/// Default direction is asc if not specified.
///
/// # Errors
/// Returns `toolkit_odata::Error::InvalidOrderByField` if the orderby string is invalid.
pub fn parse_orderby(raw: &str) -> Result<ODataOrderBy, toolkit_odata::Error> {
    let raw = raw.trim();
    if raw.is_empty() {
        return Ok(ODataOrderBy::empty());
    }

    if raw.len() > MAX_ORDERBY_LEN {
        return Err(toolkit_odata::Error::InvalidOrderByField(
            "orderby too long".into(),
        ));
    }

    let mut keys = Vec::new();

    for part in raw.split(',') {
        let part = part.trim();
        if part.is_empty() {
            continue;
        }

        let tokens: Vec<&str> = part.split_whitespace().collect();
        let (field, dir) = match tokens.as_slice() {
            [field] | [field, "asc"] => (*field, SortDir::Asc),
            [field, "desc"] => (*field, SortDir::Desc),
            _ => {
                return Err(toolkit_odata::Error::InvalidOrderByField(format!(
                    "invalid orderby clause: {part}"
                )));
            }
        };

        if field.is_empty() {
            return Err(toolkit_odata::Error::InvalidOrderByField(
                "empty field name in orderby".into(),
            ));
        }

        keys.push(OrderKey {
            field: field.to_owned(),
            dir,
        });
    }

    if keys.len() > MAX_ORDER_FIELDS {
        return Err(toolkit_odata::Error::InvalidOrderByField(
            "too many order fields".into(),
        ));
    }

    Ok(ODataOrderBy(keys))
}

/// Build a canonical `InvalidArgument` for the `$filter` field.
fn filter_invalid_arg(detail: impl Into<String>, reason: &'static str) -> CanonicalError {
    OdataError::invalid_argument()
        .with_field_violation("$filter", detail, reason)
        .create()
}

/// Build a canonical `InvalidArgument` for an unspecified query parameter
/// (used for axum-level deserialization failures).
fn query_params_invalid_arg(detail: impl Into<String>) -> CanonicalError {
    OdataError::invalid_argument()
        .with_field_violation("query", detail, "INVALID_QUERY_PARAMS")
        .create()
}

/// Replacement hint appended to the violation description, so a caller who
/// sent a plausible option learns what to send instead of only that the
/// option is refused.
fn unsupported_option_hint(option: &str) -> &'static str {
    match option {
        "$skip" => {
            "this platform pages by cursor, not by offset: send the previous \
             page's `next_cursor` as `$skiptoken` (alias `cursor`)"
        }
        "$count" => {
            "a page carries no total: `PageInfo` is \
             `{next_cursor, prev_cursor, limit}`"
        }
        "$format" => {
            "responses are JSON: negotiate the media type with the `Accept` \
             header"
        }
        _ => "not implemented by this platform",
    }
}

/// Describe one rejected `$`-prefixed query key.
fn unsupported_option_detail(option: &str) -> String {
    let canonical = option.to_ascii_lowercase();
    if ACCEPTED_SYSTEM_QUERY_OPTIONS.contains(&canonical.as_str()) {
        // The option is supported, the spelling is not: binding is
        // case-sensitive, so honoring `$Top` would take a second code path.
        // Say which spelling binds instead of dropping the request.
        return format!("`{option}` binds only as `{canonical}`");
    }
    if ODATA_SYSTEM_QUERY_OPTIONS.contains(&canonical.as_str()) {
        return format!(
            "unsupported OData system query option `{option}`; {}",
            unsupported_option_hint(&canonical)
        );
    }
    format!(
        "unknown query option `{option}`; the `$` prefix is reserved for \
         OData system query options"
    )
}

/// Reject every `$`-prefixed query key this extractor does not bind.
///
/// Required by OASIS `OData` 4.01 Part 1: Protocol, §6.1 "Query Option
/// Extensibility" — see [`ACCEPTED_SYSTEM_QUERY_OPTIONS`]. Without this,
/// axum drops unclaimed query keys and the caller gets `200` with a result
/// set that ignored what they asked for: `?$skip=20` re-reads page one,
/// `?$filtre=…` returns the whole unfiltered collection.
///
/// Every offending option is reported in one response so a caller fixes
/// them in one round trip.
///
/// # Errors
/// Returns a canonical `InvalidArgument` (`400`) carrying one
/// `UNSUPPORTED_QUERY_PARAM` field violation per offending key, in wire
/// order.
#[allow(clippy::result_large_err)]
fn reject_unsupported_system_query_options(
    pairs: &[(String, String)],
) -> Result<(), CanonicalError> {
    // Deduplicated in wire order: a repeated option is one mistake to fix,
    // and the offender list is bounded by the query string, so a linear
    // `contains` is cheaper than a set.
    let mut offending: Vec<&str> = Vec::new();
    for key in pairs.iter().map(|(key, _)| key.as_str()) {
        if key.starts_with('$')
            && !ACCEPTED_SYSTEM_QUERY_OPTIONS.contains(&key)
            && !offending.contains(&key)
        {
            offending.push(key);
        }
    }

    let mut offenders = offending.into_iter();
    let Some(first) = offenders.next() else {
        return Ok(());
    };

    let mut violations = OdataError::invalid_argument().with_field_violation(
        first,
        unsupported_option_detail(first),
        UNSUPPORTED_QUERY_PARAM,
    );
    for option in offenders {
        violations = violations.with_field_violation(
            option,
            unsupported_option_detail(option),
            UNSUPPORTED_QUERY_PARAM,
        );
    }

    Err(violations.create())
}

/// Extract and validate full `OData` query from request parts.
/// - Rejects any `$`-prefixed key outside [`ACCEPTED_SYSTEM_QUERY_OPTIONS`]
/// - Parses $filter, $orderby, $top / limit, $skiptoken / cursor
/// - Enforces budgets and validates formats
/// - Returns unified `ODataQuery`
///
/// # Errors
/// Returns a `CanonicalError` if any `OData` parameter is invalid. Axum
/// renders it as `application/problem+json` via `IntoResponse for
/// CanonicalError`; `canonical_error_middleware` fills `instance` /
/// `trace_id` on the way out.
pub async fn extract_odata_query<S>(
    parts: &mut Parts,
    state: &S,
) -> Result<ODataQuery, CanonicalError>
where
    S: Send + Sync,
{
    // Runs before any value parsing: a request naming an option this
    // extractor does not bind is malformed whatever the other values say.
    // Deserializing the raw pairs first keeps percent-decoding identical to
    // what `Query::<ODataParams>` binds below.
    let Query(pairs) = Query::<Vec<(String, String)>>::from_request_parts(parts, state)
        .await
        .map_err(|e| query_params_invalid_arg(format!("Invalid query parameters: {e}")))?;
    reject_unsupported_system_query_options(&pairs)?;

    let Query(params) = Query::<ODataParams>::from_request_parts(parts, state)
        .await
        .map_err(|e| query_params_invalid_arg(format!("Invalid query parameters: {e}")))?;

    let mut query = ODataQuery::new();

    // Parse filter
    if let Some(raw_filter) = params.filter.as_ref() {
        let raw = raw_filter.trim();
        if !raw.is_empty() {
            if raw.len() > MAX_FILTER_LEN {
                return Err(filter_invalid_arg("Filter too long", "FILTER_TOO_LONG"));
            }

            // Parse filter string using toolkit-odata
            let parsed = toolkit_odata::parse_filter_string(raw).map_err(|e| {
                // Length-only debug log; the canonical's `diagnostic()` carries
                // the actual parser cause for `canonical_error_middleware`.
                tracing::debug!(error = %e, filter_len = raw.len(), "OData filter parsing failed");
                CanonicalError::from(e)
            })?;

            if parsed.node_count() > MAX_NODES {
                tracing::debug!(
                    node_count = parsed.node_count(),
                    max_nodes = MAX_NODES,
                    "Filter complexity budget exceeded"
                );
                return Err(filter_invalid_arg(
                    "Filter too complex",
                    "FILTER_TOO_COMPLEX",
                ));
            }

            // Generate filter hash for cursor consistency (use non-consuming accessor)
            let filter_hash = toolkit_odata::pagination::short_filter_hash(Some(parsed.as_expr()));

            // Extract expression for query
            let core_expr = parsed.into_expr();

            query = query.with_filter(core_expr);
            if let Some(hash) = filter_hash {
                query = query.with_filter_hash(hash);
            }
        }
    }

    // Check for cursor+orderby conflict before parsing either
    if params.cursor.is_some() && params.orderby.is_some() {
        return Err(ODataError::OrderWithCursor.into());
    }

    // Parse cursor first (if present, skip orderby)
    if let Some(cursor_str) = params.cursor.as_ref() {
        let cursor = CursorV1::decode(cursor_str).map_err(|_| ODataError::InvalidCursor)?;
        query = query.with_cursor(cursor);
        // When cursor is present, order is empty (derived from cursor.s later)
        query = query.with_order(ODataOrderBy::empty());
    } else if let Some(raw_orderby) = params.orderby.as_ref() {
        // Parse orderby only when cursor is absent
        let order = parse_orderby(raw_orderby).map_err(CanonicalError::from)?;
        query = query.with_order(order);
    }

    // Parse limit
    if let Some(limit) = params.limit {
        if limit == 0 {
            return Err(ODataError::InvalidLimit.into());
        }
        query = query.with_limit(limit);
    }

    // Parse select
    if let Some(raw_select) = params.select.as_ref() {
        let fields = parse_select(raw_select)?;
        query = query.with_select(fields);
    }

    Ok(query)
}

use std::ops::Deref;

/// Simple Axum extractor for full `OData` query parameters.
/// Parses $filter, $orderby, limit, and cursor parameters.
/// Usage in handlers:
///   async fn `list_users(OData(query)`: `OData`, /* ... */) { /* use `query` */ }
#[derive(Debug, Clone)]
pub struct OData(pub ODataQuery);

impl OData {
    #[inline]
    pub fn into_inner(self) -> ODataQuery {
        self.0
    }
}

impl Deref for OData {
    type Target = ODataQuery;
    #[inline]
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl AsRef<ODataQuery> for OData {
    #[inline]
    fn as_ref(&self) -> &ODataQuery {
        &self.0
    }
}

impl From<OData> for ODataQuery {
    #[inline]
    fn from(x: OData) -> Self {
        x.0
    }
}

impl<S> FromRequestParts<S> for OData
where
    S: Send + Sync,
{
    type Rejection = CanonicalError;

    #[allow(clippy::manual_async_fn)]
    fn from_request_parts(
        parts: &mut Parts,
        state: &S,
    ) -> impl core::future::Future<Output = Result<Self, Self::Rejection>> + Send {
        async move {
            let query = extract_odata_query(parts, state).await?;
            Ok(OData(query))
        }
    }
}

#[cfg(test)]
#[cfg_attr(coverage_nightly, coverage(off))]
#[path = "odata_tests.rs"]
mod odata_tests;