uftp 0.1.0

UFTP 3.1, the USEF Flex Trading Protocol (LF Energy Shapeshifter), in Rust: all 26 messages, CS1 signing and a receive pipeline for DSOs and aggregators.
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
//! The trade flow: building each message from the one it follows, and checking a received
//! message against the one it names `[UFTP §3.8, §4.2.20, §4.2.24]`.
//!
//! The library holds no state. You keep the requests, offers and their revocations; these
//! functions compare two messages you hand them.

use jiff::Timestamp;
use jiff::civil::Date;

use crate::error::Rejection;
use crate::isp::IspSpan;
use crate::msg::{
    FlexHeader, FlexOffer, FlexOfferRevocation, FlexOrder, FlexRequest, Message, Metadata,
    OfferOption,
};
use crate::reason::RejectionReason as R;
use crate::types::{ActivationFactor, Currency, IspDuration, MessageUuid, TimeZoneName};

impl FlexRequest {
    /// A solicited FlexOffer answering this request: same period, congestion point, ISP
    /// duration, time zone, contract and conversation, `Unsolicited="false"` and the
    /// request's MessageID.
    #[must_use]
    pub fn offer(
        &self,
        message_id: MessageUuid,
        timestamp: Timestamp,
        expiration: Timestamp,
        currency: Currency,
        options: Vec<OfferOption>,
    ) -> FlexOffer {
        FlexOffer {
            header: follow(&self.header, message_id, timestamp),
            expiration,
            unsolicited: Some(false),
            flex_request_message_id: Some(self.header.meta.message_id),
            contract_id: self.contract_id.clone(),
            d_prognosis_message_id: None,
            baseline_reference: None,
            currency,
            options,
        }
    }
}

impl FlexOffer {
    /// A FlexOrder of one option of this offer. The ISP list is copied unchanged, as
    /// `[UFTP §4.2.24]` requires, and the price is the option's.
    ///
    /// `option_reference` may be `None` when the offer has a single option.
    ///
    /// # Errors
    /// If the option is not in the offer, or `activation_factor` is below its
    /// `MinActivationFactor`.
    pub fn order(
        &self,
        option_reference: Option<&str>,
        activation_factor: ActivationFactor,
        message_id: MessageUuid,
        timestamp: Timestamp,
        order_reference: impl Into<String>,
    ) -> Result<FlexOrder, Rejection> {
        let option = self.option(option_reference)?;
        check_factor(option, activation_factor)?;
        Ok(FlexOrder {
            header: follow(&self.header, message_id, timestamp),
            isps: option.isps.clone(),
            unsolicited: Some(false),
            flex_offer_message_id: Some(self.header.meta.message_id),
            service_type: None,
            contract_id: self.contract_id.clone(),
            d_prognosis_message_id: self.d_prognosis_message_id,
            baseline_reference: self.baseline_reference.clone(),
            price: option.price,
            currency: self.currency,
            order_reference: order_reference.into(),
            option_reference: Some(option.option_reference.clone()),
            activation_factor,
        })
    }

    /// The option named `reference`, or the only one when `reference` is `None`.
    ///
    /// # Errors
    /// `Unknown reference OptionReference` if there is no such option, or `None` was given
    /// for an offer with several.
    pub fn option(&self, reference: Option<&str>) -> Result<&OfferOption, Rejection> {
        match reference {
            Some(r) => self.options.iter().find(|o| o.option_reference == r),
            None if self.options.len() == 1 => self.options.first(),
            None => None,
        }
        .ok_or_else(|| {
            Rejection::because(
                R::UnknownReference("OptionReference"),
                match reference {
                    Some(r) => format!("Offer {} has no option {r}.", self.header.meta.message_id),
                    None => format!(
                        "Offer {} has {} options; the order must name one.",
                        self.header.meta.message_id,
                        self.options.len()
                    ),
                },
            )
            .at("FlexOrder/@OptionReference")
        })
    }

