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
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
//! The loop that couples a WebSocket to an [`Engine`].
//!
//! Everything version- and role-specific lives in the engine; this file only turns
//! [`Output`]s into socket writes, timer sleeps and handler tasks, and turns socket reads
//! and application commands into [`Input`]s.

use std::collections::{BTreeMap, HashMap};
use std::fmt;
use std::future::Future;
use std::net::SocketAddr;
use std::pin::Pin;
use std::sync::Arc;
use std::time::Duration;

use futures_util::{SinkExt, StreamExt};
use serde_json::value::RawValue;
use tokio::sync::{Semaphore, broadcast, mpsc, oneshot, watch};

use crate::decode::{DecodeOptions, Repair};
use crate::engine::{
    Answer, BootState, CallFailure, CallOptions, CallToken, ClockSample, CloseReason, Engine,
    Input, Instant, MessageStore, Output, ProtocolViolation, Timer,
};
use crate::message::{ActionName, Confirmed, DecodeRequest, NoResponse, Request, Unconfirmed};
use crate::rpc::CallError;
use crate::types::{Identity, MessageId};
use crate::version::Version;

use super::TransportError;
use super::ws::{CloseCode, CloseFrame, Message, WebSocket, WsError};

/// A boxed future, so the handler traits stay object-safe without a macro crate.
pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;

/// How many handler tasks one session may run at once.
///
/// The specification allows a single outstanding `CALL` per direction; this is generous
/// headroom for the peers that break the rule, and a hard stop for the ones that abuse it.
const MAX_CONCURRENT_HANDLERS: usize = 32;

/// A request that arrived from the peer.
pub use crate::engine::IncomingRequest;

/// What an application implements to answer the peer.
///
/// One method, taking the action name and the still-unparsed payload. Decode it with the
/// per-version dispatch union — `v2_1::CsmsRequest::decode` on a station,
/// `v2_1::CsRequest::decode` on a CSMS — and `match` on the result.
///
/// ```no_run
/// use ocpp_kit::rpc::CallError;
/// use ocpp_kit::transport::{BoxFuture, Ctx, Handler};
/// use ocpp_kit::engine::IncomingRequest;
/// use ocpp_kit::v2_1;
/// use serde_json::value::RawValue;
///
/// struct MyStation;
///
/// impl Handler for MyStation {
///     fn on_request(
///         &self,
///         ctx: Ctx,
///         request: IncomingRequest,
///     ) -> BoxFuture<'_, Result<Box<RawValue>, CallError>> {
///         Box::pin(async move {
///             let action = v2_1::Action::from_wire(&request.action)
///                 .ok_or_else(|| CallError::not_implemented(&request.action))?;
///             match v2_1::CsmsRequest::decode(action, &request.payload, ctx.decode_options())? {
///                 v2_1::CsmsRequest::Reset(_) => ctx.reply(&v2_1::ResetResponse::new(
///                     v2_1::ResetStatus::Accepted,
///                 )),
///                 other => Err(CallError::not_supported(other.action().as_str())),
///             }
///         })
///     }
/// }
/// ```
pub trait Handler: Send + Sync + 'static {
    /// Answers one request. Returning `Err` sends a `CALLERROR`.
    ///
    /// A `SEND` (`request.kind == MessageKind::Send`) is never answered; whatever this
    /// returns for one is discarded.
    fn on_request(
        &self,
        ctx: Ctx,
        request: IncomingRequest,
    ) -> BoxFuture<'_, Result<Box<RawValue>, CallError>>;

    /// Observes session lifecycle events. The default does nothing.
    fn on_event(&self, _ctx: &Ctx, _event: &Event) {}
}

/// A handler that answers every request with `NotImplemented`.
///
/// Useful as a starting point and in tests.
pub struct NotImplemented;

impl Handler for NotImplemented {
    fn on_request(
        &self,
        _ctx: Ctx,
        request: IncomingRequest,
    ) -> BoxFuture<'_, Result<Box<RawValue>, CallError>> {
        Box::pin(async move { Err(CallError::not_implemented(&request.action)) })
    }
}

