moq_transport/session/
announced.rs

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
use std::ops;

use crate::watch::State;
use crate::{message, serve::ServeError};

use super::{AnnounceInfo, Subscriber};

// There's currently no feedback from the peer, so the shared state is empty.
// If Unannounce contained an error code then we'd be talking.
#[derive(Default)]
struct AnnouncedState {}

pub struct Announced {
	session: Subscriber,
	state: State<AnnouncedState>,

	pub info: AnnounceInfo,

	ok: bool,
	error: Option<ServeError>,
}

impl Announced {
	pub(super) fn new(session: Subscriber, namespace: String) -> (Announced, AnnouncedRecv) {
		let info = AnnounceInfo { namespace };

		let (send, recv) = State::default().split();
		let send = Self {
			session,
			info,
			ok: false,
			error: None,
			state: send,
		};
		let recv = AnnouncedRecv { _state: recv };

		(send, recv)
	}

	// Send an ANNOUNCE_OK
	pub fn ok(&mut self) -> Result<(), ServeError> {
		if self.ok {
			return Err(ServeError::Duplicate);
		}

		self.session.send_message(message::AnnounceOk {
			namespace: self.namespace.clone(),
		});

		self.ok = true;

		Ok(())
	}

	pub async fn closed(&self) -> Result<(), ServeError> {
		loop {
			// Wow this is dumb and yet pretty cool.
			// Basically loop until the state changes and exit when Recv is dropped.
			self.state.lock().modified().ok_or(ServeError::Cancel)?.await;
		}
	}

	pub fn close(mut self, err: ServeError) -> Result<(), ServeError> {
		self.error = Some(err);
		Ok(())
	}
}

impl ops::Deref for Announced {
	type Target = AnnounceInfo;

	fn deref(&self) -> &AnnounceInfo {
		&self.info
	}
}

impl Drop for Announced {
	fn drop(&mut self) {
		let err = self.error.clone().unwrap_or(ServeError::Done);

		if self.ok {
			self.session.send_message(message::AnnounceCancel {
				namespace: self.namespace.clone(),
			});
		} else {
			self.session.send_message(message::AnnounceError {
				namespace: self.namespace.clone(),
				code: err.code(),
				reason: err.to_string(),
			});
		}
	}
}

pub(super) struct AnnouncedRecv {
	_state: State<AnnouncedState>,
}

impl AnnouncedRecv {
	pub fn recv_unannounce(self) -> Result<(), ServeError> {
		// Will cause the state to be dropped
		Ok(())
	}
}