    /// Checks this offer against the FlexRequest it names `[UFTP §4.2.20]`: the reference, the
    /// parties, period, congestion point, ISP duration and time zone, that the request had
    /// not expired when the offer was made, and that the offer does not expire before it
    /// is made.
    ///
    /// # Errors
    /// On the first mismatch, with its `[UFTP §3.5]` reason.
    pub fn check_against(&self, request: &FlexRequest) -> Result<(), Rejection> {
        let path = "FlexOffer";
        if self.flex_request_message_id != Some(request.header.meta.message_id) {
            return Err(unknown(
                "FlexRequestMessageID",
                self.flex_request_message_id,
                request.header.meta.message_id,
                path,
            ));
        }
        parties(
            &self.header.meta,
            &request.header.meta,
            "FlexRequestMessageID",
            path,
        )?;
        same_day(&self.header, &request.header, path)?;
        if self.header.meta.timestamp > request.expiration {
            return Err(expired(
                "FlexRequest",
                request.expiration,
                self.header.meta.timestamp,
                path,
            ));
        }
        if self.expiration <= self.header.meta.timestamp {
            return Err(Rejection::because(
                R::ExpirationOutOfBounds,
                format!(
                    "The offer expires at {}, before it was made at {}.",
                    self.expiration, self.header.meta.timestamp
                ),
            )
            .at(format!("{path}/@ExpirationDateTime")));
        }
        let requested: Vec<IspSpan> = request
            .isps
            .iter()
            .filter(|i| i.disposition == Some(crate::AvailableRequested::Requested))
            .map(|i| i.span)
            .collect();
        let overlaps = |a: IspSpan, b: IspSpan| a.start() <= b.end() && b.start() <= a.end();
        let touches = self
            .options
            .iter()
            .flat_map(|o| &o.isps)
            .any(|i| requested.iter().any(|&r| overlaps(r, i.span)));
        if !requested.is_empty() && !touches {
            return Err(Rejection::because(
                R::RequestMismatch,
                "No option covers an ISP the request marks Requested; an offer answers at least one of them.",
            )
            .at(path));
        }
        Ok(())
    }
}

impl FlexOrder {
    /// Checks this order against the FlexOffer it names `[UFTP §4.2.24]`: the reference, the
    /// parties, period, congestion point, ISP duration, time zone and currency; that the
    /// offer had not expired when the order was made; that the option exists, its ISP list
    /// is copied unchanged and the activation factor is at least the option's minimum.
    ///
    /// Whether the offer was revoked is your state: reject with
    /// [`RejectionReason::ReferenceMessageRevoked`](crate::RejectionReason::ReferenceMessageRevoked).
    ///
    /// # Errors
    /// On the first mismatch, with its `[UFTP §3.5]` reason.
    pub fn check_against(&self, offer: &FlexOffer) -> Result<(), Rejection> {
        let path = "FlexOrder";
        if self.flex_offer_message_id != Some(offer.header.meta.message_id) {
            return Err(unknown(
                "FlexOfferMessageID",
                self.flex_offer_message_id,
                offer.header.meta.message_id,
                path,
            ));
        }
        parties(
            &self.header.meta,
            &offer.header.meta,
            "FlexOfferMessageID",
            path,
        )?;
        same_day(&self.header, &offer.header, path)?;
        if self.currency != offer.currency {
            // §3.8.5 Price mismatch: a price in another currency is not the offer's price.
            return Err(Rejection::because(
                R::PriceMismatch,
                format!(
                    "The order is in {} but the offer is in {}.",
                    self.currency, offer.currency
                ),
            )
            .at(format!("{path}/@Currency")));
        }
        if self.header.meta.timestamp > offer.expiration {
            return Err(expired(
                "FlexOffer",
                offer.expiration,
                self.header.meta.timestamp,
                path,
            ));
        }
        let option = offer.option(self.option_reference.as_deref())?;
        let spans = |isps: &[crate::PowerIsp]| isps.iter().map(|i| i.span).collect::<Vec<_>>();
        if spans(&self.isps) != spans(&option.isps) {
            return Err(Rejection::because(
                R::IspMismatch,
                format!(
                    "The ISPs differ from those of option {}; an order copies them unchanged.",
                    option.option_reference
                ),
            )
            .at(path));
        }
        if self.isps != option.isps {
            return Err(Rejection::because(
                R::PowerMismatch,
                format!(
                    "The ordered power differs from option {}'s; an order copies it unchanged.",
                    option.option_reference
                ),
            )
            .at(path));
        }
        if self.price != option.price {
            return Err(Rejection::because(
                R::PriceMismatch,
                format!(
                    "Price {} is not option {}'s price {}.",
                    self.price, option.option_reference, option.price
                ),
            )
            .at(format!("{path}/@Price")));
        }
        check_factor(option, self.activation_factor)
    }
}

