qubit-metadata 0.7.2

Type-safe metadata model with schemas and composable filters
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
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
// =============================================================================
//    Copyright (c) 2025 - 2026 Haixing Hu.
//
//    SPDX-License-Identifier: Apache-2.0
//
//    Licensed under the Apache License, Version 2.0.
// =============================================================================
//! [`MetadataFilter`].

use std::cell::RefCell;
use std::fmt;
#[cfg(feature = "json")]
use std::io::Write;
use std::rc::Rc;

#[cfg(feature = "json")]
use qubit_budget::json::JsonDecodeSession;
#[cfg(feature = "json")]
use qubit_budget::json::JsonEncodeLimits;
#[cfg(feature = "json")]
use qubit_budget::json::JsonEncodeSession;
#[cfg(feature = "json")]
use qubit_json::decode::JsonDecoder;
#[cfg(feature = "json")]
use qubit_json::encode::JsonEncoder;
use qubit_redact::Redact;
use qubit_redact::RedactionWriter;
use qubit_redact::Redactor;
use qubit_utils::Transient;
#[cfg(feature = "json")]
use qubit_value::ValueWireEncodePreflight;
use serde::Deserialize;
use serde::Deserializer;
use serde::Serialize;
use serde::Serializer;
use serde::de;
use serde::de::DeserializeSeed;
use serde::ser::Error as SerError;

use super::metadata_filter_builder::MetadataFilterBuilder;
#[cfg(feature = "json")]
use super::wire::METADATA_FILTER_WIRE_VERSION_V1;
use super::wire::MetadataFilterWireV1Ref;
use super::wire::MetadataFilterWireV1Seed;
#[cfg(feature = "schema")]
use crate::Condition;
use crate::FilterExpression;
#[cfg(feature = "json")]
use crate::FilterExpressionView;
use crate::FilterLimits;
use crate::FilterMatchOptions;
use crate::Metadata;
#[cfg(feature = "schema")]
use crate::MetadataResult;
#[cfg(feature = "json")]
use crate::metadata_limits::MetadataLimits;

/// An expression, its matching policy, and its resource limits.
///
/// Boolean composition belongs to [`FilterExpression`]. This type only binds
/// an already-built expression to the options and limits used to evaluate it.
///
/// # Examples
///
/// ```
/// use qubit_metadata::FilterExpression;
/// use qubit_metadata::Metadata;
/// use qubit_metadata::MetadataFilter;
///
/// # fn main() -> qubit_metadata::MetadataResult<()> {
/// let metadata = Metadata::new().with("tenant", "acme");
/// let expression = FilterExpression::builder()
///     .eq("tenant", "acme")
///     .build()?;
/// let filter = MetadataFilter::builder().expression(expression).build()?;
/// assert!(filter.matches(&metadata));
/// # Ok(())
/// # }
/// ```
#[derive(Clone, PartialEq)]
#[must_use]
pub struct MetadataFilter {
    /// Root Boolean expression.
    expression: FilterExpression,
    /// Evaluation options.
    options: FilterMatchOptions,
    /// Bounds that the expression satisfies.
    limits: Transient<FilterLimits>,
}

impl fmt::Debug for MetadataFilter {
    /// Writes the strict-policy diagnostic representation.
    ///
    /// # Parameters
    ///
    /// * `formatter` - Formatter that receives the output.
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        let output = Redactor::strict().redact_text(self);
        let text = output.text_or_marker("<redaction incomplete>");
        formatter.write_str(text.as_ref())
    }
}

impl Redact for MetadataFilter {
    /// Writes the filter through one cumulative diagnostic budget.
    ///
    /// # Parameters
    ///
    /// * `writer` - Destination that receives the encoded or redacted output.
    fn write_redacted(&self, writer: &mut RedactionWriter<'_>) {
        writer.record("MetadataFilter", |fields| {
            fields.nested("expression", &self.expression);
            fields.unmarked("options", || self.options);
            fields.unmarked("limits", || self.limits());
        });
    }
}

impl MetadataFilter {
    /// Creates a filter that matches every metadata object.
    ///
    /// # Returns
    ///
    /// A constant-true filter using default match options and library hard
    /// limits.
    #[inline]
    pub fn all() -> Self {
        Self::new(
            FilterExpression::match_all(),
            FilterMatchOptions::default(),
            FilterLimits::MAX,
        )
    }

