cruster 0.0.27

A Rust framework for building distributed, stateful entity systems with durable workflows
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
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
use crate::envelope::EnvelopeRequest;
use crate::envelope::{STREAM_HEADER_KEY, STREAM_HEADER_VALUE};
use crate::error::ClusterError;
use crate::hash::{djb2_hash64, djb2_hash64_with_seed};
use crate::reply::{ExitResult, Reply};
use crate::sharding::Sharding;
use crate::snowflake::Snowflake;
use crate::types::{EntityId, EntityType};
use chrono::{DateTime, Utc};
use serde::de::DeserializeOwned;
use serde::Serialize;
use std::collections::{BTreeMap, HashMap, VecDeque};
use std::pin::Pin;
use std::sync::Arc;
use tokio_stream::Stream;
use tracing::instrument;

/// Client for sending messages to a specific entity type.
///
/// Created via `Sharding::make_client`. Handles shard resolution,
/// envelope construction, and response deserialization.
///
/// Cloning is cheap — the inner sharding handle is an `Arc`.
#[derive(Clone)]
pub struct EntityClient {
    sharding: Arc<dyn Sharding>,
    entity_type: EntityType,
}

/// Access to an underlying [`EntityClient`].
///
/// Used by macro-generated trait client extensions.
pub trait EntityClientAccessor {
    fn entity_client(&self) -> &EntityClient;
}

impl EntityClientAccessor for EntityClient {
    fn entity_client(&self) -> &EntityClient {
        self
    }
}

/// Factory trait for creating typed workflow/entity clients.
///
/// Automatically implemented by `#[workflow]` macros.
/// Used by the `self.client::<T>()` method inside workflow execute bodies
/// to get a typed client for another workflow or entity.
pub trait WorkflowClientFactory {
    /// The typed client type produced by this factory.
    type Client;

    /// Create a new typed client from a sharding interface.
    fn workflow_client(sharding: Arc<dyn Sharding>) -> Self::Client;
}

pub(crate) fn persisted_request_id(
    entity_type: &EntityType,
    entity_id: &EntityId,
    tag: &str,
    key_bytes: &[u8],
) -> Snowflake {
    // Include entity address in the hash to ensure uniqueness across entity instances
    let mut hash = djb2_hash64(entity_type.0.as_bytes());
    hash = djb2_hash64_with_seed(hash, &[0]);
    hash = djb2_hash64_with_seed(hash, entity_id.0.as_bytes());
    hash = djb2_hash64_with_seed(hash, &[0]);
    hash = djb2_hash64_with_seed(hash, tag.as_bytes());
    hash = djb2_hash64_with_seed(hash, &[0]);
    hash = djb2_hash64_with_seed(hash, key_bytes);
    Snowflake((hash & i64::MAX as u64) as i64)
}

impl EntityClient {
    /// Create a new entity client for the given entity type.
    pub fn new(sharding: Arc<dyn Sharding>, entity_type: EntityType) -> Self {
        Self {
            sharding,
            entity_type,
        }
    }

    /// Send a request and await a deserialized response.
    #[instrument(skip(self, request), fields(entity_type = %self.entity_type, entity_id = %entity_id))]
    pub async fn send<Req, Res>(
        &self,
        entity_id: &EntityId,
        tag: &str,
        request: &Req,
    ) -> Result<Res, ClusterError>
    where
        Req: Serialize,
        Res: DeserializeOwned,
    {
        let envelope = self.build_envelope(entity_id, tag, request).await?;
        let mut reply_rx = self.sharding.send(envelope).await?;

        let reply = reply_rx
            .recv()
            .await
            .ok_or_else(|| ClusterError::MalformedMessage {
                reason: "reply channel closed without response".into(),
                source: None,
            })?;

        match reply {
            Reply::WithExit(r) => match r.exit {
                ExitResult::Success(bytes) => {
                    rmp_serde::from_slice(&bytes).map_err(|e| ClusterError::MalformedMessage {
                        reason: format!("failed to deserialize response: {e}"),
                        source: Some(Box::new(e)),
                    })
                }
                ExitResult::Failure(msg) => Err(ClusterError::MalformedMessage {
                    reason: msg,
                    source: None,
                }),
            },
            Reply::Chunk(_) => Err(ClusterError::MalformedMessage {
                reason: "expected WithExit reply, got Chunk".into(),
                source: None,
            }),
        }
    }