impl FlexOfferRevocation {
    /// Checks this revocation against the FlexOffer it names: the reference, the parties,
    /// and that the offer had not expired already.
    ///
    /// # Errors
    /// On the first mismatch, with its `[UFTP §3.5]` reason.
    pub fn check_against(&self, offer: &FlexOffer) -> Result<(), Rejection> {
        let path = "FlexOfferRevocation";
        if self.flex_offer_message_id != offer.header.meta.message_id {
            return Err(unknown(
                "FlexOfferMessageID",
                Some(self.flex_offer_message_id),
                offer.header.meta.message_id,
                path,
            ));
        }
        // A revocation comes from the offer's sender, so the parties are the offer's own.
        if self.meta.sender_domain != offer.header.meta.sender_domain
            || self.meta.recipient_domain != offer.header.meta.recipient_domain
        {
            return Err(Rejection::because(
                R::UnknownReference("FlexOfferMessageID"),
                "The offer was exchanged between other parties.",
            )
            .at(path));
        }
        if self.meta.timestamp > offer.expiration {
            return Err(expired(
                "FlexOffer",
                offer.expiration,
                self.meta.timestamp,
                path,
            ));
        }
        Ok(())
    }
}

/// The agreed values of a market: its ISP length and time zone `[UFTP §4.2.2]`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Market {
    /// The ISP length, `PT15M` in most of Europe.
    pub isp_duration: IspDuration,
    /// The market's zone. A message in another zone with the same UTC offsets is
    /// accepted.
    pub time_zone: TimeZoneName,
}

impl Market {
    /// Checks a message's ISP-Duration and TimeZone against the market's `[UFTP §4.2.2]`. A
    /// zone passes when its UTC offset equals the market's at the start and end of the
    /// message's period (or at its TimeStamp when it has no period).
    ///
    /// # Errors
    /// `ISP duration rejected` or `Time zone rejected`.
    pub fn check(&self, message: &Message) -> Result<(), Rejection> {
        let (isp, zone, period) = timing(message);
        let name = message.type_name();
        if let Some(isp) = isp
            && isp != self.isp_duration
        {
            return Err(Rejection::because(
                R::IspDurationRejected,
                format!(
                    "ISP-Duration {isp} is not the market's {}.",
                    self.isp_duration
                ),
            )
            .at(format!("{name}/@ISP-Duration")));
        }
        if let Some(zone) = zone
            && !self.same_offsets(zone, period, message.meta().timestamp)
        {
            return Err(Rejection::because(
                R::TimeZoneRejected,
                format!(
                    "{zone} has another UTC offset than the market's {}.",
                    self.time_zone
                ),
            )
            .at(format!("{name}/@TimeZone")));
        }
        if let Message::FlexSettlement(s) = message {
            self.check_settlement(s)?;
        }
        Ok(())
    }

