shvbroker 3.26.0

Rust implementation of the SHV broker
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
use std::collections::BTreeMap;
use std::format;
use std::sync::Arc;
use log::{Level, log};
use shvrpc::metamethod::{Flags, MetaMethod};
use shvrpc::util::{children_on_path, find_longest_path_prefix};
use shvrpc::{metamethod, RpcMessageMetaTags};
use shvproto::{List, RpcValue, rpcvalue};
use shvrpc::metamethod::AccessLevel;
use shvrpc::rpc::SubscriptionParam;
use shvrpc::rpcframe::RpcFrame;
use shvrpc::rpcmessage::{PeerId, RpcError, RpcErrorCode};
use crate::brokerimpl::{BrokerImpl, BrokerToPeerMessage, user_base_roles};
use crate::brokerimpl::NodeRequestContext;

pub const METH_DIR: &str = "dir";
pub const METH_LS: &str = "ls";
pub const METH_GET: &str = "get";
pub const METH_SET: &str = "set";
pub const SIG_CHNG: &str = "chng";
pub const SIG_LSMOD: &str = "lsmod";
pub const SIG_MNTMOD: &str = "mntmod";
pub const METH_NAME: &str = "name";
pub const METH_PING: &str = "ping";
pub const METH_SUBSCRIBE: &str = "subscribe";
pub const METH_UNSUBSCRIBE: &str = "unsubscribe";

pub const META_METHOD_PUBLIC_DIR: MetaMethod = MetaMethod::new_static(METH_DIR, Flags::empty(), AccessLevel::Browse, "DirParam",  "DirResult", &[], "");
pub const META_METHOD_PUBLIC_LS: MetaMethod = MetaMethod::new_static(METH_LS, Flags::empty(), AccessLevel::Browse, "LsParam",  "LsResult", &[], "");
pub const PUBLIC_DIR_LS_METHODS: [MetaMethod; 2] = [META_METHOD_PUBLIC_DIR, META_METHOD_PUBLIC_LS];
pub const DOT_LOCAL_GRANT: &str = "dot_local";
pub const DOT_LOCAL_DIR: &str = ".local";
pub const DOT_LOCAL_HACK: &str = "dot-local-hack";
pub const DIR_APP: &str = ".app";
pub enum DirParam {
    Brief,
    Full,
    MethodExists(String),
}
impl From<Option<&RpcValue>> for DirParam {
    fn from(value: Option<&RpcValue>) -> Self {
        match value {
            Some(rpcval) if rpcval.is_string() => DirParam::MethodExists(rpcval.as_str().into()),
            Some(rpcval) if rpcval.as_bool() => DirParam::Full,
            Some(_) | None => DirParam::Brief,
        }
    }
}

pub fn dir<'a>(mut methods: impl Iterator<Item=&'a MetaMethod>, param: DirParam) -> RpcValue {
    let serializer = match param {
        DirParam::MethodExists(method_name) => return methods.any(|mm| mm.name == method_name).into(),
        DirParam::Brief => metamethod::DirFormat::IMap,
        DirParam::Full => metamethod::DirFormat::Map,
    };

    methods.map(|mm| mm.to_rpcvalue(serializer)).collect::<Vec<_>>().into()
}

pub enum LsParam {
    List,
    Exists(String),
}

impl From<Option<&RpcValue>> for LsParam {
    fn from(value: Option<&RpcValue>) -> Self {
        match value {
            Some(rpcval) if rpcval.is_string() => LsParam::Exists(rpcval.as_str().into()),
            Some(_) | None => LsParam::List
        }
    }
}

pub fn process_local_dir_ls<V>(mounts: &BTreeMap<String, V>, frame: &RpcFrame) -> Option<Result<RpcValue, RpcError>> {
    let method = frame.method().unwrap_or_default();
    if !(method == METH_DIR || method == METH_LS) {
        return None
    }
    let shv_path = frame.shv_path().unwrap_or_default();
    let children = children_on_path(mounts, shv_path);
    let children = children.map(|children| {
        if frame.meta.get(DOT_LOCAL_HACK).is_some() {
            let mut children = children;
            children.insert(0, DOT_LOCAL_DIR.into());
            children
        } else {
            children
        }
    });
    let mount_pair = find_longest_path_prefix(mounts, shv_path);
    if mount_pair.is_none() && children.is_none() {
        // path doesn't exist
        return Some(Err(RpcError::new(RpcErrorCode::MethodNotFound, format!("Invalid shv path: {shv_path}"))))
    }
    let is_mount_point = mount_pair.is_some() && mount_pair.unwrap().1.is_empty();
    let is_remote_dir = mount_pair.is_some() && children.is_none();
    let is_tree_leaf = mount_pair.is_some() && children.is_some() && children.as_ref().unwrap().is_empty();
    //println!("shv path: {shv_path}, method: {method}, mount pair: {:?}", mount_pair);
    //println!("is_mount_point: {is_mount_point}, is_tree_leaf: {is_tree_leaf}");
    if method == METH_DIR && !is_mount_point && !is_remote_dir && !is_tree_leaf {
        // dir in the middle of the tree must be resolved locally
        if let Ok(rpcmsg) = frame.to_rpcmesage() {
            let dir = dir(PUBLIC_DIR_LS_METHODS.iter(), rpcmsg.param().into());
            return Some(Ok(dir))
        } else {
            return Some(Err(RpcError::new(RpcErrorCode::InvalidRequest, "Cannot convert RPC frame to Rpc message")))
        }
    }
    if method == METH_LS && !is_tree_leaf && !is_remote_dir  {
        // ls on not-leaf node must be resolved locally
        if let Ok(rpcmsg) = frame.to_rpcmesage() {
            let ls = ls_children_to_result(children, rpcmsg.param().into());
            return Some(ls)
        } else {
            return Some(Err(RpcError::new(RpcErrorCode::InvalidRequest, "Cannot convert RPC frame to Rpc message")))
        }
    }
    None
}
fn ls_children_to_result(children: Option<Vec<String>>, param: LsParam) -> Result<RpcValue, RpcError> {
    match param {
        LsParam::List => {
            match children {
                None => {
                    Err(RpcError::new(RpcErrorCode::MethodCallException, "Invalid shv path"))
                }
                Some(dirs) => {
                    let res: rpcvalue::List = dirs.iter().map(RpcValue::from).collect();
                    Ok(res.into())
                }
            }
        }
        LsParam::Exists(path) => {
            match children {
                None => {
                    Ok(false.into())
                }
                Some(children) => {
                    Ok(children.contains(&path).into())
                }
            }
        }
    }
}
pub(crate) enum ProcessRequestRetval {
    MethodNotFound,
    RetvalDeferred,
    Retval(RpcValue),
}
pub(crate) type ProcessRequestResult = Result<ProcessRequestRetval, shvrpc::Error>;
#[async_trait::async_trait]
pub(crate) trait ShvNode : Send + Sync {
    fn methods(&self, shv_path: &str) -> &'static[&'static MetaMethod];
    async fn children(&self, shv_path: &str, broker_state: Arc<BrokerImpl>) -> Option<Vec<String>>;
    async fn is_request_granted(&self, rq: &RpcFrame, _ctx: &NodeRequestContext) -> bool {
        let shv_path = rq.shv_path().unwrap_or_default();
        let methods = self.methods(shv_path);
        is_request_granted_methods(methods, rq)
    }
    async fn process_request(&self, frame: &RpcFrame, ctx: &NodeRequestContext) -> ProcessRequestResult;
}
impl dyn ShvNode {
    pub async fn process_request_and_dir_ls(&self, frame: &RpcFrame, ctx: &NodeRequestContext) -> ProcessRequestResult {
        let result = self.process_request(frame, ctx).await;
        if let Ok(ProcessRequestRetval::MethodNotFound) = result {
            match frame.method().unwrap_or_default() {
                METH_DIR => {
                    let shv_path = frame.shv_path().unwrap_or_default();
                    let rq = frame.to_rpcmesage()?;
                    let resp = dir(self.methods(shv_path).iter().copied(), rq.param().into());
                    Ok(ProcessRequestRetval::Retval(resp))
                }
                METH_LS => {
                    let shv_path = frame.shv_path().unwrap_or_default();
                    let rq = frame.to_rpcmesage()?;
                    if let Some(children) = self.children(shv_path, ctx.state.clone()).await {
                        match LsParam::from(rq.param()) {
                            LsParam::List => {
                                Ok(ProcessRequestRetval::Retval(children.into()))
                            }
                            LsParam::Exists(path) => {
                                Ok(ProcessRequestRetval::Retval(children.iter().any(|s| s == &path).into()))
                            }
                        }

                    } else {
                        Err(format!("Invalid path: {shv_path}.").into())
                    }
                }
                _ => { Ok(ProcessRequestRetval::MethodNotFound) }
            }
        } else {
            result
        }
    }
}
pub fn is_request_granted_methods(methods: &'static[&'static MetaMethod], rq: &RpcFrame) -> bool {
    if let Some(rq_access) = rq.access_level() {
        let method = rq.method().unwrap_or_default();
        for mm in methods {
            if mm.name == method {
                return rq_access >= mm.access as i32
            }
        }
    }
    false
}