/// What happened to a session.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum Event {
    /// The WebSocket handshake completed.
    Connected {
        /// The negotiated version.
        version: Version,
        /// Whether RFC 7692 `permessage-deflate` was negotiated.
        compressed: bool,
    },
    /// The connection ended.
    Disconnected {
        /// Why, for logging.
        reason: String,
        /// The close frame the peer sent, when it sent one — its code and reason, verbatim.
        peer_close: Option<CloseFrame>,
    },
    /// The boot state machine moved.
    BootState(BootState),
    /// A `currentTime` was observed in a `BootNotificationResponse` or `HeartbeatResponse`.
    ClockSample(ClockSample),
    /// The peer broke a rule. Not fatal.
    Violation(ProtocolViolation),
    /// The peer could not use a `CALLRESULT` we sent (OCPP 2.1 `CALLRESULTERROR`).
    ResultRejected {
        /// The id of the rejected result.
        id: MessageId,
        /// Why.
        error: CallError,
    },
    /// The Charging Station switched to a different network configuration slot.
    ///
    /// This is what `OCPPCommCtrlr.ActiveNetworkProfile` reports.
    NetworkProfileSelected {
        /// The configuration slot now in use.
        configuration_slot: i32,
        /// Where it points.
        url: String,
    },
    /// A Charging Station is waiting before dialling again (Part 4 §5.4).
    Reconnecting {
        /// How many attempts have failed.
        attempt: u32,
        /// How long the station will wait.
        delay: Duration,
    },
    /// A payload from the peer decoded only because leniency forgave something.
    ///
    /// Emitted by [`Ctx::decode`] for a request and by [`Handle::call`] for a response; a
    /// conforming payload emits nothing. Count these per [`RepairKind`] and identity to know
    /// what a fleet actually sends.
    ///
    /// [`RepairKind`]: crate::decode::RepairKind
    Repaired {
        /// The action the payload belongs to.
        action: String,
        /// The `MessageId` it arrived under.
        id: MessageId,
        /// What was forgiven, and where.
        repairs: Vec<Repair>,
    },
}

/// A snapshot of a session, published on a `watch` channel.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct SessionState {
    /// Whether the WebSocket is up.
    pub connected: bool,
    /// The negotiated version.
    pub version: Version,
    /// The boot state machine's state.
    pub boot: BootState,
    /// How many messages are waiting to be sent.
    pub queued: usize,
}

/// What a completed call hands back: how it ended, and the id it was correlated with.
pub(crate) type CallAnswer = Result<(Answer, Option<MessageId>), CallFailure>;

pub(crate) enum Command {
    Call {
        action: String,
        payload: Box<RawValue>,
        options: CallOptions,
        /// Carries the answer and the `MessageId` it arrived under, which a
        /// `CALLRESULTERROR` has to quote.
        reply: oneshot::Sender<CallAnswer>,
    },
    Respond {
        id: MessageId,
        result: Result<Box<RawValue>, CallError>,
    },
    /// A `CALLRESULT` we received could not be used (OCPP 2.1 `CALLRESULTERROR`).
    RejectResult {
        id: MessageId,
        error: CallError,
    },
    Shutdown {
        deadline: Duration,
    },
}

/// Whatever an [`Authenticator`](super::Authenticator) resolved about a station, carried on
/// its session.
///
/// A CSMS maps a connection's [`Identity`] to something of its own — a charge point row, a
/// tenant, an EVSE inventory — and the lookup is the same one every deployment writes. Doing
/// it once, in the authenticator that had to look the station up anyway, and hanging the
/// result here spares every handler a second map keyed on `Identity` and the question of what
/// to do when it misses.
///
/// ```
/// # use ocpp_kit::transport::SessionContext;
/// struct ChargePoint { row_id: u64 }
///
/// let context = SessionContext::new(ChargePoint { row_id: 42 });
/// assert_eq!(context.get::<ChargePoint>().unwrap().row_id, 42);
/// // Asking for a type that was never put in is `None`, not a panic.
/// assert!(context.get::<String>().is_none());
/// ```
#[derive(Clone, Default)]
pub struct SessionContext(Option<Arc<dyn core::any::Any + Send + Sync>>);

impl SessionContext {
    /// A context carrying nothing.
    #[must_use]
    pub const fn empty() -> Self {
        Self(None)
    }

    /// A context carrying `value`.
    #[must_use]
    pub fn new<T: core::any::Any + Send + Sync>(value: T) -> Self {
        Self(Some(Arc::new(value)))
    }

    /// The value, when one was stored and it has the type asked for.
    #[must_use]
    pub fn get<T: core::any::Any + Send + Sync>(&self) -> Option<&T> {
        self.0.as_ref()?.downcast_ref::<T>()
    }

    /// Whether anything was stored.
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.0.is_none()
    }
}

impl fmt::Debug for SessionContext {
    /// The value is opaque — it is whatever the application put there — so only its presence
    /// is reported. Printing it would need a `Debug` bound the store deliberately does not
    /// impose.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("SessionContext")
            .field(&if self.is_empty() { "empty" } else { "set" })
            .finish()
    }
}

