krill 0.9.0

Resource Public Key Infrastructure (RPKI) daemon
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
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
//! Data objects used in the (RRDP) repository. I.e. the publish, update, and
//! withdraw elements, as well as the notification, snapshot and delta file
//! definitions.
use std::fmt;
use std::path::PathBuf;
use std::{collections::HashMap, path::Path};

use bytes::Bytes;
use chrono::Duration;
use serde::{de, Deserialize, Deserializer, Serialize, Serializer};
use uuid::Uuid;

use rpki::uri;
use rpki::x509::Time;

use crate::commons::api::Base64;
use crate::commons::api::HexEncodedHash;
use crate::commons::util::file;
use crate::commons::util::xml::XmlWriter;
use crate::commons::{api::publication, error::KrillIoError};

const VERSION: &str = "1";
const NS: &str = "http://www.ripe.net/rpki/rrdp";

//------------ RrdpSession ---------------------------------------------------
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct RrdpSession(Uuid);

impl Default for RrdpSession {
    fn default() -> Self {
        RrdpSession(Uuid::new_v4())
    }
}

impl RrdpSession {
    pub fn random() -> Self {
        Self::default()
    }
}

impl AsRef<Uuid> for RrdpSession {
    fn as_ref(&self) -> &Uuid {
        &self.0
    }
}

impl Serialize for RrdpSession {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        self.to_string().serialize(serializer)
    }
}

impl<'de> Deserialize<'de> for RrdpSession {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let string = String::deserialize(deserializer)?;
        let uuid = Uuid::parse_str(&string).map_err(de::Error::custom)?;

        Ok(RrdpSession(uuid))
    }
}

impl fmt::Display for RrdpSession {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.0.to_hyphenated())
    }
}

//------------ PublishElement ------------------------------------------------

/// The publishes as used in the RRDP protocol.
///
/// Note that the difference with the publication protocol is the absence of
/// the tag.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct PublishElement {
    base64: Base64,
    uri: uri::Rsync,
}

impl PublishElement {
    pub fn new(base64: Base64, uri: uri::Rsync) -> Self {
        PublishElement { base64, uri }
    }

    pub fn base64(&self) -> &Base64 {
        &self.base64
    }
    pub fn uri(&self) -> &uri::Rsync {
        &self.uri
    }
    pub fn size(&self) -> usize {
        self.base64.size()
    }

    pub fn as_withdraw(&self) -> WithdrawElement {
        WithdrawElement {
            uri: self.uri.clone(),
            hash: self.base64.to_encoded_hash(),
        }
    }

    pub fn unpack(self) -> (uri::Rsync, Base64) {
        (self.uri, self.base64)
    }
}

impl From<publication::Publish> for PublishElement {
    fn from(p: publication::Publish) -> Self {
        let (_tag, uri, base64) = p.unpack();
        PublishElement { base64, uri }
    }
}

//------------ UpdateElement -------------------------------------------------

/// The updates as used in the RRDP protocol.
///
/// Note that the difference with the publication protocol is the absence of
/// the tag.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct UpdateElement {
    uri: uri::Rsync,
    hash: HexEncodedHash,
    base64: Base64,
}

impl UpdateElement {
    pub fn uri(&self) -> &uri::Rsync {
        &self.uri
    }
    pub fn hash(&self) -> &HexEncodedHash {
        &self.hash
    }
    pub fn base64(&self) -> &Base64 {
        &self.base64
    }
    pub fn size(&self) -> usize {
        self.base64.size()
    }
}

impl From<publication::Update> for UpdateElement {
    fn from(u: publication::Update) -> Self {
        let (_tag, uri, base64, hash) = u.unwrap();
        UpdateElement { uri, hash, base64 }
    }
}

impl From<UpdateElement> for PublishElement {
    fn from(el: UpdateElement) -> Self {
        PublishElement {
            uri: el.uri,
            base64: el.base64,
        }
    }
}

//------------ WithdrawElement -----------------------------------------------

/// The withdraws as used in the RRDP protocol.
///
/// Note that the difference with the publication protocol is the absence of
/// the tag.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct WithdrawElement {
    uri: uri::Rsync,
    hash: HexEncodedHash,
}

impl WithdrawElement {
    pub fn uri(&self) -> &uri::Rsync {
        &self.uri
    }
    pub fn hash(&self) -> &HexEncodedHash {
        &self.hash
    }
}