pub const METH_SHV_VERSION_MAJOR: &str = "shvVersionMajor";
pub const METH_SHV_VERSION_MINOR: &str = "shvVersionMinor";
pub const METH_VERSION: &str = "version";
pub const METH_SERIAL_NUMBER: &str = "serialNumber";


pub struct AppNode {
    pub shv_version_major: i32,
    pub shv_version_minor: i32,
}
impl AppNode {
    pub(crate) fn new() -> Self {
        AppNode {
            shv_version_major: 3,
            shv_version_minor: 0,
        }
    }
}

const META_METH_APP_SHV_VERSION_MAJOR: MetaMethod = MetaMethod::new_static(METH_SHV_VERSION_MAJOR, Flags::IsGetter, AccessLevel::Browse, "", "i", &[], "");
const META_METH_APP_SHV_VERSION_MINOR: MetaMethod = MetaMethod::new_static(METH_SHV_VERSION_MINOR, Flags::IsGetter, AccessLevel::Browse, "", "i", &[], "");
const META_METH_APP_NAME: MetaMethod = MetaMethod::new_static(METH_NAME, Flags::IsGetter, AccessLevel::Browse, "", "s", &[], "");
const META_METH_APP_VERSION: MetaMethod = MetaMethod::new_static(METH_VERSION, Flags::IsGetter, AccessLevel::Browse, "", "s", &[], "");
const META_METH_APP_PING: MetaMethod = MetaMethod::new_static(METH_PING, Flags::empty(), AccessLevel::Browse, "", "n", &[], "");

const APP_NODE_METHODS: &[&MetaMethod] = &[
    &META_METHOD_PUBLIC_DIR,
    &META_METHOD_PUBLIC_LS,
    &META_METH_APP_SHV_VERSION_MAJOR,
    &META_METH_APP_SHV_VERSION_MINOR,
    &META_METH_APP_NAME,
    &META_METH_APP_VERSION,
    &META_METH_APP_PING
];

#[async_trait::async_trait]
impl ShvNode for AppNode {
    fn methods(&self, _shv_path: &str) -> &'static[&'static MetaMethod] {
        APP_NODE_METHODS
    }

    async fn children(&self, shv_path: &str, _broker_state: Arc<BrokerImpl>) -> Option<Vec<String>> {
        if shv_path.is_empty() {
            Some(vec![])
        } else {
            None
        }
    }

    async fn process_request(&self, frame: &RpcFrame, _ctx: &NodeRequestContext) -> ProcessRequestResult {
        match frame.method().unwrap_or_default() {
            METH_NAME => {
                Ok(ProcessRequestRetval::Retval(env!("CARGO_PKG_NAME").into()))
            }
            METH_VERSION => {
                Ok(ProcessRequestRetval::Retval(env!("CARGO_PKG_VERSION").into()))
            }
            METH_SHV_VERSION_MAJOR => {
                Ok(ProcessRequestRetval::Retval(self.shv_version_major.into()))
            }
            METH_SHV_VERSION_MINOR => {
                Ok(ProcessRequestRetval::Retval(self.shv_version_minor.into()))
            }
            METH_PING => {
                Ok(ProcessRequestRetval::Retval(().into()))
            }
            _ => {
                Ok(ProcessRequestRetval::MethodNotFound)
            }
        }
    }
}

const META_METH_VERSION: MetaMethod = MetaMethod::new_static(METH_VERSION, Flags::IsGetter, AccessLevel::Browse, "", "", &[], "");
const META_METH_NAME: MetaMethod = MetaMethod::new_static(METH_NAME, Flags::IsGetter, AccessLevel::Browse, "", "", &[], "");
const META_METH_SERIAL_NUMBER: MetaMethod = MetaMethod::new_static("serialNumber", Flags::IsGetter, AccessLevel::Browse, "", "", &[], "");

