1use std::{
2 future::Future,
3 pin::Pin,
4 sync::{
5 Arc, Mutex,
6 atomic::{AtomicBool, Ordering},
7 },
8 task::{Context, Poll, Waker},
9};
10
11use futures::{AsyncRead, AsyncWrite};
12use mpz_common::{Session as MpzSession, ThreadPool, ThreadPoolBuildError, io::Io, mux::Mux};
13use tlsn_core::config::{prover::ProverConfig, verifier::VerifierConfig};
14use tlsn_mux::{Connection, Handle};
15
16use crate::{
17 Error, Result,
18 prover::{Prover, state as prover_state},
19 verifier::{Verifier, state as verifier_state},
20};
21
22#[derive(Debug, Clone)]
24pub struct SessionConfig {
25 mux: tlsn_mux::Config,
26}
27
28impl SessionConfig {
29 pub fn builder() -> SessionConfigBuilder {
31 SessionConfigBuilder::default()
32 }
33
34 fn to_mux_config(&self) -> tlsn_mux::Config {
36 self.mux.clone()
37 }
38}
39
40impl Default for SessionConfig {
41 fn default() -> Self {
42 Self {
43 mux: session_mux_config(None).expect("default mux config is valid"),
44 }
45 }
46}
47
48fn session_mux_config(
53 max_num_streams: Option<usize>,
54) -> Result<tlsn_mux::Config, tlsn_mux::ConfigError> {
55 let mut builder = tlsn_mux::Config::builder()
56 .keep_alive(true)
57 .close_sync(true);
58
59 if let Some(max_num_streams) = max_num_streams {
60 builder = builder.max_num_streams(max_num_streams);
61 }
62
63 builder.build()
64}
65
66#[derive(Debug, Default)]
68pub struct SessionConfigBuilder {
69 max_num_streams: Option<usize>,
70}
71
72impl SessionConfigBuilder {
73 pub fn max_num_streams(mut self, max_num_streams: usize) -> Self {
79 self.max_num_streams = Some(max_num_streams);
80 self
81 }
82
83 pub fn build(self) -> Result<SessionConfig, SessionConfigError> {
88 Ok(SessionConfig {
89 mux: session_mux_config(self.max_num_streams)?,
90 })
91 }
92}
93
94#[derive(Debug, thiserror::Error)]
96#[error(transparent)]
97pub struct SessionConfigError(#[from] tlsn_mux::ConfigError);
98
99#[derive(Debug, Default)]
105pub(crate) struct SessionClosure {
106 closed: AtomicBool,
107 wakers: Mutex<Vec<Waker>>,
108}
109
110impl SessionClosure {
111 fn close(&self) {
113 if self.closed.swap(true, Ordering::AcqRel) {
114 return;
115 }
116 let wakers: Vec<Waker> = self.wakers.lock().unwrap().drain(..).collect();
117 for waker in wakers {
118 waker.wake();
119 }
120 }
121
122 pub(crate) fn is_closed(&self) -> bool {
124 self.closed.load(Ordering::Acquire)
125 }
126
127 pub(crate) fn register(&self, waker: &Waker) {
129 let mut wakers = self.wakers.lock().unwrap();
130
131 if self.is_closed() {
134 drop(wakers);
135 waker.wake_by_ref();
136 return;
137 }
138
139 if !wakers.iter().any(|w| w.will_wake(waker)) {
140 wakers.push(waker.clone());
141 }
142 }
143
144 pub(crate) fn closed(&self) -> Closed<'_> {
146 Closed { closure: self }
147 }
148}
149
150pub(crate) struct Closed<'a> {
152 closure: &'a SessionClosure,
153}
154
155impl Future for Closed<'_> {
156 type Output = ();
157
158 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
159 self.closure.register(cx.waker());
160 if self.closure.is_closed() {
161 Poll::Ready(())
162 } else {
163 Poll::Pending
164 }
165 }
166}
167
168struct ClosureGuard(Arc<SessionClosure>);
174
175impl ClosureGuard {
176 fn share(&self) -> Arc<SessionClosure> {
177 self.0.clone()
178 }
179
180 fn close(&self) {
181 self.0.close();
182 }
183}
184
185impl Drop for ClosureGuard {
186 fn drop(&mut self) {
187 self.0.close();
191 }
192}
193
194#[must_use = "session must be polled continuously to make progress, including during closing."]
210pub struct Session<Io> {
211 conn: Option<Connection<Io>>,
212 executor: MpzSession,
213 handle: Handle,
214 closure: ClosureGuard,
215}
216
217impl<Io> Session<Io>
218where
219 Io: AsyncRead + AsyncWrite + Unpin,
220{
221 pub fn new(io: Io) -> Self {
226 Self::new_with_config(io, SessionConfig::default())
227 }
228
229 pub fn new_with_config(io: Io, config: SessionConfig) -> Self {
234 let mux_config = config.to_mux_config();
235
236 let conn = tlsn_mux::Connection::new(io, mux_config);
237 let handle = conn.handle().expect("handle should be available");
238 let executor = build_executor(MuxHandle {
239 handle: handle.clone(),
240 });
241
242 Self {
243 conn: Some(conn),
244 executor,
245 handle,
246 closure: ClosureGuard(Arc::new(SessionClosure::default())),
247 }
248 }
249
250 pub fn new_prover(
252 &mut self,
253 config: ProverConfig,
254 ) -> Result<Prover<prover_state::Initialized>> {
255 let ctx = self.executor.new_context().map_err(|e| {
256 Error::internal()
257 .with_msg("failed to create new prover")
258 .with_source(e)
259 })?;
260
261 Ok(Prover::new(
262 ctx,
263 self.handle.clone(),
264 config,
265 self.closure.share(),
266 ))
267 }
268
269 pub fn new_verifier(
271 &mut self,
272 config: VerifierConfig,
273 ) -> Result<Verifier<verifier_state::Initialized>> {
274 let ctx = self.executor.new_context().map_err(|e| {
275 Error::internal()
276 .with_msg("failed to create new verifier")
277 .with_source(e)
278 })?;
279
280 Ok(Verifier::new(
281 ctx,
282 self.handle.clone(),
283 config,
284 self.closure.share(),
285 ))
286 }
287
288 pub fn is_closed(&self) -> bool {
290 self.conn
291 .as_ref()
292 .map(|mux| mux.is_complete())
293 .unwrap_or_default()
294 }
295
296 pub fn close(&mut self) {
301 if let Some(conn) = self.conn.as_mut() {
302 conn.close()
303 }
304 }
305
306 pub fn try_take(&mut self) -> Result<Io> {
308 let conn = self.conn.take().ok_or_else(|| {
309 Error::io().with_msg("failed to take the session io, it was already taken")
310 })?;
311
312 match conn.try_into_io() {
313 Err(conn) => {
314 self.conn = Some(conn);
315 Err(Error::io()
316 .with_msg("failed to take the session io, session was not completed yet"))
317 }
318 Ok(conn) => Ok(conn),
319 }
320 }
321
322 pub fn poll(&mut self, cx: &mut Context<'_>) -> Poll<Result<()>> {
324 let poll = self
325 .conn
326 .as_mut()
327 .ok_or_else(|| {
328 Error::io()
329 .with_msg("failed to poll the session connection because it has been taken")
330 })?
331 .poll(cx)
332 .map_err(|e| {
333 Error::io()
334 .with_msg("error occurred while polling the session connection")
335 .with_source(e)
336 });
337
338 if poll.is_ready() {
339 self.closure.close();
340 }
341
342 poll
343 }
344
345 pub fn split(self) -> (SessionDriver<Io>, SessionHandle) {
350 let should_close = Arc::new(AtomicBool::new(false));
351 let waker = Arc::new(Mutex::new(None::<Waker>));
352 let handle_closure = self.closure.share();
353
354 (
355 SessionDriver {
356 conn: self.conn,
357 should_close: should_close.clone(),
358 waker: waker.clone(),
359 closure: self.closure,
360 },
361 SessionHandle {
362 executor: self.executor,
363 should_close,
364 waker,
365 handle: self.handle,
366 closure: handle_closure,
367 },
368 )
369 }
370}
371
372impl<Io> Future for Session<Io>
373where
374 Io: AsyncRead + AsyncWrite + Unpin,
375{
376 type Output = Result<()>;
377
378 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
379 Session::poll(&mut (*self), cx)
380 }
381}
382
383#[must_use = "driver must be polled to make progress"]
388pub struct SessionDriver<Io> {
389 conn: Option<Connection<Io>>,
390 should_close: Arc<AtomicBool>,
391 waker: Arc<Mutex<Option<Waker>>>,
392 closure: ClosureGuard,
393}
394
395impl<Io> SessionDriver<Io>
396where
397 Io: AsyncRead + AsyncWrite + Unpin,
398{
399 pub fn poll(&mut self, cx: &mut Context<'_>) -> Poll<Result<Io>> {
401 {
403 let mut waker_guard = self.waker.lock().unwrap();
404 *waker_guard = Some(cx.waker().clone());
405 }
406
407 let conn = self
408 .conn
409 .as_mut()
410 .ok_or_else(|| Error::io().with_msg("session driver already completed"))?;
411
412 if self.should_close.load(Ordering::Acquire) {
413 conn.close();
414 }
415
416 match conn.poll(cx) {
417 Poll::Ready(Ok(())) => {
418 self.closure.close();
419 }
420 Poll::Ready(Err(e)) => {
421 self.closure.close();
422 return Poll::Ready(Err(Error::io()
423 .with_msg("error polling session connection")
424 .with_source(e)));
425 }
426 Poll::Pending => return Poll::Pending,
427 }
428
429 let conn = self.conn.take().unwrap();
430 Poll::Ready(
431 conn.try_into_io()
432 .map_err(|_| Error::io().with_msg("failed to take session io")),
433 )
434 }
435}
436
437impl<Io> Future for SessionDriver<Io>
438where
439 Io: AsyncRead + AsyncWrite + Unpin,
440{
441 type Output = Result<Io>;
442
443 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
444 SessionDriver::poll(&mut *self, cx)
445 }
446}
447
448pub struct SessionHandle {
452 executor: MpzSession,
453 should_close: Arc<AtomicBool>,
454 waker: Arc<Mutex<Option<Waker>>>,
455 handle: Handle,
456 closure: Arc<SessionClosure>,
457}
458
459impl SessionHandle {
460 pub fn new_prover(
462 &mut self,
463 config: ProverConfig,
464 ) -> Result<Prover<prover_state::Initialized>> {
465 let ctx = self.executor.new_context().map_err(|e| {
466 Error::internal()
467 .with_msg("failed to create new prover")
468 .with_source(e)
469 })?;
470
471 Ok(Prover::new(
472 ctx,
473 self.handle.clone(),
474 config,
475 self.closure.clone(),
476 ))
477 }
478
479 pub fn new_verifier(
481 &mut self,
482 config: VerifierConfig,
483 ) -> Result<Verifier<verifier_state::Initialized>> {
484 let ctx = self.executor.new_context().map_err(|e| {
485 Error::internal()
486 .with_msg("failed to create new verifier")
487 .with_source(e)
488 })?;
489
490 Ok(Verifier::new(
491 ctx,
492 self.handle.clone(),
493 config,
494 self.closure.clone(),
495 ))
496 }
497
498 pub fn close(&self) {
502 self.should_close.store(true, Ordering::Release);
503 if let Some(waker) = self.waker.lock().unwrap().take() {
504 waker.wake();
505 }
506 }
507}
508
509struct MuxHandle {
511 handle: Handle,
512}
513
514impl std::fmt::Debug for MuxHandle {
515 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
516 f.debug_struct("MuxHandle").finish_non_exhaustive()
517 }
518}
519
520impl Mux for MuxHandle {
521 fn open(&self, id: &[u8]) -> Result<Io, std::io::Error> {
522 let stream = self.handle.new_stream(id).map_err(std::io::Error::other)?;
523 let io = Io::from_io(stream);
524
525 Ok(io)
526 }
527}
528
529fn build_executor(mux: MuxHandle) -> MpzSession {
532 #[cfg(all(feature = "web", target_arch = "wasm32"))]
533 let cores = web_spawn::available_parallelism().map(|n| n.get());
534
535 #[cfg(not(all(feature = "web", target_arch = "wasm32")))]
536 let cores = std::thread::available_parallelism().map(|n| n.get());
537
538 let builder = ThreadPool::builder().num_threads(cores.unwrap_or(8));
539
540 #[cfg(all(feature = "web", target_arch = "wasm32"))]
541 let builder = builder.spawn(|f| {
542 let _ = web_spawn::spawn(f);
543 Ok(())
544 });
545
546 match builder.build_global() {
549 Ok(()) | Err(ThreadPoolBuildError::AlreadyInitialized) => {}
550 Err(e) => panic!("failed to build global thread pool: {e}"),
551 }
552
553 MpzSession::builder()
554 .pool(ThreadPool::global())
555 .build(mux)
556 .expect("session should build")
557}
558
559#[cfg(test)]
560mod tests {
561 use super::*;
562
563 #[test]
564 fn default_config_is_valid() {
565 assert!(SessionConfig::builder().build().is_ok());
566 }
567
568 #[test]
569 fn oversized_max_num_streams_is_rejected() {
570 let err = SessionConfig::builder()
571 .max_num_streams(usize::MAX)
572 .build()
573 .unwrap_err();
574 assert!(matches!(
575 err.0,
576 tlsn_mux::ConfigError::ReceiveWindowTooSmall { .. }
577 ));
578 }
579
580 #[test]
581 fn unsplit_session_drop_closes_closure() {
582 let session = Session::new(futures::io::Cursor::new(Vec::<u8>::new()));
583 let closure = session.closure.share();
584 assert!(!closure.is_closed());
585
586 drop(session);
587
588 assert!(closure.is_closed());
589 }
590
591 #[test]
592 fn handle_drop_does_not_close_session() {
593 let session = Session::new(futures::io::Cursor::new(Vec::<u8>::new()));
594 let closure = session.closure.share();
595
596 let (driver, handle) = session.split();
597 drop(handle);
598 assert!(
599 !closure.is_closed(),
600 "dropping the handle must not end the session"
601 );
602
603 drop(driver);
604 assert!(closure.is_closed());
605 }
606}