ocpp-kit 0.5.0

Open Charge Point Protocol (OCPP 1.6J, 2.0.1, 2.1) toolkit for Rust: typed messages, OCPP-J framing, a sans-I/O protocol engine, and transports for charging stations, CSMS and local controllers.
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
865
866
867
868
869
870
871
872
873
874
875
876
877
//! The Charging Station side of the transport.

use std::collections::BTreeMap;
use std::sync::Arc;
use std::time::Duration;

use http::Uri;
use tokio::net::TcpStream;
use tokio::sync::{broadcast, mpsc, watch};

use crate::decode::DecodeOptions;
use crate::engine::{
    Backoff, BootState, CallFailure, Engine, EngineConfig, Jitter, MemStore, MessageStore, Role,
};
use crate::types::Identity;
use crate::version::{Subprotocol, Version};

use super::TransportError;
use super::connection::{Driver, Ended, Event, Handle, Handler, Keepalive, SessionState, Shared};
use super::network_profile::{NetworkProfile, NetworkProfiles, ProfileCycler};
use super::security::{BasicAuthPassword, SecurityProfile, basic_auth_header};
use super::stream::MaybeTls;
use super::ws::handshake::{ClientRequest, client_handshake, percent_encode};
use super::ws::{Config as WsConfig, Role as WsRole, WebSocket, WsCodec};

/// Builds a [`Station`].
pub struct StationBuilder<S: MessageStore = MemStore> {
    identity: Option<Identity>,
    url: Option<String>,
    versions: Subprotocol,
    profile: SecurityProfile,
    password: Option<BasicAuthPassword>,
    #[cfg(feature = "rustls")]
    tls: Option<super::tls::ClientTls>,
    keepalive: Keepalive,
    backoff: Backoff,
    reconnect: bool,
    decode: DecodeOptions,
    engine: Option<EngineConfig>,
    handler: Option<Arc<dyn Handler>>,
    store: S,
    store_poll: Option<Duration>,
    ws_config: WsConfig,
    #[cfg(feature = "compression")]
    compression: bool,
    profiles: Option<NetworkProfiles>,
}

impl Default for StationBuilder<MemStore> {
    fn default() -> Self {
        Self {
            identity: None,
            url: None,
            versions: Subprotocol::default(),
            profile: SecurityProfile::BasicAuth,
            password: None,
            #[cfg(feature = "rustls")]
            tls: None,
            keepalive: Keepalive::default(),
            backoff: Backoff::default(),
            reconnect: true,
            decode: DecodeOptions::strict(),
            engine: None,
            handler: None,
            store: MemStore::new(),
            store_poll: None,
            ws_config: WsConfig::default(),
            // Part 4 §3.4 Table 2: optional for a Charging Station, but recommended — it is
            // the cheapest way to cut a fleet's mobile data bill.
            #[cfg(feature = "compression")]
            compression: true,
            profiles: None,
        }
    }
}

