uftp 0.3.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
//! The messages between aggregator and Common Reference Operator `[XSD UFTP-agr-cro.xsd]`.

use jiff::civil::Date;

use crate::error::Rejection;
use crate::msg::agr_dso::nonempty;
use crate::msg::meta::{Metadata, Reply, ResponseHeader, XsDate, named};
use crate::msg::{DecodeOptions, Message, Wire, simple_response, wire_meta};
use crate::types::{
    AcceptedRejected, EntityAddress, InternetDomain, MessageUuid, RedispatchBy, TimeZoneName,
};
use crate::xml::attrs::{Attrs, children, in_order, require_one};
use crate::xml::reader::Element;
use crate::xml::writer::Writer;

/// A connection with the days it belongs to a portfolio or congestion point.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PortfolioConnection {
    /// The connection.
    pub entity_address: EntityAddress,
    /// The first day.
    pub start_period: Date,
    /// The last day, if it is known.
    pub end_period: Option<Date>,
}

impl PortfolioConnection {
    pub(crate) fn read(el: &Element, path: String) -> Result<Self, Rejection> {
        children(el, &path, &[])?;
        let mut a = Attrs::new(el, path);
        let v = Self {
            entity_address: a.req("EntityAddress")?,
            start_period: a.req::<XsDate>("StartPeriod")?.0,
            end_period: a.opt::<XsDate>("EndPeriod")?.map(|d| d.0),
        };
        a.finish()?;
        Ok(v)
    }

    pub(crate) fn write(&self, w: &mut Writer) {
        w.start("Connection")
            .attr("EntityAddress", &self.entity_address)
            .attr("StartPeriod", self.start_period)
            .opt_attr("EndPeriod", self.end_period.as_ref())
            .end();
    }
}

fn read_addresses(el: &Element, path: &str) -> Result<Vec<EntityAddress>, Rejection> {
    named(el, path, "Connection")
        .map(|(p, c)| {
            children(c, &p, &[])?;
            let mut a = Attrs::new(c, p);
            let v = a.req("EntityAddress")?;
            a.finish()?;
            Ok(v)
        })
        .collect()
}

fn write_addresses(w: &mut Writer, addresses: &[EntityAddress]) {
    for e in addresses {
        w.start("Connection").attr("EntityAddress", e).end();
    }
}

// ---------------------------------------------------------------------------------------
// AGRPortfolioUpdate
// ---------------------------------------------------------------------------------------

/// The aggregator tells the CRO on which connections it represents prosumers
/// `[XSD AGRPortfolioUpdateType]`. Sent by the AGR.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AgrPortfolioUpdate {
    /// The common metadata.
    pub meta: Metadata,
    /// The zone in which the periods are read.
    pub time_zone: TimeZoneName,
    /// The connections; at least one by the XSD, though the PDF allows none (SS-15).
    pub connections: Vec<PortfolioConnection>,
}

impl Wire for AgrPortfolioUpdate {
    const NAME: &'static str = "AGRPortfolioUpdate";
    wire_meta!(meta);
    fn validate(&self) -> Result<(), Rejection> {
        for (i, c) in self.connections.iter().enumerate() {
            let path = format!("{}/Connection[{}]", Self::NAME, i + 1);
            check_range(c.start_period, c.end_period, None, &path)?;
        }
        Ok(())
    }
    fn read(el: &Element, _: DecodeOptions) -> Result<Self, Rejection> {
        children(el, Self::NAME, &["Connection"])?;
        require_one(el, Self::NAME, "Connection")?;
        let mut a = Attrs::new(el, Self::NAME);
        let meta = Metadata::read(&mut a)?;
        let time_zone = a.req("TimeZone")?;
        a.finish()?;
        let connections = named(el, Self::NAME, "Connection")
            .map(|(p, c)| PortfolioConnection::read(c, p))
            .collect::<Result<_, _>>()?;
        Ok(Self {
            meta,
            time_zone,
            connections,
        })
    }
    fn write(&self, w: &mut Writer) -> Result<(), Rejection> {
        nonempty(&self.connections, Self::NAME, "Connection")?;
        w.start(Self::NAME);
        self.meta.write(w);
        w.attr("TimeZone", &self.time_zone);
        for c in &self.connections {
            c.write(w);
        }
        w.end();
        Ok(())
    }
    fn answer(&self, reply: Reply) -> Option<Message> {
        Some(self.reply(reply).into())
    }
}

