-
Notifications
You must be signed in to change notification settings - Fork 151
Expand file tree
/
Copy pathcommands.rs
More file actions
1018 lines (877 loc) · 23.3 KB
/
commands.rs
File metadata and controls
1018 lines (877 loc) · 23.3 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 std::{
collections::HashMap,
fmt::Write,
iter::once,
str::FromStr,
time::{Instant, SystemTime},
};
use futures::{FutureExt, StreamExt, TryStreamExt};
use ruma::{
CanonicalJsonObject, CanonicalJsonValue, EventId, OwnedEventId, OwnedRoomId,
OwnedRoomOrAliasId, OwnedServerName, RoomId, RoomVersionId,
api::federation::event::get_room_state, events::AnyStateEvent, serde::Raw,
};
use serde::Serialize;
use tracing_subscriber::EnvFilter;
use tuwunel_core::{
Err, Result, debug_error, err, info, jwt,
matrix::{
Event,
pdu::{PduEvent, PduId, RawPduId},
},
trace,
utils::{self, stream::ReadyExt, string::EMPTY, time::now_secs},
warn,
};
use tuwunel_service::rooms::{
short::{ShortEventId, ShortRoomId},
state_compressor::HashSetCompressStateEvent,
};
use crate::{command, utils::parse_local_user_id};
#[command]
pub(super) async fn echo(&self, message: Vec<String>) -> Result<String> {
let message = message.join(" ");
Ok(message)
}
#[command]
pub(super) async fn get_auth_chain(&self, event_id: OwnedEventId) -> Result<String> {
let Ok(event) = self
.services
.timeline
.get_pdu_json(&event_id)
.await
else {
return Err!("Event not found.");
};
let room_id_str = event
.get("room_id")
.and_then(CanonicalJsonValue::as_str)
.ok_or_else(|| err!(Database("Invalid event in database")))?;
let room_id = <&RoomId>::try_from(room_id_str)
.map_err(|_| err!(Database("Invalid room id field in event in database")))?;
let start = Instant::now();
let count = self
.services
.auth_chain
.event_ids_iter(room_id, once(event_id.as_ref()))
.ready_filter_map(Result::ok)
.count()
.await;
let elapsed = start.elapsed();
Ok(format!("Loaded auth chain with length {count} in {elapsed:?}"))
}
#[command]
pub(super) async fn parse_pdu(&self) -> Result<String> {
let rules = RoomVersionId::V6
.rules()
.expect("rules for V6 rooms");
match serde_json::from_str(self.input) {
| Err(e) => Err!("Invalid json in command body: {e}"),
| Ok(value) => match ruma::signatures::reference_hash(&value, &rules) {
| Err(e) => Err!("Could not parse PDU JSON: {e:?}"),
| Ok(hash) => {
let event_id = OwnedEventId::parse(format!("${hash}"));
match serde_json::from_value::<PduEvent>(serde_json::to_value(value)?) {
| Err(e) => Err!("EventId: {event_id:?}\nCould not parse event: {e}"),
| Ok(pdu) => Ok(format!("EventId: {event_id:?}\n{pdu:#?}")),
}
},
},
}
}
#[command]
pub(super) async fn get_pdu(&self, event_id: OwnedEventId) -> Result<String> {
let mut outlier = false;
let mut pdu_json = self
.services
.timeline
.get_non_outlier_pdu_json(&event_id)
.await;
if pdu_json.is_err() {
outlier = true;
pdu_json = self
.services
.timeline
.get_pdu_json(&event_id)
.await;
}
match pdu_json {
| Err(_) => Err!("PDU not found locally."),
| Ok(json) => {
let text = serde_json::to_string_pretty(&json)?;
let msg = if outlier {
"Outlier (Rejected / Soft Failed) PDU found in our database"
} else {
"PDU found in our database"
};
Ok(format!("{msg}\n```json\n{text}\n```"))
},
}
}
#[command]
pub(super) async fn get_short_pdu(
&self,
shortroomid: ShortRoomId,
shorteventid: ShortEventId,
) -> Result<String> {
let pdu_id: RawPduId = PduId {
shortroomid,
shorteventid: shorteventid.into(),
}
.into();
let pdu_json = self
.services
.timeline
.get_pdu_json_from_id(&pdu_id)
.await;
match pdu_json {
| Err(_) => Err!("PDU not found locally."),
| Ok(json) => {
let json_text = serde_json::to_string_pretty(&json)?;
Ok(format!("```json\n{json_text}\n```"))
},
}
}
#[command]
pub(super) async fn get_remote_pdu_list(
&self,
server: OwnedServerName,
force: bool,
) -> Result<String> {
if !self.services.server.config.allow_federation {
return Err!("Federation is disabled on this homeserver.");
}
if server == self.services.globals.server_name() {
return Err!(
"Not allowed to send federation requests to ourselves. Please use `get-pdu` for \
fetching local PDUs from the database.",
);
}
let list = self
.input
.lines()
.filter_map(|pdu| EventId::parse(pdu).ok())
.collect::<Vec<_>>();
let mut failed_count: usize = 0;
let mut success_count: usize = 0;
for event_id in list {
if force {
match self
.get_remote_pdu(event_id.to_owned(), server.clone())
.await
{
| Err(e) => {
failed_count = failed_count.saturating_add(1);
self.services
.admin
.send_text(&format!("Failed to get remote PDU, ignoring error: {e}"))
.await;
warn!("Failed to get remote PDU, ignoring error: {e}");
},
| _ => {
success_count = success_count.saturating_add(1);
},
}
} else {
self.get_remote_pdu(event_id.to_owned(), server.clone())
.await?;
success_count = success_count.saturating_add(1);
}
}
Ok(format!(
"Fetched {success_count} remote PDUs successfully with {failed_count} failures"
))
}
#[command]
pub(super) async fn get_remote_pdu(
&self,
event_id: OwnedEventId,
server: OwnedServerName,
) -> Result<String> {
if !self.services.server.config.allow_federation {
return Err!("Federation is disabled on this homeserver.");
}
if server == self.services.globals.server_name() {
return Err!(
"Not allowed to send federation requests to ourselves. Please use `get-pdu` for \
fetching local PDUs.",
);
}
match self
.services
.sending
.send_federation_request(&server, ruma::api::federation::event::get_event::v1::Request {
event_id: event_id.clone(),
})
.await
{
| Err(e) => {
Err!("Remote server did not have PDU or failed sending request to remote server: {e}")
},
| Ok(response) => {
let json: CanonicalJsonObject =
serde_json::from_str(response.pdu.get()).map_err(|e| {
warn!(
"Requested event ID {event_id} from server but failed to convert from \
RawValue to CanonicalJsonObject (malformed event/response?): {e}"
);
err!(Request(Unknown(
"Received response from server but failed to parse PDU"
)))
})?;
trace!("Attempting to parse PDU: {:?}", &response.pdu);
let (room_id, ..) = {
let parsed_result = self
.services
.event_handler
.parse_incoming_pdu(&response.pdu)
.boxed()
.await;
match parsed_result {
| Ok(t) => t,
| Err(e) => {
warn!("Failed to parse PDU: {e}");
info!("Full PDU: {:?}", &response.pdu);
return Err!("Failed to parse PDU remote server {server} sent us: {e}");
},
}
};
info!("Attempting to handle event ID {event_id} as backfilled PDU");
self.services
.timeline
.backfill_pdu(&room_id, &server, response.pdu)
.await?;
let text = serde_json::to_string_pretty(&json)?;
let msg = "Got PDU from specified server and handled as backfilled";
Ok(format!("{msg}. Event body:\n```json\n{text}\n```"))
},
}
}
#[command]
pub(super) async fn get_room_state(&self, room: OwnedRoomOrAliasId) -> Result<String> {
let room_id = self.services.alias.maybe_resolve(&room).await?;
let room_state: Vec<Raw<AnyStateEvent>> = self
.services
.state_accessor
.room_state_full_pdus(&room_id)
.map_ok(Event::into_format)
.try_collect()
.await?;
if room_state.is_empty() {
return Err!("Unable to find room state in our database (vector is empty)");
}
let json = serde_json::to_string_pretty(&room_state).map_err(|e| {
err!(Database(
"Failed to convert room state events to pretty JSON, possible invalid room state \
events in our database {e}",
))
})?;
Ok(format!("```json\n{json}\n```"))
}
#[command]
pub(super) async fn ping(&self, server: OwnedServerName) -> Result<String> {
if server == self.services.globals.server_name() {
return Err!("Not allowed to send federation requests to ourselves.");
}
let timer = tokio::time::Instant::now();
match self
.services
.sending
.send_federation_request(
&server,
ruma::api::federation::discovery::get_server_version::v1::Request {},
)
.await
{
| Err(e) => {
Err!("Failed sending federation request to specified server:\n\n{e}")
},
| Ok(response) => {
let ping_time = timer.elapsed();
let json_text_res = serde_json::to_string_pretty(&response.server);
let out = if let Ok(json) = json_text_res {
format!("Got response which took {ping_time:?} time:\n```json\n{json}\n```")
} else {
format!("Got non-JSON response which took {ping_time:?} time:\n{response:?}")
};
Ok(out)
},
}
}
#[command]
pub(super) async fn force_device_list_updates(&self) -> Result<String> {
// Force E2EE device list updates for all users
self.services
.users
.stream()
.for_each(|user_id| {
self.services
.users
.mark_device_key_update(user_id)
})
.await;
Ok("Marked all devices for all users as having new keys to update".to_owned())
}
#[command]
pub(super) async fn change_log_level(
&self,
filter: Option<String>,
reset: bool,
) -> Result<String> {
let handles = &["console"];
if reset {
let old_filter_layer = match EnvFilter::try_new(&self.services.server.config.log) {
| Ok(s) => s,
| Err(e) => return Err!("Log level from config appears to be invalid now: {e}"),
};
match self
.services
.server
.log
.reload
.reload(&old_filter_layer, Some(handles))
{
| Err(e) => {
return Err!("Failed to modify and reload the global tracing log level: {e}");
},
| Ok(()) => {
let value = &self.services.server.config.log;
return Ok(format!(
"Successfully changed log level back to config value {value}"
));
},
}
}
if let Some(filter) = filter {
let new_filter_layer = match EnvFilter::try_new(filter) {
| Ok(s) => s,
| Err(e) => return Err!("Invalid log level filter specified: {e}"),
};
match self
.services
.server
.log
.reload
.reload(&new_filter_layer, Some(handles))
{
| Ok(()) => {
return Ok("Successfully changed log level".to_owned());
},
| Err(e) => {
return Err!("Failed to modify and reload the global tracing log level: {e}");
},
}
}
Err!("No log level was specified.")
}
#[command]
pub(super) async fn sign_json(&self) -> Result<String> {
match serde_json::from_str(self.input) {
| Err(e) => Err!("Invalid json: {e}"),
| Ok(mut value) => {
self.services.server_keys.sign_json(&mut value)?;
let json_text = serde_json::to_string_pretty(&value)?;
Ok(json_text)
},
}
}
#[command]
pub(super) async fn verify_json(&self) -> Result<String> {
match serde_json::from_str::<CanonicalJsonObject>(self.input) {
| Err(e) => Err!("Invalid json: {e}"),
| Ok(value) => match self
.services
.server_keys
.verify_json(&value, None)
.await
{
| Err(e) => Err!("Signature verification failed: {e}"),
| Ok(()) => Ok("Signature correct".to_owned()),
},
}
}
#[command]
pub(super) async fn verify_pdu(&self, event_id: OwnedEventId) -> Result<String> {
use ruma::signatures::Verified;
let mut event = self
.services
.timeline
.get_pdu_json(&event_id)
.await?;
event.remove("event_id");
let msg = match self
.services
.server_keys
.verify_event(&event, None)
.await
{
| Err(e) => return Err(e),
| Ok(Verified::Signatures) => "signatures OK, but content hash failed (redaction).",
| Ok(Verified::All) => "signatures and hashes OK.",
};
Ok(msg.to_owned())
}
#[command]
#[tracing::instrument(skip(self))]
pub(super) async fn first_pdu_in_room(&self, room_id: OwnedRoomId) -> Result<String> {
if !self
.services
.state_cache
.server_in_room(&self.services.server.name, &room_id)
.await
{
return Err!("We are not participating in the room / we don't know about the room ID.");
}
let first_pdu = self
.services
.timeline
.first_pdu_in_room(&room_id)
.await
.map_err(|_| err!(Database("Failed to find the first PDU in database")))?;
Ok(format!("{first_pdu:?}"))
}
#[command]
#[tracing::instrument(skip(self))]
pub(super) async fn latest_pdu_in_room(&self, room_id: OwnedRoomId) -> Result<String> {
if !self
.services
.state_cache
.server_in_room(&self.services.server.name, &room_id)
.await
{
return Err!("We are not participating in the room / we don't know about the room ID.");
}
let latest_pdu = self
.services
.timeline
.latest_pdu_in_room(&room_id)
.await
.map_err(|_| err!(Database("Failed to find the latest PDU in database")))?;
Ok(format!("{latest_pdu:?}"))
}
#[command]
#[tracing::instrument(skip(self))]
pub(super) async fn force_set_room_state_from_server(
&self,
room_id: OwnedRoomId,
server_name: OwnedServerName,
) -> Result<String> {
if !self
.services
.state_cache
.server_in_room(&self.services.server.name, &room_id)
.await
{
return Err!("We are not participating in the room / we don't know about the room ID.");
}
let first_pdu = self
.services
.timeline
.latest_pdu_in_room(&room_id)
.await
.map_err(|_| err!(Database("Failed to find the latest PDU in database")))?;
let room_version = self
.services
.state
.get_room_version(&room_id)
.await?;
let mut state: HashMap<u64, OwnedEventId> = HashMap::new();
let remote_state_response = self
.services
.sending
.send_federation_request(&server_name, get_room_state::v1::Request {
room_id: room_id.clone(),
event_id: first_pdu.event_id().to_owned(),
})
.await?;
for pdu in remote_state_response.pdus.clone() {
match self
.services
.event_handler
.parse_incoming_pdu(&pdu)
.await
{
| Ok(t) => t,
| Err(e) => {
warn!("Could not parse PDU, ignoring: {e}");
continue;
},
};
}
info!("Going through room_state response PDUs");
for result in remote_state_response.pdus.iter().map(|pdu| {
self.services
.server_keys
.validate_and_add_event_id(pdu, &room_version)
}) {
let Ok((event_id, mut value)) = result.await else {
continue;
};
let invalid_pdu_err = |e| {
debug_error!("Invalid PDU in fetching remote room state PDUs response: {value:#?}");
err!(BadServerResponse(debug_error!("Invalid PDU in send_join response: {e:?}")))
};
let pdu = if value["type"] == "m.room.create" {
PduEvent::from_rid_val(&room_id, &event_id, value.clone()).map_err(invalid_pdu_err)?
} else {
PduEvent::from_id_val(&event_id, value.clone()).map_err(invalid_pdu_err)?
};
if !value.contains_key("room_id") {
let room_id = CanonicalJsonValue::String(room_id.as_str().into());
value.insert("room_id".into(), room_id);
}
self.services
.timeline
.add_pdu_outlier(&event_id, &value);
if let Some(state_key) = &pdu.state_key {
let shortstatekey = self
.services
.short
.get_or_create_shortstatekey(&pdu.kind.to_string().into(), state_key)
.await;
state.insert(shortstatekey, pdu.event_id.clone());
}
}
info!("Going through auth_chain response");
for result in remote_state_response
.auth_chain
.iter()
.map(|pdu| {
self.services
.server_keys
.validate_and_add_event_id(pdu, &room_version)
}) {
let Ok((event_id, value)) = result.await else {
continue;
};
self.services
.timeline
.add_pdu_outlier(&event_id, &value);
}
let new_room_state = self
.services
.event_handler
.resolve_state(&room_id, &room_version, state)
.await?;
info!("Forcing new room state");
let HashSetCompressStateEvent {
shortstatehash: short_state_hash,
added,
removed,
} = self
.services
.state_compressor
.save_state(room_id.clone().as_ref(), new_room_state)
.await?;
let state_lock = self.services.state.mutex.lock(&*room_id).await;
self.services
.state
.force_state(room_id.clone().as_ref(), short_state_hash, added, removed, &state_lock)
.await?;
info!(
"Updating joined counts for room just in case (e.g. we may have found a difference in \
the room's m.room.member state"
);
self.services
.state_cache
.update_joined_count(&room_id)
.await;
Ok("Successfully forced the room state from the requested remote server.".to_owned())
}
#[command]
pub(super) async fn get_signing_keys(
&self,
server_name: Option<OwnedServerName>,
notary: Option<OwnedServerName>,
query: bool,
) -> Result<String> {
let server_name = server_name.unwrap_or_else(|| self.services.server.name.clone());
if let Some(notary) = notary {
let signing_keys = self
.services
.server_keys
.notary_request(¬ary, &server_name)
.await?;
return Ok(format!("```rs\n{signing_keys:#?}\n```"));
}
let signing_keys = if query {
self.services
.server_keys
.server_request(&server_name)
.await?
} else {
self.services
.server_keys
.signing_keys_for(&server_name)
.await?
};
Ok(format!("```rs\n{signing_keys:#?}\n```"))
}
#[command]
pub(super) async fn get_verify_keys(
&self,
server_name: Option<OwnedServerName>,
) -> Result<String> {
let server_name = server_name.unwrap_or_else(|| self.services.server.name.clone());
let keys = self
.services
.server_keys
.verify_keys_for(&server_name)
.await;
let mut out = String::new();
writeln!(out, "| Key ID | Public Key |")?;
writeln!(out, "| --- | --- |")?;
for (key_id, key) in keys {
writeln!(out, "| {key_id} | {key:?} |")?;
}
Ok(out)
}
#[command]
pub(super) async fn resolve_true_destination(
&self,
server_name: OwnedServerName,
no_cache: bool,
) -> Result<String> {
if !self.services.server.config.allow_federation {
return Err!("Federation is disabled on this homeserver.");
}
if server_name == self.services.server.name {
return Err!(
"Not allowed to send federation requests to ourselves. Please use `get-pdu` for \
fetching local PDUs.",
);
}
let actual = self
.services
.resolver
.resolve_actual_dest(&server_name, !no_cache)
.await?;
Ok(format!("Destination: {}\nHostname URI: {}", actual.dest, actual.host))
}
#[command]
pub(super) async fn memory_stats(&self, opts: Option<String>) -> Result<String> {
const OPTS: &str = "abcdefghijklmnopqrstuvwxyz";
let opts: String = OPTS
.chars()
.filter(|&c| {
let allow_any = opts.as_ref().is_some_and(|opts| opts == "*");
let allow = allow_any || opts.as_ref().is_some_and(|opts| opts.contains(c));
!allow
})
.collect();
let stats = tuwunel_core::alloc::memory_stats(&opts).unwrap_or_default();
Ok(format!("```\n{stats}\n```"))
}
#[cfg(tokio_unstable)]
#[command]
pub(super) async fn runtime_metrics(&self) -> Result<String> {
let out = self
.services
.server
.metrics
.runtime_metrics()
.map_or_else(
|| "Runtime metrics are not available.".to_owned(),
|metrics| {
format!(
"```rs\nnum_workers: {}\nnum_alive_tasks: {}\nglobal_queue_depth: {}\n```",
metrics.num_workers(),
metrics.num_alive_tasks(),
metrics.global_queue_depth()
)
},
);
Ok(out)
}
#[cfg(not(tokio_unstable))]
#[command]
pub(super) async fn runtime_metrics(&self) -> Result<String> {
Ok("Runtime metrics require building with `tokio_unstable`.".to_owned())
}
#[cfg(tokio_unstable)]
#[command]
pub(super) async fn runtime_interval(&self) -> Result<String> {
let out = self
.services
.server
.metrics
.runtime_interval()
.map_or_else(
|| "Runtime metrics are not available.".to_owned(),
|metrics| format!("```rs\n{metrics:#?}\n```"),
);
Ok(out)
}
#[cfg(not(tokio_unstable))]
#[command]
pub(super) async fn runtime_interval(&self) -> Result<String> {
Ok("Runtime metrics require building with `tokio_unstable`.".to_owned())
}
#[command]
pub(super) async fn time(&self) -> Result<String> {
let now = SystemTime::now();
let now = utils::time::format(now, "%+");
Ok(now)
}
#[command]
pub(super) async fn list_dependencies(&self, names: bool) -> Result<String> {
if names {
let out = info::cargo::dependencies_names().join(" ");
return Ok(out);
}
let mut out = String::new();
let deps = info::cargo::dependencies();
writeln!(out, "| name | version | features |")?;
writeln!(out, "| ---- | ------- | -------- |")?;
for (name, dep) in deps {
let version = dep.try_req().unwrap_or("*");
let feats = dep.req_features();
let feats = if !feats.is_empty() {
feats.join(" ")
} else {
String::new()
};
writeln!(out, "| {name} | {version} | {feats} |")?;
}
Ok(out)
}
#[command]
pub(super) async fn database_stats(
&self,
property: Option<String>,
map: Option<String>,
) -> Result<String> {
let map_name = map.as_ref().map_or(EMPTY, String::as_str);
let property = property.unwrap_or_else(|| "rocksdb.stats".to_owned());
let mut out = String::new();
for (&name, map) in self.services.db.iter() {
if map_name.is_empty() || map_name == name {
let res = map.property(&property).expect("invalid property");
writeln!(out, "##### {name}:\n```\n{}\n```", res.trim())?;
}
}
Ok(out)
}
#[command]
pub(super) async fn database_files(
&self,
map: Option<String>,
level: Option<i32>,
) -> Result<String> {
let mut files: Vec<_> = self
.services
.db
.engine
.file_list()
.collect::<Result<_>>()?;
files.sort_by_key(|f| f.name.clone());
let mut out = String::new();
writeln!(out, "| lev | sst | keys | dels | size | column |")?;
writeln!(out, "| ---: | :--- | ---: | ---: | ---: | :--- |")?;
for file in files {
if map
.as_deref()
.is_some_and(|map| map != file.column_family_name)
{
continue;
}
if level
.as_ref()
.is_some_and(|&level| level != file.level)
{
continue;
}
writeln!(
out,
"| {} | {:<13} | {:7}+ | {:4}- | {:9} | {} |",
file.level,
file.name,
file.num_entries,
file.num_deletions,
file.size,
file.column_family_name,
)?;
}
Ok(out)
}
#[command]
pub(super) async fn trim_memory(&self) -> Result<String> {
tuwunel_core::alloc::trim(None)?;
Ok("done".to_owned())
}
#[command]
pub(super) async fn create_jwt(
&self,
user: String,
exp_from_now: Option<u64>,
nbf_from_now: Option<u64>,
issuer: Option<String>,
audience: Option<String>,
) -> Result<String> {
use jwt::{Algorithm, EncodingKey, Header, encode};
#[derive(Serialize)]
struct Claim {
sub: String,
iss: Option<String>,
aud: Option<String>,
exp: Option<usize>,
nbf: Option<usize>,
}
let config = &self.services.config.jwt;
if config.format.as_str() != "HMAC" {
return Err!("This command only supports HMAC key format, not {}.", config.format);
}
let key = EncodingKey::from_secret(config.key.as_ref());
let alg = Algorithm::from_str(config.algorithm.as_str()).map_err(|e| {
err!(Config("jwt.algorithm", "JWT algorithm is not recognized or configured {e}"))
})?;
let header = Header { alg, ..Default::default() };
let claim = Claim {
sub: user,
iss: issuer,
aud: audience,
exp: exp_from_now
.and_then(|val| now_secs().checked_add(val))
.map(TryInto::try_into)
.and_then(Result::ok),
nbf: nbf_from_now
.and_then(|val| now_secs().checked_add(val))
.map(TryInto::try_into)
.and_then(Result::ok),
};
let token = encode(&header, &claim, &key).map_err(|e| err!("Failed to encode JWT: {e}"))?;
Ok(token)
}
#[command]
pub(super) async fn resync_database(&self) -> Result<String> {
if !self.services.db.is_secondary() {
return Err!("Not a secondary instance.");
}
self.services
.db
.engine
.update()
.map_err(|e| err!("Failed to update from primary: {e:?}"))?;
Ok("Done".to_owned())
}
#[command]
pub(super) async fn sudo_command(&self, user: String) -> Result<String> {
let user_id = parse_local_user_id(self.services, &user)?;
let result = self
.services
.userroom
.run_command(self.input, "", &user_id)
.await;