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
use crate :: { import::*, Filter, ObserveConfig, observable::Channel, Error };

/// A stream of events. This is returned from [Observable::observe](crate::Observable::observe).
///
/// For pharos 0.3.0 on x64 linux: `std::mem::size_of::<Events<_>>() == 16`
//
#[ derive( Debug ) ]
//
pub struct Events<Event> where Event: Clone + 'static + Send
{
	rx: Receiver<Event>,
}


impl<Event> Events<Event> where Event: Clone + 'static + Send
{
	pub(crate) fn new( config: ObserveConfig<Event> ) -> (Self, Sender<Event>)
	{
		let (tx, rx) = match config.channel
		{
			Channel::Bounded( queue_size ) =>
			{
				let (tx, rx) = mpsc::channel( queue_size );

				( Sender::Bounded{ tx, filter: config.filter }, Receiver::Bounded{ rx } )
			}

			Channel::Unbounded =>
			{
				let (tx, rx) = mpsc::unbounded();

				( Sender::Unbounded{ tx, filter: config.filter }, Receiver::Unbounded{ rx } )
			}

			_ => unreachable!(),
		};


		( Self{ rx }, tx )
	}


	/// Close the channel. This way the sender will stop sending new events, and you can still
	/// continue to read any events that are still pending in the channel. This avoids data loss
	/// compared to just dropping this object.
	//
	pub fn close( &mut self )
	{
		self.rx.close();
	}
}




impl<Event> Stream for Events<Event> where Event: Clone + 'static + Send
{
	type Item = Event;

	fn poll_next( mut self: Pin<&mut Self>, cx: &mut Context<'_> ) -> Poll< Option<Self::Item> >
	{
		Pin::new( &mut self.rx ).poll_next( cx )
	}
}



/// The sender of the channel.
/// For pharos 0.3.0 on x64 linux: `std::mem::size_of::<Sender<_>>() == 56`
//
#[ pin_project ]
//
pub(crate) enum Sender<Event> where Event: Clone + 'static + Send
{
	Bounded  { #[pin] tx: FutSender<Event>         , filter: Option<Filter<Event>> } ,
	Unbounded{ #[pin] tx: FutUnboundedSender<Event>, filter: Option<Filter<Event>> } ,
}




impl<Event> Sender<Event>  where Event: Clone + 'static + Send
{
	// Verify whether this observer is still around
	//
	pub(crate) fn is_closed( &self ) -> bool
	{
		match self
		{
			Sender::Bounded  { tx, .. } => tx.is_closed(),
			Sender::Unbounded{ tx, .. } => tx.is_closed(),
		}
	}


	// Notify the observer and return a bool indicating whether this observer is still
	// operational. If an error happens on a channel it usually means that the channel
	// is closed, in which case we should drop this sender.
	//
	pub(crate) async fn notify( &mut self, evt: &Event ) -> bool
	{
		if self.is_closed() { return false }

		match self
		{
			Sender::Bounded  { tx, filter } => Self::notifier( tx, filter, evt ).await,
			Sender::Unbounded{ tx, filter } => Self::notifier( tx, filter, evt ).await,
		}
	}


	async fn notifier
	(
		mut tx: impl Sink<Event> + Unpin   ,
		filter: &mut Option<Filter<Event>> ,
		evt   : &Event                     ,
	)

		-> bool

	{
		let interested = match filter
		{
			Some(f) => f.call(evt),
			None    => true       ,
		};


		#[ allow( clippy::match_bool ) ]
		//
		match interested
		{
			true  => tx.send( evt.clone() ).await.is_ok(),

			// since we don't try to send, we know nothing about whether they are still
			// observing, so assume they do.
			//
			false => true,
		}
	}
}



/// The receiver of the channel.
//
#[ pin_project ]
//
enum Receiver<Event> where Event: Clone + 'static + Send
{
	Bounded  { #[pin] rx: FutReceiver<Event>          } ,
	Unbounded{ #[pin] rx: FutUnboundedReceiver<Event> } ,
}


impl<Event> Receiver<Event> where Event: Clone + 'static + Send
{
	fn close( &mut self )
	{
		match self
		{
			Receiver::Bounded  { rx } => rx.close(),
			Receiver::Unbounded{ rx } => rx.close(),
		};
	}
}



impl<Event> fmt::Debug for Receiver<Event>  where Event: 'static + Clone + Send
{
	fn fmt( &self, f: &mut fmt::Formatter<'_> ) -> fmt::Result
	{
		match self
		{
			Self::Bounded  {..} => write!( f, "pharos::events::Receiver::<{}>::Bounded(_)"  , type_name::<Event>() ),
			Self::Unbounded{..} => write!( f, "pharos::events::Receiver::<{}>::Unbounded(_)", type_name::<Event>() ),
		}
	}
}




impl<Event> Stream for Receiver<Event> where Event: Clone + 'static + Send
{
	type Item = Event;

	#[ project ]
	//
	fn poll_next( self: Pin<&mut Self>, cx: &mut Context<'_> ) -> Poll< Option<Self::Item> >
	{
		#[ project ]
		//
		match self.project()
		{
			Receiver::Bounded  { rx } => rx.poll_next( cx ),
			Receiver::Unbounded{ rx } => rx.poll_next( cx ),
		}
	}
}



impl<Event> Sink<Event> for Sender<Event> where Event: Clone + 'static + Send
{
	type Error = Error;

	#[ project ]
	//
	fn poll_ready( self: Pin<&mut Self>, cx: &mut Context<'_> ) -> Poll<Result<(), Self::Error>>
	{
		#[ project ]
		//
		match self.project()
		{
			Sender::Bounded  { tx, .. } => tx.poll_ready( cx ).map_err( Into::into ),
			Sender::Unbounded{ tx, .. } => tx.poll_ready( cx ).map_err( Into::into ),
		}
	}

	#[ project ]
	//
	fn start_send( self: Pin<&mut Self>, item: Event ) -> Result<(), Self::Error>
	{
		#[ project ]
		//
		match self.project()
		{
			Sender::Bounded  { tx, .. } => tx.start_send( item ).map_err( Into::into ),
			Sender::Unbounded{ tx, .. } => tx.start_send( item ).map_err( Into::into ),
		}
	}

	/// This will do a send under the hood, so the same errors as from start_send can occur here.
	//
	#[ project ]
	//
	fn poll_flush( self: Pin<&mut Self>, cx: &mut Context<'_> ) -> Poll<Result<(), Self::Error>>
	{
		#[ project ]
		//
		match self.project()
		{
			Sender::Bounded  { tx, .. } => tx.poll_flush( cx ).map_err( Into::into ),
			Sender::Unbounded{ tx, .. } => tx.poll_flush( cx ).map_err( Into::into ),
		}
	}

	#[ project ]
	//
	fn poll_close( self: Pin<&mut Self>, cx: &mut Context<'_> ) -> Poll<Result<(), Self::Error>>
	{
		#[ project ]
		//
		match self.project()
		{
			Sender::Bounded  { tx, .. } => tx.poll_close( cx ).map_err( Into::into ),
			Sender::Unbounded{ tx, .. } => tx.poll_close( cx ).map_err( Into::into ),
		}
	}
}





#[ cfg( test ) ]
//
mod tests
{
	use super::*;

	#[test]
	//
	fn debug()
	{
		let e = Events::<bool>::new( ObserveConfig::default() );

		assert_eq!( "Events { rx: pharos::events::Receiver::<bool>::Unbounded(_) }", &format!( "{:?}", e.0 ) );
	}
}