pub struct AppDeviceNode {
    pub device_name: &'static str,
    pub version: &'static str,
    pub serial_number: Option<String>,
}

const APP_DEVICE_NODE_METHODS: &[&MetaMethod] = &[
    &META_METHOD_PUBLIC_DIR,
    &META_METHOD_PUBLIC_LS,
    &META_METH_NAME,
    &META_METH_VERSION,
    &META_METH_SERIAL_NUMBER
];

#[async_trait::async_trait]
impl ShvNode for AppDeviceNode {
    fn methods(&self, _shv_path: &str) -> &'static[&'static MetaMethod] {
        APP_DEVICE_NODE_METHODS
    }

    async fn children(&self, shv_path: &str, _broker_state: Arc<BrokerImpl>) -> Option<Vec<String>> {
        if shv_path.is_empty() {
            Some(vec![])
        } else {
            None
        }
    }

    async fn process_request(&self, frame: &RpcFrame, _ctx: &NodeRequestContext) -> ProcessRequestResult {
        match frame.method().unwrap_or_default() {
            METH_NAME => {
                Ok(ProcessRequestRetval::Retval(self.device_name.into()))
            }
            METH_VERSION => {
                Ok(ProcessRequestRetval::Retval(self.version.into()))
            }
            METH_SERIAL_NUMBER => {
                Ok(ProcessRequestRetval::Retval(self.serial_number.as_ref().map(|s| s.to_string()).unwrap_or_default().into()))
            }
            METH_PING => {
                Ok(ProcessRequestRetval::Retval(().into()))
            }
            _ => {
                Ok(ProcessRequestRetval::MethodNotFound)
            }
        }
    }
}

pub const DIR_BROKER: &str = ".broker";
pub const DIR_BROKER_CURRENT_CLIENT: &str = ".broker/currentClient";
pub const DIR_BROKER_ACCESS_MOUNTS: &str = ".broker/access/mounts";
pub const DIR_BROKER_ACCESS_USERS: &str = ".broker/access/users";
pub const DIR_BROKER_ACCESS_ROLES: &str = ".broker/access/roles";
pub const DIR_BROKER_ACCESS_ALLOWED_IPS: &str = ".broker/access/allowedIps";
pub const DIR_BROKER_ACCESS_LAST_LOGIN: &str = ".broker/access/lastLogin";

pub const DIR_SHV2_BROKER_APP: &str = ".broker/app";
pub const DIR_SHV2_BROKER_ETC_ACL_USERS: &str = ".broker/etc/acl/users";
pub const DIR_SHV2_BROKER_ETC_ACL_ROLES: &str = ".broker/etc/acl/roles";
pub const DIR_SHV2_BROKER_ETC_ACL_ACCESS: &str = ".broker/etc/acl/access";
pub const DIR_SHV2_BROKER_ETC_ACL_MOUNTS: &str = ".broker/etc/acl/mounts";

pub const METH_CLIENT_INFO: &str = "clientInfo";
pub const METH_MOUNTED_CLIENT_INFO: &str = "mountedClientInfo";
pub const METH_CLIENTS: &str = "clients";
pub const METH_MOUNTS: &str = "mounts";
pub const METH_DISCONNECT_CLIENT: &str = "disconnectClient";
pub const METH_BROKER_ID: &str = "brokerId";

const META_METH_CLIENT_INFO: MetaMethod = MetaMethod::new_static(METH_CLIENT_INFO, Flags::empty(), AccessLevel::Service, "Int", "ClientInfo", &[], "");
const META_METH_MOUNTED_CLIENT_INFO: MetaMethod = MetaMethod::new_static(METH_MOUNTED_CLIENT_INFO, Flags::empty(), AccessLevel::Service, "String", "ClientInfo", &[], "");
const META_METH_CLIENTS: MetaMethod = MetaMethod::new_static(METH_CLIENTS, Flags::empty(), AccessLevel::SuperService, "void", "List[Int]", &[], "");
const META_METH_USER_ACCESS_LEVEL_FOR_METHOD_CALL: MetaMethod = MetaMethod::new_static(
    METH_USER_ACCESS_LEVEL_FOR_METHOD_CALL,
    Flags::empty(),
    AccessLevel::Service,
    "[s:username,s:path,s:method]",
    "Int",
    &[],
    r#"params: ["username", "shv_path", "method"]
    only works for currently logged-in clients"#,
);
const META_METH_MOUNTS: MetaMethod = MetaMethod::new_static(METH_MOUNTS, Flags::empty(), AccessLevel::SuperService, "void", "List[String]", &[], "");
const META_METH_DISCONNECT_CLIENT: MetaMethod = MetaMethod::new_static(METH_DISCONNECT_CLIENT, Flags::empty(), AccessLevel::SuperService, "Int", "void", &[], "");
const META_METH_BROKER_ID: MetaMethod = MetaMethod::new_static(METH_BROKER_ID, Flags::IsGetter, AccessLevel::Service, "", "String", &[], "");

pub const METH_INFO: &str = "info";
pub const METH_SUBSCRIPTIONS: &str = "subscriptions";
pub const METH_CHANGE_PASSWORD: &str = "changePassword";
pub const METH_ACCESS_LEVEL_FOR_METHOD_CALL: &str = "accessLevelForMethodCall";
pub const METH_USER_ACCESS_LEVEL_FOR_METHOD_CALL: &str = "userAccessLevelForMethodCall";
pub const METH_USER_PROFILE: &str = "userProfile";
pub const METH_USER_ROLES: &str = "userRoles";


pub(crate) struct BrokerNode {}
impl BrokerNode {
    pub(crate) fn new() -> Self {
        Self {
        }
    }
}
const BROKER_NODE_METHODS: &[&MetaMethod] = &[
    &META_METHOD_PUBLIC_DIR,
    &META_METHOD_PUBLIC_LS,
    &META_METH_CLIENT_INFO,
    &META_METH_MOUNTED_CLIENT_INFO,
    &META_METH_CLIENTS,
    &META_METH_USER_ACCESS_LEVEL_FOR_METHOD_CALL,
    &META_METH_MOUNTS,
    &META_METH_DISCONNECT_CLIENT,
    &META_METH_BROKER_ID,
];