impl From<publication::Withdraw> for WithdrawElement {
    fn from(w: publication::Withdraw) -> Self {
        let (_tag, uri, hash) = w.unwrap();
        WithdrawElement { uri, hash }
    }
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct Notification {
    session: RrdpSession,
    serial: u64,
    time: Time,
    #[serde(skip_serializing_if = "Option::is_none")]
    replaced: Option<Time>,
    snapshot: SnapshotRef,
    deltas: Vec<DeltaRef>,
    last_delta: Option<u64>,
}

impl Notification {
    pub fn new(session: RrdpSession, serial: u64, snapshot: SnapshotRef, deltas: Vec<DeltaRef>) -> Self {
        let last_delta = Self::find_last_delta(&deltas);
        Notification {
            session,
            serial,
            time: Time::now(),
            replaced: None,
            snapshot,
            deltas,
            last_delta,
        }
    }

    pub fn time(&self) -> Time {
        self.time
    }

    #[deprecated] // use 'older_than_seconds'
    pub fn replaced_after(&self, timestamp: i64) -> bool {
        if let Some(replaced) = self.replaced {
            replaced.timestamp() > timestamp
        } else {
            false
        }
    }

    pub fn older_than_seconds(&self, seconds: i64) -> bool {
        match self.replaced {
            Some(time) => {
                let then = Time::now() - Duration::seconds(seconds);
                time < then
            }
            None => false,
        }
    }

    pub fn replace(&mut self, time: Time) {
        self.replaced = Some(time);
    }

    pub fn serial(&self) -> u64 {
        self.serial
    }

    pub fn session(&self) -> RrdpSession {
        self.session
    }

    pub fn last_delta(&self) -> Option<u64> {
        self.last_delta
    }

    pub fn includes_delta(&self, delta: u64) -> bool {
        if let Some(last) = self.last_delta {
            last <= delta
        } else {
            false
        }
    }

    pub fn includes_snapshot(&self, version: u64) -> bool {
        self.serial == version
    }

    fn find_last_delta(deltas: &[DeltaRef]) -> Option<u64> {
        if deltas.is_empty() {
            None
        } else {
            let mut serial = deltas[0].serial;
            for d in deltas {
                if d.serial < serial {
                    serial = d.serial
                }
            }

            Some(serial)
        }
    }
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct NotificationUpdate {
    time: Time,
    session: Option<RrdpSession>,
    snapshot: SnapshotRef,
    delta: DeltaRef,
    last_delta: u64,
}

impl NotificationUpdate {
    pub fn new(
        time: Time,
        session: Option<RrdpSession>,
        snapshot: SnapshotRef,
        delta: DeltaRef,
        last_delta: u64,
    ) -> Self {
        NotificationUpdate {
            time,
            session,
            snapshot,
            delta,
            last_delta,
        }
    }
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct NotificationCreate {
    session: RrdpSession,
    snapshot: SnapshotRef,
}

impl NotificationUpdate {
    pub fn unwrap(self) -> (Time, Option<RrdpSession>, SnapshotRef, DeltaRef, u64) {
        (self.time, self.session, self.snapshot, self.delta, self.last_delta)
    }
}

impl Notification {
    pub fn update_old_way(&mut self, update: NotificationUpdate) {
        let (time, session_opt, snapshot, delta, last_delta) = update.unwrap();
        if let Some(session) = session_opt {
            self.session = session;
        }

        self.serial += 1;
        self.time = time;

        let mut refs_to_retire = vec![(Time::now(), self.snapshot.clone())];

        self.snapshot = snapshot;

        for d in &self.deltas {
            if d.serial < last_delta {
                refs_to_retire.push((Time::now(), d.file_ref.clone()));
            }
        }

        self.deltas.insert(0, delta);
        self.deltas.retain(|delta| delta.serial >= last_delta);
    }

    pub fn create(session: RrdpSession, snapshot: SnapshotRef) -> Self {
        Notification::new(session, 0, snapshot, vec![])
    }