simple_response!(
    /// The CRO's answer to an AGRPortfolioUpdate `[XSD AGRPortfolioUpdateResponseType]`.
    AgrPortfolioUpdateResponse,
    "AGRPortfolioUpdateResponse",
    "AGRPortfolioUpdateMessageID",
    agr_portfolio_update_message_id,
    AgrPortfolioUpdate
);

// ---------------------------------------------------------------------------------------
// AGRPortfolioQuery
// ---------------------------------------------------------------------------------------

/// The aggregator asks the CRO which DSOs and congestion points its connections belong to
/// on a day `[XSD AGRPortfolioQueryType]`. Sent by the AGR.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AgrPortfolioQuery {
    /// The common metadata.
    pub meta: Metadata,
    /// The zone of `period`; required by the XSD, absent from the PDF (SS-16).
    pub time_zone: TimeZoneName,
    /// The day asked about.
    pub period: Date,
}

impl Wire for AgrPortfolioQuery {
    const NAME: &'static str = "AGRPortfolioQuery";
    wire_meta!(meta);
    fn read(el: &Element, _: DecodeOptions) -> Result<Self, Rejection> {
        children(el, Self::NAME, &[])?;
        let mut a = Attrs::new(el, Self::NAME);
        let v = Self {
            meta: Metadata::read(&mut a)?,
            time_zone: a.req("TimeZone")?,
            period: a.req::<XsDate>("Period")?.0,
        };
        a.finish()?;
        Ok(v)
    }
    fn write(&self, w: &mut Writer) -> Result<(), Rejection> {
        w.start(Self::NAME);
        self.meta.write(w);
        w.attr("TimeZone", &self.time_zone)
            .attr("Period", self.period)
            .end();
        Ok(())
    }
    /// Only a rejection: an accepted answer carries the views, which only the CRO's data
    /// can give (`AgrPortfolioQuery::reply`).
    fn answer(&self, reply: Reply) -> Option<Message> {
        (reply.result == AcceptedRejected::Rejected).then(|| self.reply(reply, Vec::new()).into())
    }
}

/// A congestion point of a DSO, as the CRO shows it to an aggregator.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PortfolioCongestionPoint {
    /// The congestion point.
    pub entity_address: EntityAddress,
    /// Whether the DSO accepts mutually exclusive offer options here.
    pub mutex_offers_supported: bool,
    /// Who redispatches day-ahead.
    pub day_ahead_redispatch_by: RedispatchBy,
    /// Who redispatches intraday; no intraday trading when absent.
    pub intraday_redispatch_by: Option<RedispatchBy>,
    /// The aggregator's connections on it; at least one.
    pub connections: Vec<EntityAddress>,
}

/// One DSO's congestion points with the aggregator's connections on them.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DsoPortfolio {
    /// The DSO.
    pub dso_domain: InternetDomain,
    /// Its congestion points; at least one.
    pub congestion_points: Vec<PortfolioCongestionPoint>,
}

/// One view of the aggregator's portfolio.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DsoView {
    /// The DSO portfolios; at least one.
    pub portfolios: Vec<DsoPortfolio>,
    /// Connections that are on no congestion point.
    pub connections: Vec<EntityAddress>,
}