    /// Send a request and receive a stream of deserialized responses.
    #[allow(clippy::type_complexity)]
    #[instrument(skip(self, request), fields(entity_type = %self.entity_type, entity_id = %entity_id))]
    pub async fn send_stream<Req, Res>(
        &self,
        entity_id: &EntityId,
        tag: &str,
        request: &Req,
    ) -> Result<Pin<Box<dyn Stream<Item = Result<Res, ClusterError>> + Send>>, ClusterError>
    where
        Req: Serialize,
        Res: DeserializeOwned + Send + 'static,
    {
        fn push_values<Res: DeserializeOwned>(
            pending: &mut VecDeque<Result<Res, ClusterError>>,
            values: Vec<Vec<u8>>,
        ) {
            for bytes in values {
                let item =
                    rmp_serde::from_slice(&bytes).map_err(|e| ClusterError::MalformedMessage {
                        reason: format!("failed to deserialize chunk: {e}"),
                        source: Some(Box::new(e)),
                    });
                pending.push_back(item);
            }
        }

        let mut envelope = self.build_envelope(entity_id, tag, request).await?;
        envelope.headers.insert(
            STREAM_HEADER_KEY.to_string(),
            STREAM_HEADER_VALUE.to_string(),
        );
        let reply_rx = self.sharding.send(envelope).await?;

        let stream = tokio_stream::wrappers::ReceiverStream::new(reply_rx);

        struct StreamState<Res> {
            stream: Pin<Box<dyn Stream<Item = Reply> + Send>>,
            next_sequence: i32,
            pending_chunks: BTreeMap<i32, Vec<Vec<u8>>>,
            pending_items: VecDeque<Result<Res, ClusterError>>,
            exit: Option<Result<Res, ClusterError>>,
            finished: bool,
        }

        let ordered = futures::stream::unfold(
            StreamState {
                stream: Box::pin(stream),
                next_sequence: 0,
                pending_chunks: BTreeMap::new(),
                pending_items: VecDeque::new(),
                exit: None,
                finished: false,
            },
            |mut state| async move {
                use tokio_stream::StreamExt;

                loop {
                    if let Some(item) = state.pending_items.pop_front() {
                        return Some((item, state));
                    }

                    if state.finished {
                        if !state.pending_chunks.is_empty() {
                            let pending_chunks = std::mem::take(&mut state.pending_chunks);
                            for (_, values) in pending_chunks {
                                push_values(&mut state.pending_items, values);
                            }
                            if let Some(item) = state.pending_items.pop_front() {
                                return Some((item, state));
                            }
                        }

                        if let Some(exit) = state.exit.take() {
                            return Some((exit, state));
                        }

                        return None;
                    }

                    match state.stream.next().await {
                        Some(Reply::Chunk(chunk)) => {
                            if chunk.values.is_empty() {
                                continue;
                            }
                            if chunk.sequence < state.next_sequence {
                                continue;
                            }
                            state.pending_chunks.insert(chunk.sequence, chunk.values);
                            while let Some(values) =
                                state.pending_chunks.remove(&state.next_sequence)
                            {
                                push_values(&mut state.pending_items, values);
                                state.next_sequence += 1;
                            }
                        }
                        Some(Reply::WithExit(r)) => {
                            let result = match r.exit {
                                ExitResult::Success(bytes) => {
                                    if bytes.is_empty() {
                                        None
                                    } else {
                                        Some(rmp_serde::from_slice(&bytes).map_err(|e| {
                                            ClusterError::MalformedMessage {
                                                reason: format!(
                                                    "failed to deserialize response: {e}"
                                                ),
                                                source: Some(Box::new(e)),
                                            }
                                        }))
                                    }
                                }
                                ExitResult::Failure(msg) => {
                                    Some(Err(ClusterError::MalformedMessage {
                                        reason: msg,
                                        source: None,
                                    }))
                                }
                            };
                            state.exit = result;
                        }
                        None => {
                            state.finished = true;
                        }
                    }
                }
            },
        );

        Ok(Box::pin(ordered))
    }

    /// Fire-and-forget notification to an entity.
    #[instrument(skip(self, request), fields(entity_type = %self.entity_type, entity_id = %entity_id))]
    pub async fn notify<Req: Serialize>(
        &self,
        entity_id: &EntityId,
        tag: &str,
        request: &Req,
    ) -> Result<(), ClusterError> {
        let envelope = self.build_envelope(entity_id, tag, request).await?;
        self.sharding.notify(envelope).await
    }

    /// Send a persisted request and await a deserialized response.
    ///
    /// Persisted messages are saved to `MessageStorage` before delivery, ensuring
    /// at-least-once delivery even if the target runner crashes.
    #[instrument(skip(self, request), fields(entity_type = %self.entity_type, entity_id = %entity_id))]
    pub async fn send_persisted<Req, Res>(
        &self,
        entity_id: &EntityId,
        tag: &str,
        request: &Req,
        uninterruptible: crate::schema::Uninterruptible,
    ) -> Result<Res, ClusterError>
    where
        Req: Serialize,
        Res: DeserializeOwned,
    {
        self.send_persisted_with_key(entity_id, tag, request, None, uninterruptible)
            .await
    }

    /// Send a persisted request with an explicit idempotency key.
    ///
    /// When `key_bytes` is provided, the request ID is derived from the
    /// tag + key bytes instead of the serialized request payload.
    #[instrument(skip(self, request, key_bytes), fields(entity_type = %self.entity_type, entity_id = %entity_id))]
    pub async fn send_persisted_with_key<Req, Res>(
        &self,
        entity_id: &EntityId,
        tag: &str,
        request: &Req,
        key_bytes: Option<Vec<u8>>,
        uninterruptible: crate::schema::Uninterruptible,
    ) -> Result<Res, ClusterError>
    where
        Req: Serialize,
        Res: DeserializeOwned,
    {
        let mut envelope = self.build_envelope(entity_id, tag, request).await?;
        envelope.persisted = true;
        envelope.uninterruptible = uninterruptible;
        let key_bytes = key_bytes.unwrap_or_else(|| envelope.payload.clone());
        envelope.request_id = persisted_request_id(&self.entity_type, entity_id, tag, &key_bytes);
        let mut reply_rx = self.sharding.send(envelope).await?;

        let reply = reply_rx
            .recv()
            .await
            .ok_or_else(|| ClusterError::MalformedMessage {
                reason: "reply channel closed without response".into(),
                source: None,
            })?;

        match reply {
            Reply::WithExit(r) => match r.exit {
                ExitResult::Success(bytes) => {
                    rmp_serde::from_slice(&bytes).map_err(|e| ClusterError::MalformedMessage {
                        reason: format!("failed to deserialize response: {e}"),
                        source: Some(Box::new(e)),
                    })
                }
                ExitResult::Failure(msg) => Err(ClusterError::MalformedMessage {
                    reason: msg,
                    source: None,
                }),
            },
            Reply::Chunk(_) => Err(ClusterError::MalformedMessage {
                reason: "expected WithExit reply, got Chunk".into(),
                source: None,
            }),
        }
    }