    pub fn write_xml(&self, path: &Path) -> Result<(), KrillIoError> {
        trace!("Writing notification file: {}", path.to_string_lossy());
        let mut file = file::create_file_with_path(&path)?;

        XmlWriter::encode_to_file(&mut file, |w| {
            let a = [
                ("xmlns", NS),
                ("version", VERSION),
                ("session_id", &format!("{}", self.session)),
                ("serial", &format!("{}", self.serial)),
            ];

            w.put_element("notification", Some(&a), |w| {
                {
                    // snapshot ref
                    let uri = self.snapshot.uri.to_string();
                    let a = [("uri", uri.as_str()), ("hash", self.snapshot.hash.as_ref())];
                    w.put_element("snapshot", Some(&a), |w| w.empty())?;
                }

                {
                    // delta refs
                    for delta in &self.deltas {
                        let serial = format!("{}", delta.serial);
                        let uri = delta.file_ref.uri.to_string();
                        let a = [
                            ("serial", serial.as_ref()),
                            ("uri", uri.as_str()),
                            ("hash", delta.file_ref.hash.as_ref()),
                        ];
                        w.put_element("delta", Some(&a), |w| w.empty())?;
                    }
                }

                Ok(())
            })
        })
        .map_err(|e| KrillIoError::new(format!("Could not write XML to: {}", path.to_string_lossy()), e))
    }
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct FileRef {
    uri: uri::Https,
    path: PathBuf,
    hash: HexEncodedHash,
}

impl FileRef {
    pub fn new(uri: uri::Https, path: PathBuf, hash: HexEncodedHash) -> Self {
        FileRef { uri, path, hash }
    }
    pub fn uri(&self) -> &uri::Https {
        &self.uri
    }
    pub fn path(&self) -> &PathBuf {
        &self.path
    }
    pub fn hash(&self) -> &HexEncodedHash {
        &self.hash
    }
}

pub type SnapshotRef = FileRef;

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct DeltaRef {
    serial: u64,
    file_ref: FileRef,
}

impl DeltaRef {
    pub fn new(serial: u64, file_ref: FileRef) -> Self {
        DeltaRef { serial, file_ref }
    }

    pub fn serial(&self) -> u64 {
        self.serial
    }
}

impl AsRef<FileRef> for DeltaRef {
    fn as_ref(&self) -> &FileRef {
        &self.file_ref
    }
}

//------------ CurrentObjects ------------------------------------------------

/// Defines a current set of published elements.
///
// Note this is mapped internally for speedy access, by hash, rather than uri
// for two reasons:
// a) URIs in RPKI may change in future
// b) The publish element as it appears in an RFC8182 snapshot.xml includes
// the uri and the base64, but not the hash. So keeping the actual elements
// around means we can be more efficient in producing that output.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct CurrentObjects(HashMap<HexEncodedHash, PublishElement>);

impl Default for CurrentObjects {
    fn default() -> Self {
        CurrentObjects(HashMap::new())
    }
}

impl CurrentObjects {
    pub fn new(map: HashMap<HexEncodedHash, PublishElement>) -> Self {
        CurrentObjects(map)
    }

    pub fn elements(&self) -> Vec<&PublishElement> {
        let mut res = vec![];
        for el in self.0.values() {
            res.push(el)
        }
        res
    }

    pub fn into_elements(self) -> Vec<PublishElement> {
        self.0.into_iter().map(|(_, e)| e).collect()
    }

    fn has_match(&self, hash: &HexEncodedHash, uri: &uri::Rsync) -> bool {
        match self.0.get(hash) {
            Some(el) => el.uri() == uri,
            None => false,
        }
    }

    fn verify_delta(&self, delta: &DeltaElements, jail: &uri::Rsync) -> Result<(), PublicationDeltaError> {
        for p in delta.publishes() {
            if !jail.is_parent_of(p.uri()) {
                return Err(PublicationDeltaError::outside(jail, p.uri()));
            }
            let hash = p.base64().to_encoded_hash();
            if self.0.contains_key(&hash) {
                return Err(PublicationDeltaError::present(p.uri()));
            }
        }

        for u in delta.updates() {
            if !jail.is_parent_of(u.uri()) {
                return Err(PublicationDeltaError::outside(jail, u.uri()));
            }
            if !self.has_match(u.hash(), u.uri()) {
                return Err(PublicationDeltaError::no_match(u.uri()));
            }
        }

        for w in delta.withdraws() {
            if !jail.is_parent_of(w.uri()) {
                return Err(PublicationDeltaError::outside(jail, w.uri()));
            }
            if !self.has_match(w.hash(), w.uri()) {
                return Err(PublicationDeltaError::no_match(w.uri()));
            }
        }

        Ok(())
    }

    /// Applies a delta to CurrentObjects. This will verify that the
    /// delta is legal with regards to existing objects, and the jail
    /// specified for the publisher.
    pub fn apply_delta(&mut self, delta: DeltaElements, jail: &uri::Rsync) -> Result<(), PublicationDeltaError> {
        self.verify_delta(&delta, jail)?;

        let (publishes, updates, withdraws) = delta.unpack();

        for p in publishes {
            let hash = p.base64().to_encoded_hash();
            self.0.insert(hash, p);
        }

        for u in updates {
            self.0.remove(u.hash());
            let p: PublishElement = u.into();
            let hash = p.base64().to_encoded_hash();
            self.0.insert(hash, p);
        }

        for w in withdraws {
            self.0.remove(w.hash());
        }

        Ok(())
    }