/// The CRO's answer to an AGRPortfolioQuery `[XSD AGRPortfolioQueryResponseType]`.
///
/// The XSD requires at least one `DSO-View` even in a rejection, which no CRO can fill
/// (SS-18). This crate writes a Rejected response without views, and reads one.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AgrPortfolioQueryResponse {
    header: ResponseHeader,
    agr_portfolio_query_message_id: MessageUuid,
    /// The zone of `period`, copied from the query.
    pub time_zone: TimeZoneName,
    /// The day, copied from the query.
    pub period: Date,
    /// The views; at least one when accepted.
    pub dso_views: Vec<DsoView>,
}

impl AgrPortfolioQueryResponse {
    /// The response metadata and result.
    #[must_use]
    pub fn header(&self) -> &ResponseHeader {
        &self.header
    }

    /// The `MessageID` of the AGRPortfolioQuery this answers.
    #[must_use]
    pub fn agr_portfolio_query_message_id(&self) -> MessageUuid {
        self.agr_portfolio_query_message_id
    }
}

impl AgrPortfolioQuery {
    /// Answers this query, copying the conversation, time zone and period.
    #[must_use]
    pub fn reply(&self, reply: Reply, dso_views: Vec<DsoView>) -> AgrPortfolioQueryResponse {
        AgrPortfolioQueryResponse {
            header: ResponseHeader::reply_to(&self.meta, reply),
            agr_portfolio_query_message_id: self.meta.message_id,
            time_zone: self.time_zone.clone(),
            period: self.period,
            dso_views,
        }
    }
}

fn read_view(el: &Element, path: &str) -> Result<DsoView, Rejection> {
    children(el, path, &["DSO-Portfolio", "Connection"])?;
    in_order(el, path, &["DSO-Portfolio", "Connection"])?;
    require_one(el, path, "DSO-Portfolio")?;
    Attrs::new(el, path).finish()?;
    let portfolios = named(el, path, "DSO-Portfolio")
        .map(|(p, c)| {
            children(c, &p, &["CongestionPoint"])?;
            require_one(c, &p, "CongestionPoint")?;
            let mut a = Attrs::new(c, p.clone());
            let dso_domain = a.req("DSO-Domain")?;
            a.finish()?;
            let congestion_points = named(c, &p, "CongestionPoint")
                .map(|(pp, cp)| {
                    children(cp, &pp, &["Connection"])?;
                    require_one(cp, &pp, "Connection")?;
                    let mut a = Attrs::new(cp, pp.clone());
                    let v = PortfolioCongestionPoint {
                        entity_address: a.req("EntityAddress")?,
                        mutex_offers_supported: a.req_bool("MutexOffersSupported")?,
                        day_ahead_redispatch_by: a.req("DayAheadRedispatchBy")?,
                        intraday_redispatch_by: a.opt("IntradayRedispatchBy")?,
                        connections: read_addresses(cp, &pp)?,
                    };
                    a.finish()?;
                    Ok(v)
                })
                .collect::<Result<_, Rejection>>()?;
            Ok(DsoPortfolio {
                dso_domain,
                congestion_points,
            })
        })
        .collect::<Result<_, Rejection>>()?;
    Ok(DsoView {
        portfolios,
        connections: read_addresses(el, path)?,
    })
}