#[async_trait::async_trait]
impl ShvNode for BrokerNode {
    fn methods(&self, _shv_path: &str) -> &'static[&'static MetaMethod] {
        BROKER_NODE_METHODS
    }

    async fn children(&self, shv_path: &str, _broker_state: Arc<BrokerImpl>) -> Option<Vec<String>> {
        if shv_path.is_empty() {
            Some(vec![])
        } else {
            None
        }
    }

    async fn process_request(&self, frame: &RpcFrame, ctx: &NodeRequestContext) -> ProcessRequestResult {
        match frame.method().unwrap_or_default() {
            METH_CLIENT_INFO => {
                let rq = &frame.to_rpcmesage()?;
                let peer_id: PeerId = rq.param().unwrap_or_default().try_into()?;
                let info = match ctx.state.client_info(peer_id).await {
                    None => { RpcValue::null() }
                    Some(info) => { RpcValue::from(info) }
                };
                Ok(ProcessRequestRetval::Retval(info))
            }
            METH_MOUNTED_CLIENT_INFO => {
                let rq = &frame.to_rpcmesage()?;
                let mount_point = rq.param().unwrap_or_default().try_into()?;
                let info = match ctx.state.mounted_client_info(mount_point).await {
                    None => { RpcValue::null() }
                    Some(info) => { RpcValue::from(info) }
                };
                Ok(ProcessRequestRetval::Retval(info))
            }
            METH_CLIENTS => {
                let clients: rpcvalue::List = ctx.state.peers.read().await.keys().map(|id| RpcValue::from(*id)).collect();
                Ok(ProcessRequestRetval::Retval(clients.into()))
            }
            METH_MOUNTS => {
                let mounts: List = ctx.state.peers.read().await.values()
                    .filter(|peer| peer.mount_point.is_some())
                    .map(|peer| if let Some(mount_point) = &peer.mount_point {RpcValue::from(mount_point)} else { RpcValue::null() } )
                    .collect();
                Ok(ProcessRequestRetval::Retval(mounts.into()))
            }
            METH_DISCONNECT_CLIENT => {
                let rq = &frame.to_rpcmesage()?;
                let peer_id: PeerId = rq.param().unwrap_or_default().try_into()?;
                if let Some(peer) = ctx.state.peers.read().await.get(&peer_id) {
                    let peer_sender = peer.sender.clone();
                    smol::spawn(async move {
                        let _ = peer_sender.unbounded_send(BrokerToPeerMessage::DisconnectByBroker {reason: Some(format!("Disconnected by .broker:{METH_DISCONNECT_CLIENT}"))});
                    }).detach();
                    Ok(ProcessRequestRetval::Retval(().into()))
                } else {
                    Err(format!("Disconnect client error - peer {peer_id} not found.").into())
                }
            }
            METH_BROKER_ID => {
                Ok(ProcessRequestRetval::Retval(ctx.state.config.name.clone().into()))
            }
            METH_USER_ACCESS_LEVEL_FOR_METHOD_CALL => {
                const WRONG_FORMAT_ERR: &str = r#"Expected params format: ["<username>", "<shv_path>", "<method>"]"#;
                let rq = &frame.to_rpcmesage()?;
                let params = rq
                    .param()
                    .ok_or_else(|| WRONG_FORMAT_ERR.into())
                    .and_then(|rv| Vec::<String>::try_from(rv)
                        .map_err(|e| format!("{WRONG_FORMAT_ERR}. Error: {e}"))
                    )?;

                let [username, shv_path, method] = params.as_slice() else {
                    return Err(WRONG_FORMAT_ERR.into());
                };
                let Some(peer_id) = ctx.state.peers.read().await
                    .iter()
                    .find_map(|(peer_id, peer)| match &peer.peer_kind {
                        crate::brokerimpl::PeerKind::Client { user } | crate::brokerimpl::PeerKind::Device { user , ..} if user == username => Some(*peer_id),
                        _ => None,
                    }) else {
                        return Err("Couldn't determine access level".into());
                    };

                let access_level = ctx.state
                    .access_level_for_request_params(
                        peer_id,
                        shv_path,
                        method,
                        None,
                        frame.tag(shvrpc::rpcmessage::Tag::Access as i32).map(RpcValue::as_str),
                    )
                    .await
                    .map(|(access_level, _)| access_level.unwrap_or_default())
                    .or_else(|rpc_err| if rpc_err.code == RpcErrorCode::PermissionDenied.into() {
                        Ok(0)
                    } else {
                        Err(rpc_err)
                    })?;

                Ok(ProcessRequestRetval::Retval(access_level.into()))
            }
            _ => {
                Ok(ProcessRequestRetval::MethodNotFound)
            }
        }
    }
}

const META_METH_INFO: MetaMethod = MetaMethod::new_static(METH_INFO, Flags::empty(), AccessLevel::Browse, "Int", "ClientInfo", &[], "");
const META_METH_SUBSCRIBE: MetaMethod = MetaMethod::new_static(METH_SUBSCRIBE, Flags::empty(), AccessLevel::Browse, "SubscribeParams", "void", &[], "");
const META_METH_UNSUBSCRIBE: MetaMethod = MetaMethod::new_static(METH_UNSUBSCRIBE, Flags::empty(), AccessLevel::Browse, "SubscribeParams", "void", &[], "");
const META_METH_SUBSCRIPTIONS: MetaMethod = MetaMethod::new_static(METH_SUBSCRIPTIONS, Flags::empty(), AccessLevel::Browse, "void", "Map", &[], "");
const META_METH_CHANGE_PASSWORD: MetaMethod = MetaMethod::new_static(
    METH_CHANGE_PASSWORD,
    Flags::empty(),
    AccessLevel::Write,
    "[s:old_password,s:new_password]",
    "Bool",
    &[],
    r#"(params: ["old_password", "new_password"], old and new passwords are in plain format)"#
);
const META_METH_ACCESS_LEVEL_FOR_METHOD_CALL: MetaMethod = MetaMethod::new_static(
    METH_ACCESS_LEVEL_FOR_METHOD_CALL,
    Flags::empty(),
    AccessLevel::Read,
    "[s:path,s:method]",
    "Int",
    &[],
    r#"(params: ["shv_path", "method"]"#,
);

const META_METH_USER_PROFILE: MetaMethod = MetaMethod::new_static(METH_USER_PROFILE, Flags::empty(), AccessLevel::Read, "void", "RpcValue", &[], "");
const META_METH_USER_ROLES: MetaMethod = MetaMethod::new_static(METH_USER_ROLES, Flags::empty(), AccessLevel::Read, "void", "List", &[], "");

pub(crate) struct BrokerCurrentClientNode {}
impl BrokerCurrentClientNode {
    pub(crate) fn new() -> Self {
        Self {
        }
    }
}

