edi-energy 0.15.0

EDI@Energy EDIFACT parser and validator for the German energy market
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
/// Explicit application handle for multi-tenant and test-isolated EDI@Energy processing.
///
/// A [`Platform`] bundles a custom [`ReleaseRegistry`] with optional configuration
/// so multiple platform instances can coexist in the same process — each with its
/// own profile subset, grace-period override, or test fixtures.
///
/// # Motivation
///
/// The top-level functions ([`crate::parse`], [`crate::parse_interchange`], …) use
/// [`ReleaseRegistry::global()`], which is a process-singleton initialised on first
/// use.  This is convenient for simple applications but prevents:
///
/// - **Test isolation** — tests that manipulate registered profiles cannot run
///   concurrently without interfering.
/// - **Multi-tenant gateways** — an AS4 gateway serving both Strom and Gas tenants
///   with different profile subsets cannot maintain separate registries via globals.
/// - **Hot-reload** — incorporating a new release requires a process restart.
///
/// `Platform` solves these by owning an explicit `Arc<ReleaseRegistry>` that callers
/// build and configure.
///
/// # Usage
///
/// ```rust,no_run
/// use edi_energy::Platform;
///
/// // All built-in profiles:
/// let platform = Platform::with_all_profiles();
///
/// let input = b"UNB+UNOA:3+...";
/// let msg = platform.parse(input)?;
/// # Ok::<(), edi_energy::Error>(())
/// ```
///
/// # Custom profile subset
///
/// ```rust,ignore
/// use edi_energy::{Platform, registry::{Profile, ReleaseRegistry}};
///
/// let mut profiles: Vec<&'static dyn Profile> = Vec::new();
/// my_profiles::register(&mut profiles);
/// let platform = Platform::new(ReleaseRegistry::new(profiles));
/// ```
use std::sync::Arc;

use crate::{AnyMessage, Error, ParseConfig, generated, registry::ReleaseRegistry};
#[cfg(any(
    feature = "utilmd",
    feature = "mscons",
    feature = "aperak",
    feature = "contrl",
    feature = "invoic",
    feature = "remadv",
    feature = "orders",
    feature = "iftsta",
    feature = "insrpt",
    feature = "reqote",
    feature = "partin",
    feature = "ordchg",
    feature = "ordrsp",
    feature = "quotes",
    feature = "comdis",
    feature = "pricat",
    feature = "utilts",
))]
use crate::{EdiEnergyReport, Release};

/// An explicit EDI@Energy processing context.
///
/// See module-level docs for a full explanation of when to use this
/// instead of the top-level free functions.
#[derive(Clone)]
pub struct Platform {
    registry: Arc<ReleaseRegistry>,
}

impl std::fmt::Debug for Platform {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Platform")
            .field("profiles", &self.registry.all_profiles().len())
            .finish()
    }
}

impl Platform {
    /// Create a platform backed by a custom registry.
    ///
    /// Use [`Platform::with_all_profiles()`] for the standard set of registered
    /// profiles, or build a [`ReleaseRegistry`] from a custom profile list for
    /// test isolation or subset deployments.
    #[must_use]
    pub fn new(registry: ReleaseRegistry) -> Self {
        Self {
            registry: Arc::new(registry),
        }
    }

    /// Create a platform with all built-in profiles registered.
    ///
    /// Equivalent to calling `Platform::new(ReleaseRegistry::with_all_profiles())`
    /// but more convenient.  Unlike [`ReleaseRegistry::global()`], each call creates
    /// a fresh, independent registry — useful for test isolation.
    #[must_use]
    pub fn with_all_profiles() -> Self {
        let mut profiles: Vec<&'static dyn crate::registry::Profile> = Vec::new();
        generated::register_profiles(&mut profiles);
        Self::new(ReleaseRegistry::new(profiles))
    }

    /// Override the transition grace period for this platform's registry.
    ///
    /// The BDEW default is 7 calendar days (GPKE §10, `WiM` §12).  Use this when
    /// a specific tenant contract or test scenario requires a different window.
    ///
    /// Returns `self` for builder chaining:
    /// ```rust,no_run
    /// use edi_energy::Platform;
    /// let platform = Platform::with_all_profiles().with_transition_grace_days(14);
    /// ```
    #[must_use]
    pub fn with_transition_grace_days(self, days: i64) -> Self {
        let registry = Arc::try_unwrap(self.registry)
            .unwrap_or_else(|arc| (*arc).clone())
            .with_transition_grace_days(days);
        Self {
            registry: Arc::new(registry),
        }
    }