    pub fn len(&self) -> usize {
        self.0.len()
    }

    pub fn size(&self) -> usize {
        self.0.values().fold(0, |tot, el| tot + el.size())
    }

    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    pub fn to_list_reply(&self) -> publication::ListReply {
        let elements = self
            .0
            .iter()
            .map(|el| {
                let hash = el.0.clone();
                let uri = el.1.uri().clone();
                publication::ListElement::new(uri, hash)
            })
            .collect();

        publication::ListReply::new(elements)
    }
}

//------------ PublicationDeltaError ---------------------------------------------

/// Issues with relation to verifying deltas.
#[derive(Clone, Debug)]
pub enum PublicationDeltaError {
    UriOutsideJail(uri::Rsync, uri::Rsync),
    ObjectAlreadyPresent(uri::Rsync),
    NoObjectForHashAndOrUri(uri::Rsync),
}

impl fmt::Display for PublicationDeltaError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            PublicationDeltaError::UriOutsideJail(uri, jail) => {
                write!(f, "Publishing ({}) outside of jail URI ({}) is not allowed.", uri, jail)
            }
            PublicationDeltaError::ObjectAlreadyPresent(uri) => {
                write!(f, "File already exists for uri (use update!): {}", uri)
            }
            PublicationDeltaError::NoObjectForHashAndOrUri(uri) => {
                write!(f, "File does not match hash at uri: {}", uri)
            }
        }
    }
}

impl PublicationDeltaError {
    fn outside(jail: &uri::Rsync, uri: &uri::Rsync) -> Self {
        PublicationDeltaError::UriOutsideJail(uri.clone(), jail.clone())
    }

    fn present(uri: &uri::Rsync) -> Self {
        PublicationDeltaError::ObjectAlreadyPresent(uri.clone())
    }

    fn no_match(uri: &uri::Rsync) -> Self {
        PublicationDeltaError::NoObjectForHashAndOrUri(uri.clone())
    }
}
//------------ Snapshot ------------------------------------------------------

/// A structure to contain the RRDP snapshot data.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct Snapshot {
    session: RrdpSession,
    serial: u64,
    current_objects: CurrentObjects,
}

impl Snapshot {
    pub fn new(session: RrdpSession, serial: u64, current_objects: CurrentObjects) -> Self {
        Snapshot {
            session,
            serial,
            current_objects,
        }
    }

    pub fn unpack(self) -> (RrdpSession, u64, CurrentObjects) {
        (self.session, self.serial, self.current_objects)
    }

    pub fn create(session: RrdpSession) -> Self {
        let current_objects = CurrentObjects::default();
        Snapshot {
            session,
            serial: 0,
            current_objects,
        }
    }

    pub fn session_reset(&self, session: RrdpSession) -> Self {
        Snapshot {
            session,
            serial: 0,
            current_objects: self.current_objects.clone(),
        }
    }

    pub fn elements(&self) -> Vec<&PublishElement> {
        self.current_objects.elements()
    }

    pub fn serial(&self) -> u64 {
        self.serial
    }

    pub fn apply_delta(&mut self, elements: DeltaElements, jail: &uri::Rsync) -> Result<(), PublicationDeltaError> {
        self.serial += 1;
        self.current_objects.apply_delta(elements, jail)
    }

    pub fn size(&self) -> usize {
        self.current_objects.elements().iter().fold(0, |sum, p| sum + p.size())
    }

    pub fn write_xml(&self, path: &Path) -> Result<(), KrillIoError> {
        trace!("Writing snapshot file: {}", path.to_string_lossy());
        let vec = self.xml();
        let bytes = Bytes::from(vec);

        file::save(&bytes, path)
    }

    pub fn xml(&self) -> Vec<u8> {
        XmlWriter::encode_vec(|w| {
            let a = [
                ("xmlns", NS),
                ("version", VERSION),
                ("session_id", &format!("{}", self.session)),
                ("serial", &format!("{}", self.serial)),
            ];

            w.put_element("snapshot", Some(&a), |w| {
                for el in self.current_objects.elements() {
                    let uri = el.uri.to_string();
                    let atr = [("uri", uri.as_ref())];
                    w.put_element("publish", Some(&atr), |w| w.put_text(el.base64.as_ref()))
                        .unwrap();
                }
                Ok(())
            })
        })
    }
}

//------------ DeltaElements -------------------------------------------------

/// Defines the elements for an RRDP delta.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct DeltaElements {
    publishes: Vec<PublishElement>,
    updates: Vec<UpdateElement>,
    withdraws: Vec<WithdrawElement>,
}