    /// Fire-and-forget persisted notification to an entity.
    ///
    /// Persisted notifications are saved to `MessageStorage` before delivery.
    #[instrument(skip(self, request), fields(entity_type = %self.entity_type, entity_id = %entity_id))]
    pub async fn notify_persisted<Req: Serialize>(
        &self,
        entity_id: &EntityId,
        tag: &str,
        request: &Req,
    ) -> Result<(), ClusterError> {
        self.notify_persisted_with_key(entity_id, tag, request, None)
            .await
    }

    /// Fire-and-forget persisted notification with an explicit idempotency key.
    pub async fn notify_persisted_with_key<Req: Serialize>(
        &self,
        entity_id: &EntityId,
        tag: &str,
        request: &Req,
        key_bytes: Option<Vec<u8>>,
    ) -> Result<(), ClusterError> {
        let mut envelope = self.build_envelope(entity_id, tag, request).await?;
        envelope.persisted = true;
        let key_bytes = key_bytes.unwrap_or_else(|| envelope.payload.clone());
        envelope.request_id = persisted_request_id(&self.entity_type, entity_id, tag, &key_bytes);
        self.sharding.notify(envelope).await
    }

    /// Send a request with scheduled delivery at a specific time.
    ///
    /// The message is persisted to `MessageStorage` but will not be delivered
    /// to the entity until `deliver_at` time is reached. The storage polling
    /// loop filters out messages where `deliver_at > now()`.
    #[instrument(skip(self, request), fields(entity_type = %self.entity_type, entity_id = %entity_id))]
    pub async fn send_at<Req, Res>(
        &self,
        entity_id: &EntityId,
        tag: &str,
        request: &Req,
        deliver_at: DateTime<Utc>,
    ) -> Result<Res, ClusterError>
    where
        Req: Serialize,
        Res: DeserializeOwned,
    {
        let mut envelope = self.build_envelope(entity_id, tag, request).await?;
        envelope.persisted = true;
        envelope.deliver_at = Some(deliver_at);
        let mut reply_rx = self.sharding.send(envelope).await?;

        let reply = reply_rx
            .recv()
            .await
            .ok_or_else(|| ClusterError::MalformedMessage {
                reason: "reply channel closed without response".into(),
                source: None,
            })?;

        match reply {
            Reply::WithExit(r) => match r.exit {
                ExitResult::Success(bytes) => {
                    rmp_serde::from_slice(&bytes).map_err(|e| ClusterError::MalformedMessage {
                        reason: format!("failed to deserialize response: {e}"),
                        source: Some(Box::new(e)),
                    })
                }
                ExitResult::Failure(msg) => Err(ClusterError::MalformedMessage {
                    reason: msg,
                    source: None,
                }),
            },
            Reply::Chunk(_) => Err(ClusterError::MalformedMessage {
                reason: "expected WithExit reply, got Chunk".into(),
                source: None,
            }),
        }
    }

    /// Fire-and-forget notification with scheduled delivery at a specific time.
    ///
    /// The message is persisted to `MessageStorage` but will not be delivered
    /// until `deliver_at` time is reached.
    #[instrument(skip(self, request), fields(entity_type = %self.entity_type, entity_id = %entity_id))]
    pub async fn notify_at<Req: Serialize>(
        &self,
        entity_id: &EntityId,
        tag: &str,
        request: &Req,
        deliver_at: DateTime<Utc>,
    ) -> Result<(), ClusterError> {
        let mut envelope = self.build_envelope(entity_id, tag, request).await?;
        envelope.persisted = true;
        envelope.deliver_at = Some(deliver_at);
        self.sharding.notify(envelope).await
    }

    /// Poll for a persisted reply without sending a new message.
    ///
    /// Computes the deterministic request ID from the entity address and tag/key,
    /// then queries `MessageStorage` for any stored exit reply. Returns `Ok(Some(result))`
    /// if the workflow has completed, `Ok(None)` if it is still running or no reply exists.
    ///
    /// The `key_bytes` are the same bytes used by `send_persisted`/`notify_persisted`
    /// for deterministic request ID derivation (typically the serialized request payload).
    #[instrument(skip(self, key_bytes), fields(entity_type = %self.entity_type, entity_id = %entity_id))]
    pub async fn poll_reply<Res>(
        &self,
        entity_id: &EntityId,
        tag: &str,
        key_bytes: &[u8],
    ) -> Result<Option<Res>, ClusterError>
    where
        Res: DeserializeOwned,
    {
        let request_id = persisted_request_id(&self.entity_type, entity_id, tag, key_bytes);
        let replies = self.sharding.replies_for(request_id).await?;

        // Look for an exit reply
        for reply in replies {
            if let Reply::WithExit(r) = reply {
                return match r.exit {
                    ExitResult::Success(bytes) => {
                        let result = rmp_serde::from_slice(&bytes).map_err(|e| {
                            ClusterError::MalformedMessage {
                                reason: format!("failed to deserialize poll response: {e}"),
                                source: Some(Box::new(e)),
                            }
                        })?;
                        Ok(Some(result))
                    }
                    ExitResult::Failure(msg) => Err(ClusterError::MalformedMessage {
                        reason: msg,
                        source: None,
                    }),
                };
            }
        }

        Ok(None)
    }