pub(crate) struct Shared {
    pub identity: Identity,
    pub remote: Option<SocketAddr>,
    pub session: SessionContext,
    pub decode: DecodeOptions,
    pub commands: mpsc::Sender<Command>,
    pub events: broadcast::Sender<Event>,
    pub state: watch::Receiver<SessionState>,
}

impl Shared {
    /// Publishes what leniency forgave in one payload. Nothing for a conforming one.
    pub(crate) fn report_repairs(&self, action: &str, id: &MessageId, repairs: Vec<Repair>) {
        if repairs.is_empty() {
            return;
        }
        #[cfg(feature = "tracing")]
        for repair in &repairs {
            tracing::debug!(
                identity = %self.identity,
                action,
                pointer = %repair.pointer,
                kind = repair.kind.as_str(),
                "lenient decode repaired a member"
            );
        }
        let _ = self.events.send(Event::Repaired {
            action: action.to_owned(),
            id: id.clone(),
            repairs,
        });
    }
}

/// Everything a handler needs: who the peer is, what was negotiated, and a way to call back.
#[derive(Clone)]
pub struct Ctx {
    shared: Arc<Shared>,
    version: Version,
    id: MessageId,
}

impl Ctx {
    pub(crate) fn new(shared: Arc<Shared>, version: Version, id: MessageId) -> Self {
        Self {
            shared,
            version,
            id,
        }
    }

    /// The Charging Station this session belongs to.
    #[must_use]
    pub fn identity(&self) -> &Identity {
        &self.shared.identity
    }

    /// The peer's address, when the transport knows it.
    #[must_use]
    pub fn remote_addr(&self) -> Option<SocketAddr> {
        self.shared.remote
    }

    /// What the [`Authenticator`](super::Authenticator) resolved about this station, if it
    /// stored anything of type `T`.
    ///
    /// See [`SessionContext`]. Always `None` on a Charging Station or Local Controller
    /// session, which has no authenticator to store anything.
    #[must_use]
    pub fn session<T: core::any::Any + Send + Sync>(&self) -> Option<&T> {
        self.shared.session.get::<T>()
    }

    /// The negotiated protocol version.
    #[must_use]
    pub fn version(&self) -> Version {
        self.version
    }

    /// The `MessageId` of the request being handled.
    #[must_use]
    pub fn message_id(&self) -> &MessageId {
        &self.id
    }

    /// The decoding policy configured for this peer.
    #[must_use]
    pub fn decode_options(&self) -> &DecodeOptions {
        &self.shared.decode
    }

    /// Decodes the request being handled into this side's request union, with this peer's
    /// [`DecodeOptions`], and reports anything leniency forgave as [`Event::Repaired`].
    ///
    /// The one call a handler needs before matching:
    ///
    /// ```no_run
    /// # use ocpp_kit::{RawValue, engine::IncomingRequest, rpc::CallError, v2_1};
    /// # fn example(ctx: ocpp_kit::transport::Ctx, request: IncomingRequest) -> Result<Box<RawValue>, CallError> {
    /// match ctx.decode::<v2_1::CsRequest>(&request)? {
    ///     v2_1::CsRequest::Heartbeat(_) => ctx.reply(&v2_1::HeartbeatResponse::new(
    ///         ocpp_kit::types::DateTime::now(),
    ///     )),
    ///     other => Err(CallError::not_supported(other.action().as_str())),
    /// }
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// `NotImplemented` for an action this version does not define, and otherwise the
    /// [`CallError`] the specification names for the decode failure.
    pub fn decode<U: DecodeRequest>(&self, request: &IncomingRequest) -> Result<U, CallError> {
        let action = U::Action::from_wire(&request.action)
            .ok_or_else(|| CallError::not_implemented(&request.action))?;
        let decoded = U::decode_reporting(action, &request.payload, &self.shared.decode)?;
        self.shared
            .report_repairs(&request.action, &request.id, decoded.repairs);
        Ok(decoded.value)
    }

    /// A handle for calling the peer back, including from inside a handler.
    ///
    /// Reverse calls are queued by the engine, so using this does not deadlock against the
    /// one-outstanding-`CALL` rule.
    #[must_use]
    pub fn handle(&self) -> Handle {
        Handle {
            shared: self.shared.clone(),
        }
    }

    /// Serializes a typed response payload.
    pub fn reply<R: serde::Serialize>(&self, response: &R) -> Result<Box<RawValue>, CallError> {
        serde_json::value::to_raw_value(response)
            .map_err(|error| CallError::internal(format!("response is not serializable: {error}")))
    }
}