    /// A FlexSettlement carries no TimeZone or ISP-Duration (spec note SS-20): its ISP
    /// numbers are read in the market's.
    fn check_settlement(&self, s: &crate::FlexSettlement) -> Result<(), Rejection> {
        let days = s
            .order_settlements
            .iter()
            .enumerate()
            .map(|(i, o)| {
                (
                    format!("FlexSettlement/FlexOrderSettlement[{}]", i + 1),
                    o.period,
                    o.isps.iter().map(|x| x.span).collect::<Vec<_>>(),
                )
            })
            .chain(
                s.contract_settlements
                    .iter()
                    .enumerate()
                    .flat_map(|(i, c)| {
                        c.periods.iter().enumerate().map(move |(j, p)| {
                            (
                                format!(
                                    "FlexSettlement/ContractSettlement[{}]/Period[{}]",
                                    i + 1,
                                    j + 1
                                ),
                                p.period,
                                p.isps.iter().map(|x| x.span).collect::<Vec<_>>(),
                            )
                        })
                    }),
            );
        for (path, day, spans) in days {
            crate::DayGrid::new(day, self.time_zone.clone(), self.isp_duration)
                .and_then(|grid| grid.check(&spans))
                .map_err(|e| e.at(path))?;
        }
        Ok(())
    }

    fn same_offsets(&self, zone: &TimeZoneName, period: Option<Date>, at: Timestamp) -> bool {
        let offset = |z: &TimeZoneName, t: Timestamp| z.zone().to_offset(t);
        let instants = match period {
            Some(d) => [d, d.tomorrow().unwrap_or(d)]
                .into_iter()
                .filter_map(|d| {
                    d.to_zoned_datetime(self.time_zone.zone().clone())
                        .and_then(|z| z.start_of_day())
                        .ok()
                })
                .map(|z| z.timestamp())
                .collect(),
            None => vec![at],
        };
        instants
            .into_iter()
            .all(|t| offset(zone, t) == offset(&self.time_zone, t))
    }
}

type Timing<'a> = (Option<IspDuration>, Option<&'a TimeZoneName>, Option<Date>);

fn flex(h: &FlexHeader) -> Timing<'_> {
    (Some(h.isp_duration), Some(&h.time_zone), Some(h.period))
}

fn timing(m: &Message) -> Timing<'_> {
    match m {
        Message::FlexRequest(x) => flex(&x.header),
        Message::FlexOffer(x) => flex(&x.header),
        Message::FlexOrder(x) => flex(&x.header),
        Message::DPrognosis(x) => flex(&x.header),
        Message::FlexReservationUpdate(x) => flex(&x.header),
        Message::Metering(x) => (Some(x.isp_duration), Some(&x.time_zone), Some(x.period)),
        Message::AgrPortfolioUpdate(x) => (None, Some(&x.time_zone), None),
        Message::AgrPortfolioQuery(x) => (None, Some(&x.time_zone), Some(x.period)),
        Message::AgrPortfolioQueryResponse(x) => (None, Some(&x.time_zone), Some(x.period)),
        Message::DsoPortfolioUpdate(x) => (None, Some(&x.time_zone), None),
        Message::DsoPortfolioQuery(x) => (None, Some(&x.time_zone), Some(x.period)),
        Message::DsoPortfolioQueryResponse(x) => (None, Some(&x.time_zone), Some(x.period)),
        _ => (None, None, None),
    }
}

/// The header of a message that follows `previous` in the same conversation, from its
/// recipient back to its sender.
fn follow(previous: &FlexHeader, message_id: MessageUuid, timestamp: Timestamp) -> FlexHeader {
    FlexHeader {
        meta: previous.meta.reply(message_id, timestamp),
        ..previous.clone()
    }
}

fn check_factor(option: &OfferOption, factor: ActivationFactor) -> Result<(), Rejection> {
    if factor < option.min_activation_factor {
        return Err(Rejection::because(
            R::InvalidSender,
            format!(
                "ActivationFactor {factor} is below option {}'s MinActivationFactor {}.",
                option.option_reference, option.min_activation_factor
            ),
        )
        .at("FlexOrder/@ActivationFactor"));
    }
    Ok(())
}

fn unknown(
    field: &'static str,
    named: Option<MessageUuid>,
    expected: MessageUuid,
    path: &str,
) -> Rejection {
    let named = named.map_or_else(|| "missing".to_owned(), |id| format!("{id}"));
    Rejection::because(
        R::UnknownReference(field),
        format!("{field} is {named}, but the message it is checked against is {expected}."),
    )
    .at(format!("{path}/@{field}"))
}

