-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathclient_events.rs
More file actions
1818 lines (1682 loc) · 72.5 KB
/
client_events.rs
File metadata and controls
1818 lines (1682 loc) · 72.5 KB
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
use bytes::Bytes;
use flatbuffers::WIPOffset;
use std::borrow::Cow;
use std::fmt::Display;
use std::net::SocketAddr;
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use crate::client_api::TryFromFbs;
use crate::generated::client_request::{
root_as_client_request, ClientRequestType, ContractRequest as FbsContractRequest,
ContractRequestType, DelegateRequest as FbsDelegateRequest, DelegateRequestType,
};
use crate::generated::common::{
ApplicationMessage as FbsApplicationMessage, ApplicationMessageArgs, ContractCode,
ContractCodeArgs, ContractContainer as FbsContractContainer, ContractContainerArgs,
ContractInstanceId as FbsContractInstanceId, ContractInstanceIdArgs,
ContractKey as FbsContractKey, ContractKeyArgs, ContractType, DeltaUpdate, DeltaUpdateArgs,
RelatedDeltaUpdate, RelatedDeltaUpdateArgs, RelatedStateAndDeltaUpdate,
RelatedStateAndDeltaUpdateArgs, RelatedStateUpdate, RelatedStateUpdateArgs,
StateAndDeltaUpdate, StateAndDeltaUpdateArgs, StateUpdate, StateUpdateArgs,
UpdateData as FbsUpdateData, UpdateDataArgs, UpdateDataType, WasmContractV1,
WasmContractV1Args,
};
use crate::generated::host_response::{
finish_host_response_buffer, ClientResponse as FbsClientResponse, ClientResponseArgs,
ContextUpdated as FbsContextUpdated, ContextUpdatedArgs,
ContractResponse as FbsContractResponse, ContractResponseArgs, ContractResponseType,
DelegateKey as FbsDelegateKey, DelegateKeyArgs, DelegateResponse as FbsDelegateResponse,
DelegateResponseArgs, GetResponse as FbsGetResponse, GetResponseArgs,
HostResponse as FbsHostResponse, HostResponseArgs, HostResponseType, NotFound as FbsNotFound,
NotFoundArgs, Ok as FbsOk, OkArgs, OutboundDelegateMsg as FbsOutboundDelegateMsg,
OutboundDelegateMsgArgs, OutboundDelegateMsgType, PutResponse as FbsPutResponse,
PutResponseArgs, RequestUserInput as FbsRequestUserInput, RequestUserInputArgs,
StreamChunk as FbsHostStreamChunk, StreamChunkArgs as FbsHostStreamChunkArgs,
UpdateNotification as FbsUpdateNotification, UpdateNotificationArgs,
UpdateResponse as FbsUpdateResponse, UpdateResponseArgs,
};
use crate::prelude::ContractContainer::Wasm;
use crate::prelude::ContractWasmAPIVersion::V1;
use crate::prelude::UpdateData::{
Delta, RelatedDelta, RelatedState, RelatedStateAndDelta, State, StateAndDelta,
};
use crate::{
delegate_interface::{DelegateKey, InboundDelegateMsg, OutboundDelegateMsg},
prelude::{
ContractInstanceId, ContractKey, DelegateContainer, Parameters, RelatedContracts,
SecretsId, StateSummary, UpdateData, WrappedState,
},
versioning::ContractContainer,
};
use super::WsApiError;
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct ClientError {
kind: Box<ErrorKind>,
}
impl ClientError {
pub fn into_fbs_bytes(self) -> Result<Vec<u8>, Box<ClientError>> {
use crate::generated::host_response::{Error, ErrorArgs};
let mut builder = flatbuffers::FlatBufferBuilder::new();
let msg_offset = builder.create_string(&self.to_string());
let err_offset = Error::create(
&mut builder,
&ErrorArgs {
msg: Some(msg_offset),
},
);
let host_response_offset = FbsHostResponse::create(
&mut builder,
&HostResponseArgs {
response_type: HostResponseType::Ok,
response: Some(err_offset.as_union_value()),
},
);
finish_host_response_buffer(&mut builder, host_response_offset);
Ok(builder.finished_data().to_vec())
}
pub fn kind(&self) -> &ErrorKind {
&self.kind
}
}
impl From<ErrorKind> for ClientError {
fn from(kind: ErrorKind) -> Self {
ClientError {
kind: Box::new(kind),
}
}
}
impl<T: Into<Cow<'static, str>>> From<T> for ClientError {
fn from(cause: T) -> Self {
ClientError {
kind: Box::new(ErrorKind::Unhandled {
cause: cause.into(),
}),
}
}
}
#[derive(thiserror::Error, Debug, Serialize, Deserialize, Clone)]
#[non_exhaustive]
pub enum ErrorKind {
#[error("comm channel between client/host closed")]
ChannelClosed,
#[error("error while deserializing: {cause}")]
DeserializationError { cause: Cow<'static, str> },
#[error("client disconnected")]
Disconnect,
#[error("failed while trying to unpack state for {0}")]
IncorrectState(ContractKey),
#[error("node not available")]
NodeUnavailable,
#[error("lost the connection with the protocol handling connections")]
TransportProtocolDisconnect,
#[error("unhandled error: {cause}")]
Unhandled { cause: Cow<'static, str> },
#[error("unknown client id: {0}")]
UnknownClient(usize),
#[error(transparent)]
RequestError(#[from] RequestError),
#[error("error while executing operation in the network: {cause}")]
OperationError { cause: Cow<'static, str> },
// TODO: identify requests by some id so we can inform clients which one failed exactly
#[error("operation timed out")]
FailedOperation,
#[error("peer should shutdown")]
Shutdown,
#[error("no ring connections found")]
EmptyRing,
#[error("peer has not joined the network yet")]
PeerNotJoined,
}
impl Display for ClientError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "client error: {}", self.kind)
}
}
impl std::error::Error for ClientError {}
#[derive(Debug, thiserror::Error, Serialize, Deserialize, Clone)]
#[non_exhaustive]
pub enum RequestError {
#[error(transparent)]
ContractError(#[from] ContractError),
#[error(transparent)]
DelegateError(#[from] DelegateError),
#[error("client disconnect")]
Disconnect,
#[error("operation timed out")]
Timeout,
}
/// Errors that may happen while interacting with delegates.
#[derive(Debug, thiserror::Error, Serialize, Deserialize, Clone)]
#[non_exhaustive]
pub enum DelegateError {
#[error("error while registering delegate {0}")]
RegisterError(DelegateKey),
#[error("execution error, cause {0}")]
ExecutionError(Cow<'static, str>),
#[error("missing delegate {0}")]
Missing(DelegateKey),
#[error("missing secret `{secret}` for delegate {key}")]
MissingSecret { key: DelegateKey, secret: SecretsId },
#[error("forbidden access to secret: {0}")]
ForbiddenSecretAccess(SecretsId),
}
/// Errors that may happen while interacting with contracts.
#[derive(Debug, thiserror::Error, Serialize, Deserialize, Clone)]
#[non_exhaustive]
pub enum ContractError {
#[error("failed to get contract {key}, reason: {cause}")]
Get {
key: ContractKey,
cause: Cow<'static, str>,
},
#[error("put error for contract {key}, reason: {cause}")]
Put {
key: ContractKey,
cause: Cow<'static, str>,
},
#[error("update error for contract {key}, reason: {cause}")]
Update {
key: ContractKey,
cause: Cow<'static, str>,
},
#[error("failed to subscribe for contract {key}, reason: {cause}")]
Subscribe {
key: ContractKey,
cause: Cow<'static, str>,
},
// todo: actually build a stack of the involved keys
#[error("dependency contract stack overflow : {key}")]
ContractStackOverflow {
key: crate::contract_interface::ContractInstanceId,
},
#[error("missing related contract: {key}")]
MissingRelated {
key: crate::contract_interface::ContractInstanceId,
},
#[error("missing contract: {key}")]
MissingContract {
key: crate::contract_interface::ContractInstanceId,
},
}
impl ContractError {
const EXECUTION_ERROR: &'static str = "execution error";
const INVALID_PUT: &'static str = "invalid put";
pub fn update_exec_error(key: ContractKey, additional_info: impl std::fmt::Display) -> Self {
Self::Update {
key,
cause: format!(
"{exec_err}: {additional_info}",
exec_err = Self::EXECUTION_ERROR
)
.into(),
}
}
pub fn invalid_put(key: ContractKey) -> Self {
Self::Put {
key,
cause: Self::INVALID_PUT.into(),
}
}
pub fn invalid_update(key: ContractKey) -> Self {
Self::Update {
key,
cause: Self::INVALID_PUT.into(),
}
}
}
/// A request from a client application to the host.
#[derive(Serialize, Deserialize, Debug, Clone)]
#[non_exhaustive]
// #[cfg_attr(test, derive(arbitrary::Arbitrary))]
pub enum ClientRequest<'a> {
DelegateOp(#[serde(borrow)] DelegateRequest<'a>),
ContractOp(#[serde(borrow)] ContractRequest<'a>),
Disconnect {
cause: Option<Cow<'static, str>>,
},
Authenticate {
token: String,
},
NodeQueries(NodeQuery),
/// Gracefully disconnect from the host.
Close,
/// A chunk of a larger streamed message.
StreamChunk {
stream_id: u32,
index: u32,
total: u32,
data: Bytes,
},
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct ConnectedPeers {}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct NodeDiagnostics {
/// Optional contract key to filter diagnostics for specific contract
pub contract_key: Option<ContractKey>,
}
impl ClientRequest<'_> {
pub fn into_owned(self) -> ClientRequest<'static> {
match self {
ClientRequest::ContractOp(op) => {
let owned = match op {
ContractRequest::Put {
contract,
state,
related_contracts,
subscribe,
blocking_subscribe,
} => {
let related_contracts = related_contracts.into_owned();
ContractRequest::Put {
contract,
state,
related_contracts,
subscribe,
blocking_subscribe,
}
}
ContractRequest::Update { key, data } => {
let data = data.into_owned();
ContractRequest::Update { key, data }
}
ContractRequest::Get {
key,
return_contract_code,
subscribe,
blocking_subscribe,
} => ContractRequest::Get {
key,
return_contract_code,
subscribe,
blocking_subscribe,
},
ContractRequest::Subscribe { key, summary } => ContractRequest::Subscribe {
key,
summary: summary.map(StateSummary::into_owned),
},
};
owned.into()
}
ClientRequest::DelegateOp(op) => {
let op = op.into_owned();
ClientRequest::DelegateOp(op)
}
ClientRequest::Disconnect { cause } => ClientRequest::Disconnect { cause },
ClientRequest::Authenticate { token } => ClientRequest::Authenticate { token },
ClientRequest::NodeQueries(query) => ClientRequest::NodeQueries(query),
ClientRequest::Close => ClientRequest::Close,
ClientRequest::StreamChunk {
stream_id,
index,
total,
data,
} => ClientRequest::StreamChunk {
stream_id,
index,
total,
data,
},
}
}
pub fn is_disconnect(&self) -> bool {
matches!(self, Self::Disconnect { .. })
}
pub fn try_decode_fbs(msg: &[u8]) -> Result<ClientRequest<'_>, WsApiError> {
let req = {
match root_as_client_request(msg) {
Ok(client_request) => match client_request.client_request_type() {
ClientRequestType::ContractRequest => {
let contract_request =
client_request.client_request_as_contract_request().unwrap();
ContractRequest::try_decode_fbs(&contract_request)?.into()
}
ClientRequestType::DelegateRequest => {
let delegate_request =
client_request.client_request_as_delegate_request().unwrap();
DelegateRequest::try_decode_fbs(&delegate_request)?.into()
}
ClientRequestType::Disconnect => {
let delegate_request =
client_request.client_request_as_disconnect().unwrap();
let cause = delegate_request
.cause()
.map(|cause_msg| cause_msg.to_string().into());
ClientRequest::Disconnect { cause }
}
ClientRequestType::Authenticate => {
let auth_req = client_request.client_request_as_authenticate().unwrap();
let token = auth_req.token();
ClientRequest::Authenticate {
token: token.to_owned(),
}
}
ClientRequestType::StreamChunk => {
let chunk = client_request.client_request_as_stream_chunk().unwrap();
ClientRequest::StreamChunk {
stream_id: chunk.stream_id(),
index: chunk.index(),
total: chunk.total(),
data: Bytes::from(chunk.data().bytes().to_vec()),
}
}
_ => {
return Err(WsApiError::deserialization(
"unknown client request type".to_string(),
))
}
},
Err(e) => {
let cause = format!("{e}");
return Err(WsApiError::deserialization(cause));
}
}
};
Ok(req)
}
}
#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum ContractRequest<'a> {
/// Insert a new value in a contract corresponding with the provided key.
Put {
contract: ContractContainer,
/// Value to upsert in the contract.
state: WrappedState,
/// Related contracts.
#[serde(borrow)]
related_contracts: RelatedContracts<'a>,
/// If this flag is set then subscribe to updates for this contract.
subscribe: bool,
/// If true, the PUT response waits for the subscription to complete.
/// Only meaningful when `subscribe` is true.
#[serde(default)]
blocking_subscribe: bool,
},
/// Update an existing contract corresponding with the provided key.
Update {
key: ContractKey,
#[serde(borrow)]
data: UpdateData<'a>,
},
/// Fetch the current state from a contract corresponding to the provided key.
Get {
/// Instance ID of the contract (the hash of code + params).
/// Only the instance ID is needed since the client doesn't have the code hash yet.
key: ContractInstanceId,
/// If this flag is set then fetch also the contract itself.
return_contract_code: bool,
/// If this flag is set then subscribe to updates for this contract.
subscribe: bool,
/// If true, the GET response waits for the subscription to complete.
/// Only meaningful when `subscribe` is true.
#[serde(default)]
blocking_subscribe: bool,
},
/// Subscribe to the changes in a given contract. Implicitly starts a get operation
/// if the contract is not present yet.
Subscribe {
/// Instance ID of the contract.
key: ContractInstanceId,
summary: Option<StateSummary<'a>>,
},
}
impl ContractRequest<'_> {
pub fn into_owned(self) -> ContractRequest<'static> {
match self {
Self::Put {
contract,
state,
related_contracts,
subscribe,
blocking_subscribe,
} => ContractRequest::Put {
contract,
state,
related_contracts: related_contracts.into_owned(),
subscribe,
blocking_subscribe,
},
Self::Update { key, data } => ContractRequest::Update {
key,
data: data.into_owned(),
},
Self::Get {
key,
return_contract_code: fetch_contract,
subscribe,
blocking_subscribe,
} => ContractRequest::Get {
key,
return_contract_code: fetch_contract,
subscribe,
blocking_subscribe,
},
Self::Subscribe { key, summary } => ContractRequest::Subscribe {
key,
summary: summary.map(StateSummary::into_owned),
},
}
}
}
impl<'a> From<ContractRequest<'a>> for ClientRequest<'a> {
fn from(op: ContractRequest<'a>) -> Self {
ClientRequest::ContractOp(op)
}
}
/// Deserializes a `ContractRequest` from a Flatbuffers message.
impl<'a> TryFromFbs<&FbsContractRequest<'a>> for ContractRequest<'a> {
fn try_decode_fbs(request: &FbsContractRequest<'a>) -> Result<Self, WsApiError> {
let req = {
match request.contract_request_type() {
ContractRequestType::Get => {
let get = request.contract_request_as_get().unwrap();
// Extract just the instance ID - GET only needs the instance ID,
// not the full key (which may not be complete on the client side)
let fbs_key = get.key();
let key_bytes: [u8; 32] = fbs_key.instance().data().bytes().try_into().unwrap();
let key = ContractInstanceId::new(key_bytes);
let fetch_contract = get.fetch_contract();
let subscribe = get.subscribe();
let blocking_subscribe = get.blocking_subscribe();
ContractRequest::Get {
key,
return_contract_code: fetch_contract,
subscribe,
blocking_subscribe,
}
}
ContractRequestType::Put => {
let put = request.contract_request_as_put().unwrap();
let contract = ContractContainer::try_decode_fbs(&put.container())?;
let state = WrappedState::new(put.wrapped_state().bytes().to_vec());
let related_contracts =
RelatedContracts::try_decode_fbs(&put.related_contracts())?.into_owned();
let subscribe = put.subscribe();
let blocking_subscribe = put.blocking_subscribe();
ContractRequest::Put {
contract,
state,
related_contracts,
subscribe,
blocking_subscribe,
}
}
ContractRequestType::Update => {
let update = request.contract_request_as_update().unwrap();
let key = ContractKey::try_decode_fbs(&update.key())?;
let data = UpdateData::try_decode_fbs(&update.data())?.into_owned();
ContractRequest::Update { key, data }
}
ContractRequestType::Subscribe => {
let subscribe = request.contract_request_as_subscribe().unwrap();
// Extract just the instance ID for Subscribe
let fbs_key = subscribe.key();
let key_bytes: [u8; 32] = fbs_key.instance().data().bytes().try_into().unwrap();
let key = ContractInstanceId::new(key_bytes);
let summary = subscribe
.summary()
.map(|summary_data| StateSummary::from(summary_data.bytes()));
ContractRequest::Subscribe { key, summary }
}
_ => unreachable!(),
}
};
Ok(req)
}
}
impl<'a> From<DelegateRequest<'a>> for ClientRequest<'a> {
fn from(op: DelegateRequest<'a>) -> Self {
ClientRequest::DelegateOp(op)
}
}
#[derive(Serialize, Deserialize, Debug, Clone)]
#[non_exhaustive]
pub enum DelegateRequest<'a> {
ApplicationMessages {
key: DelegateKey,
#[serde(deserialize_with = "Parameters::deser_params")]
params: Parameters<'a>,
#[serde(borrow)]
inbound: Vec<InboundDelegateMsg<'a>>,
},
RegisterDelegate {
delegate: DelegateContainer,
cipher: [u8; 32],
nonce: [u8; 24],
},
UnregisterDelegate(DelegateKey),
}
impl DelegateRequest<'_> {
pub const DEFAULT_CIPHER: [u8; 32] = [
0, 24, 22, 150, 112, 207, 24, 65, 182, 161, 169, 227, 66, 182, 237, 215, 206, 164, 58, 161,
64, 108, 157, 195, 0, 0, 0, 0, 0, 0, 0, 0,
];
pub const DEFAULT_NONCE: [u8; 24] = [
57, 18, 79, 116, 63, 134, 93, 39, 208, 161, 156, 229, 222, 247, 111, 79, 210, 126, 127, 55,
224, 150, 139, 80,
];
pub fn into_owned(self) -> DelegateRequest<'static> {
match self {
DelegateRequest::ApplicationMessages {
key,
inbound,
params,
} => DelegateRequest::ApplicationMessages {
key,
params: params.into_owned(),
inbound: inbound.into_iter().map(|e| e.into_owned()).collect(),
},
DelegateRequest::RegisterDelegate {
delegate,
cipher,
nonce,
} => DelegateRequest::RegisterDelegate {
delegate,
cipher,
nonce,
},
DelegateRequest::UnregisterDelegate(key) => DelegateRequest::UnregisterDelegate(key),
}
}
pub fn key(&self) -> &DelegateKey {
match self {
DelegateRequest::ApplicationMessages { key, .. } => key,
DelegateRequest::RegisterDelegate { delegate, .. } => delegate.key(),
DelegateRequest::UnregisterDelegate(key) => key,
}
}
}
impl Display for ClientRequest<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ClientRequest::ContractOp(op) => match op {
ContractRequest::Put {
contract, state, ..
} => {
write!(
f,
"ContractRequest::Put for contract `{contract}` with state {state}"
)
}
ContractRequest::Update { key, .. } => write!(f, "update request for {key}"),
ContractRequest::Get {
key,
return_contract_code: contract,
..
} => {
write!(
f,
"ContractRequest::Get for key `{key}` (fetch full contract: {contract})"
)
}
ContractRequest::Subscribe { key, .. } => {
write!(f, "ContractRequest::Subscribe for `{key}`")
}
},
ClientRequest::DelegateOp(op) => match op {
DelegateRequest::ApplicationMessages { key, inbound, .. } => {
write!(
f,
"DelegateRequest::ApplicationMessages for `{key}` with {} messages",
inbound.len()
)
}
DelegateRequest::RegisterDelegate { delegate, .. } => {
write!(
f,
"DelegateRequest::RegisterDelegate for delegate.key()=`{}`",
delegate.key()
)
}
DelegateRequest::UnregisterDelegate(key) => {
write!(f, "DelegateRequest::UnregisterDelegate for key `{key}`")
}
},
ClientRequest::Disconnect { .. } => write!(f, "client disconnected"),
ClientRequest::Authenticate { .. } => write!(f, "authenticate"),
ClientRequest::NodeQueries(query) => write!(f, "node queries: {:?}", query),
ClientRequest::Close => write!(f, "close"),
ClientRequest::StreamChunk {
stream_id,
index,
total,
..
} => write!(f, "stream chunk {index}/{total} (stream {stream_id})"),
}
}
}
/// Deserializes a `DelegateRequest` from a Flatbuffers message.
impl<'a> TryFromFbs<&FbsDelegateRequest<'a>> for DelegateRequest<'a> {
fn try_decode_fbs(request: &FbsDelegateRequest<'a>) -> Result<Self, WsApiError> {
let req = {
match request.delegate_request_type() {
DelegateRequestType::ApplicationMessages => {
let app_msg = request.delegate_request_as_application_messages().unwrap();
let key = DelegateKey::try_decode_fbs(&app_msg.key())?;
let params = Parameters::from(app_msg.params().bytes());
let inbound = app_msg
.inbound()
.iter()
.map(|msg| InboundDelegateMsg::try_decode_fbs(&msg))
.collect::<Result<Vec<_>, _>>()?;
DelegateRequest::ApplicationMessages {
key,
params,
inbound,
}
}
DelegateRequestType::RegisterDelegate => {
let register = request.delegate_request_as_register_delegate().unwrap();
let delegate = DelegateContainer::try_decode_fbs(®ister.delegate())?;
let cipher =
<[u8; 32]>::try_from(register.cipher().bytes().to_vec().as_slice())
.unwrap();
let nonce =
<[u8; 24]>::try_from(register.nonce().bytes().to_vec().as_slice()).unwrap();
DelegateRequest::RegisterDelegate {
delegate,
cipher,
nonce,
}
}
DelegateRequestType::UnregisterDelegate => {
let unregister = request.delegate_request_as_unregister_delegate().unwrap();
let key = DelegateKey::try_decode_fbs(&unregister.key())?;
DelegateRequest::UnregisterDelegate(key)
}
_ => unreachable!(),
}
};
Ok(req)
}
}
/// A response to a previous [`ClientRequest`]
#[derive(Serialize, Deserialize, Debug, Clone)]
#[non_exhaustive]
pub enum HostResponse<T = WrappedState> {
ContractResponse(#[serde(bound(deserialize = "T: DeserializeOwned"))] ContractResponse<T>),
DelegateResponse {
key: DelegateKey,
values: Vec<OutboundDelegateMsg>,
},
QueryResponse(QueryResponse),
/// A requested action which doesn't require an answer was performed successfully.
Ok,
/// A chunk of a larger streamed response.
StreamChunk {
stream_id: u32,
index: u32,
total: u32,
data: Bytes,
},
/// Header message announcing the start of a streamed response.
/// Sent before the corresponding [`StreamChunk`] messages so the client
/// can set up incremental consumption via [`WsStreamHandle`].
StreamHeader {
stream_id: u32,
total_bytes: u64,
content: StreamContent,
},
}
/// Describes what kind of response is being streamed.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub enum StreamContent {
/// A streamed GetResponse — the large state is delivered via StreamChunks.
GetResponse {
key: ContractKey,
includes_contract: bool,
},
/// Raw binary stream (future use).
Raw,
}
type Peer = String;
#[derive(Serialize, Deserialize, Debug, Clone)]
pub enum QueryResponse {
ConnectedPeers { peers: Vec<(Peer, SocketAddr)> },
NetworkDebug(NetworkDebugInfo),
NodeDiagnostics(NodeDiagnosticsResponse),
ProximityCache(ProximityCacheInfo),
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct NetworkDebugInfo {
pub subscriptions: Vec<SubscriptionInfo>,
pub connected_peers: Vec<(String, SocketAddr)>,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct NodeDiagnosticsResponse {
/// Node information
pub node_info: Option<NodeInfo>,
/// Network connectivity information
pub network_info: Option<NetworkInfo>,
/// Contract subscription information
pub subscriptions: Vec<SubscriptionInfo>,
/// Contract states for specific contracts
pub contract_states: std::collections::HashMap<ContractKey, ContractState>,
/// System metrics
pub system_metrics: Option<SystemMetrics>,
/// Information about connected peers with detailed data
pub connected_peers_detailed: Vec<ConnectedPeerInfo>,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct NodeInfo {
pub peer_id: String,
pub is_gateway: bool,
pub location: Option<String>,
pub listening_address: Option<String>,
pub uptime_seconds: u64,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct NetworkInfo {
pub connected_peers: Vec<(String, String)>, // (peer_id, address)
pub active_connections: usize,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct ContractState {
/// Number of nodes subscribed to this contract
pub subscribers: u32,
/// Peer IDs of nodes that are subscribed to this contract
pub subscriber_peer_ids: Vec<String>,
/// Size of the contract state in bytes
#[serde(default)]
pub size_bytes: u64,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct SystemMetrics {
pub active_connections: u32,
pub seeding_contracts: u32,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct SubscriptionInfo {
pub contract_key: ContractInstanceId,
pub client_id: usize,
}
/// Basic information about a connected peer
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct ConnectedPeerInfo {
pub peer_id: String,
pub address: String,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub enum NodeQuery {
ConnectedPeers,
SubscriptionInfo,
NodeDiagnostics {
/// Diagnostic configuration specifying what information to collect
config: NodeDiagnosticsConfig,
},
/// Phase 3: Query proximity cache information for update propagation
ProximityCacheInfo,
}
/// Phase 3: Proximity cache information for update propagation
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct ProximityCacheInfo {
/// Contracts this node is currently caching
pub my_cache: Vec<ContractCacheEntry>,
/// What we know about neighbor caches
pub neighbor_caches: Vec<NeighborCacheInfo>,
/// Proximity propagation statistics
pub stats: ProximityStats,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct ContractCacheEntry {
/// Full contract key as string
pub contract_key: String,
/// 32-bit hash for proximity matching
pub cache_hash: u32,
/// When this contract was cached (Unix timestamp)
pub cached_since: u64,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct NeighborCacheInfo {
/// Peer identifier
pub peer_id: String,
/// Contract hashes this neighbor is known to cache
pub known_contracts: Vec<u32>,
/// Last update received from this neighbor (Unix timestamp)
pub last_update: u64,
/// Number of updates received from this neighbor
pub update_count: u64,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct ProximityStats {
/// Number of cache announcements sent
pub cache_announces_sent: u64,
/// Number of cache announcements received
pub cache_announces_received: u64,
/// Updates forwarded via proximity (not subscription)
pub updates_via_proximity: u64,
/// Updates forwarded via subscription
pub updates_via_subscription: u64,
/// False positives due to hash collisions
pub false_positive_forwards: u64,
/// Average number of contracts per neighbor
pub avg_neighbor_cache_size: f32,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct NodeDiagnosticsConfig {
/// Include basic node information (ID, location, uptime, etc.)
pub include_node_info: bool,
/// Include network connectivity information
pub include_network_info: bool,
/// Include contract subscription information
pub include_subscriptions: bool,
/// Include contract states for specific contracts (empty = all contracts)
pub contract_keys: Vec<ContractKey>,
/// Include memory and performance metrics
pub include_system_metrics: bool,
/// Include detailed information about connected peers (vs basic peer list)
pub include_detailed_peer_info: bool,
/// Include peer IDs of subscribers in contract state information
pub include_subscriber_peer_ids: bool,
}
impl NodeDiagnosticsConfig {
/// Create a comprehensive diagnostic config for debugging update propagation issues
pub fn for_update_propagation_debugging(contract_key: ContractKey) -> Self {
Self {
include_node_info: true,
include_network_info: true,
include_subscriptions: true,
contract_keys: vec![contract_key],
include_system_metrics: true,
include_detailed_peer_info: true,
include_subscriber_peer_ids: true,
}
}
/// Create a lightweight diagnostic config for basic node status
pub fn basic_status() -> Self {
Self {
include_node_info: true,
include_network_info: true,
include_subscriptions: false,
contract_keys: vec![],
include_system_metrics: false,
include_detailed_peer_info: false,
include_subscriber_peer_ids: false,
}
}
/// Create a full diagnostic config (all information)
pub fn full() -> Self {
Self {
include_node_info: true,
include_network_info: true,
include_subscriptions: true,
contract_keys: vec![], // empty = all contracts
include_system_metrics: true,
include_detailed_peer_info: true,
include_subscriber_peer_ids: true,
}
}
}
impl HostResponse {
pub fn unwrap_put(self) -> ContractKey {
if let Self::ContractResponse(ContractResponse::PutResponse { key }) = self {
key
} else {
panic!("called `HostResponse::unwrap_put()` on other than `PutResponse` value")
}
}
pub fn unwrap_get(self) -> (WrappedState, Option<ContractContainer>) {
if let Self::ContractResponse(ContractResponse::GetResponse {
contract, state, ..
}) = self
{
(state, contract)
} else {
panic!("called `HostResponse::unwrap_put()` on other than `PutResponse` value")
}