/// The application's handle on a session.
#[derive(Clone)]
pub struct Handle {
    shared: Arc<Shared>,
}

impl Handle {
    pub(crate) fn new(shared: Arc<Shared>) -> Self {
        Self { shared }
    }

    /// What the [`Authenticator`](super::Authenticator) resolved about this station, if it
    /// stored anything of type `T`. See [`SessionContext`].
    #[must_use]
    pub fn session<T: core::any::Any + Send + Sync>(&self) -> Option<&T> {
        self.shared.session.get::<T>()
    }

    /// The Charging Station identity this handle talks to.
    #[must_use]
    pub fn identity(&self) -> &Identity {
        &self.shared.identity
    }

    /// The current session state.
    #[must_use]
    pub fn state(&self) -> SessionState {
        *self.shared.state.borrow()
    }

    /// Subscribes to session events.
    #[must_use]
    pub fn events(&self) -> broadcast::Receiver<Event> {
        self.shared.events.subscribe()
    }

    /// Waits until the session is connected and the boot state machine allows traffic.
    ///
    /// Returns `false` if the session ends first.
    pub async fn wait_ready(&self) -> bool {
        let mut state = self.shared.state.clone();
        loop {
            if state.borrow().connected && state.borrow().boot.allows_traffic() {
                return true;
            }
            if state.changed().await.is_err() {
                return false;
            }
        }
    }

    /// Sends a typed request and waits for the typed response.
    ///
    /// The [`Confirmed`] bound excludes the OCPP 2.1 `SEND`s, which are never answered
    /// (Part 4 §4.2.4); they go through [`send`](Self::send).
    ///
    /// ```no_run
    /// # async fn example(handle: ocpp_kit::transport::Handle) -> Result<(), Box<dyn std::error::Error>> {
    /// use ocpp_kit::v2_1;
    /// let response = handle.call(v2_1::HeartbeatRequest::new()).await?;
    /// println!("CSMS time is {}", response.current_time);
    /// # Ok(()) }
    /// ```
    pub async fn call<R>(&self, request: R) -> Result<R::Response, CallFailure>
    where
        R: Request + Confirmed,
    {
        self.call_with(request, CallOptions::default()).await
    }

    /// Sends a typed request with per-call overrides.
    ///
    /// [`CallOptions::triggered`] is the one that matters most: B02.FR.02 keeps a station
    /// quiet until the CSMS accepts it, *except* for messages the CSMS asked for. A
    /// `TriggerMessage` answered without it sits in the queue until boot completes.
    ///
    /// ```no_run
    /// # async fn example(handle: ocpp_kit::transport::Handle) -> Result<(), Box<dyn std::error::Error>> {
    /// use ocpp_kit::engine::CallOptions;
    /// use ocpp_kit::v2_1;
    ///
    /// // Answering a TriggerMessage(StatusNotification) while the boot is still `Pending`.
    /// handle
    ///     .call_with(
    ///         v2_1::StatusNotificationRequest::new(
    ///             ocpp_kit::types::DateTime::now(),
    ///             v2_1::ConnectorStatus::Available,
    ///             1,
    ///             1,
    ///         ),
    ///         CallOptions::triggered(),
    ///     )
    ///     .await?;
    /// # Ok(()) }
    /// ```
    pub async fn call_with<R>(
        &self,
        request: R,
        options: CallOptions,
    ) -> Result<R::Response, CallFailure>
    where
        R: Request + Confirmed,
    {
        let payload = serde_json::value::to_raw_value(&request).map_err(|error| {
            CallFailure::Rejected(CallError::internal(format!(
                "request is not serializable: {error}"
            )))
        })?;
        let (answer, id) = self
            .call_raw_with_id(R::ACTION.as_str(), payload, options)
            .await?;
        let Some(raw) = answer.into_payload() else {
            // Unreachable: `Confirmed` is only implemented for actions with a response.
            return Err(CallFailure::Rejected(CallError::internal(
                "a CALL was completed as a SEND",
            )));
        };
        match crate::decode::decode_payload_reporting::<R::Response>(&raw, &self.shared.decode) {
            Ok(decoded) => {
                if let Some(id) = &id {
                    self.shared
                        .report_repairs(R::ACTION.as_str(), id, decoded.repairs);
                }
                Ok(decoded.value)
            }
            Err(error) => {
                let error = CallError::from(error);
                // Part 4 §4.2.3: on 2.1 the sender of an unusable `CALLRESULT` is told so
                // with a `CALLRESULTERROR` instead of being left believing it succeeded.
                // Older versions have no such message, so the failure stays local.
                if let Some(id) = id {
                    let _ = self
                        .shared
                        .commands
                        .send(Command::RejectResult {
                            id,
                            error: error.clone(),
                        })
                        .await;
                }
                Err(CallFailure::Rejected(error))
            }
        }
    }