const BROKER_CURRENT_CLIENT_NODE_METHODS: &[&MetaMethod] = &[
    &META_METHOD_PUBLIC_DIR,
    &META_METHOD_PUBLIC_LS,
    &META_METH_INFO,
    &META_METH_SUBSCRIBE,
    &META_METH_UNSUBSCRIBE,
    &META_METH_SUBSCRIPTIONS,
    &META_METH_CHANGE_PASSWORD,
    &META_METH_ACCESS_LEVEL_FOR_METHOD_CALL,
    &META_METH_USER_PROFILE,
    &META_METH_USER_ROLES,
];

impl BrokerCurrentClientNode {
    async fn subscribe(peer_id: PeerId, subpar: &SubscriptionParam, state: Arc<BrokerImpl>) -> shvrpc::Result<bool> {
        let res = state.subscribe(peer_id, subpar).await;
        log!(target: "Subscr", Level::Debug, "subscribe handler for peer id: {peer_id} - {subpar}, res: {res:?}");
        res
    }
    async fn unsubscribe(peer_id: PeerId, subpar: &SubscriptionParam, state: Arc<BrokerImpl>) -> shvrpc::Result<bool> {
        let res = state.unsubscribe(peer_id, subpar).await;
        log!(target: "Subscr", Level::Debug, "unsubscribe handler for peer id: {peer_id} - {subpar}, res: {res:?}");
        res
    }
}

#[async_trait::async_trait]
impl ShvNode for BrokerCurrentClientNode {
    fn methods(&self, _shv_path: &str) -> &'static[&'static MetaMethod] {
        BROKER_CURRENT_CLIENT_NODE_METHODS
    }

    async fn children(&self, _shv_path: &str, _broker_state: Arc<BrokerImpl>) -> Option<Vec<String>> {
        Some(vec![])
    }

    async fn process_request(&self, frame: &RpcFrame, ctx: &NodeRequestContext) -> ProcessRequestResult {
        match frame.method().unwrap_or_default() {
            METH_SUBSCRIBE => {
                let rq = &frame.to_rpcmesage()?;
                let subscription = SubscriptionParam::from_rpcvalue(rq.param().unwrap_or_default())?;
                let subs_added = Self::subscribe(ctx.peer_id, &subscription, ctx.state.clone()).await?;
                Ok(ProcessRequestRetval::Retval(subs_added.into()))
            }
            METH_UNSUBSCRIBE => {
                let rq = &frame.to_rpcmesage()?;
                let subscription = SubscriptionParam::from_rpcvalue(rq.param().unwrap_or_default())?;
                let subs_removed = Self::unsubscribe(ctx.peer_id, &subscription, ctx.state.clone()).await?;
                Ok(ProcessRequestRetval::Retval(subs_removed.into()))
            }
            METH_SUBSCRIPTIONS => {
                let result = ctx.state.subscriptions(ctx.peer_id).await?;
                Ok(ProcessRequestRetval::Retval(result.into()))
            }
            METH_INFO => {
                let info = match ctx.state.client_info(ctx.peer_id).await {
                    None => { RpcValue::null() }
                    Some(info) => { RpcValue::from(info) }
                };
                Ok(ProcessRequestRetval::Retval(info))
            }
            METH_CHANGE_PASSWORD => {
                const WRONG_FORMAT_ERR: &str = r#"Expected params format: ["<old_password>", "<new_password>"]"#;
                let Some(sql_connection) = &ctx.state.sql_connection else {
                    return Err("Cannot change password, access database is not available.".into());
                };
                let rq = &frame.to_rpcmesage()?;
                let params = rq
                    .param()
                    .ok_or_else(|| WRONG_FORMAT_ERR.to_string())
                    .and_then(|rv| Vec::<String>::try_from(rv)
                        .map_err(|e| format!("{WRONG_FORMAT_ERR}. Error: {e}"))
                    )?;

                let [old_password, new_password] = params.as_slice() else {
                    return Err(WRONG_FORMAT_ERR.into());
                };

                if old_password.is_empty() || new_password.is_empty() {
                    return Err("Both old and new password mustn't be empty.".into());
                }

                let Some(user_name) = ctx.state.peer_user(ctx.peer_id).await else {
                    return Err("Undefined user".into());
                };
                if user_name.starts_with("ldap:") {
                    return Err("Can't change password, because you are logged in over LDAP".into());
                }
                if user_name.starts_with("azure:") {
                    return Err("Can't change password, because you are logged in over Azure".into());
                }
                let mut access = ctx.state.access.write().await;
                let Some(user) = access.access_user(&user_name) else {
                    return Err(format!("Invalid user: {user_name})").into());
                };
                let current_password_sha1 = match &user.password {
                    crate::config::Password::Plain(password) => shvrpc::util::sha1_hash(password.as_bytes()),
                    crate::config::Password::Sha1(password) => password.clone(),
                };

                let old_password_sha1 = shvrpc::util::sha1_hash(old_password.as_bytes());

                if old_password_sha1 != current_password_sha1 {
                    return Err("Old password does not match.".into());
                }

                let new_password_sha1 = shvrpc::util::sha1_hash(new_password.as_bytes());
                let mut user = user.clone();
                user.password = crate::config::Password::Sha1(new_password_sha1);
                let res = access.set_access_user(&user_name, Some(user), sql_connection).await?;
                Ok(ProcessRequestRetval::Retval(res))
            }
            METH_ACCESS_LEVEL_FOR_METHOD_CALL => {
                const WRONG_FORMAT_ERR: &str = r#"Expected params format: ["<shv_path>", "<method>"]"#;
                let rq = &frame.to_rpcmesage()?;
                let params = rq
                    .param()
                    .ok_or_else(|| WRONG_FORMAT_ERR.into())
                    .and_then(|rv| Vec::<String>::try_from(rv)
                        .map_err(|e| format!("{WRONG_FORMAT_ERR}. Error: {e}"))
                    )?;

                let [shv_path, method] = params.as_slice() else {
                    return Err(WRONG_FORMAT_ERR.into());
                };

                let access_level = ctx.state
                    .access_level_for_request_params(
                        ctx.peer_id,
                        shv_path,
                        method,
                        None,
                        frame.tag(shvrpc::rpcmessage::Tag::Access as i32).map(RpcValue::as_str),
                    )
                    .await
                    .map(|(access_level, _)| access_level.unwrap_or_default())
                    .or_else(|rpc_err| if rpc_err.code == RpcErrorCode::PermissionDenied.into() {
                        Ok(0)
                    } else {
                        Err(rpc_err)
                    })?;

                Ok(ProcessRequestRetval::Retval(access_level.into()))
            }
            METH_USER_PROFILE => {
                let state = ctx.state.clone();
                let Some(user_roles) = user_base_roles(&*state.oauth2_user_groups.read().await, &*state.peers.read().await, &*state.access.read().await, ctx.peer_id) else {
                    return Err("This connection does not have any roles associated with it".into());
                };
                let access = state.access.read().await;
                let merged_profile = ctx.state
                    .flatten_roles(user_roles.as_slice())
                    .await
                    .iter()
                    .flat_map(|role| access.access_role(role))
                    .flat_map(|role| role.profile.clone())
                    .fold(None, |mut res: Option<crate::config::ProfileValue>, profile| {
                        match &mut res {
                            Some(res) => res.merge(profile),
                            None => res = Some(profile),
                        }
                        res
                    });
                Ok(ProcessRequestRetval::Retval(shvproto::to_rpcvalue(&merged_profile)?))
            }
            METH_USER_ROLES => {
                let state = ctx.state.clone();
                let Some(user_roles) = user_base_roles(&*state.oauth2_user_groups.read().await, &*state.peers.read().await, &*state.access.read().await, ctx.peer_id) else {
                    return Err("This connection does not have any roles associated with it".into());
                };

                if user_roles.is_empty() {
                    return Err(RpcError::new(RpcErrorCode::InternalError, "A user needs to have at least one role defined").into());
                }

                Ok(ProcessRequestRetval::Retval(ctx.state.flatten_roles(user_roles.as_slice()).await.into()))
            }
            _ => {
                Ok(ProcessRequestRetval::MethodNotFound)
            }
        }
    }
}