    /// Parse an EDIFACT/EDI@Energy byte slice using the platform's registry.
    ///
    /// Unlike the free-function [`crate::parse`], this method uses the platform's
    /// own [`ReleaseRegistry`] for PID-source lookup and profile dispatch.
    /// Two platform instances with disjoint profile subsets will each resolve
    /// Prüfidentifikatoren against their own registry.
    ///
    /// # Errors
    ///
    /// Returns `Err` when the byte slice cannot be parsed as valid EDIFACT.
    #[cfg_attr(
        feature = "tracing",
        tracing::instrument(
            skip(self, input),
            fields(
                bytes = input.len(),
                // message_type and release are recorded after parsing via Span::current().record(...)
                message_type = tracing::field::Empty,
                release = tracing::field::Empty,
                pruefidentifikator = tracing::field::Empty,
            )
        )
    )]
    pub fn parse(&self, input: &[u8]) -> Result<AnyMessage, Error> {
        let msg = crate::parse::parse_with_registry(input, ParseConfig::default(), &self.registry)?;
        // Record structured span fields after parsing.
        #[cfg(feature = "tracing")]
        {
            let span = tracing::Span::current();
            if let Some(mt) = msg.try_message_type() {
                span.record("message_type", mt.as_str());
            }
            if let Ok(release) = crate::EdiEnergyMessage::detect_release(&msg) {
                span.record("release", release.as_str());
            }
            if let Ok(pid) = crate::EdiEnergyMessage::detect_pruefidentifikator(&msg) {
                span.record("pruefidentifikator", pid.as_u32());
            }
        }
        Ok(msg)
    }

    /// Parse with explicit [`ParseConfig`], using the platform's registry.
    ///
    /// # Errors
    ///
    /// Returns `Err` when parsing fails.
    #[cfg_attr(
        feature = "tracing",
        tracing::instrument(
            skip(self, input),
            fields(
                bytes = input.len(),
                message_type = tracing::field::Empty,
                release = tracing::field::Empty,
                pruefidentifikator = tracing::field::Empty,
            )
        )
    )]
    pub fn parse_with_config(
        &self,
        input: &[u8],
        config: ParseConfig,
    ) -> Result<AnyMessage, Error> {
        let msg = crate::parse::parse_with_registry(input, config, &self.registry)?;
        #[cfg(feature = "tracing")]
        {
            let span = tracing::Span::current();
            if let Some(mt) = msg.try_message_type() {
                span.record("message_type", mt.as_str());
            }
            if let Ok(release) = crate::EdiEnergyMessage::detect_release(&msg) {
                span.record("release", release.as_str());
            }
            if let Ok(pid) = crate::EdiEnergyMessage::detect_pruefidentifikator(&msg) {
                span.record("pruefidentifikator", pid.as_u32());
            }
        }
        Ok(msg)
    }

    /// Parse all messages from an EDIFACT interchange, using the platform's registry.
    ///
    /// Returns a lazy iterator yielding one [`AnyMessage`] per UNH…UNT window.
    /// PID extraction and profile dispatch use this platform's registry, not the
    /// global singleton.
    pub fn parse_interchange(
        &self,
        reader: impl std::io::Read,
    ) -> impl Iterator<Item = Result<AnyMessage, Error>> {
        self.parse_interchange_with_config(reader, ParseConfig::default())
    }

    /// Parse all messages from an interchange with explicit [`ParseConfig`], using
    /// the platform's registry.
    pub fn parse_interchange_with_config(
        &self,
        reader: impl std::io::Read,
        config: ParseConfig,
    ) -> impl Iterator<Item = Result<AnyMessage, Error>> {
        crate::parse::parse_interchange_with_arc_registry(
            reader,
            config,
            Arc::clone(&self.registry),
        )
    }

    /// Fully parse a byte slice as an EDIFACT interchange, returning a
    /// [`ParsedInterchange`][crate::interchange::ParsedInterchange] that
    /// contains both the UNB envelope and all contained messages.
    ///
    /// Use [`Platform::parse_interchange`] for large interchanges where you
    /// want lazy, per-message iteration instead of materialising everything.
    ///
    /// # Errors
    ///
    /// Returns `Err` on syntax errors, envelope structural errors (missing UNB/UNZ,
    /// mismatched control reference or count), or individual message parse errors.
    pub fn parse_interchange_full(
        &self,
        data: &[u8],
    ) -> Result<crate::interchange::ParsedInterchange, Error> {
        crate::parse::parse_interchange_full_with_arc_registry(
            data,
            ParseConfig::default(),
            Arc::clone(&self.registry),
        )
    }

    /// Validate `message` using this platform's registry instead of the global one.
    ///
    /// Useful for testing with a stripped-down or synthetic registry that does not
    /// contain production profiles.
    ///
    /// # Errors
    ///
    /// Returns `Err(Error::ProfileNotFound)` when the message's release is not
    /// registered in this platform's registry.
    ///
    /// Returns `Err(Error::UnknownMessageType)` for [`AnyMessage::Unknown`].
    #[cfg(any(
        feature = "utilmd",
        feature = "mscons",
        feature = "aperak",
        feature = "contrl",
        feature = "invoic",
        feature = "remadv",
        feature = "orders",
        feature = "iftsta",
        feature = "insrpt",
        feature = "reqote",
        feature = "partin",
        feature = "ordchg",
        feature = "ordrsp",
        feature = "quotes",
        feature = "comdis",
        feature = "pricat",
        feature = "utilts",
    ))]
    #[cfg_attr(
        feature = "tracing",
        tracing::instrument(skip(self, message), fields(message_type = ?message.try_message_type()))
    )]
    pub fn validate(&self, message: &AnyMessage) -> Result<EdiEnergyReport, Error> {
        let core = message
            .message_core()
            .ok_or_else(|| Error::UnknownMessageType {
                raw_code: crate::error::sanitize_code(
                    message.try_message_type().map_or("Unknown", |t| t.as_str()),
                ),
            })?;
        let release = core.detect_release()?;
        core.validate_against_with_semantic_and_registry(release, None, &self.registry)
    }

    /// Validate `message` against an explicit `release`, using this platform's registry.
    ///
    /// # Errors
    ///
    /// Returns `Err(Error::ProfileNotFound)` when `release` is not registered.
    ///
    /// Returns `Err(Error::UnknownMessageType)` for [`AnyMessage::Unknown`].
    #[cfg(any(
        feature = "utilmd",
        feature = "mscons",
        feature = "aperak",
        feature = "contrl",
        feature = "invoic",
        feature = "remadv",
        feature = "orders",
        feature = "iftsta",
        feature = "insrpt",
        feature = "reqote",
        feature = "partin",
        feature = "ordchg",
        feature = "ordrsp",
        feature = "quotes",
        feature = "comdis",
        feature = "pricat",
        feature = "utilts",
    ))]
    #[cfg_attr(
        feature = "tracing",
        tracing::instrument(
            skip(self, message),
            fields(message_type = ?message.try_message_type(), release = %release.as_str())
        )
    )]
    pub fn validate_against(
        &self,
        message: &AnyMessage,
        release: &Release,
    ) -> Result<EdiEnergyReport, Error> {
        let core = message
            .message_core()
            .ok_or_else(|| Error::UnknownMessageType {
                raw_code: crate::error::sanitize_code(
                    message.try_message_type().map_or("Unknown", |t| t.as_str()),
                ),
            })?;
        core.validate_against_with_semantic_and_registry(release, None, &self.registry)
    }

    /// A reference to the underlying [`ReleaseRegistry`].
    #[must_use]
    pub fn registry(&self) -> &ReleaseRegistry {
        &self.registry
    }

    /// Return an `Arc` clone of the underlying registry.
    ///
    /// Use this to share the registry across threads or to construct a
    /// [`crate::registry::ProcessContext`] manually.
    #[must_use]
    pub fn registry_arc(&self) -> Arc<ReleaseRegistry> {
        Arc::clone(&self.registry)
    }

    /// Create a [`crate::registry::ProcessContext`] anchored to `date`, backed
    /// by this platform's isolated registry.
    ///
    /// Use this instead of [`crate::ProcessContext::for_date`] when working
    /// with a [`Platform`] that holds a custom or test-isolated registry.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use edi_energy::Platform;
    ///
    /// let platform = Platform::with_all_profiles();
    /// let ctx = platform.process_context(time::Date::from_calendar_date(2026, time::Month::January, 1).unwrap());
    /// ```
    #[must_use]
    pub fn process_context(&self, date: time::Date) -> crate::registry::ProcessContext {
        crate::registry::ProcessContext::for_date_with_registry(date, Arc::clone(&self.registry))
    }

    /// Create a [`crate::registry::ProcessContext`] anchored to today's UTC date,
    /// backed by this platform's isolated registry.
    #[must_use]
    pub fn current_context(&self) -> crate::registry::ProcessContext {
        let today = time::OffsetDateTime::now_utc().date();
        self.process_context(today)
    }

    /// Check whether the wire release code in `envelope` is normatively
    /// acceptable on `date`, using this platform's registry.
    ///
    /// This is the platform-aware alternative to
    /// `MessageEnvelope::is_wire_code_acceptable_on_global`: it uses the
    /// platform's own [`ReleaseRegistry`] so that test registries and
    /// multi-tenant configurations are respected.
    #[must_use]
    pub fn is_wire_code_acceptable_on(
        &self,
        envelope: &crate::interchange::MessageEnvelope,
        date: time::Date,
    ) -> bool {
        envelope.is_wire_code_acceptable_on(date, &self.registry)
    }

    /// Warm up all `LazyLock` rule-pack statics across every registered profile.
    ///
    /// Triggers eager initialisation of every MIG and AHB union rule pack so
    /// that the first real validation call incurs no latency spike.
    /// Call this once during service startup, before the first request is accepted.
    pub fn warm_up(&self) {
        for profile in self.registry.all_profiles() {
            // Force initialisation of the LazyLock<Arc<ProfileRulePack>> statics.
            let _ = profile.mig_rule_pack();
            let _ = profile.ahb_rule_pack(None);
        }
    }
}