impl<S: MessageStore + Send + 'static> StationBuilder<S> {
    /// The Charging Station identity. It becomes the last path segment of the WebSocket URL
    /// and, under profiles 1 and 2, the HTTP Basic user name.
    pub fn identity(mut self, identity: &str) -> Result<Self, TransportError> {
        self.identity = Some(
            Identity::new(identity)
                .map_err(|error| TransportError::Configuration(error.to_string()))?,
        );
        Ok(self)
    }

    /// The CSMS endpoint *without* the identity, e.g. `wss://csms.example.com/ocpp`.
    ///
    /// The identity is appended, percent-encoded, as Part 4 §3.1 prescribes.
    #[must_use]
    pub fn url(mut self, url: impl Into<String>) -> Self {
        self.url = Some(url.into());
        self
    }

    /// The versions to offer, most preferred first.
    ///
    /// Part 4 §3.2 recommends that a 2.1 station also offer 2.0.1, which the default does.
    #[must_use]
    pub fn versions(mut self, versions: impl IntoIterator<Item = Version>) -> Self {
        self.versions = Subprotocol::new(versions);
        self
    }

    /// The security profile to use.
    #[must_use]
    pub fn security_profile(mut self, profile: SecurityProfile) -> Self {
        self.profile = profile;
        self
    }

    /// The HTTP Basic password, for profiles 1 and 2. With
    /// [`network_profiles`](Self::network_profiles), it is the password of every profile that
    /// does not set its own (B09.FR.16).
    #[must_use]
    pub fn password(mut self, password: BasicAuthPassword) -> Self {
        self.password = Some(password);
        self
    }

    /// The TLS configuration, for profiles 2 and 3.
    #[cfg(feature = "rustls")]
    #[must_use]
    pub fn tls(mut self, tls: super::tls::ClientTls) -> Self {
        self.tls = Some(tls);
        self
    }

    /// How often to send a WebSocket ping — the `WebSocketPingInterval` variable.
    ///
    /// Part 4 §5.3: ping/pong keeps the connection alive and can stand in for most
    /// `Heartbeat`s, but not for the clock synchronisation the `Heartbeat` response carries,
    /// so the engine keeps sending real heartbeats on their own interval.
    ///
    /// A ping that is never answered ends the session after
    /// [`Keepalive::timeout`](super::Keepalive::timeout), which is what turns a mobile
    /// network's silently dropped connection into a reconnect instead of a hang. Use
    /// [`keepalive`](Self::keepalive) to change that timeout.
    #[must_use]
    pub fn ping_interval(mut self, interval: Option<Duration>) -> Self {
        self.keepalive.interval = interval;
        self
    }

    /// The full WebSocket keepalive policy: ping interval and pong deadline.
    #[must_use]
    pub fn keepalive(mut self, keepalive: Keepalive) -> Self {
        self.keepalive = keepalive;
        self
    }

    /// The reconnect schedule (Part 4 §5.4).
    #[must_use]
    pub fn backoff(mut self, backoff: Backoff) -> Self {
        self.backoff = backoff;
        self
    }

    /// Whether to reconnect at all. On by default.
    #[must_use]
    pub fn reconnect(mut self, reconnect: bool) -> Self {
        self.reconnect = reconnect;
        self
    }

    /// How forgiving to be about payloads the CSMS sends.
    ///
    /// [`DecodeOptions::max_payload_size`] is carried down to the WebSocket layer too, so an
    /// oversized message is refused as it arrives rather than after it has been buffered — and
    /// a compressed one is measured as it inflates. A station talks to one CSMS, so unlike a
    /// server it has no reason to keep the two limits apart.
    #[must_use]
    pub fn decode_options(mut self, options: DecodeOptions) -> Self {
        self.ws_config.max_message_size = options.max_payload_size;
        self.ws_config.max_frame_size = options.max_payload_size;
        self.decode = options;
        self
    }

    /// Whether to offer RFC 7692 `permessage-deflate`.
    ///
    /// On by default with the `compression` feature. Part 4 §3.4 makes it optional for a
    /// Charging Station and recommends it; §3.4 also says a station must **not** close the
    /// connection when the CSMS declines, and this implementation does not.
    #[cfg(feature = "compression")]
    #[must_use]
    pub fn compression(mut self, enabled: bool) -> Self {
        self.compression = enabled;
        self
    }

    /// Overrides the engine configuration. The role and version are set by the builder.
    #[must_use]
    pub fn engine_config(mut self, config: EngineConfig) -> Self {
        self.engine = Some(config);
        self
    }

    /// The handler for requests the CSMS sends.
    #[must_use]
    pub fn handler(mut self, handler: impl Handler) -> Self {
        self.handler = Some(Arc::new(handler));
        self
    }

    /// The station's network configuration slots, in priority order.
    ///
    /// This is the 2.x model: numbered slots, a `NetworkConfigurationPriority` order and a
    /// `NetworkProfileConnectionAttempts` budget per slot. Use it instead of
    /// [`url`](Self::url) when the station has a fallback CSMS — which is what makes
    /// migrating to a new CSMS (use case B10) a configuration change rather than a
    /// reflash.
    #[must_use]
    pub fn network_profiles(mut self, profiles: NetworkProfiles) -> Self {
        self.profiles = Some(profiles);
        self
    }

    /// A durable message store, so queued `TransactionEvent`s survive a power cut.
    pub fn store<T: MessageStore + Send + 'static>(self, store: T) -> StationBuilder<T> {
        StationBuilder {
            identity: self.identity,
            url: self.url,
            versions: self.versions,
            profile: self.profile,
            password: self.password,
            #[cfg(feature = "rustls")]
            tls: self.tls,
            keepalive: self.keepalive,
            backoff: self.backoff,
            reconnect: self.reconnect,
            decode: self.decode,
            engine: self.engine,
            handler: self.handler,
            store,
            store_poll: self.store_poll,
            ws_config: self.ws_config,
            #[cfg(feature = "compression")]
            compression: self.compression,
            profiles: self.profiles,
        }
    }

    /// Picks up messages another process adds to the store while the station runs.
    ///
    /// For a store shared between processes — a station and a metering daemon on one
    /// database. While connected, the station calls
    /// [`Engine::adopt_pending`](crate::engine::Engine::adopt_pending) on connect and then
    /// every `interval`, so a message the other process pushed leaves within one interval
    /// instead of at the next start. A store failure is reported as
    /// [`Event::Violation`](super::Event::Violation). Off by default: with a store only this
    /// station writes, there is nothing to pick up.
    #[must_use]
    pub fn store_poll(mut self, interval: Duration) -> Self {
        self.store_poll = Some(interval);
        self
    }

    /// Builds the station.
    pub fn build(self) -> Result<Station<S>, TransportError> {
        let identity = self
            .identity
            .ok_or_else(|| TransportError::Configuration("identity is required".into()))?;

        // A station configured with a single URL is just a one-slot network configuration, so
        // there is one code path for both.
        let profiles = if let Some(mut profiles) = self.profiles {
            // B09.FR.16 (2.1): a profile that sets no BasicAuthPassword of its own uses the
            // station's (`SecurityCtrlr.BasicAuthPassword`); one that sets it uses its own
            // (B09.FR.18). 2.0.1 does not say, and failing the build is no better a reading.
            if let Some(password) = &self.password {
                profiles.default_password(password);
            }
            profiles
        } else {
            {
                let url = self.url.ok_or_else(|| {
                    TransportError::Configuration(
                        "either `url` or `network_profiles` is required".into(),
                    )
                })?;
                let mut profile = NetworkProfile::new(0, url).security_profile(self.profile);
                if let Some(password) = self.password {
                    profile = profile.password(password);
                }
                #[cfg(feature = "rustls")]
                if let Some(tls) = self.tls {
                    profile = profile.tls(tls);
                }
                NetworkProfiles::new([profile])
            }
        };

        let preferred = *self.versions.offered().first().ok_or_else(|| {
            TransportError::Configuration("at least one version must be offered".into())
        })?;

        // Every slot is validated now, not when the station first fails over to it — a
        // fallback profile that turns out to be unusable is worse than no fallback at all.
        let mut endpoints = Vec::with_capacity(profiles.configured_slots().len());
        for slot in profiles.configured_slots() {
            let profile = profiles.get(slot).expect("configured");
            endpoints.push(Endpoint::for_profile(profile, &identity, &self.versions)?);
        }

        let mut engine_config = self
            .engine
            .unwrap_or_else(|| EngineConfig::new(Role::ChargingStation, preferred));
        engine_config.role = Role::ChargingStation;
        engine_config.version = preferred;
        engine_config.backoff = self.backoff;

        Ok(Station {
            connector: Connector {
                identity,
                versions: self.versions,
                profiles,
                endpoints: endpoints.into_iter().map(|e| (e.slot, e)).collect(),
                ws_config: self.ws_config,
                #[cfg(feature = "compression")]
                compression: self.compression,
            },
            keepalive: self.keepalive,
            backoff: self.backoff,
            reconnect: self.reconnect,
            decode: self.decode,
            engine_config,
            handler: self
                .handler
                .unwrap_or_else(|| Arc::new(super::connection::NotImplemented)),
            store: self.store,
            store_poll: self.store_poll,
        })
    }
}