const META_METHOD_PRIVATE_DIR: MetaMethod = MetaMethod::new_static(METH_DIR, Flags::empty(), AccessLevel::Read, "DirParam", "DirResult", &[], "");
const META_METHOD_PRIVATE_LS: MetaMethod = MetaMethod::new_static(METH_LS, Flags::empty(), AccessLevel::Read, "LsParam", "LsResult", &[], "");

pub const METH_VALUE: &str = "value";
pub const METH_SET_VALUE: &str = "setValue";
pub const METH_DEACTIVATE: &str = "deactivate";
pub const METH_ACTIVATE: &str = "activate";

const META_METH_VALUE: MetaMethod = MetaMethod::new_static(METH_VALUE, Flags::empty(), AccessLevel::Superuser, "void", "Map", &[], "");
const META_METH_SET_VALUE: MetaMethod = MetaMethod::new_static(METH_SET_VALUE, Flags::empty(), AccessLevel::Superuser, "[String, Map | Null]", "void", &[], "");
const META_METH_DEACTIVATE: MetaMethod = MetaMethod::new_static(METH_DEACTIVATE, Flags::empty(), AccessLevel::Superuser, "Null", "void", &[], "");
const META_METH_ACTIVATE: MetaMethod = MetaMethod::new_static(METH_ACTIVATE, Flags::empty(), AccessLevel::Superuser, "Null", "void", &[], "");
const SET_VALUE_NODE_METHODS: &[&MetaMethod] = &[&META_METHOD_PRIVATE_DIR, &META_METHOD_PRIVATE_LS, &META_METH_SET_VALUE];
const VALUE_NODE_METHODS: &[&MetaMethod] = &[&META_METHOD_PRIVATE_DIR, &META_METHOD_PRIVATE_LS, &META_METH_VALUE];
const USER_ACCESS_VALUE_NODE_METHODS: &[&MetaMethod] = &[&META_METHOD_PRIVATE_DIR, &META_METHOD_PRIVATE_LS, &META_METH_VALUE, &META_METH_ACTIVATE, &META_METH_DEACTIVATE];
pub(crate) struct BrokerAccessMountsNode {}
impl BrokerAccessMountsNode {
    pub(crate) fn new() -> Self {
        Self {
        }
    }
}
fn make_access_ro_error() -> String {
    "Broker config is read only, use --use-access-db config option.".to_string()
}
#[async_trait::async_trait]
impl ShvNode for BrokerAccessMountsNode {
    fn methods(&self, shv_path: &str) -> &'static[&'static MetaMethod] {
        if shv_path.is_empty() {
            SET_VALUE_NODE_METHODS
        } else {
            VALUE_NODE_METHODS
        }
    }

    async fn children(&self, shv_path: &str, broker_state: Arc<BrokerImpl>) -> Option<Vec<String>> {
        if shv_path.is_empty() {
            Some(broker_state.access.read().await.mounts().keys().map(|m| m.to_string()).collect())
        } else {
            Some(vec![])
        }
    }

    async fn process_request(&self, frame: &RpcFrame, ctx: &NodeRequestContext) -> ProcessRequestResult {
        match frame.method().unwrap_or_default() {
            METH_VALUE => {
                match ctx.state.access.read().await.access_mount(&ctx.node_path) {
                    None => {
                        Err(format!("Invalid node key: {}", &ctx.node_path).into())
                    }
                    Some(mount) => {
                        Ok(ProcessRequestRetval::Retval(mount.to_rpcvalue()?))
                    }
                }
            }
            METH_SET_VALUE => {
                let Some(sql_connection) = &ctx.state.sql_connection else {
                    return Err(make_access_ro_error().into())
                };
                let param = frame.to_rpcmesage()?.param().ok_or("Invalid params")?.clone();
                let param = param.as_list();
                let key = param.first().ok_or("Key is missing")?;
                let mount = param.get(1).and_then(|m| if m.is_null() {None} else {Some(m)});
                let mount = mount.map(crate::config::Mount::try_from);
                let mount = match mount {
                    None => None,
                    Some(Ok(mount)) => {Some(mount)}
                    Some(Err(e)) => { return Err(e.into() )}
                };
                let res = ctx.state.access.write().await.set_access_mount(key.as_str(), mount, sql_connection).await?;
                Ok(ProcessRequestRetval::Retval(res))
            }
            _ => {
                Ok(ProcessRequestRetval::MethodNotFound)
            }
        }
    }
}

pub(crate) struct BrokerAccessUsersNode {}
impl BrokerAccessUsersNode {
    pub(crate) fn new() -> Self {
        Self {
        }
    }
}