impl DeltaElements {
    pub fn new(publishes: Vec<PublishElement>, updates: Vec<UpdateElement>, withdraws: Vec<WithdrawElement>) -> Self {
        DeltaElements {
            publishes,
            updates,
            withdraws,
        }
    }

    pub fn unpack(self) -> (Vec<PublishElement>, Vec<UpdateElement>, Vec<WithdrawElement>) {
        (self.publishes, self.updates, self.withdraws)
    }

    pub fn len(&self) -> usize {
        self.publishes.len() + self.updates.len() + self.withdraws.len()
    }

    pub fn size(&self) -> usize {
        let sum_publishes = self.publishes.iter().fold(0, |sum, p| sum + p.size());
        let sum_updates = self.updates.iter().fold(0, |sum, u| sum + u.size());

        sum_publishes + sum_updates
    }

    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    pub fn publishes(&self) -> &Vec<PublishElement> {
        &self.publishes
    }

    pub fn updates(&self) -> &Vec<UpdateElement> {
        &self.updates
    }

    pub fn withdraws(&self) -> &Vec<WithdrawElement> {
        &self.withdraws
    }
}

impl From<publication::PublishDelta> for DeltaElements {
    fn from(d: publication::PublishDelta) -> Self {
        let (publishers, updates, withdraws) = d.unwrap();

        let publishes = publishers.into_iter().map(PublishElement::from).collect();
        let updates = updates.into_iter().map(UpdateElement::from).collect();
        let withdraws = withdraws.into_iter().map(WithdrawElement::from).collect();

        DeltaElements {
            publishes,
            updates,
            withdraws,
        }
    }
}

//------------ Delta ---------------------------------------------------------

/// Defines an RRDP delta.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct Delta {
    session: RrdpSession,
    serial: u64,
    time: Time,
    elements: DeltaElements,
}

impl Delta {
    pub fn new(session: RrdpSession, serial: u64, elements: DeltaElements) -> Self {
        Delta {
            session,
            time: Time::now(),
            serial,
            elements,
        }
    }

    pub fn session(&self) -> RrdpSession {
        self.session
    }
    pub fn serial(&self) -> u64 {
        self.serial
    }
    pub fn time(&self) -> &Time {
        &self.time
    }

    pub fn older_than_seconds(&self, seconds: i64) -> bool {
        let then = Time::now() - Duration::seconds(seconds);
        self.time < then
    }

    pub fn younger_than_seconds(&self, seconds: i64) -> bool {
        let then = Time::now() - Duration::seconds(seconds);
        self.time > then
    }

    pub fn elements(&self) -> &DeltaElements {
        &self.elements
    }

    /// Total number of elements
    ///
    /// This is a cheap approximation of the size of the delta that can help
    /// in determining the choice of how many deltas to include in a
    /// notification file.
    pub fn len(&self) -> usize {
        self.elements.len()
    }

    pub fn is_empty(&self) -> bool {
        self.elements.is_empty()
    }

    pub fn unwrap(self) -> (RrdpSession, u64, DeltaElements) {
        (self.session, self.serial, self.elements)
    }

    pub fn write_xml(&self, path: &Path) -> Result<(), KrillIoError> {
        trace!("Writing delta file: {}", path.to_string_lossy());
        let vec = self.xml();
        let bytes = Bytes::from(vec);
        file::save(&bytes, &path)?;

        Ok(())
    }

    pub fn xml(&self) -> Vec<u8> {
        XmlWriter::encode_vec(|w| {
            let a = [
                ("xmlns", NS),
                ("version", VERSION),
                ("session_id", &format!("{}", self.session)),
                ("serial", &format!("{}", self.serial)),
            ];

            w.put_element("delta", Some(&a), |w| {
                for el in &self.elements.publishes {
                    let uri = el.uri.to_string();
                    let atr = [("uri", uri.as_ref())];
                    w.put_element("publish", Some(&atr), |w| w.put_text(el.base64.as_ref()))?;
                }

                for el in &self.elements.updates {
                    let uri = el.uri.to_string();
                    let atr = [("uri", uri.as_ref()), ("hash", el.hash.as_ref())];
                    w.put_element("publish", Some(&atr), |w| w.put_text(el.base64.as_ref()))?;
                }

                for el in &self.elements.withdraws {
                    let uri = el.uri.to_string();
                    let atr = [("uri", uri.as_ref()), ("hash", el.hash.as_ref())];
                    w.put_element("withdraw", Some(&atr), |w| w.empty())?;
                }

                Ok(())
            })
        })
    }
}