/// Everything needed to open one connection, separate from the session state so the
/// reconnect loop can own it while the engine owns the store.
struct Connector {
    identity: Identity,
    versions: Subprotocol,
    profiles: NetworkProfiles,
    /// One validated endpoint per configuration slot.
    endpoints: BTreeMap<i32, Endpoint>,
    ws_config: WsConfig,
    #[cfg(feature = "compression")]
    compression: bool,
}

/// A Charging Station client.
pub struct Station<S: MessageStore = MemStore> {
    connector: Connector,
    keepalive: Keepalive,
    backoff: Backoff,
    reconnect: bool,
    decode: DecodeOptions,
    engine_config: EngineConfig,
    handler: Arc<dyn Handler>,
    store: S,
    store_poll: Option<Duration>,
}

impl Station<MemStore> {
    /// Starts building a station.
    #[must_use]
    pub fn builder() -> StationBuilder<MemStore> {
        StationBuilder::default()
    }
}

impl<S: MessageStore + Send + 'static> Station<S> {
    /// Runs the station on the current task until it is shut down.
    ///
    /// The engine — and therefore the offline queue and the boot state — survives every
    /// reconnect, which is what Part 4 §5.4 requires: a station does not repeat
    /// `BootNotification` on a mere reconnect.
    pub async fn run(self) -> Result<(), TransportError> {
        let (handle, task) = self.into_parts()?;
        drop(handle);
        task.await
    }

    /// Spawns the station and returns a handle for calling the CSMS.
    pub fn spawn(self) -> Result<Handle, TransportError> {
        let (handle, task) = self.into_parts()?;
        tokio::spawn(async move {
            if let Err(error) = task.await {
                #[cfg(feature = "tracing")]
                tracing::error!(%error, "charging station stopped");
                let _ = error;
            }
        });
        Ok(handle)
    }

    fn into_parts(
        self,
    ) -> Result<
        (
            Handle,
            impl std::future::Future<Output = Result<(), TransportError>>,
        ),
        TransportError,
    > {
        let (commands_tx, mut commands_rx) = mpsc::channel(64);
        let (events_tx, _) = broadcast::channel(256);
        let (state_tx, state_rx) = watch::channel(SessionState {
            connected: false,
            version: self.engine_config.version,
            boot: BootState::Idle,
            queued: 0,
        });
        let shared = Arc::new(Shared {
            // A station has no authenticator to resolve anything about itself.
            session: super::connection::SessionContext::empty(),
            identity: self.connector.identity.clone(),
            remote: None,
            decode: self.decode.clone(),
            commands: commands_tx,
            events: events_tx,
            state: state_rx,
        });
        let handle = Handle::new(shared.clone());

        let engine = Engine::with_store(self.engine_config, self.store)?;
        let mut driver = Driver::new(engine, shared.clone(), self.handler, state_tx);
        driver.store_poll = self.store_poll;
        let connector = self.connector;
        let keepalive = self.keepalive;
        let backoff = self.backoff;
        // The configured default, restored whenever the active profile does not override it
        // (Part 4 §4.1.1: `NetworkConnectionProfile.messageTimeout`) — otherwise one slot's
        // timeout would leak into every slot the station later fails over to.
        let default_call_timeout = driver.engine.config().call_timeout;
        let reconnect = self.reconnect;

        let task = async move {
            let mut attempt = 0u32;
            let mut cycler = ProfileCycler::new(&connector.profiles);
            let mut announced = None;
            // The slot the last session ran on: B10.FR.10 re-boots after a switch.
            let mut last_connected: Option<i32> = None;

            loop {
                let (profile, _) = connector.profile_at(cycler.index());
                let slot = profile.slot();
                // `OCPPCommCtrlr.ActiveNetworkProfile` — report the slot the station is on,
                // once per change rather than once per attempt.
                if announced != Some(slot) {
                    announced = Some(slot);
                    let _ = shared.events.send(Event::NetworkProfileSelected {
                        configuration_slot: slot,
                        url: profile.url().to_owned(),
                    });
                }
                // Part 4 §4.1.1: `NetworkConnectionProfile.messageTimeout` overrides the
                // default while this profile is active.
                let message_timeout = profile.message_timeout;

                match connector.connect(cycler.index()).await {
                    Ok((socket, version)) => {
                        attempt = 0;
                        cycler.succeeded();
                        // B10.FR.10: connected after switching NetworkConnectionProfile, so
                        // register again even without a reboot.
                        if last_connected.is_some_and(|previous| previous != slot) {
                            let now = driver.now();
                            driver.engine.require_boot(now);
                        }
                        last_connected = Some(slot);
                        driver
                            .engine
                            .set_call_timeout(message_timeout.unwrap_or(default_call_timeout));
                        // A write that failed, a peer that broke the WebSocket protocol, a
                        // clean close: these all end the *connection*, not the station.
                        // Part 4 §5.4 says to reconnect when the connection is lost and does
                        // not carve out the ways in which it can be lost — so only a drain
                        // the application asked for stops the loop.
                        let ended = driver
                            .run(socket, &mut commands_rx, version, keepalive)
                            .await;
                        if matches!(ended, Ended::Closed(_)) || !reconnect {
                            driver.abandon(&CallFailure::Disconnected);
                            return Ok(());
                        }
                        #[cfg(feature = "tracing")]
                        if let Ended::Disconnected(reason) = &ended {
                            tracing::info!(%reason, slot, "the session ended; reconnecting");
                        }
                    }
                    Err(error) => {
                        if !reconnect {
                            return Err(error);
                        }
                        #[cfg(feature = "tracing")]
                        tracing::warn!(%error, attempt, slot, "connection to the CSMS failed");
                        let _ = &error;
                        // `NetworkProfileConnectionAttempts`: after this profile's share of
                        // failures, move to the next slot in NetworkConfigurationPriority.
                        cycler.failed();
                    }
                }

                if !reconnect {
                    return Ok(());
                }
                let delay = backoff.delay(attempt, jitter());
                let _ = shared.events.send(Event::Reconnecting { attempt, delay });
                attempt = attempt.saturating_add(1);
                tokio::time::sleep(delay).await;
            }
        };
        Ok((handle, task))
    }
}