    /// Sends an unconfirmed OCPP 2.1 `SEND` and returns once it has been written.
    ///
    /// Part 4 §4.2.4 forbids the receiver from answering, so `Ok(())` means "on the wire",
    /// not "accepted".
    ///
    /// ```no_run
    /// # async fn example(handle: ocpp_kit::transport::Handle) -> Result<(), Box<dyn std::error::Error>> {
    /// use ocpp_kit::types::DateTime;
    /// use ocpp_kit::v2_1;
    /// handle
    ///     .send(v2_1::NotifyPeriodicEventStreamRequest::new(
    ///         vec![],
    ///         1,
    ///         0,
    ///         DateTime::now(),
    ///     ))
    ///     .await?;
    /// # Ok(()) }
    /// ```
    pub async fn send<R>(&self, request: R) -> Result<(), CallFailure>
    where
        R: Request<Response = NoResponse> + Unconfirmed,
    {
        self.send_with(request, CallOptions::default()).await
    }

    /// Sends an unconfirmed `SEND` with per-call overrides.
    pub async fn send_with<R>(&self, request: R, options: CallOptions) -> Result<(), CallFailure>
    where
        R: Request<Response = NoResponse> + Unconfirmed,
    {
        let payload = serde_json::value::to_raw_value(&request).map_err(|error| {
            CallFailure::Rejected(CallError::internal(format!(
                "request is not serializable: {error}"
            )))
        })?;
        self.call_raw_with_id(R::ACTION.as_str(), payload, options)
            .await
            .map(|_| ())
    }

    /// Sends a request the caller has already serialized.
    ///
    /// Returns [`Answer::Sent`] for a `SEND` and [`Answer::Result`] for everything else.
    pub async fn call_raw(
        &self,
        action: &str,
        payload: Box<RawValue>,
        options: CallOptions,
    ) -> Result<Answer, CallFailure> {
        self.call_raw_with_id(action, payload, options)
            .await
            .map(|(answer, _)| answer)
    }

    /// As [`call_raw`](Self::call_raw), but also reports the `MessageId` the call went out
    /// with — which is what a `CALLRESULTERROR` has to quote.
    async fn call_raw_with_id(
        &self,
        action: &str,
        payload: Box<RawValue>,
        options: CallOptions,
    ) -> Result<(Answer, Option<MessageId>), CallFailure> {
        let (reply, answer) = oneshot::channel();
        let command = Command::Call {
            action: action.to_owned(),
            payload,
            options,
            reply,
        };
        if self.shared.commands.send(command).await.is_err() {
            return Err(CallFailure::Disconnected);
        }
        let outcome = answer.await.unwrap_or(Err(CallFailure::Disconnected))?;
        Ok(outcome)
    }

    /// Starts a graceful drain and waits for it to finish or time out.
    pub async fn shutdown(&self, deadline: Duration) {
        let _ = self
            .shared
            .commands
            .send(Command::Shutdown { deadline })
            .await;
        let mut state = self.shared.state.clone();
        while state.borrow().connected {
            if state.changed().await.is_err() {
                break;
            }
        }
    }
}

// ---------------------------------------------------------------------------
// The driver loop
// ---------------------------------------------------------------------------

/// How a session run ended.
pub(crate) enum Ended {
    /// The peer or the network closed it; a station should reconnect.
    Disconnected(String),
    /// The engine asked for the connection to close.
    Closed(CloseReason),
}

pub(crate) struct Driver<S: MessageStore> {
    pub engine: Engine<S>,
    pub shared: Arc<Shared>,
    pub handler: Arc<dyn Handler>,
    pub state: watch::Sender<SessionState>,
    pub started: tokio::time::Instant,
    pending: HashMap<CallToken, oneshot::Sender<CallAnswer>>,
    timers: BTreeMap<Timer, Instant>,
    /// Bounds how many handler tasks may run at once for this session.
    ///
    /// The engine already caps the peer's unanswered calls; this caps the *work* they can
    /// start, so one talkative station cannot occupy the runtime on behalf of the rest.
    slots: Arc<Semaphore>,
    /// The close frame the peer sent on the current connection, for `Event::Disconnected`.
    peer_close: Option<CloseFrame>,
    /// How often to adopt what another process added to the store; `None` never.
    pub store_poll: Option<Duration>,
}