    /// Creates a filter that matches no metadata object.
    ///
    /// # Returns
    ///
    /// A constant-false filter using default match options and library hard
    /// limits.
    #[inline]
    pub fn none() -> Self {
        Self::new(
            FilterExpression::match_none(),
            FilterMatchOptions::default(),
            FilterLimits::MAX,
        )
    }

    /// Creates a builder for a metadata filter.
    #[inline]
    #[must_use]
    pub const fn builder() -> MetadataFilterBuilder {
        MetadataFilterBuilder::new()
    }

    /// Creates a filter from already validated parts.
    ///
    /// # Parameters
    ///
    /// * `expression` - Filter expression stored by the filter.
    /// * `options` - Options used when matching.
    /// * `limits` - Resource limits applied by this operation.
    ///
    /// # Returns
    ///
    /// A filter containing the supplied validated parts.
    #[inline]
    pub(crate) const fn new(expression: FilterExpression, options: FilterMatchOptions, limits: FilterLimits) -> Self {
        Self {
            expression,
            options,
            limits: Transient::new(limits),
        }
    }

    /// Deserializes a filter and validates a receiver-controlled AST bound.
    ///
    /// The receiver bound is charged while the AST is being decoded. Callers
    /// must separately bound raw input bytes and any deserializer-specific
    /// resources before accepting untrusted data.
    ///
    /// # Type Parameters
    ///
    /// * `D` - Deserializer that provides the encoded representation.
    ///
    /// # Parameters
    ///
    /// * `deserializer` - Source of the versioned filter representation.
    /// * `receiver_limits` - Local upper bounds applied to the decoded AST.
    ///
    /// # Returns
    ///
    /// The decoded filter using the supplied receiver limits.
    ///
    /// # Errors
    ///
    /// Returns a deserialization error for malformed V1 data or an unsupported
    /// version. The underlying deserializer's error type receives the
    /// structured filter-limit or policy failure through `D::Error::custom`;
    /// this generic API cannot return `MetadataWireDecodeError` directly.
    pub fn deserialize_with_filter_limits<'de, D>(
        deserializer: D,
        receiver_limits: FilterLimits,
    ) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let error_slot = Rc::new(RefCell::new(None));
        let wire = MetadataFilterWireV1Seed::new(receiver_limits, Rc::clone(&error_slot))
            .deserialize(deserializer)
            .map_err(|error| {
                error_slot
                    .borrow_mut()
                    .take()
                    .map_or_else(|| de::Error::custom(error), de::Error::custom)
            })?;
        wire.into_filter(receiver_limits).map_err(de::Error::custom)
    }

    /// Decodes a strict metadata-filter JSON envelope using the default wire
    /// byte and receiver AST limits.
    ///
    /// # Parameters
    ///
    /// * `input` - Complete untrusted JSON input.
    ///
    /// # Returns
    ///
    /// The decoded filter.
    ///
    /// # Errors
    ///
    /// Returns `Budget` or `Quantity` when shared JSON traversal exceeds a
    /// configured budget, `Filter` when the receiver AST or filter contract
    /// exceeds its limit, `UnsupportedVersion` for a version mismatch,
    /// `InvalidLimits` for invalid metadata limits, and `Syntax` for empty
    /// input or lexical JSON errors. Shared decoder failures such as invalid
    /// UTF-8, unexpected top-level types, or deserialization failures return
    /// `Decode`.
    /// The complete unique-key JSON source tree is first materialized under
    /// the shared JSON decode budgets. The domain seed then checks receiver AST
    /// and membership limits while constructing the filter. Receiver AST or
    /// filter-contract failures return `Filter`; tightening `FilterLimits`
    /// does not stop the preceding source-tree materialization, so configure
    /// both the generic JSON budgets and domain limits.
    #[cfg(feature = "json")]
    #[inline]
    pub fn decode_json_slice(input: &[u8]) -> Result<Self, crate::MetadataWireDecodeError> {
        Self::decode_json_slice_with_limits(input, MetadataLimits::default(), FilterLimits::MAX)
    }

    /// Decodes a strict metadata-filter JSON envelope after validating the
    /// shared metadata limits. The complete unique-key JSON source tree is
    /// first materialized under the shared JSON decode budgets. The domain
    /// seed then checks receiver AST and membership limits while constructing
    /// the filter. Tightening `receiver_filter_limits` does not stop the
    /// preceding source-tree materialization, so configure both the generic
    /// JSON budgets and domain limits.
    ///
    /// # Parameters
    ///
    /// * `input` - Complete untrusted JSON input.
    /// * `limits` - Shared JSON limits for this decoding session.
    /// * `receiver_filter_limits` - Local AST limits charged while decoding the
    ///   expression tree.
    ///
    /// # Returns
    ///
    /// The decoded filter constrained by receiver-controlled limits.
    ///
    /// # Errors
    ///
    /// Returns `Budget` or `Quantity` when generic JSON traversal exceeds a
    /// configured budget, `Filter` when domain traversal detects an AST limit
    /// or the decoded filter violates its contract, `UnsupportedVersion` for a
    /// version mismatch, and `InvalidLimits` for invalid metadata limits.
    /// Empty input and lexical JSON errors return `Syntax`; shared decoder
    /// failures such as invalid UTF-8, unexpected top-level types, or other
    /// deserialization failures return `Decode`. Receiver AST or filter
    /// contract failures return `Filter` and do not retain source coordinates.
    /// Individual JSON strings and embedded value payloads remain bounded by
    /// the outer input-byte limit.
    #[cfg(feature = "json")]
    pub fn decode_json_slice_with_limits(
        input: &[u8],
        limits: MetadataLimits,
        receiver_filter_limits: FilterLimits,
    ) -> Result<Self, crate::MetadataWireDecodeError> {
        limits
            .validate()
            .map_err(crate::MetadataWireDecodeError::InvalidLimits)?;
        let mut decoder = JsonDecoder::new(JsonDecodeSession::from_limits(limits.json_decode()));
        let error_slot = Rc::new(RefCell::new(None));
        let wire = decoder
            .decode_unique_seed_utf8(
                MetadataFilterWireV1Seed::new(receiver_filter_limits, Rc::clone(&error_slot)),
                input,
            )
            .map_err(|error| {
                error_slot.borrow_mut().take().map_or_else(
                    || Into::<crate::MetadataWireDecodeError>::into(error),
                    crate::MetadataWireDecodeError::Filter,
                )
            })?;
        if wire.version() != METADATA_FILTER_WIRE_VERSION_V1 {
            return Err(crate::MetadataWireDecodeError::UnsupportedVersion {
                expected: METADATA_FILTER_WIRE_VERSION_V1,
                actual: wire.version(),
            });
        }
        wire.into_filter(receiver_filter_limits)
            .map_err(crate::MetadataWireDecodeError::Filter)
    }

    /// Encodes this filter with the default JSON budget profile.
    ///
    /// Uses [`crate::default_json_encode_limits`]. Decode limits do not
    /// affect output budgets. Successful filter construction does not
    /// guarantee that the encoded document fits these JSON budgets.
    ///
    /// # Returns
    ///
    /// Compact JSON bytes representing this filter in the V1 wire format.
    ///
    /// # Errors
    ///
    /// Returns [`crate::MetadataWireEncodeError`] when operand preflight,
    /// JSON budget checks, or serialization fails.
    #[cfg(feature = "json")]
    pub fn to_json_vec(&self) -> Result<Vec<u8>, crate::MetadataWireEncodeError> {
        self.to_json_vec_with_limits(crate::metadata_limits::default_json_encode_limits())
    }

    /// Encodes this filter with caller-provided JSON budgets.
    ///
    /// The supplied limits apply to this encoding operation independently
    /// of the AST limits enforced during filter construction. A successfully
    /// constructed filter can still exceed these JSON budgets.
    ///
    /// # Parameters
    ///
    /// * `limits` - Output and JSON-value budgets for this operation.
    ///
    /// # Returns
    ///
    /// Compact JSON bytes representing this filter in the V1 wire format.
    ///
    /// # Errors
    ///
    /// Returns [`crate::MetadataWireEncodeError`] when operand preflight,
    /// JSON budget checks, or serialization fails.
    #[cfg(feature = "json")]
    pub fn to_json_vec_with_limits(&self, limits: JsonEncodeLimits) -> Result<Vec<u8>, crate::MetadataWireEncodeError> {
        self.preflight_wire_values(limits)?;
        let session = JsonEncodeSession::from_limits(limits);
        JsonEncoder::new(session).to_vec(self).map_err(Into::into)
    }

    /// Encodes this filter to a writer with the default JSON budget profile.
    ///
    /// The complete compact JSON document is buffered after operand preflight
    /// and budget checks, before any bytes are written to the destination. A
    /// preflight, budget, or serialization error therefore leaves the writer
    /// untouched. An I/O error during writing may leave a prefix in the writer;
    /// this method does not provide atomicity, rollback, or automatic retries.
    /// Applications are responsible for persistence and retry decisions.
    /// The default profile is returned by
    /// [`crate::default_json_encode_limits`]; decode limits do not affect
    /// the output budget.
    ///
    /// # Type Parameters
    ///
    /// * `W` - Writer that receives the encoded representation.
    ///
    /// # Parameters
    ///
    /// * `writer` - Destination receiving the compact JSON document.
    ///
    /// # Returns
    ///
    /// Returns `Ok(())` after the complete document is written.
    ///
    /// # Errors
    ///
    /// Returns [`crate::MetadataWireEncodeError`] when operand preflight,
    /// budget checks, serialization, or destination I/O fails. Only destination
    /// I/O errors can occur after writing has started.
    #[cfg(feature = "json")]
    pub fn to_json_writer<W>(&self, writer: W) -> Result<(), crate::MetadataWireEncodeError>
    where
        W: Write,
    {
        self.to_json_writer_with_limits(writer, crate::metadata_limits::default_json_encode_limits())
    }

    /// Encodes this filter to a writer with caller-provided JSON budgets.
    ///
    /// The complete compact JSON document is buffered after operand preflight
    /// and budget checks, before any bytes are written to the destination. A
    /// preflight, budget, or serialization error therefore leaves the writer
    /// untouched. An I/O error during writing may leave a prefix in the writer;
    /// this method does not provide atomicity, rollback, or automatic retries.
    /// Applications are responsible for persistence and retry decisions. The
    /// supplied [`JsonEncodeLimits`] controls encoding; decode limits do not
    /// affect the output budget.
    ///
    /// # Type Parameters
    ///
    /// * `W` - Writer that receives the encoded representation.
    ///
    /// # Parameters
    ///
    /// * `writer` - Destination receiving the compact JSON document.
    /// * `limits` - Output and JSON-value budgets for this operation.
    ///
    /// # Returns
    ///
    /// Returns `Ok(())` after the complete document is written.
    ///
    /// # Errors
    ///
    /// Returns [`crate::MetadataWireEncodeError`] when operand preflight,
    /// budget checks, serialization, or destination I/O fails. Only destination
    /// I/O errors can occur after writing has started.
    #[cfg(feature = "json")]
    pub fn to_json_writer_with_limits<W>(
        &self,
        mut writer: W,
        limits: JsonEncodeLimits,
    ) -> Result<(), crate::MetadataWireEncodeError>
    where
        W: Write,
    {
        self.preflight_wire_values(limits)?;
        let session = JsonEncodeSession::from_limits(limits);
        JsonEncoder::new(session)
            .write_buffered(&mut writer, self)
            .map_err(Into::into)
    }

    /// Returns the root expression.
    ///
    /// # Returns
    ///
    /// The expression evaluated by this filter.
    #[inline]
    #[must_use = "the filter expression should be inspected"]
    pub const fn expression(&self) -> &FilterExpression {
        &self.expression
    }

    /// Returns the evaluation options.
    ///
    /// # Returns
    ///
    /// The policy used when evaluating conditions.
    #[inline]
    #[must_use]
    pub const fn options(&self) -> FilterMatchOptions {
        self.options
    }

    /// Returns the resource limits.
    ///
    /// # Returns
    ///
    /// The limits validated when this filter was constructed.
    #[inline]
    #[must_use = "the filter limits should be inspected"]
    pub const fn limits(&self) -> FilterLimits {
        *self.limits.get()
    }

    /// Returns whether `metadata` satisfies this filter.
    ///
    /// # Parameters
    ///
    /// * `metadata` - Metadata inspected by the filter.
    ///
    /// # Returns
    ///
    /// `true` when the metadata satisfies the expression and match options.
    #[inline]
    #[must_use]
    pub fn matches(&self, metadata: &Metadata) -> bool {
        self.expression.evaluate(metadata, self.options).is_match()
    }

    /// Visits every leaf condition in the expression.
    ///
    /// # Type Parameters
    ///
    /// * `F` - Callback invoked for each visited condition.
    ///
    /// # Parameters
    ///
    /// * `visitor` - Callback applied to each leaf condition.
    ///
    /// # Errors
    ///
    /// Returns the first error produced by `visitor`.
    #[cfg(feature = "schema")]
    #[inline]
    pub(crate) fn visit_conditions<F>(&self, mut visitor: F) -> MetadataResult<()>
    where
        F: FnMut(&Condition) -> MetadataResult<()>,
    {
        self.expression.visit_conditions(&mut visitor)
    }

    /// Preflights every operand against the shared JSON encoding budget.
    ///
    /// # Parameters
    ///
    /// * `limits` - Resource limits applied by this operation.
    ///
    /// # Errors
    ///
    /// Returns an encoding error if any operand exceeds the budget.
    #[cfg(feature = "json")]
    fn preflight_wire_values(&self, limits: JsonEncodeLimits) -> Result<(), crate::MetadataWireEncodeError> {
        /// Checks every value operand in one expression subtree.
        ///
        /// # Parameters
        ///
        /// * `expression` - Filter expression stored by the filter.
        /// * `checker` - Shared preflight checker for encoded values.
        ///
        /// # Returns
        ///
        /// `Ok(())` after every operand in the subtree passes preflight.
        ///
        /// # Errors
        ///
        /// Returns an encoding error when an operand exceeds the shared budget.
        fn visit(
            expression: &FilterExpression,
            checker: &mut ValueWireEncodePreflight,
        ) -> Result<(), crate::MetadataWireEncodeError> {
            match expression.view() {
                FilterExpressionView::Condition(condition) => condition.visit_operands(&mut |value| {
                    checker.check_value(value).map_err(crate::MetadataWireEncodeError::from)
                }),
                FilterExpressionView::And(children) | FilterExpressionView::Or(children) => {
                    for child in children {
                        visit(child, checker)?;
                    }
                    Ok(())
                }
                FilterExpressionView::Not(inner) => visit(inner, checker),
                FilterExpressionView::True | FilterExpressionView::False => Ok(()),
            }
        }
        let mut checker = ValueWireEncodePreflight::new(limits);
        visit(&self.expression, &mut checker)
    }
}

