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
// SPDX-FileCopyrightText: 2024-2026 Cloudflare Inc., Luke Curley, Mike English and contributors
// SPDX-FileCopyrightText: 2023-2024 Luke Curley and contributors
// SPDX-License-Identifier: MIT OR Apache-2.0
mod announce;
mod announced;
mod error;
mod publisher;
mod reader;
mod subscribe;
mod subscribed;
mod subscriber;
mod track_status_requested;
mod writer;
pub use announce::*;
pub use announced::*;
pub use error::*;
pub use publisher::*;
pub use subscribe::*;
pub use subscribed::*;
pub use subscriber::*;
pub use track_status_requested::*;
use reader::*;
use writer::*;
use futures::{stream::FuturesUnordered, StreamExt};
use std::sync::{atomic, Arc, Mutex};
use crate::coding::{KeyValuePairs, Value};
use crate::message::Message;
use crate::mlog;
use crate::watch::Queue;
use crate::{message, setup};
use std::path::PathBuf;
/// The transport protocol negotiated for this MoQT connection.
///
/// MoQT can run over either WebTransport (HTTP/3 + QUIC) or raw QUIC.
/// The transport type affects protocol behavior — for example, the PATH
/// parameter is only sent in CLIENT_SETUP for raw QUIC connections,
/// since WebTransport carries the path in the HTTP/3 CONNECT URL.
///
/// This enum is intentionally extensible for future transport options
/// (e.g., QMUX, WebSocket fallback).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Transport {
/// WebTransport over HTTP/3 (RFC 9220).
/// ALPN: "h3". Path carried in HTTP/3 CONNECT :path pseudo-header.
WebTransport,
/// Raw QUIC with MoQT framing directly on QUIC streams.
/// ALPN: "moq-00". Path carried in CLIENT_SETUP PATH parameter.
RawQuic,
}
/// Session object for managing all communications in a single QUIC connection.
#[must_use = "run() must be called"]
pub struct Session {
webtransport: web_transport::Session,
/// Control Stream Reader and Writer (QUIC bi-directional stream)
sender: Writer, // Control Stream Sender
recver: Reader, // Control Stream Receiver
publisher: Option<Publisher>, // Contains Publisher side logic, uses outgoing message queue to send control messages
subscriber: Option<Subscriber>, // Contains Subscriber side logic, uses outgoing message queue to send control messages
/// Queue used by Publisher and Subscriber for sending Control Messages
outgoing: Queue<Message>,
/// Optional mlog writer for MoQ Transport events
/// Wrapped in Arc<Mutex<>> to share across send/recv tasks when enabled
mlog: Option<Arc<Mutex<mlog::MlogWriter>>>,
/// The transport protocol negotiated for this connection.
transport: Transport,
/// The connection path, derived from the WebTransport URL path or CLIENT_SETUP PATH parameter.
/// For incoming connections: extracted during accept() from the WebTransport CONNECT URL
/// (takes precedence) or the CLIENT_SETUP PATH parameter (key 0x1).
/// For outgoing connections: auto-extracted from the session URL in connect().
connection_path: Option<String>,
}
impl Session {
const MAX_CONNECTION_PATH_LEN: usize = 1024;
/// Normalize and validate a connection path.
///
/// Returns `Ok(None)` for empty or root-only paths. Returns `Err` for
/// paths that are too long, don't start with `/`, contain empty,
/// dot, or percent-encoded segments, or are otherwise malformed.
///
/// Percent-encoded characters are rejected rather than decoded because
/// scope identity must be unambiguous: `/foo%2Fbar` and `/foo/bar`
/// must not silently map to different scopes, and `%2E%2E` must not
/// bypass the dot-segment check.
///
/// This is used internally by `accept()` and `connect()`, but is also
/// available for callers that need to validate paths from other sources
/// (e.g., announce URLs used for forward connections).
pub fn normalize_connection_path(raw: &str) -> Result<Option<String>, SessionError> {
if raw.is_empty() || raw == "/" {
return Ok(None);
}
if raw.len() > Self::MAX_CONNECTION_PATH_LEN {
return Err(SessionError::InvalidPath("path too long".to_string()));
}
if !raw.starts_with('/') {
return Err(SessionError::InvalidPath(
"path must start with '/'".to_string(),
));
}
let trimmed = raw.trim_end_matches('/');
if trimmed.is_empty() {
return Ok(None);
}
let mut segments = trimmed.split('/');
let _ = segments.next();
for segment in segments {
if segment.is_empty() {
return Err(SessionError::InvalidPath(
"path contains empty segment".to_string(),
));
}
if segment.contains('%') {
return Err(SessionError::InvalidPath(
"path must not contain percent-encoded characters".to_string(),
));
}
if segment == "." || segment == ".." {
return Err(SessionError::InvalidPath(
"path contains invalid segment".to_string(),
));
}
}
Ok(Some(trimmed.to_string()))
}
fn decode_client_setup_path(params: &KeyValuePairs) -> Result<Option<String>, SessionError> {
let Some(kvp) = params.get(setup::ParameterType::Path.into()) else {
return Ok(None);
};
let bytes = match &kvp.value {
Value::BytesValue(bytes) => bytes,
_ => {
return Err(SessionError::InvalidPath(
"PATH parameter must be bytes-encoded".to_string(),
))
}
};
if bytes.len() > Self::MAX_CONNECTION_PATH_LEN {
return Err(SessionError::InvalidPath("path too long".to_string()));
}
let path = std::str::from_utf8(bytes)
.map_err(|_| SessionError::InvalidPath("path must be UTF-8".to_string()))?;
Self::normalize_connection_path(path)
}
/// Returns the negotiated transport protocol for this connection.
pub fn transport(&self) -> Transport {
self.transport
}
/// Returns the connection path, if one was present on the incoming connection.
///
/// For server-side sessions (created via `accept()`), this is derived from:
/// 1. The WebTransport CONNECT URL path (takes precedence), or
/// 2. The CLIENT_SETUP PATH parameter (key 0x1), used for raw QUIC connections.
///
/// Returns `None` if no path was present or if the path was just "/".
pub fn connection_path(&self) -> Option<&str> {
self.connection_path.as_deref()
}
// Helper for determining the largest supported version
fn largest_common<T: Ord + Clone + Eq>(a: &[T], b: &[T]) -> Option<T> {
a.iter()
.filter(|x| b.contains(x)) // keep only items also in b
.cloned() // clone because we return T, not &T
.max() // take the largest
}
/// Log a control message with structured fields for observability.
/// Uses target "moq_transport::control" so it can be filtered independently.
fn log_control_message(msg: &Message, direction: &str) {
match msg {
Message::Subscribe(m) => {
tracing::debug!(
target: "moq_transport::control",
direction,
msg_type = "SUBSCRIBE",
subscribe_id = m.id,
namespace = %m.track_namespace,
track_name = %m.track_name,
filter_type = ?m.filter_type,
"MoQT control message"
);
}
Message::SubscribeOk(m) => {
tracing::debug!(
target: "moq_transport::control",
direction,
msg_type = "SUBSCRIBE_OK",
subscribe_id = m.id,
track_alias = m.track_alias,
content_exists = m.content_exists,
"MoQT control message"
);
}
Message::SubscribeError(m) => {
tracing::debug!(
target: "moq_transport::control",
direction,
msg_type = "SUBSCRIBE_ERROR",
subscribe_id = m.id,
error_code = m.error_code,
reason = %m.reason_phrase.0,
"MoQT control message"
);
}
Message::SubscribeUpdate(m) => {
tracing::debug!(
target: "moq_transport::control",
direction,
msg_type = "SUBSCRIBE_UPDATE",
request_id = m.id,
subscription_request_id = m.subscription_request_id,
"MoQT control message"
);
}
Message::Unsubscribe(m) => {
tracing::debug!(
target: "moq_transport::control",
direction,
msg_type = "UNSUBSCRIBE",
subscribe_id = m.id,
"MoQT control message"
);
}
Message::PublishNamespace(m) => {
tracing::debug!(
target: "moq_transport::control",
direction,
msg_type = "PUBLISH_NAMESPACE",
request_id = m.id,
namespace = %m.track_namespace,
"MoQT control message"
);
}
Message::PublishNamespaceOk(m) => {
tracing::debug!(
target: "moq_transport::control",
direction,
msg_type = "PUBLISH_NAMESPACE_OK",
request_id = m.id,
"MoQT control message"
);
}
Message::PublishNamespaceError(m) => {
tracing::debug!(
target: "moq_transport::control",
direction,
msg_type = "PUBLISH_NAMESPACE_ERROR",
request_id = m.id,
error_code = m.error_code,
reason = %m.reason_phrase.0,
"MoQT control message"
);
}
Message::PublishNamespaceDone(m) => {
tracing::debug!(
target: "moq_transport::control",
direction,
msg_type = "PUBLISH_NAMESPACE_DONE",
namespace = %m.track_namespace,
"MoQT control message"
);
}
Message::PublishNamespaceCancel(m) => {
tracing::debug!(
target: "moq_transport::control",
direction,
msg_type = "PUBLISH_NAMESPACE_CANCEL",
namespace = %m.track_namespace,
error_code = m.error_code,
reason = %m.reason_phrase.0,
"MoQT control message"
);
}
Message::TrackStatus(m) => {
tracing::debug!(
target: "moq_transport::control",
direction,
msg_type = "TRACK_STATUS",
request_id = m.id,
namespace = %m.track_namespace,
track_name = %m.track_name,
"MoQT control message"
);
}
Message::TrackStatusOk(m) => {
tracing::debug!(
target: "moq_transport::control",
direction,
msg_type = "TRACK_STATUS_OK",
request_id = m.id,
track_alias = m.track_alias,
content_exists = m.content_exists,
"MoQT control message"
);
}
Message::TrackStatusError(m) => {
tracing::debug!(
target: "moq_transport::control",
direction,
msg_type = "TRACK_STATUS_ERROR",
request_id = m.id,
error_code = m.error_code,
reason = %m.reason_phrase.0,
"MoQT control message"
);
}
Message::SubscribeNamespace(m) => {
tracing::debug!(
target: "moq_transport::control",
direction,
msg_type = "SUBSCRIBE_NAMESPACE",
request_id = m.id,
namespace_prefix = %m.track_namespace_prefix,
"MoQT control message"
);
}
Message::SubscribeNamespaceOk(m) => {
tracing::debug!(
target: "moq_transport::control",
direction,
msg_type = "SUBSCRIBE_NAMESPACE_OK",
request_id = m.id,
"MoQT control message"
);
}
Message::SubscribeNamespaceError(m) => {
tracing::debug!(
target: "moq_transport::control",
direction,
msg_type = "SUBSCRIBE_NAMESPACE_ERROR",
request_id = m.id,
error_code = m.error_code,
reason = %m.reason_phrase.0,
"MoQT control message"
);
}
Message::UnsubscribeNamespace(m) => {
tracing::debug!(
target: "moq_transport::control",
direction,
msg_type = "UNSUBSCRIBE_NAMESPACE",
namespace_prefix = %m.track_namespace_prefix,
"MoQT control message"
);
}
Message::Fetch(m) => {
tracing::debug!(
target: "moq_transport::control",
direction,
msg_type = "FETCH",
request_id = m.id,
fetch_type = ?m.fetch_type,
"MoQT control message"
);
}
Message::FetchOk(m) => {
tracing::debug!(
target: "moq_transport::control",
direction,
msg_type = "FETCH_OK",
request_id = m.id,
end_of_track = m.end_of_track,
"MoQT control message"
);
}
Message::FetchError(m) => {
tracing::debug!(
target: "moq_transport::control",
direction,
msg_type = "FETCH_ERROR",
request_id = m.id,
error_code = m.error_code,
reason = %m.reason_phrase.0,
"MoQT control message"
);
}
Message::FetchCancel(m) => {
tracing::debug!(
target: "moq_transport::control",
direction,
msg_type = "FETCH_CANCEL",
request_id = m.id,
"MoQT control message"
);
}
Message::Publish(m) => {
tracing::debug!(
target: "moq_transport::control",
direction,
msg_type = "PUBLISH",
request_id = m.id,
namespace = %m.track_namespace,
track_name = %m.track_name,
track_alias = m.track_alias,
"MoQT control message"
);
}
Message::PublishOk(m) => {
tracing::debug!(
target: "moq_transport::control",
direction,
msg_type = "PUBLISH_OK",
request_id = m.id,
filter_type = ?m.filter_type,
"MoQT control message"
);
}
Message::PublishError(m) => {
tracing::debug!(
target: "moq_transport::control",
direction,
msg_type = "PUBLISH_ERROR",
request_id = m.id,
error_code = m.error_code,
reason = %m.reason_phrase.0,
"MoQT control message"
);
}
Message::PublishDone(m) => {
tracing::debug!(
target: "moq_transport::control",
direction,
msg_type = "PUBLISH_DONE",
request_id = m.id,
status_code = m.status_code,
stream_count = m.stream_count,
"MoQT control message"
);
}
Message::GoAway(m) => {
tracing::debug!(
target: "moq_transport::control",
direction,
msg_type = "GOAWAY",
uri = %m.uri.0,
"MoQT control message"
);
}
Message::MaxRequestId(m) => {
tracing::debug!(
target: "moq_transport::control",
direction,
msg_type = "MAX_REQUEST_ID",
request_id = m.request_id,
"MoQT control message"
);
}
Message::RequestsBlocked(m) => {
tracing::debug!(
target: "moq_transport::control",
direction,
msg_type = "REQUESTS_BLOCKED",
max_request_id = m.max_request_id,
"MoQT control message"
);
}
}
}
fn new(
webtransport: web_transport::Session,
sender: Writer,
recver: Reader,
first_requestid: u64,
mlog: Option<mlog::MlogWriter>,
transport: Transport,
connection_path: Option<String>,
) -> (Self, Option<Publisher>, Option<Subscriber>) {
let next_requestid = Arc::new(atomic::AtomicU64::new(first_requestid));
let outgoing = Queue::default().split();
// Wrap mlog in Arc<Mutex<>> for sharing across tasks
let mlog_shared = mlog.map(|m| Arc::new(Mutex::new(m)));
let publisher = Some(Publisher::new(
outgoing.0.clone(),
webtransport.clone(),
next_requestid.clone(),
mlog_shared.clone(),
));
let subscriber = Some(Subscriber::new(
outgoing.0,
next_requestid,
mlog_shared.clone(),
));
let session = Self {
webtransport,
sender,
recver,
publisher: publisher.clone(),
subscriber: subscriber.clone(),
outgoing: outgoing.1,
mlog: mlog_shared,
transport,
connection_path,
};
(session, publisher, subscriber)
}
/// Create an outbound/client QUIC connection, by opening a bi-directional QUIC stream for
/// MOQT control messaging. Performs SETUP messaging and version negotiation.
///
/// If the session URL contains a non-trivial path (not empty or "/"), the PATH
/// parameter (key 0x1) is automatically sent in CLIENT_SETUP. This propagates
/// the connection path (App ID / MoQT scope) to the remote peer, which is needed
/// for relay-to-relay connections. To connect without sending PATH, use a URL
/// with no path component.
pub async fn connect(
session: web_transport::Session,
mlog_path: Option<PathBuf>,
transport: Transport,
) -> Result<(Session, Publisher, Subscriber), SessionError> {
// Auto-extract path from the session URL.
// This aligns with the unified moqt:// URI scheme direction (IETF PR #1486)
// where the path is always part of the URI regardless of transport.
let url_path = session.url().path();
let path = Self::normalize_connection_path(url_path)?;
let mlog = mlog_path.and_then(|path| {
mlog::MlogWriter::new(path)
.map_err(|e| tracing::warn!("Failed to create mlog: {}", e))
.ok()
});
let control = session.open_bi().await?;
let mut sender = Writer::new(control.0);
let mut recver = Reader::new(control.1);
let versions: setup::Versions = [setup::Version::DRAFT_14].into();
// TODO SLG - make configurable?
let mut params = KeyValuePairs::default();
params.set_intvalue(setup::ParameterType::MaxRequestId.into(), 100);
// Only send PATH in CLIENT_SETUP for raw QUIC connections.
// For WebTransport, the path is already carried in the HTTP/3 CONNECT URL.
if let Some(ref path) = path {
if transport == Transport::RawQuic {
params.set_bytesvalue(setup::ParameterType::Path.into(), path.as_bytes().to_vec());
}
}
let client = setup::Client {
versions: versions.clone(),
params,
};
tracing::debug!(
target: "moq_transport::control",
direction = "sent",
msg_type = "CLIENT_SETUP",
versions = ?client.versions,
?transport,
path = path.as_deref(),
"MoQT control message"
);
sender.encode(&client).await?;
// TODO: emit client_setup_created event when we add that
let server: setup::Server = recver.decode().await?;
tracing::debug!(
target: "moq_transport::control",
direction = "recv",
msg_type = "SERVER_SETUP",
version = ?server.version,
"MoQT control message"
);
// TODO: emit server_setup_parsed event
// We are the client, so the first request id is 0
let session = Session::new(session, sender, recver, 0, mlog, transport, path);
Ok((session.0, session.1.unwrap(), session.2.unwrap()))
}
/// Accepts an inbound/server QUIC connection, by accepting a bi-directional QUIC stream for
/// MOQT control messaging. Performs SETUP messaging and version negotiation.
pub async fn accept(
session: web_transport::Session,
mlog_path: Option<PathBuf>,
transport: Transport,
) -> Result<(Session, Option<Publisher>, Option<Subscriber>), SessionError> {
let mut mlog = mlog_path.and_then(|path| {
mlog::MlogWriter::new(path)
.map_err(|e| tracing::warn!("Failed to create mlog: {}", e))
.ok()
});
let control = session.accept_bi().await?;
let mut sender = Writer::new(control.0);
let mut recver = Reader::new(control.1);
let client: setup::Client = recver.decode().await?;
tracing::debug!(
target: "moq_transport::control",
direction = "recv",
msg_type = "CLIENT_SETUP",
versions = ?client.versions,
"MoQT control message"
);
// Extract WebTransport URL path from the underlying session.
// For WebTransport connections, this comes from the HTTP/3 CONNECT :path.
// For raw QUIC, this is the placeholder URL ("moqt://localhost") and has no meaningful path.
let wt_url_path = session.url().path();
let wt_path = Self::normalize_connection_path(wt_url_path)?;
// Extract CLIENT_SETUP PATH parameter (key 0x1, BytesValue).
// Used for raw QUIC connections where there's no HTTP CONNECT URL.
let client_setup_path = if wt_path.is_none() {
Self::decode_client_setup_path(&client.params)?
} else {
None
};
// Combine: WebTransport URL path takes precedence over CLIENT_SETUP PATH.
// WebTransport connections always have the path in the CONNECT URL.
// Raw QUIC connections only have CLIENT_SETUP PATH.
let connection_path = wt_path.or(client_setup_path);
if connection_path.is_some() {
tracing::debug!(
connection_path = connection_path.as_deref(),
"Connection path resolved"
);
}
// Emit mlog event for CLIENT_SETUP parsed
if let Some(ref mut mlog) = mlog {
let event = mlog::events::client_setup_parsed(mlog.elapsed_ms(), 0, &client);
let _ = mlog.add_event(event);
}
let server_versions = setup::Versions(vec![setup::Version::DRAFT_14]);
if let Some(largest_common_version) =
Self::largest_common(&server_versions, &client.versions)
{
// TODO SLG - make configurable?
let mut params = KeyValuePairs::default();
params.set_intvalue(setup::ParameterType::MaxRequestId.into(), 100);
let server = setup::Server {
version: largest_common_version,
params,
};
tracing::debug!(
target: "moq_transport::control",
direction = "sent",
msg_type = "SERVER_SETUP",
version = ?server.version,
"MoQT control message"
);
// Emit mlog event for SERVER_SETUP created
if let Some(ref mut mlog) = mlog {
let event = mlog::events::server_setup_created(mlog.elapsed_ms(), 0, &server);
let _ = mlog.add_event(event);
}
sender.encode(&server).await?;
// We are the server, so the first request id is 1
Ok(Session::new(
session,
sender,
recver,
1,
mlog,
transport,
connection_path,
))
} else {
Err(SessionError::Version(client.versions, server_versions))
}
}
/// Run Tasks for the session, including sending of control messages, receiving and processing
/// inbound control messages, receiving and processing new inbound uni-directional QUIC streams,
/// and receiving and processing QUIC datagrams received
pub async fn run(self) -> Result<(), SessionError> {
tokio::select! {
res = Self::run_recv(self.recver, self.publisher, self.subscriber.clone(), self.mlog.clone()) => res,
res = Self::run_send(self.sender, self.outgoing, self.mlog.clone()) => res,
res = Self::run_streams(self.webtransport.clone(), self.subscriber.clone()) => res,
res = Self::run_datagrams(self.webtransport, self.subscriber) => res,
}
}
/// Processes the outgoing control message queue, and sends queued messages on the control stream sender/writer.
async fn run_send(
mut sender: Writer,
mut outgoing: Queue<message::Message>,
mlog: Option<Arc<Mutex<mlog::MlogWriter>>>,
) -> Result<(), SessionError> {
while let Some(msg) = outgoing.pop().await {
// Emit structured tracing log for sent control messages
Self::log_control_message(&msg, "sent");
// Emit mlog event for sent control messages
if let Some(ref mlog) = mlog {
if let Ok(mut mlog_guard) = mlog.lock() {
let time = mlog_guard.elapsed_ms();
let stream_id = 0; // Control stream is always stream 0
// Emit events based on message type
let event = match &msg {
Message::Subscribe(m) => {
Some(mlog::events::subscribe_created(time, stream_id, m))
}
Message::SubscribeOk(m) => {
Some(mlog::events::subscribe_ok_created(time, stream_id, m))
}
Message::SubscribeError(m) => {
Some(mlog::events::subscribe_error_created(time, stream_id, m))
}
Message::Unsubscribe(m) => {
Some(mlog::events::unsubscribe_created(time, stream_id, m))
}
Message::PublishNamespace(m) => {
Some(mlog::events::publish_namespace_created(time, stream_id, m))
}
Message::PublishNamespaceOk(m) => Some(
mlog::events::publish_namespace_ok_created(time, stream_id, m),
),
Message::PublishNamespaceError(m) => Some(
mlog::events::publish_namespace_error_created(time, stream_id, m),
),
Message::GoAway(m) => {
Some(mlog::events::go_away_created(time, stream_id, m))
}
_ => None, // TODO: Add other message types
};
if let Some(event) = event {
let _ = mlog_guard.add_event(event);
}
}
}
sender.encode(&msg).await?;
}
Ok(())
}
/// Receives inbound messages from the control stream reader/receiver. Analyzes if the message
/// is to be handled by Subscriber or Publisher logic and calls recv_message on either the
/// Publisher or Subscriber.
/// Note: Should also be handling messages common to both roles, ie: GOAWAY, MAX_REQUEST_ID and
/// REQUESTS_BLOCKED
async fn run_recv(
mut recver: Reader,
mut publisher: Option<Publisher>,
mut subscriber: Option<Subscriber>,
mlog: Option<Arc<Mutex<mlog::MlogWriter>>>,
) -> Result<(), SessionError> {
loop {
let msg: message::Message = recver.decode().await?;
// Emit structured tracing log for received control messages
Self::log_control_message(&msg, "recv");
// Emit mlog event for received control messages
if let Some(ref mlog) = mlog {
if let Ok(mut mlog_guard) = mlog.lock() {
let time = mlog_guard.elapsed_ms();
let stream_id = 0; // Control stream is always stream 0
// Emit events based on message type
let event = match &msg {
Message::Subscribe(m) => {
Some(mlog::events::subscribe_parsed(time, stream_id, m))
}
Message::SubscribeOk(m) => {
Some(mlog::events::subscribe_ok_parsed(time, stream_id, m))
}
Message::SubscribeError(m) => {
Some(mlog::events::subscribe_error_parsed(time, stream_id, m))
}
Message::Unsubscribe(m) => {
Some(mlog::events::unsubscribe_parsed(time, stream_id, m))
}
Message::PublishNamespace(m) => {
Some(mlog::events::publish_namespace_parsed(time, stream_id, m))
}
Message::PublishNamespaceOk(m) => Some(
mlog::events::publish_namespace_ok_parsed(time, stream_id, m),
),
Message::PublishNamespaceError(m) => Some(
mlog::events::publish_namespace_error_parsed(time, stream_id, m),
),
Message::GoAway(m) => {
Some(mlog::events::go_away_parsed(time, stream_id, m))
}
_ => None, // TODO: Add other message types
};
if let Some(event) = event {
let _ = mlog_guard.add_event(event);
}
}
}
let msg = match TryInto::<message::Publisher>::try_into(msg) {
Ok(msg) => {
subscriber
.as_mut()
.ok_or(SessionError::RoleViolation)?
.recv_message(msg)?;
continue;
}
Err(msg) => msg,
};
let msg = match TryInto::<message::Subscriber>::try_into(msg) {
Ok(msg) => {
publisher
.as_mut()
.ok_or(SessionError::RoleViolation)?
.recv_message(msg)?;
continue;
}
Err(msg) => msg,
};
// TODO GOAWAY, MAX_REQUEST_ID, REQUESTS_BLOCKED
tracing::warn!("Unimplemented message type received: {:?}", msg);
return Err(SessionError::unimplemented(&format!(
"message type {:?}",
msg
)));
}
}
/// Accepts uni-directional quic streams and starts handling for them.
/// Will read stream header to know what type of stream it is and create
/// the appropriate stream handlers.
async fn run_streams(
webtransport: web_transport::Session,
subscriber: Option<Subscriber>,
) -> Result<(), SessionError> {
let mut tasks = FuturesUnordered::new();
loop {
tokio::select! {
res = webtransport.accept_uni() => {
let stream = res?;
let subscriber = subscriber.clone().ok_or(SessionError::RoleViolation)?;
tasks.push(async move {
if let Err(err) = Subscriber::recv_stream(subscriber, stream).await {
tracing::warn!("failed to serve stream: {}", err);
};
});
},
_ = tasks.next(), if !tasks.is_empty() => {},
};
}
}
/// Receives QUIC datagrams and processes them using the Subscriber logic
async fn run_datagrams(
webtransport: web_transport::Session,
mut subscriber: Option<Subscriber>,
) -> Result<(), SessionError> {
loop {
let datagram = webtransport.recv_datagram().await?;
subscriber
.as_mut()
.ok_or(SessionError::RoleViolation)?
.recv_datagram(datagram)
.await?;
}
}
}
#[cfg(test)]
mod tests {
use super::*;
// ========================================================================
// normalize_connection_path
// ========================================================================
#[test]
fn normalize_empty_and_root() {
assert_eq!(Session::normalize_connection_path("").unwrap(), None);
assert_eq!(Session::normalize_connection_path("/").unwrap(), None);
assert_eq!(Session::normalize_connection_path("///").unwrap(), None);
}
#[test]
fn normalize_valid_paths() {
assert_eq!(
Session::normalize_connection_path("/app").unwrap(),
Some("/app".to_string())
);
assert_eq!(
Session::normalize_connection_path("/tenant/stream-1").unwrap(),
Some("/tenant/stream-1".to_string())
);
// Trailing slash is trimmed
assert_eq!(
Session::normalize_connection_path("/app/").unwrap(),
Some("/app".to_string())
);
}
#[test]
fn normalize_rejects_missing_leading_slash() {
assert!(Session::normalize_connection_path("app").is_err());
}
#[test]
fn normalize_rejects_empty_segments() {
assert!(Session::normalize_connection_path("/app//stream").is_err());
}
#[test]
fn normalize_rejects_dot_segments() {
assert!(Session::normalize_connection_path("/app/./stream").is_err());
assert!(Session::normalize_connection_path("/app/../secret").is_err());
assert!(Session::normalize_connection_path("/..").is_err());
}
#[test]
fn normalize_rejects_percent_encoded_characters() {
// %2F = '/' — would create scope ambiguity
assert!(Session::normalize_connection_path("/foo%2Fbar").is_err());
// %2E%2E = '..' — would bypass dot-segment check
assert!(Session::normalize_connection_path("/%2E%2E/secret").is_err());
// %00 = null — general injection risk
assert!(Session::normalize_connection_path("/app/%00").is_err());
// Uppercase hex digits
assert!(Session::normalize_connection_path("/app/%2e%2e").is_err());
}
#[test]
fn normalize_rejects_too_long_path() {
let long_path = format!("/{}", "a".repeat(Session::MAX_CONNECTION_PATH_LEN));
assert!(Session::normalize_connection_path(&long_path).is_err());
}
#[test]
fn normalize_accepts_max_length_path() {
// Exactly at the limit (1024 total including leading slash)
let path = format!("/{}", "a".repeat(Session::MAX_CONNECTION_PATH_LEN - 1));
assert!(Session::normalize_connection_path(&path).is_ok());
}
}