/// How the driver watches for a connection that has died without saying so.
///
/// A TCP connection that a mobile network silently dropped stays writable for minutes. The
/// WebSocket ping is the only end-to-end liveness signal there is (Part 4 §5.3), and it is
/// only a signal if an unanswered one eventually ends the session.
#[derive(Clone, Copy, Debug)]
pub struct Keepalive {
    /// How often to send a ping. `None` disables both the ping and the timeout.
    pub interval: Option<Duration>,
    /// How long to wait for the pong before giving up on the connection.
    pub timeout: Duration,
}

impl Default for Keepalive {
    fn default() -> Self {
        Self {
            interval: Some(Duration::from_secs(60)),
            timeout: Duration::from_secs(30),
        }
    }
}

impl Keepalive {
    /// A keepalive with the given ping interval and the default timeout.
    #[must_use]
    pub fn every(interval: Duration) -> Self {
        Self {
            interval: Some(interval),
            ..Self::default()
        }
    }

    /// No pings, and therefore no liveness check.
    #[must_use]
    pub const fn disabled() -> Self {
        Self {
            interval: None,
            timeout: Duration::ZERO,
        }
    }

    /// Sets how long an unanswered ping may go unanswered.
    #[must_use]
    pub const fn with_timeout(mut self, timeout: Duration) -> Self {
        self.timeout = timeout;
        self
    }
}

impl<S: MessageStore> Driver<S> {
    pub fn new(
        engine: Engine<S>,
        shared: Arc<Shared>,
        handler: Arc<dyn Handler>,
        state: watch::Sender<SessionState>,
    ) -> Self {
        Self {
            engine,
            shared,
            handler,
            state,
            started: tokio::time::Instant::now(),
            pending: HashMap::new(),
            timers: BTreeMap::new(),
            slots: Arc::new(Semaphore::new(MAX_CONCURRENT_HANDLERS)),
            peer_close: None,
            store_poll: None,
        }
    }

    /// Queues what another process added to the store (`StationBuilder::store_poll`).
    fn adopt_pending(&mut self) {
        if let Err(error) = self.engine.adopt_pending(self.now()) {
            let _ = self
                .shared
                .events
                .send(Event::Violation(ProtocolViolation::StoreFailure { error }));
        }
    }

    pub(crate) fn now(&self) -> Instant {
        Instant::from_millis(u64::try_from(self.started.elapsed().as_millis()).unwrap_or(u64::MAX))
    }