/// The follow-up goes from the referenced message's recipient to its sender.
fn parties(
    follow_up: &Metadata,
    referenced: &Metadata,
    field: &'static str,
    path: &str,
) -> Result<(), Rejection> {
    if follow_up.sender_domain != referenced.recipient_domain
        || follow_up.recipient_domain != referenced.sender_domain
    {
        return Err(Rejection::because(
            R::UnknownReference(field),
            format!(
                "The referenced message went from {} to {}, not between these parties.",
                referenced.sender_domain, referenced.recipient_domain
            ),
        )
        .at(path.to_owned()));
    }
    Ok(())
}

fn same_day(a: &FlexHeader, b: &FlexHeader, path: &str) -> Result<(), Rejection> {
    let mismatch = |reason, attr: &str, ours: String, theirs: String| {
        Err(Rejection::because(
            reason,
            format!("{attr} is {ours}; the referenced message has {theirs}."),
        )
        .at(format!("{path}/@{attr}")))
    };
    if a.period != b.period {
        return mismatch(
            R::ReferencePeriodMismatch,
            "Period",
            a.period.to_string(),
            b.period.to_string(),
        );
    }
    if a.congestion_point != b.congestion_point {
        return mismatch(
            R::InvalidCongestionPoint,
            "CongestionPoint",
            a.congestion_point.to_string(),
            b.congestion_point.to_string(),
        );
    }
    if a.isp_duration != b.isp_duration {
        return mismatch(
            R::IspDurationRejected,
            "ISP-Duration",
            a.isp_duration.to_string(),
            b.isp_duration.to_string(),
        );
    }
    if a.time_zone != b.time_zone {
        return mismatch(
            R::TimeZoneRejected,
            "TimeZone",
            a.time_zone.to_string(),
            b.time_zone.to_string(),
        );
    }
    Ok(())
}

fn expired(what: &str, expiration: Timestamp, at: Timestamp, path: &str) -> Rejection {
    Rejection::because(
        R::ReferenceMessageExpired,
        format!("The {what} expired at {expiration}, before this message was made at {at}."),
    )
    .at(path.to_owned())
}

impl Message {
    /// The time rules of `[UFTP §3.5]` at `now`, which the caller supplies:
    /// - `Period out of bounds`: a Flex message (FlexRequest, FlexOffer, FlexOrder,
    ///   D-Prognosis, FlexReservationUpdate) whose Period ended at or before `now`, in the
    ///   message's own TimeZone;
    /// - `ExpirationDateTime out of bounds`: a FlexRequest or FlexOffer that expired before
    ///   `now`.
    ///
    /// Other messages pass. Run it after [`open`](crate::open), on the receiving side.
    ///
    /// # Errors
    /// The first rule broken, with its reason; [`Rejection::response`] answers it.
    pub fn check_time(&self, now: Timestamp) -> Result<(), Rejection> {
        let (header, expiration) = match self {
            Message::FlexRequest(x) => (&x.header, Some(x.expiration)),
            Message::FlexOffer(x) => (&x.header, Some(x.expiration)),
            Message::FlexOrder(x) => (&x.header, None),
            Message::DPrognosis(x) => (&x.header, None),
            Message::FlexReservationUpdate(x) => (&x.header, None),
            _ => return Ok(()),
        };
        let name = self.type_name();
        let grid = header.grid().map_err(|e| e.at(name))?;
        let (_, day_end) = grid.interval(grid.count()).map_err(|e| e.at(name))?;
        if day_end <= now {
            return Err(Rejection::because(
                R::PeriodOutOfBounds,
                format!(
                    "Period {} in {} ended at {day_end}, before {now}.",
                    header.period, header.time_zone
                ),
            )
            .at(format!("{name}/@Period")));
        }
        if let Some(expiration) = expiration
            && expiration < now
        {
            return Err(Rejection::because(
                R::ExpirationOutOfBounds,
                format!("The {name} expired at {expiration}, before {now}."),
            )
            .at(format!("{name}/@ExpirationDateTime")));
        }
        Ok(())
    }
}