impl Wire for AgrPortfolioQueryResponse {
    const NAME: &'static str = "AGRPortfolioQueryResponse";
    const RESPONSE: bool = true;
    fn meta(&self) -> &Metadata {
        self.header.meta()
    }
    fn meta_mut(&mut self) -> &mut Metadata {
        self.header.meta_mut()
    }
    fn in_reply_to(&self) -> Option<MessageUuid> {
        Some(self.agr_portfolio_query_message_id)
    }
    const REFERENCE: &'static str = "AGRPortfolioQueryMessageID";
    fn read(el: &Element, _: DecodeOptions) -> Result<Self, Rejection> {
        children(el, Self::NAME, &["DSO-View"])?;
        let mut a = Attrs::new(el, Self::NAME);
        let header = ResponseHeader::read(&mut a)?;
        let agr_portfolio_query_message_id = a.req("AGRPortfolioQueryMessageID")?;
        let time_zone = a.req("TimeZone")?;
        let period = a.req::<XsDate>("Period")?.0;
        a.finish()?;
        if header.result() == AcceptedRejected::Accepted {
            require_one(el, Self::NAME, "DSO-View")?;
        }
        let dso_views = named(el, Self::NAME, "DSO-View")
            .map(|(p, c)| read_view(c, &p))
            .collect::<Result<_, _>>()?;
        Ok(Self {
            header,
            agr_portfolio_query_message_id,
            time_zone,
            period,
            dso_views,
        })
    }
    fn write(&self, w: &mut Writer) -> Result<(), Rejection> {
        if self.header.result() == AcceptedRejected::Accepted {
            nonempty(&self.dso_views, Self::NAME, "DSO-View")?;
        }
        for (i, v) in self.dso_views.iter().enumerate() {
            let p = format!("{}/DSO-View[{}]", Self::NAME, i + 1);
            nonempty(&v.portfolios, &p, "DSO-Portfolio")?;
            for (j, d) in v.portfolios.iter().enumerate() {
                let pp = format!("{p}/DSO-Portfolio[{}]", j + 1);
                nonempty(&d.congestion_points, &pp, "CongestionPoint")?;
                for (k, c) in d.congestion_points.iter().enumerate() {
                    nonempty(
                        &c.connections,
                        &format!("{pp}/CongestionPoint[{}]", k + 1),
                        "Connection",
                    )?;
                }
            }
        }
        w.start(Self::NAME);
        self.header.write(w);
        w.attr("TimeZone", &self.time_zone)
            .attr(
                "AGRPortfolioQueryMessageID",
                self.agr_portfolio_query_message_id,
            )
            .attr("Period", self.period);
        for v in &self.dso_views {
            w.start("DSO-View");
            for d in &v.portfolios {
                w.start("DSO-Portfolio").attr("DSO-Domain", &d.dso_domain);
                for c in &d.congestion_points {
                    w.start("CongestionPoint")
                        .attr("EntityAddress", &c.entity_address)
                        .attr("MutexOffersSupported", c.mutex_offers_supported)
                        .attr("DayAheadRedispatchBy", c.day_ahead_redispatch_by)
                        .opt_attr("IntradayRedispatchBy", c.intraday_redispatch_by.as_ref());
                    write_addresses(w, &c.connections);
                    w.end();
                }
                w.end();
            }
            write_addresses(w, &v.connections);
            w.end();
        }
        w.end();
        Ok(())
    }
}

/// `[UFTP §3.5]` Period out of bounds: a range that ends before it starts, or one that is not
/// inside the range it belongs to. `None` as an end means open-ended.
pub(crate) fn check_range(
    start: Date,
    end: Option<Date>,
    within: Option<(Date, Option<Date>)>,
    path: &str,
) -> Result<(), Rejection> {
    use crate::reason::RejectionReason as R;
    let refuse = |message: String| {
        Err(Rejection::rule(
            R::PeriodOutOfBounds,
            "[UFTP §3.5] Period of the message is inappropriate",
            message,
        )
        .at(path.to_owned()))
    };
    if let Some(end) = end
        && end < start
    {
        return refuse(format!("EndPeriod {end} is before StartPeriod {start}."));
    }
    if let Some((outer_start, outer_end)) = within {
        let ends_inside = match (end, outer_end) {
            (_, None) => true,
            (Some(e), Some(oe)) => e <= oe,
            (None, Some(_)) => false,
        };
        if start < outer_start || !ends_inside {
            let show = |e: Option<Date>| e.map_or_else(|| "open".to_owned(), |d| d.to_string());
            return refuse(format!(
                "The range {start} to {} is not inside its congestion point's {outer_start} to {}.",
                show(end),
                show(outer_end)
            ));
        }
    }
    Ok(())
}