    /// Runs one connection until it ends. The engine survives, so a station keeps its queue
    /// and its boot state across reconnects (Part 4 §5.4: no `BootNotification` on a mere
    /// reconnect).
    ///
    /// This cannot fail, only end: every way a socket can break is a reason to reconnect, and
    /// there is no error a caller could usefully do anything else with.
    pub async fn run<St>(
        &mut self,
        socket: WebSocket<St>,
        commands: &mut mpsc::Receiver<Command>,
        version: Version,
        keepalive: Keepalive,
    ) -> Ended
    where
        St: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send,
    {
        let compressed = socket.codec().is_compressed();
        let (mut sink, mut stream) = socket.split();
        self.peer_close = None;

        self.engine.handle(self.now(), Input::Connected { version });
        if self.store_poll.is_some() {
            self.adopt_pending();
        }
        self.publish(true, version);
        let _ = self.shared.events.send(Event::Connected {
            version,
            compressed,
        });

        let mut ping = keepalive.interval.map(|interval| {
            let mut timer = tokio::time::interval(interval);
            timer.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
            timer
        });
        let mut store_poll = self.store_poll.map(|interval| {
            let mut timer =
                tokio::time::interval_at(tokio::time::Instant::now() + interval, interval);
            timer.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
            timer
        });
        // `Some` while a ping is outstanding: the deadline by which a pong must arrive.
        let mut pong_due: Option<tokio::time::Instant> = None;

        // Every failure inside the loop ends this *connection*, never the driver: the engine
        // has to be told the socket is gone so it can fail or requeue what was outstanding,
        // and a station has to be free to reconnect (Part 4 §5.4, which says to reconnect
        // when the connection is lost and does not enumerate the ways it can be lost).
        // Returning early — which a bare `?` on the write path did — skipped both.
        let ended = loop {
            match self.flush(&mut sink).await {
                Ok(Some(outcome)) => break outcome,
                Ok(None) => {}
                Err(error) => break Ended::Disconnected(error.to_string()),
            }

            let sleep = self.next_deadline();
            // No `biased`: a fair poll keeps a flood of application commands from starving
            // the socket, and vice versa.
            tokio::select! {
                command = commands.recv() => {
                    match command {
                        Some(command) => self.apply(command),
                        None => break Ended::Closed(CloseReason::Requested),
                    }
                }

                message = stream.next() => {
                    // A pong proves the peer is alive; RFC 6455 §5.5.3 does not require the
                    // payload to match, and some peers do not echo it.
                    if matches!(message, Some(Ok(Message::Pong(_)))) {
                        pong_due = None;
                    }
                    if let Some(ended) = self.on_message(message, &mut sink).await {
                        break ended;
                    }
                }

                () = sleep => {
                    let now = self.now();
                    self.engine.handle(now, Input::Timeout);
                    self.timers.retain(|_, at| *at > now);
                }

                _ = async { ping.as_mut().expect("checked").tick().await }, if ping.is_some() => {
                    if pong_due.is_none() {
                        pong_due = Some(tokio::time::Instant::now() + keepalive.timeout);
                    }
                    if let Err(error) = sink.send(Message::Ping(Vec::new())).await {
                        break Ended::Disconnected(error.to_string());
                    }
                }

                _ = async { store_poll.as_mut().expect("checked").tick().await },
                    if store_poll.is_some() =>
                {
                    self.adopt_pending();
                }

                // Part 4 §5.3: the ping is the end-to-end liveness check. A connection that
                // stops answering is gone, however healthy the TCP socket still looks.
                () = async { tokio::time::sleep_until(pong_due.expect("checked")).await },
                    if pong_due.is_some() =>
                {
                    break Ended::Disconnected(format!(
                        "no pong within {:?} of a WebSocket ping",
                        keepalive.timeout
                    ));
                }
            }
        };

        self.engine.handle(self.now(), Input::Disconnected);
        let _ = self.flush(&mut sink).await;
        let reason = match &ended {
            Ended::Disconnected(reason) => reason.clone(),
            Ended::Closed(why) => format!("{why:?}"),
        };
        self.publish(false, version);
        let _ = self.shared.events.send(Event::Disconnected {
            reason,
            peer_close: self.peer_close.take(),
        });
        if matches!(ended, Ended::Closed(_)) {
            let _ = sink
                .send(Message::Close(Some(CloseFrame::new(CloseCode::NORMAL, ""))))
                .await;
        }
        let _ = sink.close().await;
        ended
    }

    /// Handles one message off the socket. `Some` ends the connection.
    async fn on_message<Si>(
        &mut self,
        message: Option<Result<Message, WsError>>,
        sink: &mut Si,
    ) -> Option<Ended>
    where
        Si: futures_util::Sink<Message, Error = WsError> + Unpin,
    {
        match message {
            Some(Ok(Message::Text(text))) => {
                self.engine.handle(self.now(), Input::Received(&text));
                None
            }
            Some(Ok(Message::Ping(payload))) => {
                // RFC 6455 §5.5.2: answer as soon as practical.
                sink.send(Message::Pong(payload))
                    .await
                    .err()
                    .map(|error| Ended::Disconnected(error.to_string()))
            }
            // Part 4 §4.1: OCPP-J is text-only. A binary frame — and a pong, already
            // accounted for by the caller — is ignored rather than treated as fatal.
            Some(Ok(Message::Pong(_) | Message::Binary(_))) => None,
            Some(Ok(Message::Close(frame))) => {
                let reason = frame.as_ref().map_or_else(
                    || "peer closed".to_owned(),
                    |frame| format!("peer closed: {} {}", frame.code, frame.reason),
                );
                // §5.5.1: echo the close, then stop.
                let echo = frame.as_ref().map(|frame| CloseFrame::new(frame.code, ""));
                self.peer_close = frame;
                let _ = sink.send(Message::Close(echo)).await;
                Some(Ended::Disconnected(reason))
            }
            Some(Err(error)) => {
                // A protocol error deserves the close code RFC 6455 assigns it, so the peer
                // learns what it did wrong.
                if let Some(code) = error.close_code() {
                    let _ = sink
                        .send(Message::Close(Some(CloseFrame::new(
                            code,
                            error.to_string(),
                        ))))
                        .await;
                }
                Some(Ended::Disconnected(error.to_string()))
            }
            None => Some(Ended::Disconnected("stream ended".to_owned())),
        }
    }

    /// Fails every outstanding call, for a session that ends without the engine running.
    pub fn abandon(&mut self, why: &CallFailure) {
        for (_, reply) in self.pending.drain() {
            let _ = reply.send(Err(why.clone()));
        }
    }