impl Serialize for MetadataFilter {
    /// Serializes this filter through its versioned wire representation.
    ///
    /// # Type Parameters
    ///
    /// * `S` - Serializer that receives the encoded representation.
    ///
    /// # Parameters
    ///
    /// * `serializer` - Serializer receiving the filter representation.
    ///
    /// # Returns
    ///
    /// The serializer's representation of this filter.
    ///
    /// # Errors
    ///
    /// Returns the serializer's error if conversion to the wire form or
    /// serialization fails.
    #[inline]
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        MetadataFilterWireV1Ref::try_from(self)
            .map_err(<S::Error as SerError>::custom)?
            .serialize(serializer)
    }
}

impl<'de> Deserialize<'de> for MetadataFilter {
    /// Deserializes a filter using library hard limits as receiver limits.
    ///
    /// # Type Parameters
    ///
    /// * `D` - Deserializer that provides the encoded representation.
    ///
    /// # Parameters
    ///
    /// * `deserializer` - Deserializer providing the filter representation.
    ///
    /// # Returns
    ///
    /// The reconstructed filter.
    ///
    /// # Errors
    ///
    /// Returns the deserializer's error if the versioned representation is
    /// malformed or violates the filter limits.
    #[inline]
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        Self::deserialize_with_filter_limits(deserializer, FilterLimits::MAX)
    }
}