impl Connector {
    /// The profile at `index` of the priority list.
    fn profile_at(&self, index: usize) -> (&NetworkProfile, &Endpoint) {
        let profile = self.profiles.at(index);
        let endpoint = self
            .endpoints
            .get(&profile.slot)
            .expect("validated at build time");
        (profile, endpoint)
    }

    /// Opens one connection over the profile at `index` and performs the OCPP-J handshake.
    async fn connect(
        &self,
        index: usize,
    ) -> Result<(WebSocket<MaybeTls>, Version), TransportError> {
        let (profile, endpoint) = self.profile_at(index);
        let versions = profile.versions.as_ref().unwrap_or(&self.versions);

        let tcp = TcpStream::connect((endpoint.host.as_str(), endpoint.port)).await?;
        tcp.set_nodelay(true)?;

        let mut stream = if endpoint.secure {
            #[cfg(feature = "rustls")]
            {
                let tls = profile.tls.as_ref().expect("checked by the builder");
                let name = super::tls::ClientTls::server_name(&endpoint.host)
                    .map_err(|error| TransportError::Configuration(error.to_string()))?;
                MaybeTls::ClientTls(Box::new(tls.connector().connect(name, tcp).await?))
            }
            #[cfg(not(feature = "rustls"))]
            {
                return Err(TransportError::Configuration(
                    "TLS needs the `rustls` feature".into(),
                ));
            }
        } else {
            MaybeTls::Plain(tcp)
        };

        let authorization = if profile.security.uses_basic_auth() {
            let password = profile.password.as_ref().expect("checked by the builder");
            Some(basic_auth_header(&endpoint.identity, password))
        } else {
            None
        };
        #[allow(unused_mut)]
        let mut extensions: Option<String> = None;
        #[cfg(feature = "compression")]
        if self.compression {
            extensions = Some(super::ws::deflate::DeflateParams::default().client_offer());
        }

        let handshake = client_handshake(
            &mut stream,
            &ClientRequest {
                host: &endpoint.authority,
                path: &endpoint.path,
                subprotocols: &versions.header_value(),
                authorization: authorization.as_deref(),
                extensions: extensions.as_deref(),
            },
        )
        .await?;

        // Part 4 §3.1.2 — the server selects exactly one of the offered subprotocols, and a
        // handshake without the header is a negotiation failure, not a 1.6 fallback.
        let version = versions.accept(handshake.subprotocol.as_deref())?;

        #[allow(unused_mut)]
        let mut codec = WsCodec::new(WsRole::Client, self.ws_config);
        #[cfg(feature = "compression")]
        if extensions.is_some() {
            // §3.4: a CSMS that declines compression is served uncompressed, and the station
            // must not close the connection over it.
            match super::ws::deflate::accept_response(handshake.extensions.as_deref()) {
                Ok(Some(params)) => codec = codec.with_deflate(params),
                Ok(None) => {}
                Err(error) => {
                    return Err(TransportError::Configuration(format!(
                        "permessage-deflate negotiation failed: {error}"
                    )));
                }
            }
        }

        Ok((super::ws::attach(stream, codec, &handshake.rest), version))
    }
}