#[async_trait::async_trait]
impl ShvNode for crate::shvnode::BrokerAccessUsersNode {
    fn methods(&self, shv_path: &str) -> &'static[&'static MetaMethod] {
        if shv_path.is_empty() {
            SET_VALUE_NODE_METHODS
        } else {
            USER_ACCESS_VALUE_NODE_METHODS
        }
    }

    async fn children(&self, shv_path: &str, broker_state: Arc<BrokerImpl>) -> Option<Vec<String>> {
        if shv_path.is_empty() {
            Some(broker_state.access.read().await.users().keys().map(|m| m.to_string()).collect())
        } else {
            Some(vec![])
        }
    }

    async fn process_request(&self, frame: &RpcFrame, ctx: &NodeRequestContext) -> ProcessRequestResult {
        const DEACTIVATE: bool = true;
        const ACTIVATE: bool = false;
        let process_activation_change = async |new_deactivated| {
            let Some(sql_connection) = &ctx.state.sql_connection else {
                return Err(make_access_ro_error().into())
            };
            let mut access = ctx.state.access.write().await;
            let user = access.access_user(&ctx.node_path).cloned();
            match user {
                None => {
                    Err(format!("Invalid node key: {}", &ctx.node_path).into())
                }
                Some(mut user) => {
                    if user.deactivated == new_deactivated {
                        return Err(format!("User {username} already {what}", username = &ctx.node_path, what = if new_deactivated { "deactivated" } else { "activated" }).into());
                    }
                    user.deactivated = new_deactivated;
                    let res = access.set_access_user(&ctx.node_path, Some(user), sql_connection).await?;
                    Ok(ProcessRequestRetval::Retval(res))
                }
            }
        };

        match frame.method().unwrap_or_default() {
            METH_VALUE => {
                match ctx.state.access.read().await.access_user(&ctx.node_path) {
                    None => {
                        Err(format!("Invalid node key: {}", &ctx.node_path).into())
                    }
                    Some(user) => {
                        Ok(ProcessRequestRetval::Retval(user.to_rpcvalue()?))
                    }
                }
            }
            METH_DEACTIVATE => process_activation_change(DEACTIVATE).await,
            METH_ACTIVATE => process_activation_change(ACTIVATE).await,
            METH_SET_VALUE => {
                let Some(sql_connection) = &ctx.state.sql_connection else {
                    return Err(make_access_ro_error().into())
                };
                let param = frame.to_rpcmesage()?.param().ok_or("Invalid params")?.clone();
                let param = param.as_list();
                let key = param.first().ok_or("Key is missing")?;
                let rv = param.get(1).and_then(|m| if m.is_null() {None} else {Some(m)});
                let user = if let Some(rv) = rv {
                    match crate::config::User::try_from(rv) {
                        Ok(user) => { Some(user) }
                        Err(e) => {
                            return Err(e.into())
                        }
                    }
                } else {
                    None
                };
                let res = ctx.state.access.write().await.set_access_user(key.as_str(), user, sql_connection).await?;
                Ok(ProcessRequestRetval::Retval(res))
            }
            _ => {
                Ok(ProcessRequestRetval::MethodNotFound)
            }
        }
    }
}

pub(crate) struct BrokerAccessRolesNode {}
impl crate::shvnode::BrokerAccessRolesNode {
    pub(crate) fn new() -> Self {
        Self {
        }
    }
}

#[async_trait::async_trait]
impl ShvNode for BrokerAccessRolesNode {
    fn methods(&self, shv_path: &str) -> &'static[&'static MetaMethod] {
        if shv_path.is_empty() {
            SET_VALUE_NODE_METHODS
        } else {
            VALUE_NODE_METHODS
        }
    }

    async fn children(&self, shv_path: &str, broker_state: Arc<BrokerImpl>) -> Option<Vec<String>> {
        if shv_path.is_empty() {
            Some(broker_state.access.read().await.roles().keys().map(|m| m.to_string()).collect())
        } else {
            Some(vec![])
        }
    }

    async fn process_request(&self, frame: &RpcFrame, ctx: &NodeRequestContext) -> ProcessRequestResult {
        match frame.method().unwrap_or_default() {
            METH_VALUE => {
                match ctx.state.access.read().await.access_role(&ctx.node_path) {
                    None => {
                        Err(format!("Invalid node key: {}", &ctx.node_path).into())
                    }
                    Some(role) => {
                        Ok(ProcessRequestRetval::Retval(role.to_rpcvalue()?))
                    }
                }
            }
            METH_SET_VALUE => {
                let Some(sql_connection) = &ctx.state.sql_connection else {
                    return Err(make_access_ro_error().into())
                };
                let param = frame.to_rpcmesage()?.param().ok_or("Invalid params")?.clone();
                let param = param.as_list();
                let key = param.first().ok_or("Key is missing")?.clone();
                let rv = param.get(1).and_then(|m| if m.is_null() {None} else {Some(m)});
                let role = rv.map(crate::config::Role::try_from);
                let role = match role {
                    None => None,
                    Some(Ok(role)) => {Some(role)}
                    Some(Err(e)) => { return Err(e.into() )}
                };
                let res = ctx.state.access.write().await.set_access_role(key.as_str(), role, &ctx.state.role_access_rules, sql_connection).await?;
                Ok(ProcessRequestRetval::Retval(res))
            }
            _ => {
                Ok(ProcessRequestRetval::MethodNotFound)
            }
        }
    }
}

pub(crate) struct BrokerAccessAllowedIpsNode {}
impl BrokerAccessAllowedIpsNode {
    pub(crate) fn new() -> Self {
        Self {
        }
    }
}

#[async_trait::async_trait]
impl ShvNode for BrokerAccessAllowedIpsNode {
    fn methods(&self, shv_path: &str) -> &'static[&'static MetaMethod] {
        if shv_path.is_empty() {
            SET_VALUE_NODE_METHODS
        } else {
            VALUE_NODE_METHODS
        }
    }

    async fn children(&self, shv_path: &str, broker_state: Arc<BrokerImpl>) -> Option<Vec<String>> {
        if shv_path.is_empty() {
            Some(broker_state.access.read().await.allowed_ips().keys().map(|m| m.to_string()).collect())
        } else {
            Some(vec![])
        }
    }

    async fn process_request(&self, frame: &RpcFrame, ctx: &NodeRequestContext) -> ProcessRequestResult {
        match frame.method().unwrap_or_default() {
            METH_VALUE => {
                match ctx.state.access.read().await.access_allowed_ips(&ctx.node_path) {
                    None => {
                        Err(format!("Invalid node key: {}", &ctx.node_path).into())
                    }
                    Some(allowed_ips) => {
                        Ok(ProcessRequestRetval::Retval(serde_json::to_string(&allowed_ips)?.into()))
                    }
                }
            }
            METH_SET_VALUE => {
                let Some(sql_connection) = &ctx.state.sql_connection else {
                    return Err(make_access_ro_error().into())
                };
                let param = frame.to_rpcmesage()?.param().ok_or("Invalid params")?.clone();
                let param = param.as_list();
                let key = param.first().ok_or("Key is missing")?;
                let allowed_ips = param.get(1).and_then(|m| if m.is_null() {None} else {Some(m)});
                let allowed_ips: Option<Result<Vec<ipnet::IpNet>,_>> = allowed_ips
                    .map(|val| val
                        .as_list()
                        .iter()
                        .map(|ip| ip
                            .as_str()
                            .parse()
                        ).collect::<Result<Vec<_>,_>>());
                let allowed_ips  = match allowed_ips {
                    None => None,
                    Some(Ok(allowed_ips)) => {Some(allowed_ips)}
                    Some(Err(e)) => { return Err(e.into() )}
                };
                let res = ctx.state.access.write().await.set_allowed_ips(key.as_str(), allowed_ips, sql_connection).await?;
                Ok(ProcessRequestRetval::Retval(res))
            }
            _ => {
                Ok(ProcessRequestRetval::MethodNotFound)
            }
        }
    }
}