    /// Join (await) the result of a previously-started persisted request.
    ///
    /// Like [`poll_reply`](Self::poll_reply) but blocks until the result is
    /// available instead of returning `Option`. If the reply already exists in
    /// storage it is returned immediately; otherwise a live handler is
    /// registered and the call awaits the reply in real-time.
    ///
    /// The `key_bytes` are the same bytes used by `send_persisted`/`notify_persisted`
    /// for deterministic request ID derivation (typically the entity_id bytes for
    /// workflow executions).
    #[instrument(skip(self, key_bytes), fields(entity_type = %self.entity_type, entity_id = %entity_id))]
    pub async fn join_reply<Res>(
        &self,
        entity_id: &EntityId,
        tag: &str,
        key_bytes: &[u8],
    ) -> Result<Res, ClusterError>
    where
        Res: DeserializeOwned,
    {
        let request_id = persisted_request_id(&self.entity_type, entity_id, tag, key_bytes);
        let mut reply_rx = self.sharding.await_reply(request_id).await?;

        let reply = reply_rx
            .recv()
            .await
            .ok_or_else(|| ClusterError::MalformedMessage {
                reason: "reply channel closed without response".into(),
                source: None,
            })?;

        match reply {
            Reply::WithExit(r) => match r.exit {
                ExitResult::Success(bytes) => {
                    rmp_serde::from_slice(&bytes).map_err(|e| ClusterError::MalformedMessage {
                        reason: format!("failed to deserialize join response: {e}"),
                        source: Some(Box::new(e)),
                    })
                }
                ExitResult::Failure(msg) => Err(ClusterError::MalformedMessage {
                    reason: msg,
                    source: None,
                }),
            },
            Reply::Chunk(_) => Err(ClusterError::MalformedMessage {
                reason: "expected WithExit reply, got Chunk".into(),
                source: None,
            }),
        }
    }

    /// Get the entity type this client targets.
    pub fn entity_type(&self) -> &EntityType {
        &self.entity_type
    }