/// Where to connect, and under which identity.
#[derive(Clone, Debug)]
struct Endpoint {
    /// The configuration slot this endpoint belongs to.
    slot: i32,
    host: String,
    port: u16,
    secure: bool,
    /// The `Host` header value: host, plus the port when it is not the default.
    authority: String,
    /// The request target, including the identity path segment.
    path: String,
    /// The full URL, which is what a configuration error quotes back.
    url: String,
    /// The identity this slot connects under: the profile's own, else the station's.
    identity: Identity,
}

impl Endpoint {
    /// Validates one configuration slot: the URL, and that its credentials match its
    /// security profile.
    fn for_profile(
        profile: &NetworkProfile,
        identity: &Identity,
        default_versions: &Subprotocol,
    ) -> Result<Self, TransportError> {
        let identity = profile.identity.as_ref().unwrap_or(identity);
        let endpoint = Self::parse(profile.slot, &profile.url, identity)?;
        let slot = profile.slot;
        let security = profile.security;

        if endpoint.secure != security.is_transport_encrypted() {
            return Err(TransportError::Configuration(format!(
                "configuration slot {slot}: {security} and the URL {} disagree about TLS",
                endpoint.url
            )));
        }
        let offered = profile
            .versions
            .as_ref()
            .unwrap_or(default_versions)
            .offered();
        if security == SecurityProfile::Unsecured
            && offered.iter().any(|v| *v != crate::version::Version::V1_6)
        {
            return Err(TransportError::Configuration(format!(
                "configuration slot {slot}: {security} is OCPP 1.6 only — 2.x requires HTTP \
                 Basic at least (A00.FR.202); offer only 1.6, or use profile 1"
            )));
        }
        if security.uses_basic_auth() && profile.password.is_none() {
            return Err(TransportError::Configuration(format!(
                "configuration slot {slot}: {security} needs a password"
            )));
        }
        #[cfg(feature = "rustls")]
        if security.is_transport_encrypted() && profile.tls.is_none() {
            return Err(TransportError::Configuration(format!(
                "configuration slot {slot}: {security} needs a TLS configuration"
            )));
        }
        #[cfg(not(feature = "rustls"))]
        if security.is_transport_encrypted() {
            return Err(TransportError::Configuration(
                "TLS needs the `rustls` feature".into(),
            ));
        }
        if profile
            .versions
            .as_ref()
            .unwrap_or(default_versions)
            .offered()
            .is_empty()
        {
            return Err(TransportError::Configuration(format!(
                "configuration slot {slot}: at least one version must be offered"
            )));
        }
        Ok(endpoint)
    }