pub(crate) struct BrokerAccessLastLoginNode {}
impl BrokerAccessLastLoginNode {
    pub(crate) fn new() -> Self {
        Self {
        }
    }
}

#[async_trait::async_trait]
impl ShvNode for BrokerAccessLastLoginNode {
    fn methods(&self, _shv_path: &str) -> &'static[&'static MetaMethod] {
        VALUE_NODE_METHODS
    }

    async fn children(&self, shv_path: &str, broker_state: Arc<BrokerImpl>) -> Option<Vec<String>> {
        if shv_path.is_empty() {
            Some(broker_state.last_login().await.0.keys().map(|m| m.to_string()).collect())
        } else {
            Some(vec![])
        }
    }

    async fn process_request(&self, frame: &RpcFrame, ctx: &NodeRequestContext) -> ProcessRequestResult {
        match frame.method().unwrap_or_default() {
            METH_VALUE => {
                if ctx.node_path.is_empty() {
                    return Ok(ProcessRequestRetval::Retval(ctx.state.last_login().await.0.clone().into()));
                }

                match ctx.state.last_login().await.0.get(&ctx.node_path) {
                    None => {
                        Err(format!("Invalid node key: {}", &ctx.node_path).into())
                    }
                    Some(dt) => {
                        Ok(ProcessRequestRetval::Retval(shvproto::to_rpcvalue(&dt)?))
                    }
                }
            }
            _ => {
                Ok(ProcessRequestRetval::MethodNotFound)
            }
        }
    }
}

pub const SHV2_METH_APP_VERSION: &str = "appVersion";
const SHV2_META_METH_APP_VERSION: MetaMethod = MetaMethod::new_static(SHV2_METH_APP_VERSION, Flags::IsGetter, AccessLevel::Browse, "", "", &[], "");
const SHV2_BROKER_APP_NODE_METHODS: &[&MetaMethod] = &[&META_METHOD_PRIVATE_DIR, &META_METHOD_PRIVATE_LS, &META_METH_APP_NAME, &SHV2_META_METH_APP_VERSION, &META_METH_APP_PING, &META_METH_SUBSCRIBE, &META_METH_UNSUBSCRIBE];

pub(crate) struct Shv2BrokerAppNode {}
impl Shv2BrokerAppNode {
    pub(crate) fn new() -> Self {
        Self {
        }
    }

    async fn subscribe(peer_id: PeerId, subpar: &SubscriptionParam, state: Arc<BrokerImpl>) -> shvrpc::Result<bool> {
        let ri_to_shv2_compat = |ri: &shvrpc::rpc::ShvRI| {
            let path = if !ri.path().ends_with("/**") {
                format!("{path}/**", path = ri.path())
            } else {
                ri.path().into()
            };
            shvrpc::rpc::ShvRI::from_path_method_signal(&path, ri.method(), ri.signal())
        };
        let subpar = SubscriptionParam {
            ri: ri_to_shv2_compat(&subpar.ri)
                .map_err(|err| format!("Cannot convert RI '{ri}' to shv2 compatible equivalent: {err}", ri = subpar.ri.as_str()))?,
            ttl: subpar.ttl,
        };
        let res = state.subscribe(peer_id, &subpar).await;
        log!(target: "Subscr", Level::Debug, "subscribe handler for peer id: {peer_id} - {subpar}, res: {res:?}");
        res
    }

    async fn unsubscribe(peer_id: PeerId, subpar: &SubscriptionParam, state: Arc<BrokerImpl>) -> shvrpc::Result<bool> {
        let res = state.unsubscribe(peer_id, subpar).await;
        log!(target: "Subscr", Level::Debug, "unsubscribe handler for peer id: {peer_id} - {subpar}, res: {res:?}");
        res
    }
}

#[async_trait::async_trait]
impl ShvNode for Shv2BrokerAppNode {
    fn methods(&self, _shv_path: &str) -> &'static[&'static MetaMethod] {
        SHV2_BROKER_APP_NODE_METHODS
    }

    async fn children(&self, _shv_path: &str, _broker_state: Arc<BrokerImpl>) -> Option<Vec<String>> {
        Some(vec![])
    }

    async fn process_request(&self, frame: &RpcFrame, ctx: &NodeRequestContext) -> ProcessRequestResult {
        match frame.method().unwrap_or_default() {
            METH_PING => {
                Ok(ProcessRequestRetval::Retval(().into()))
            }
            METH_NAME => {
                Ok(ProcessRequestRetval::Retval(env!("CARGO_PKG_NAME").into()))
            }
            SHV2_METH_APP_VERSION => {
                Ok(ProcessRequestRetval::Retval(env!("CARGO_PKG_VERSION").into()))
            }
            METH_SUBSCRIBE => {
                let rq = &frame.to_rpcmesage()?;
                let subscription = SubscriptionParam::from_rpcvalue(rq.param().unwrap_or_default())?;
                let subs_added = Self::subscribe(ctx.peer_id, &subscription, ctx.state.clone()).await?;
                Ok(ProcessRequestRetval::Retval(subs_added.into()))
            }
            METH_UNSUBSCRIBE => {
                let rq = &frame.to_rpcmesage()?;
                let subscription = SubscriptionParam::from_rpcvalue(rq.param().unwrap_or_default())?;
                let subs_removed = Self::unsubscribe(ctx.peer_id, &subscription, ctx.state.clone()).await?;
                Ok(ProcessRequestRetval::Retval(subs_removed.into()))
            }
            _ => {
                Ok(ProcessRequestRetval::MethodNotFound)
            }
        }
    }
}