    #[instrument(level = "debug", skip(self, request), fields(entity_type = %self.entity_type, entity_id = %entity_id))]
    async fn build_envelope(
        &self,
        entity_id: &EntityId,
        tag: &str,
        request: &impl Serialize,
    ) -> Result<EnvelopeRequest, ClusterError> {
        let shard_id = self.sharding.get_shard_id(&self.entity_type, entity_id);

        let payload = rmp_serde::to_vec(request).map_err(|e| ClusterError::MalformedMessage {
            reason: format!("failed to serialize request: {e}"),
            source: Some(Box::new(e)),
        })?;

        Ok(EnvelopeRequest {
            request_id: self.sharding.snowflake().next_async().await?,
            address: crate::types::EntityAddress {
                shard_id,
                entity_type: self.entity_type.clone(),
                entity_id: entity_id.clone(),
            },
            tag: tag.to_string(),
            payload,
            headers: HashMap::new(),
            span_id: None,
            trace_id: None,
            sampled: None,
            persisted: false,
            uninterruptible: Default::default(),
            deliver_at: None,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::entity::Entity;
    use crate::envelope::{AckChunk, Interrupt};
    use crate::hash::shard_for_entity;
    use crate::message::ReplyReceiver;
    use crate::reply::{ReplyChunk, ReplyWithExit};
    use crate::sharding::ShardingRegistrationEvent;
    use crate::singleton::SingletonContext;
    use crate::snowflake::{Snowflake, SnowflakeGenerator};
    use crate::types::ShardId;
    use async_trait::async_trait;
    use futures::future::BoxFuture;
    use std::sync::Mutex;

    /// Minimal mock Sharding implementation for testing EntityClient.
    struct MockSharding {
        snowflake: SnowflakeGenerator,
        shards_per_group: i32,
    }

    impl MockSharding {
        fn new() -> Self {
            Self {
                snowflake: SnowflakeGenerator::new(),
                shards_per_group: 300,
            }
        }
    }

    struct CapturingSharding {
        inner: MockSharding,
        captured: Arc<Mutex<Vec<EnvelopeRequest>>>,
    }

    struct OutOfOrderSharding {
        inner: MockSharding,
    }

    struct MissingSequenceSharding {
        inner: MockSharding,
    }

    #[async_trait]
    impl Sharding for CapturingSharding {
        fn get_shard_id(&self, et: &EntityType, eid: &EntityId) -> ShardId {
            self.inner.get_shard_id(et, eid)
        }

        fn has_shard_id(&self, shard_id: &ShardId) -> bool {
            self.inner.has_shard_id(shard_id)
        }

        fn snowflake(&self) -> &SnowflakeGenerator {
            self.inner.snowflake()
        }

        fn is_shutdown(&self) -> bool {
            false
        }

        async fn register_entity(&self, _entity: Arc<dyn Entity>) -> Result<(), ClusterError> {
            Ok(())
        }

        async fn register_singleton(
            &self,
            _name: &str,
            _shard_group: Option<&str>,
            _run: Arc<
                dyn Fn(SingletonContext) -> BoxFuture<'static, Result<(), ClusterError>>
                    + Send
                    + Sync,
            >,
        ) -> Result<(), ClusterError> {
            Ok(())
        }

        fn make_client(self: Arc<Self>, entity_type: EntityType) -> EntityClient {
            EntityClient::new(self, entity_type)
        }

        async fn send(&self, envelope: EnvelopeRequest) -> Result<ReplyReceiver, ClusterError> {
            self.captured.lock().unwrap().push(envelope.clone());
            self.inner.send(envelope).await
        }

        async fn notify(&self, envelope: EnvelopeRequest) -> Result<(), ClusterError> {
            self.captured.lock().unwrap().push(envelope);
            Ok(())
        }

        async fn ack_chunk(&self, _ack: AckChunk) -> Result<(), ClusterError> {
            Ok(())
        }

        async fn interrupt(&self, _interrupt: Interrupt) -> Result<(), ClusterError> {
            Ok(())
        }

        async fn poll_storage(&self) -> Result<(), ClusterError> {
            Ok(())
        }

        fn active_entity_count(&self) -> usize {
            0
        }

        async fn registration_events(
            &self,
        ) -> Pin<Box<dyn Stream<Item = ShardingRegistrationEvent> + Send>> {
            Box::pin(tokio_stream::empty())
        }

        async fn shutdown(&self) -> Result<(), ClusterError> {
            Ok(())
        }
    }

    #[async_trait]
    impl Sharding for MockSharding {
        fn get_shard_id(&self, _entity_type: &EntityType, entity_id: &EntityId) -> ShardId {
            let shard = shard_for_entity(entity_id.as_ref(), self.shards_per_group);
            ShardId::new("default", shard)
        }

        fn has_shard_id(&self, _shard_id: &ShardId) -> bool {
            true
        }

        fn snowflake(&self) -> &SnowflakeGenerator {
            &self.snowflake
        }

        fn is_shutdown(&self) -> bool {
            false
        }

        async fn register_entity(&self, _entity: Arc<dyn Entity>) -> Result<(), ClusterError> {
            Ok(())
        }

        async fn register_singleton(
            &self,
            _name: &str,
            _shard_group: Option<&str>,
            _run: Arc<
                dyn Fn(SingletonContext) -> BoxFuture<'static, Result<(), ClusterError>>
                    + Send
                    + Sync,
            >,
        ) -> Result<(), ClusterError> {
            Ok(())
        }

        fn make_client(self: Arc<Self>, entity_type: EntityType) -> EntityClient {
            EntityClient::new(self, entity_type)
        }

        async fn send(&self, envelope: EnvelopeRequest) -> Result<ReplyReceiver, ClusterError> {
            // Echo back the payload as a success reply
            let (tx, rx) = tokio::sync::mpsc::channel(1);
            let reply = Reply::WithExit(ReplyWithExit {
                request_id: envelope.request_id,
                id: self.snowflake.next_async().await?,
                exit: ExitResult::Success(envelope.payload),
            });
            tx.send(reply).await.unwrap();
            Ok(rx)
        }

        async fn notify(&self, _envelope: EnvelopeRequest) -> Result<(), ClusterError> {
            Ok(())
        }

        async fn ack_chunk(&self, _ack: AckChunk) -> Result<(), ClusterError> {
            Ok(())
        }

        async fn interrupt(&self, _interrupt: Interrupt) -> Result<(), ClusterError> {
            Ok(())
        }

        async fn poll_storage(&self) -> Result<(), ClusterError> {
            Ok(())
        }

        fn active_entity_count(&self) -> usize {
            0
        }

        async fn registration_events(
            &self,
        ) -> Pin<Box<dyn Stream<Item = ShardingRegistrationEvent> + Send>> {
            Box::pin(tokio_stream::empty())
        }

        async fn shutdown(&self) -> Result<(), ClusterError> {
            Ok(())
        }
    }

    #[async_trait]
    impl Sharding for OutOfOrderSharding {
        fn get_shard_id(&self, et: &EntityType, eid: &EntityId) -> ShardId {
            self.inner.get_shard_id(et, eid)
        }

        fn has_shard_id(&self, shard_id: &ShardId) -> bool {
            self.inner.has_shard_id(shard_id)
        }

        fn snowflake(&self) -> &SnowflakeGenerator {
            self.inner.snowflake()
        }

        fn is_shutdown(&self) -> bool {
            false
        }

        async fn register_entity(&self, _entity: Arc<dyn Entity>) -> Result<(), ClusterError> {
            Ok(())
        }

        async fn register_singleton(
            &self,
            _name: &str,
            _shard_group: Option<&str>,
            _run: Arc<
                dyn Fn(SingletonContext) -> BoxFuture<'static, Result<(), ClusterError>>
                    + Send
                    + Sync,
            >,
        ) -> Result<(), ClusterError> {
            Ok(())
        }

        fn make_client(self: Arc<Self>, entity_type: EntityType) -> EntityClient {
            EntityClient::new(self, entity_type)
        }

        async fn send(&self, envelope: EnvelopeRequest) -> Result<ReplyReceiver, ClusterError> {
            let (tx, rx) = tokio::sync::mpsc::channel(4);
            let request_id = envelope.request_id;
            tokio::spawn(async move {
                let chunk_one = Reply::Chunk(ReplyChunk {
                    request_id,
                    id: Snowflake(1),
                    sequence: 1,
                    values: vec![rmp_serde::to_vec(&1i32).unwrap()],
                });
                let exit = Reply::WithExit(ReplyWithExit {
                    request_id,
                    id: Snowflake(2),
                    exit: ExitResult::Success(rmp_serde::to_vec(&2i32).unwrap()),
                });
                let chunk_zero = Reply::Chunk(ReplyChunk {
                    request_id,
                    id: Snowflake(3),
                    sequence: 0,
                    values: vec![rmp_serde::to_vec(&0i32).unwrap()],
                });
                tx.send(chunk_one).await.unwrap();
                tx.send(exit).await.unwrap();
                tx.send(chunk_zero).await.unwrap();
            });
            Ok(rx)
        }

        async fn notify(&self, _envelope: EnvelopeRequest) -> Result<(), ClusterError> {
            Ok(())
        }

        async fn ack_chunk(&self, _ack: AckChunk) -> Result<(), ClusterError> {
            Ok(())
        }

        async fn interrupt(&self, _interrupt: Interrupt) -> Result<(), ClusterError> {
            Ok(())
        }

        async fn poll_storage(&self) -> Result<(), ClusterError> {
            Ok(())
        }

        fn active_entity_count(&self) -> usize {
            0
        }

        async fn registration_events(
            &self,
        ) -> Pin<Box<dyn Stream<Item = ShardingRegistrationEvent> + Send>> {
            Box::pin(tokio_stream::empty())
        }

        async fn shutdown(&self) -> Result<(), ClusterError> {
            Ok(())
        }
    }

    #[async_trait]
    impl Sharding for MissingSequenceSharding {
        fn get_shard_id(&self, et: &EntityType, eid: &EntityId) -> ShardId {
            self.inner.get_shard_id(et, eid)
        }

        fn has_shard_id(&self, shard_id: &ShardId) -> bool {
            self.inner.has_shard_id(shard_id)
        }

        fn snowflake(&self) -> &SnowflakeGenerator {
            self.inner.snowflake()
        }

        fn is_shutdown(&self) -> bool {
            false
        }

        async fn register_entity(&self, _entity: Arc<dyn Entity>) -> Result<(), ClusterError> {
            Ok(())
        }

        async fn register_singleton(
            &self,
            _name: &str,
            _shard_group: Option<&str>,
            _run: Arc<
                dyn Fn(SingletonContext) -> BoxFuture<'static, Result<(), ClusterError>>
                    + Send
                    + Sync,
            >,
        ) -> Result<(), ClusterError> {
            Ok(())
        }

        fn make_client(self: Arc<Self>, entity_type: EntityType) -> EntityClient {
            EntityClient::new(self, entity_type)
        }

        async fn send(&self, envelope: EnvelopeRequest) -> Result<ReplyReceiver, ClusterError> {
            let (tx, rx) = tokio::sync::mpsc::channel(2);
            let request_id = envelope.request_id;
            tokio::spawn(async move {
                let chunk_one = Reply::Chunk(ReplyChunk {
                    request_id,
                    id: Snowflake(10),
                    sequence: 1,
                    values: vec![rmp_serde::to_vec(&1i32).unwrap()],
                });
                let exit = Reply::WithExit(ReplyWithExit {
                    request_id,
                    id: Snowflake(11),
                    exit: ExitResult::Success(rmp_serde::to_vec(&2i32).unwrap()),
                });
                tx.send(chunk_one).await.unwrap();
                tx.send(exit).await.unwrap();
            });
            Ok(rx)
        }

        async fn notify(&self, _envelope: EnvelopeRequest) -> Result<(), ClusterError> {
            Ok(())
        }

        async fn ack_chunk(&self, _ack: AckChunk) -> Result<(), ClusterError> {
            Ok(())
        }

        async fn interrupt(&self, _interrupt: Interrupt) -> Result<(), ClusterError> {
            Ok(())
        }

        async fn poll_storage(&self) -> Result<(), ClusterError> {
            Ok(())
        }

        fn active_entity_count(&self) -> usize {
            0
        }

        async fn registration_events(
            &self,
        ) -> Pin<Box<dyn Stream<Item = ShardingRegistrationEvent> + Send>> {
            Box::pin(tokio_stream::empty())
        }

        async fn shutdown(&self) -> Result<(), ClusterError> {
            Ok(())
        }
    }

    #[tokio::test]
    async fn send_request_and_receive_response() {
        let sharding: Arc<dyn Sharding> = Arc::new(MockSharding::new());
        let client = EntityClient::new(Arc::clone(&sharding), EntityType::new("Counter"));

        let entity_id = EntityId::new("c-1");
        // Send i32, expect same bytes back deserialized as i32
        let result: i32 = client.send(&entity_id, "increment", &42i32).await.unwrap();
        assert_eq!(result, 42);
    }

    #[tokio::test]
    async fn notify_succeeds() {
        let sharding: Arc<dyn Sharding> = Arc::new(MockSharding::new());
        let client = EntityClient::new(Arc::clone(&sharding), EntityType::new("Counter"));

        let entity_id = EntityId::new("c-1");
        client.notify(&entity_id, "ping", &()).await.unwrap();
    }

    #[tokio::test]
    async fn entity_type_accessor() {
        let sharding: Arc<dyn Sharding> = Arc::new(MockSharding::new());
        let client = EntityClient::new(Arc::clone(&sharding), EntityType::new("Order"));
        assert_eq!(client.entity_type(), &EntityType::new("Order"));
    }

    #[tokio::test]
    async fn build_envelope_uses_correct_shard() {
        let sharding: Arc<dyn Sharding> = Arc::new(MockSharding::new());
        let client = EntityClient::new(Arc::clone(&sharding), EntityType::new("User"));

        let entity_id = EntityId::new("u-123");
        let envelope = client
            .build_envelope(&entity_id, "getProfile", &())
            .await
            .unwrap();

        // Verify the envelope fields
        assert_eq!(envelope.address.entity_type, EntityType::new("User"));
        assert_eq!(envelope.address.entity_id, EntityId::new("u-123"));
        assert_eq!(envelope.tag, "getProfile");
        assert_eq!(envelope.address.shard_id.group, "default");
        // Shard ID should be deterministic
        let expected_shard = shard_for_entity("u-123", 300);
        assert_eq!(envelope.address.shard_id.id, expected_shard);
    }

    #[tokio::test]
    async fn send_persisted_request() {
        let sharding: Arc<dyn Sharding> = Arc::new(MockSharding::new());
        let client = EntityClient::new(Arc::clone(&sharding), EntityType::new("Counter"));

        let entity_id = EntityId::new("c-1");
        let result: i32 = client
            .send_persisted(
                &entity_id,
                "increment",
                &42i32,
                crate::schema::Uninterruptible::Server,
            )
            .await
            .unwrap();
        assert_eq!(result, 42);
    }

    #[tokio::test]
    async fn send_persisted_is_deterministic_for_same_payload() {
        let captured = Arc::new(Mutex::new(Vec::new()));
        let sharding: Arc<dyn Sharding> = Arc::new(CapturingSharding {
            inner: MockSharding::new(),
            captured: Arc::clone(&captured),
        });
        let client = EntityClient::new(Arc::clone(&sharding), EntityType::new("Counter"));

        let entity_id = EntityId::new("c-1");
        let _: i32 = client
            .send_persisted(
                &entity_id,
                "increment",
                &42i32,
                crate::schema::Uninterruptible::No,
            )
            .await
            .unwrap();
        let _: i32 = client
            .send_persisted(
                &entity_id,
                "increment",
                &42i32,
                crate::schema::Uninterruptible::No,
            )
            .await
            .unwrap();

        let captured = captured.lock().unwrap();
        assert_eq!(captured.len(), 2);
        assert_eq!(captured[0].request_id, captured[1].request_id);
    }

    #[tokio::test]
    async fn send_persisted_with_key_overrides_payload_hash() {
        let captured = Arc::new(Mutex::new(Vec::new()));
        let sharding: Arc<dyn Sharding> = Arc::new(CapturingSharding {
            inner: MockSharding::new(),
            captured: Arc::clone(&captured),
        });
        let client = EntityClient::new(Arc::clone(&sharding), EntityType::new("Counter"));

        let entity_id = EntityId::new("c-1");
        let key_bytes = rmp_serde::to_vec(&"key").unwrap();
        let _: i32 = client
            .send_persisted_with_key(
                &entity_id,
                "increment",
                &42i32,
                Some(key_bytes.clone()),
                crate::schema::Uninterruptible::No,
            )
            .await
            .unwrap();
        let _: i32 = client
            .send_persisted_with_key(
                &entity_id,
                "increment",
                &43i32,
                Some(key_bytes),
                crate::schema::Uninterruptible::No,
            )
            .await
            .unwrap();

        let captured = captured.lock().unwrap();
        assert_eq!(captured.len(), 2);
        assert_eq!(captured[0].request_id, captured[1].request_id);
    }

    #[tokio::test]
    async fn notify_persisted_succeeds() {
        let sharding: Arc<dyn Sharding> = Arc::new(MockSharding::new());
        let client = EntityClient::new(Arc::clone(&sharding), EntityType::new("Counter"));

        let entity_id = EntityId::new("c-1");
        client
            .notify_persisted(&entity_id, "ping", &())
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn send_at_sets_deliver_at_and_persisted() {
        use std::sync::Mutex;

        let captured: Arc<Mutex<Vec<EnvelopeRequest>>> = Arc::new(Mutex::new(Vec::new()));

        struct CapturingSharding {
            inner: MockSharding,
            captured: Arc<Mutex<Vec<EnvelopeRequest>>>,
        }

        #[async_trait]
        impl Sharding for CapturingSharding {
            fn get_shard_id(&self, et: &EntityType, eid: &EntityId) -> crate::types::ShardId {
                self.inner.get_shard_id(et, eid)
            }
            fn has_shard_id(&self, sid: &crate::types::ShardId) -> bool {
                self.inner.has_shard_id(sid)
            }
            fn snowflake(&self) -> &crate::snowflake::SnowflakeGenerator {
                self.inner.snowflake()
            }
            fn is_shutdown(&self) -> bool {
                false
            }
            async fn register_entity(
                &self,
                _: Arc<dyn crate::entity::Entity>,
            ) -> Result<(), ClusterError> {
                Ok(())
            }
            async fn register_singleton(
                &self,
                _: &str,
                _: Option<&str>,
                _: Arc<
                    dyn Fn(SingletonContext) -> BoxFuture<'static, Result<(), ClusterError>>
                        + Send
                        + Sync,
                >,
            ) -> Result<(), ClusterError> {
                Ok(())
            }
            fn make_client(self: Arc<Self>, et: EntityType) -> EntityClient {
                EntityClient::new(self, et)
            }
            async fn send(&self, envelope: EnvelopeRequest) -> Result<ReplyReceiver, ClusterError> {
                self.captured.lock().unwrap().push(envelope.clone());
                self.inner.send(envelope).await
            }
            async fn notify(&self, envelope: EnvelopeRequest) -> Result<(), ClusterError> {
                self.captured.lock().unwrap().push(envelope);
                Ok(())
            }
            async fn ack_chunk(&self, _: AckChunk) -> Result<(), ClusterError> {
                Ok(())
            }
            async fn interrupt(&self, _: Interrupt) -> Result<(), ClusterError> {
                Ok(())
            }
            async fn poll_storage(&self) -> Result<(), ClusterError> {
                Ok(())
            }
            fn active_entity_count(&self) -> usize {
                0
            }
            async fn registration_events(
                &self,
            ) -> Pin<Box<dyn Stream<Item = ShardingRegistrationEvent> + Send>> {
                Box::pin(tokio_stream::empty())
            }
            async fn shutdown(&self) -> Result<(), ClusterError> {
                Ok(())
            }
        }

        let sharding: Arc<dyn Sharding> = Arc::new(CapturingSharding {
            inner: MockSharding::new(),
            captured: captured.clone(),
        });
        let client = EntityClient::new(Arc::clone(&sharding), EntityType::new("Counter"));

        let entity_id = EntityId::new("c-1");
        let deliver_time = chrono::Utc::now() + chrono::Duration::hours(1);
        let _result: i32 = client
            .send_at(&entity_id, "increment", &42i32, deliver_time)
            .await
            .unwrap();

        let captured = captured.lock().unwrap();
        assert_eq!(captured.len(), 1);
        assert!(captured[0].persisted);
        assert_eq!(captured[0].deliver_at, Some(deliver_time));
    }

    #[tokio::test]
    async fn notify_at_sets_deliver_at_and_persisted() {
        let sharding: Arc<dyn Sharding> = Arc::new(MockSharding::new());
        let client = EntityClient::new(Arc::clone(&sharding), EntityType::new("Counter"));

        let entity_id = EntityId::new("c-1");
        let deliver_time = chrono::Utc::now() + chrono::Duration::hours(1);
        client
            .notify_at(&entity_id, "ping", &(), deliver_time)
            .await
            .unwrap();
        // notify_at doesn't capture, but we can verify it doesn't error
    }

    #[tokio::test]
    async fn send_stream_returns_stream() {
        use tokio_stream::StreamExt;

        let sharding: Arc<dyn Sharding> = Arc::new(MockSharding::new());
        let client = EntityClient::new(Arc::clone(&sharding), EntityType::new("Counter"));

        let entity_id = EntityId::new("c-1");
        // MockSharding.send returns a WithExit reply, which send_stream handles
        let mut stream = client
            .send_stream::<i32, i32>(&entity_id, "count", &99)
            .await
            .unwrap();

        let first = stream.next().await.unwrap().unwrap();
        assert_eq!(first, 99);
    }

    #[tokio::test]
    async fn send_stream_orders_chunks_by_sequence() {
        use tokio_stream::StreamExt;

        let sharding: Arc<dyn Sharding> = Arc::new(OutOfOrderSharding {
            inner: MockSharding::new(),
        });
        let client = EntityClient::new(Arc::clone(&sharding), EntityType::new("Counter"));

        let entity_id = EntityId::new("c-1");
        let mut stream = client
            .send_stream::<i32, i32>(&entity_id, "count", &99)
            .await
            .unwrap();

        let mut items = Vec::new();
        while let Some(item) = stream.next().await {
            items.push(item.unwrap());
        }

        assert_eq!(items, vec![0, 1, 2]);
    }

    #[tokio::test]
    async fn send_stream_flushes_missing_sequences_on_close() {
        use tokio_stream::StreamExt;

        let sharding: Arc<dyn Sharding> = Arc::new(MissingSequenceSharding {
            inner: MockSharding::new(),
        });
        let client = EntityClient::new(Arc::clone(&sharding), EntityType::new("Counter"));

        let entity_id = EntityId::new("c-1");
        let mut stream = client
            .send_stream::<i32, i32>(&entity_id, "count", &99)
            .await
            .unwrap();

        let mut items = Vec::new();
        while let Some(item) = stream.next().await {
            items.push(item.unwrap());
        }

        assert_eq!(items, vec![1, 2]);
    }

    #[tokio::test]
    async fn build_envelope_without_otel_sets_none_trace_context() {
        // Without an OTel subscriber layer, trace context fields should be None.
        let sharding: Arc<dyn Sharding> = Arc::new(MockSharding::new());
        let client = EntityClient::new(Arc::clone(&sharding), EntityType::new("User"));

        let entity_id = EntityId::new("u-1");
        let envelope = client
            .build_envelope(&entity_id, "test", &())
            .await
            .unwrap();

        // No OTel subscriber configured, so trace context should be None
        assert_eq!(envelope.trace_id, None);
        assert_eq!(envelope.span_id, None);
        assert_eq!(envelope.sampled, None);
    }
}