    /// Splits a `ws://` / `wss://` base URL and appends the identity.
    fn parse(slot: i32, base: &str, identity: &Identity) -> Result<Self, TransportError> {
        let uri: Uri = base
            .parse()
            .map_err(|_| TransportError::Url(base.to_owned()))?;
        let scheme = uri.scheme_str().unwrap_or("ws");
        let secure = match scheme {
            "ws" | "http" => false,
            "wss" | "https" => true,
            _ => return Err(TransportError::Url(base.to_owned())),
        };
        let host = uri
            .host()
            .ok_or_else(|| TransportError::Url(base.to_owned()))?
            .to_owned();
        let port = uri.port_u16().unwrap_or(if secure { 443 } else { 80 });
        // Part 4 §3.1: the identity is the last path segment.
        let path = format!(
            "{}/{}",
            uri.path().trim_end_matches('/'),
            percent_encode(identity.as_str())
        );
        let authority = if uri.port().is_some() {
            format!("{host}:{port}")
        } else {
            host.clone()
        };
        let url = format!("{}://{authority}{path}", if secure { "wss" } else { "ws" });
        Ok(Self {
            slot,
            host,
            port,
            secure,
            authority,
            path,
            url,
            identity: identity.clone(),
        })
    }
}

/// A jitter value for the reconnect back-off (Part 4 §5.4).
///
/// Drawn from the operating system rather than the clock. The whole point of §5.4's random
/// range is that a fleet coming back after a CSMS restart does not arrive together — and a
/// fleet is exactly the population whose clocks are synchronised to the same NTP source, so
/// clock-derived "randomness" is correlated precisely when it must not be.
fn jitter() -> Jitter {
    let mut bytes = [0u8; 4];
    if getrandom::fill(&mut bytes).is_err() {
        return Jitter::from_ratio(1, 2);
    }
    Jitter::from_random_u32(u32::from_le_bytes(bytes))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn the_identity_becomes_the_last_path_segment() {
        let identity = Identity::new("CS-0001").unwrap();
        let endpoint = Endpoint::parse(0, "wss://csms.example.com/ocpp", &identity).unwrap();
        assert_eq!(endpoint.url, "wss://csms.example.com/ocpp/CS-0001");
        assert_eq!(endpoint.port, 443);
        assert!(endpoint.secure);

        let endpoint = Endpoint::parse(0, "ws://localhost:9000/", &identity).unwrap();
        assert_eq!(endpoint.url, "ws://localhost:9000/CS-0001");
        assert_eq!(endpoint.port, 9000);
        assert!(!endpoint.secure);
    }

    #[test]
    fn identities_that_need_escaping_still_produce_one_segment() {
        let identity = Identity::new("station/one").unwrap();
        let endpoint = Endpoint::parse(0, "ws://host/ocpp", &identity).unwrap();
        assert_eq!(endpoint.url, "ws://host/ocpp/station%2Fone");
    }

    #[test]
    fn the_builder_refuses_contradictory_security_settings() {
        let error = Station::builder()
            .identity("CS-0001")
            .unwrap()
            .url("ws://host/ocpp")
            .security_profile(SecurityProfile::TlsBasicAuth)
            .build()
            .err()
            .expect("a TLS profile on a ws:// URL is a contradiction");
        assert!(matches!(error, TransportError::Configuration(_)), "{error}");

        let error = Station::builder()
            .identity("CS-0001")
            .unwrap()
            .url("ws://host/ocpp")
            .security_profile(SecurityProfile::BasicAuth)
            .build()
            .err()
            .expect("profile 1 needs a password");
        assert!(error.to_string().contains("needs a password"), "{error}");
    }

    /// B09.FR.18: a profile with its own identity connects under it — path and Basic-auth
    /// user — and one without uses the station's.
    #[test]
    fn a_profile_can_connect_under_its_own_identity() {
        use super::super::network_profile::{NetworkProfile, NetworkProfiles};

        let password = || BasicAuthPassword::utf8("0123456789abcdef").unwrap();
        let station = Station::builder()
            .identity("CS-0001")
            .unwrap()
            .network_profiles(NetworkProfiles::new([
                NetworkProfile::new(0, "ws://primary/ocpp").password(password()),
                NetworkProfile::new(1, "ws://other-csms/ocpp")
                    .identity(Identity::new("OTHER-7").unwrap())
                    .password(password()),
            ]))
            .build()
            .unwrap();
        let endpoints = &station.connector.endpoints;
        assert_eq!(endpoints[&0].path, "/ocpp/CS-0001");
        assert_eq!(endpoints[&1].path, "/ocpp/OTHER-7");
        assert_eq!(endpoints[&1].identity.as_str(), "OTHER-7");
    }

    /// B09.FR.16: a profile without its own password uses the station's; B09.FR.18: one
    /// with its own keeps it.
    #[test]
    fn a_profile_without_a_password_uses_the_stations() {
        use super::super::network_profile::{NetworkProfile, NetworkProfiles};

        let own = BasicAuthPassword::utf8("ffffffffffffffff").unwrap();
        let station = Station::builder()
            .identity("CS-0001")
            .unwrap()
            .password(BasicAuthPassword::utf8("0123456789abcdef").unwrap())
            .network_profiles(NetworkProfiles::new([
                NetworkProfile::new(0, "ws://fallback/ocpp")
                    .security_profile(SecurityProfile::BasicAuth),
                NetworkProfile::new(1, "ws://primary/ocpp")
                    .security_profile(SecurityProfile::BasicAuth)
                    .password(own.clone()),
            ]))
            .build()
            .expect("slot 0 falls back to the station password");
        let profiles = &station.connector.profiles;
        assert!(profiles.get(0).unwrap().password.is_some());
        assert_eq!(
            profiles
                .get(1)
                .unwrap()
                .password
                .as_ref()
                .map(BasicAuthPassword::as_bytes),
            Some(own.as_bytes())
        );
    }

    #[test]
    fn every_configuration_slot_is_validated_at_build_time() {
        use super::super::network_profile::{NetworkProfile, NetworkProfiles};

        // The *fallback* slot is misconfigured. Discovering that only when the primary CSMS
        // goes down would be the worst possible moment.
        let error = Station::builder()
            .identity("CS-0001")
            .unwrap()
            .network_profiles(
                NetworkProfiles::new([
                    NetworkProfile::new(0, "ws://fallback/ocpp")
                        .security_profile(SecurityProfile::BasicAuth),
                    NetworkProfile::new(1, "ws://primary/ocpp")
                        .security_profile(SecurityProfile::BasicAuth)
                        .password(BasicAuthPassword::utf8("0123456789abcdef").unwrap()),
                ])
                .priority([1, 0])
                .unwrap(),
            )
            .build()
            .err()
            .expect("slot 0 has no password");
        assert!(
            error.to_string().contains("configuration slot 0"),
            "{error}"
        );
    }
}