    fn apply(&mut self, command: Command) {
        match command {
            Command::Call {
                action,
                payload,
                options,
                reply,
            } => match self.engine.call_with(self.now(), &action, payload, options) {
                Ok(token) => {
                    self.pending.insert(token, reply);
                }
                Err(error) => {
                    let _ = reply.send(Err(CallFailure::Rejected(CallError::internal(
                        error.to_string(),
                    ))));
                }
            },
            Command::RejectResult { id, error } => {
                // Only 2.1 has CALLRESULTERROR; on older versions the engine says so and the
                // failure has already been reported to the caller.
                let _ = self.engine.reject_result(self.now(), &id, error);
            }
            Command::Respond { id, result } => {
                let now = self.now();
                let outcome = match result {
                    Ok(payload) => self.engine.respond(now, &id, &payload),
                    Err(error) => self.engine.respond_error(now, &id, error),
                };
                if let Err(error) = outcome {
                    let _ = self.shared.events.send(Event::Violation(
                        ProtocolViolation::UnexpectedResponse {
                            id: match error {
                                crate::engine::EngineError::NoSuchRequest(id) => id,
                                _ => id,
                            },
                        },
                    ));
                }
            }
            Command::Shutdown { deadline } => {
                let now = self.now();
                self.engine.shutdown(now, now.saturating_add(deadline));
            }
        }
    }

    /// Drains the engine's outputs, writing frames and spawning handler tasks.
    ///
    /// Returns `Some` when the engine asked for the connection to close.
    async fn flush<Si>(&mut self, sink: &mut Si) -> Result<Option<Ended>, TransportError>
    where
        Si: futures_util::Sink<Message, Error = WsError> + Unpin,
    {
        let mut close = None;
        let mut wrote = false;
        while let Some(output) = self.engine.poll_output() {
            match output {
                Output::Transmit(text) => {
                    sink.feed(Message::Text(text)).await?;
                    wrote = true;
                }
                Output::Request(request) => self.dispatch(request),
                Output::Outcome(outcome) => {
                    if let Some(reply) = self.pending.remove(&outcome.token) {
                        let id = outcome.id;
                        let _ = reply.send(outcome.result.map(|answer| (answer, id)));
                    }
                }
                Output::SetTimer { timer, at } => {
                    self.timers.insert(timer, at);
                }
                Output::ClearTimer(timer) => {
                    self.timers.remove(&timer);
                }
                Output::BootState(state) => {
                    let _ = self.shared.events.send(Event::BootState(state));
                }
                Output::ClockSample(sample) => {
                    let _ = self.shared.events.send(Event::ClockSample(sample));
                }
                Output::ResultRejected { id, error } => {
                    let _ = self.shared.events.send(Event::ResultRejected { id, error });
                }
                Output::Violation(violation) => {
                    let _ = self.shared.events.send(Event::Violation(violation));
                }
                Output::Close(reason) => close = Some(Ended::Closed(reason)),
            }
        }
        if wrote {
            sink.flush().await?;
        }
        let version = self.engine.version();
        self.publish(self.engine.is_connected(), version);
        Ok(close)
    }

    fn dispatch(&self, request: IncomingRequest) {
        let handler = self.handler.clone();
        let shared = self.shared.clone();
        let slots = self.slots.clone();
        let ctx = Ctx::new(shared.clone(), self.engine.version(), request.id.clone());
        let is_send = request.kind == crate::message::MessageKind::Send;
        let id = request.id.clone();
        tokio::spawn(async move {
            // Acquiring the permit *inside* the task keeps the driver loop non-blocking:
            // the request waits its turn instead of the socket doing so.
            let Ok(_permit) = slots.acquire().await else {
                return;
            };
            let result = handler.on_request(ctx, request).await;
            // FR.07 — a SEND is never answered.
            if is_send {
                return;
            }
            let _ = shared.commands.send(Command::Respond { id, result }).await;
        });
    }

    fn publish(&self, connected: bool, version: Version) {
        let next = SessionState {
            connected,
            version,
            boot: self.engine.boot_state(),
            queued: self.engine.queued(),
        };
        self.state.send_if_modified(|state| {
            if *state == next {
                false
            } else {
                *state = next;
                true
            }
        });
    }

    /// Sleeps until the earliest armed timer, or forever when none is armed.
    fn next_deadline(&self) -> impl Future<Output = ()> + use<S> {
        let next = self.timers.values().min().copied();
        let started = self.started;
        async move {
            match next {
                Some(at) => {
                    tokio::time::sleep_until(started + Duration::from_millis(at.as_millis())).await;
                }
                None => std::future::pending::<()>().await,
            }
        }
    }
}