aimdb_core/session/server.rs
1//! The reactive **server** engine of the session substrate.
2//!
3//! - [`run_session`] drives one accepted [`Connection`]: a biased `select_biased!`
4//! loop interleaving inbound requests (RPC + subscribe + write) with outbound
5//! subscription events.
6//! - [`serve`] is the accept loop over a [`Listener`], honoring
7//! [`SessionLimits::max_connections`].
8//!
9//! Spawn-free (every per-connection/-subscription task lives in a
10//! [`FuturesUnordered`] the runner drives) and runtime-neutral (purely reactive,
11//! so no timer and no `tokio`/`embassy-*`).
12//!
13//! The loops use an **extract-then-act** shape: `select_biased!` only computes a
14//! small [`Step`], then the loop acts on it once the arm futures (and their
15//! borrows of `conn`/`subs`) drop — `futures`' macro, unlike `tokio::select!`,
16//! keeps non-selected futures alive across the handler.
17
18use crate::session::events::{report, SessionEvent};
19
20use alloc::boxed::Box;
21use alloc::string::{String, ToString};
22use alloc::sync::Arc;
23use alloc::vec::Vec;
24use core::future::Future;
25use core::pin::Pin;
26use core::task::{Context, Poll};
27
28use async_channel::Sender;
29use futures_channel::oneshot;
30use futures_util::stream::{FuturesUnordered, StreamExt};
31use futures_util::{select_biased, FutureExt};
32use hashbrown::HashMap;
33
34use super::{
35 BoxFut, BoxStream, Connection, Dispatch, EnvelopeCodec, Inbound, Listener, Outbound, Payload,
36 RpcError, SessionLimits, SubUpdate, TransportError,
37};
38
39/// Per-session engine knobs.
40#[derive(Debug, Clone, Default)]
41pub struct SessionConfig {
42 /// Connection cap (consulted by [`serve`]) and per-connection subscription
43 /// cap (by [`run_session`]).
44 pub limits: SessionLimits,
45 /// If `true`, read one frame before authenticating and pass it to
46 /// [`Dispatch::authenticate`] as an in-band Hello. If `false` (default),
47 /// authenticate from [`PeerInfo`](super::PeerInfo) alone.
48 pub reads_hello: bool,
49 /// If `true`, emit an explicit [`Outbound::Subscribed`] ack before the first
50 /// event. If `false` (default) the ack is implicit (events carry the
51 /// subscription id back).
52 pub acks_subscribe: bool,
53}
54
55/// Bound for the per-connection event funnel: pending outbound updates a
56/// connection may buffer before pumps start dropping.
57const EVENT_BUFFER: usize = 256;
58
59/// One subscription update on its way back to the connection's send half.
60struct SubEvent {
61 sub: String,
62 seq: u64,
63 /// Concrete record topic, when the subscription tags its updates
64 /// (see [`SubUpdate::topic`]).
65 topic: Option<Arc<str>>,
66 ts: crate::clock::Stamp,
67 data: Payload,
68}
69
70/// What [`run_session`]'s `select_biased!` decided this iteration — extracted so
71/// the work runs after the arm futures' borrows of `conn`/`subs` release.
72enum Step {
73 /// A logical frame arrived from the peer (decode + dispatch).
74 Frame(Vec<u8>),
75 /// Peer closed or the transport errored — end the session.
76 Closed,
77 /// A subscription update to encode and forward to the peer.
78 Event(SubEvent),
79 /// A subscription pump finished — reap it and prune its `cancels` entry,
80 /// but only while that entry is still the pump's own (same generation).
81 SubDrained(PumpEnd),
82}
83
84/// How a subscription pump ended, returned to [`run_session`].
85struct PumpEnd {
86 sub_id: String,
87 /// Which `cancels` entry was the pump's own.
88 generation: u64,
89 /// The stream ran out on its own, not through a cancel or a closed funnel.
90 exhausted: bool,
91}
92
93/// Drive one accepted [`Connection`] until it closes.
94///
95/// Authenticates once, then interleaves (biased toward inbound reads, so a chatty
96/// subscription cannot starve the RPC path) incoming requests, outgoing
97/// subscription events, and reaping of finished subscription pumps. Dropping the
98/// engine cancels every live subscription.
99pub async fn run_session<C, D>(
100 mut conn: Box<dyn Connection>,
101 codec: &C,
102 dispatch: &D,
103 config: &SessionConfig,
104) where
105 C: EnvelopeCodec + ?Sized,
106 D: Dispatch + ?Sized,
107{
108 // Resolve the session context (Hello-frame or peer-only — see `reads_hello`).
109 let first = if config.reads_hello {
110 match conn.recv().await {
111 Ok(Some(frame)) => Some(frame),
112 // Peer closed or errored before sending the Hello — nothing to serve.
113 _ => return,
114 }
115 } else {
116 None
117 };
118 let ctx = match dispatch.authenticate(conn.peer(), first.as_deref()).await {
119 Ok(ctx) => ctx,
120 Err(_e) => {
121 report(SessionEvent::AuthenticationRejected { error: &_e });
122 return;
123 }
124 };
125
126 // Open the per-connection session once; the loop threads `&mut` into it.
127 let mut session = dispatch.open(&ctx);
128
129 // Event funnel: every per-subscription pump sends updates here; the main loop
130 // is the sole writer to the connection. Bounded, so a slow client cannot grow
131 // it without limit — pumps drop on overflow (events carry a monotonic `seq`).
132 let (mut event_tx, mut event_rx) = async_channel::bounded::<SubEvent>(EVENT_BUFFER);
133 // Per-connection subscription pumps; the engine future is their sole owner.
134 // Each resolves to its own sub id and generation, so the loop can prune the
135 // matching `cancels` entry (a no-op if Unsubscribe already removed it).
136 let mut subs: FuturesUnordered<BoxFut<'static, PumpEnd>> = FuturesUnordered::new();
137 // sub-id → (generation, cancel handle); dropping/firing the oneshot cancels
138 // the pump. The generation tells a pump's own entry from a later
139 // subscription that reuses its id after an Unsubscribe: a pump that ends
140 // late must not remove that one.
141 let mut cancels: HashMap<String, (u64, oneshot::Sender<()>)> = HashMap::new();
142 let mut next_generation: u64 = 0;
143 // Whether this connection has seen a handshake; a second one starts a new
144 // session (see `Session::starts_session`).
145 let mut greeted = false;
146 // Reused encode scratch buffer.
147 let mut out = Vec::new();
148
149 loop {
150 // Biased toward inbound reads. The select only decides the next step; the
151 // work happens after, in the `match`, once the arm borrows release.
152 let step = {
153 // Per-iteration futures, fused for the select. `event_rx.recv()` is
154 // `!Unpin`, so pin it; `subs` (a `FusedStream`) parks on the empty set
155 // while the always-active `recv` arm keeps the select alive.
156 let mut recv = conn.recv().fuse();
157 let mut event = core::pin::pin!(event_rx.recv().fuse());
158 select_biased! {
159 // ---- inbound: one logical frame from the peer --------------
160 r = recv => match r {
161 Ok(Some(frame)) => Step::Frame(frame),
162 Ok(None) | Err(_) => Step::Closed, // peer closed / transport error
163 },
164 // ---- outbound: a subscription update to forward ------------
165 ev = event => match ev {
166 Ok(ev) => Step::Event(ev),
167 // Funnel closed — only if every sender dropped, which can't
168 // happen while the loop holds `event_tx`, so this is
169 // unreachable; end the session defensively if it ever does.
170 Err(_) => Step::Closed,
171 },
172 // ---- drain finished subscription pumps ---------------------
173 end = subs.select_next_some() => Step::SubDrained(end),
174 }
175 };
176
177 match step {
178 Step::Closed => break,
179 // A pump finished; drop its cancel handle so the ended subscription
180 // neither leaks nor keeps counting against
181 // `max_subs_per_connection` — unless the id now belongs to a newer
182 // subscription (Unsubscribe, then Subscribe with the same id).
183 Step::SubDrained(end) => {
184 let own = cancels
185 .get(&end.sub_id)
186 .is_some_and(|(g, _)| *g == end.generation);
187 if !own {
188 continue;
189 }
190 cancels.remove(&end.sub_id);
191 // A subscription the client still holds ended on its own: its
192 // source closed, or never opened (a buffer with no subscriber
193 // slot left). Tell the client, which turns the error reply to
194 // its subscribe id into a terminal error, instead of leaving an
195 // acknowledged subscription that never delivers.
196 if end.exhausted {
197 // Its last events may still sit in the funnel: the pump
198 // runs inside the reap arm, so a stream that is ready at
199 // once fills the funnel and ends in one poll. Send them
200 // first, so the error is the subscription's last word.
201 let mut flushed = true;
202 while let Ok(ev) = event_rx.try_recv() {
203 if !send_event(&mut conn, codec, &mut out, ev).await {
204 flushed = false;
205 break;
206 }
207 }
208 if !flushed {
209 break;
210 }
211 report(SessionEvent::SubscriptionEnded { id: &end.sub_id });
212 if let Ok(id) = end.sub_id.parse::<u64>() {
213 send_reply_err(&mut conn, codec, &mut out, id, RpcError::Internal).await;
214 }
215 }
216 }
217
218 Step::Event(ev) => {
219 if !send_event(&mut conn, codec, &mut out, ev).await {
220 break;
221 }
222 }
223
224 Step::Frame(frame) => {
225 let msg = match codec.decode(&frame) {
226 Ok(msg) => msg,
227 Err(_e) => continue, // skip a malformed frame, keep the session
228 };
229 match msg {
230 Inbound::Request { id, method, params } => {
231 if session.starts_session(&method) {
232 if greeted {
233 // A new client on a connection that never closed
234 // (a serial line): nothing of the old session
235 // may reach it or outlive it. Dropping the pumps
236 // releases their buffer subscribers; a fresh
237 // funnel discards their queued events.
238 report(SessionEvent::HandshakeReset {
239 ended_subscriptions: cancels.len(),
240 });
241 subs = FuturesUnordered::new();
242 cancels.clear();
243 (event_tx, event_rx) =
244 async_channel::bounded::<SubEvent>(EVENT_BUFFER);
245 session = dispatch.open(&ctx);
246 }
247 greeted = true;
248 }
249 let result = session.call(&method, params).await;
250 out.clear();
251 if codec
252 .encode(Outbound::Reply { id, result }, &mut out)
253 .is_err()
254 {
255 continue;
256 }
257 if conn.send(&out).await.is_err() {
258 break;
259 }
260 }
261 Inbound::Subscribe { id, topic } => {
262 // The opening request id is the subscription's routing key;
263 // events carry it back as `Outbound::Event.sub`.
264 let sub_id = id.to_string();
265 // An id that still names a live subscription is refused:
266 // replacing it would cancel the live one without a word.
267 if cancels.contains_key(&sub_id) {
268 report(SessionEvent::SubscribeRefused { id: &sub_id });
269 send_reply_err(&mut conn, codec, &mut out, id, RpcError::Denied).await;
270 continue;
271 }
272 if cancels.len() >= config.limits.max_subs_per_connection {
273 send_reply_err(&mut conn, codec, &mut out, id, RpcError::Denied).await;
274 continue;
275 }
276 match session.subscribe(&topic).await {
277 Ok(stream) => {
278 // Optional explicit ack (see `acks_subscribe`).
279 if config.acks_subscribe {
280 out.clear();
281 if codec
282 .encode(Outbound::Subscribed { sub: &sub_id }, &mut out)
283 .is_ok()
284 && conn.send(&out).await.is_err()
285 {
286 break;
287 }
288 }
289 // Optional late-join snapshots (one per covered
290 // record), before the first event. They share
291 // the subscription's `seq` space — numbered
292 // `1..=N` here, events continue at `N + 1` — so
293 // every snapshot is accounted for end-to-end:
294 // one dropped by a slow client sink (or skipped
295 // by the encode failure below) leaves a hole the
296 // client reports as `skipped`, and a loss at the
297 // tail of the burst surfaces on the first event.
298 let snaps = session.snapshots(&topic);
299 let total = snaps.len();
300 let mut seq: u64 = 0;
301 let mut send_failed = false;
302 for (i, (snap_topic, data, ts)) in snaps.into_iter().enumerate() {
303 seq += 1;
304 out.clear();
305 let encoded = codec.encode(
306 Outbound::Snapshot {
307 sub: &sub_id,
308 seq,
309 // The client reserves a sink slot
310 // for this one, so the burst's
311 // loss total always lands.
312 last: i + 1 == total,
313 topic: &snap_topic,
314 ts,
315 data,
316 },
317 &mut out,
318 );
319 if let Err(_e) = encoded {
320 // A record whose serialized bytes aren't
321 // valid for this envelope — broken for
322 // every read of it, not just here, so say
323 // so rather than dropping it in silence.
324 // `seq` already advanced, so the client
325 // still counts it as loss; if this was the
326 // burst's last snapshot the `last` flag
327 // goes with it and no `snapshot_end`
328 // reaches the subscriber.
329 report(SessionEvent::SnapshotEncodeFailed {
330 id: &sub_id,
331 topic: &snap_topic,
332 error: &_e,
333 });
334 continue;
335 }
336 if conn.send(&out).await.is_err() {
337 send_failed = true;
338 break;
339 }
340 }
341 if send_failed {
342 break;
343 }
344 let (cancel_tx, cancel_rx) = oneshot::channel();
345 let generation = next_generation;
346 next_generation += 1;
347 cancels.insert(sub_id.clone(), (generation, cancel_tx));
348 subs.push(Box::pin(pump_subscription(
349 sub_id,
350 generation,
351 stream,
352 event_tx.clone(),
353 cancel_rx,
354 seq,
355 )));
356 }
357 Err(e) => {
358 send_reply_err(&mut conn, codec, &mut out, id, e).await;
359 }
360 }
361 }
362 Inbound::Unsubscribe { sub } => {
363 // Dropping the sender resolves the pump's cancel future.
364 cancels.remove(&sub);
365 }
366 Inbound::Write { topic, payload } => {
367 // Fire-and-forget; single-writer-per-key stays intact.
368 let _ = session.write(&topic, payload).await;
369 }
370 Inbound::Ping => {
371 out.clear();
372 if codec.encode(Outbound::Pong, &mut out).is_ok()
373 && conn.send(&out).await.is_err()
374 {
375 break;
376 }
377 }
378 }
379 }
380 }
381 }
382
383 // Dropping `subs` here cancels every live subscription pump.
384 drop(subs);
385}
386
387/// Encode + send one subscription event. `false` only when the connection is
388/// gone; an event that does not encode is skipped.
389async fn send_event<C: EnvelopeCodec + ?Sized>(
390 conn: &mut Box<dyn Connection>,
391 codec: &C,
392 out: &mut Vec<u8>,
393 ev: SubEvent,
394) -> bool {
395 out.clear();
396 let encoded = codec
397 .encode(
398 Outbound::Event {
399 sub: &ev.sub,
400 seq: ev.seq,
401 topic: ev.topic.as_deref(),
402 ts: ev.ts,
403 data: ev.data,
404 },
405 out,
406 )
407 .is_ok();
408 !encoded || conn.send(out).await.is_ok()
409}
410
411/// Encode + send a `Reply` carrying an [`RpcError`]; best-effort (a send/encode
412/// failure just ends this attempt — the caller's loop handles a dead connection
413/// on its next `send`).
414async fn send_reply_err<C: EnvelopeCodec + ?Sized>(
415 conn: &mut Box<dyn Connection>,
416 codec: &C,
417 out: &mut Vec<u8>,
418 id: u64,
419 err: RpcError,
420) {
421 out.clear();
422 if codec
423 .encode(
424 Outbound::Reply {
425 id,
426 result: Err(err),
427 },
428 out,
429 )
430 .is_ok()
431 {
432 let _ = conn.send(out).await;
433 }
434}
435
436/// Pump one `Session::subscribe` stream into the connection's event funnel,
437/// tagging each update with a monotonic `seq`. Ends when the stream finishes or
438/// the cancel handle is dropped/fired (Unsubscribe or connection teardown).
439///
440/// `start_seq` is the last sequence number the late-join snapshot burst used
441/// (`0` when there were none), so events continue the *same* counter and a
442/// snapshot lost at the tail of the burst still shows up as a gap on the first
443/// event.
444///
445/// Returns its `sub_id` and `generation` so [`run_session`] can prune the
446/// `cancels` entry for a pump that ended on its own; the Unsubscribe path
447/// already removed it, and a newer subscription under the same id has another
448/// generation, so that later prune leaves both alone. `exhausted` tells a
449/// stream that ran out from a cancel or a closed funnel.
450async fn pump_subscription(
451 sub_id: String,
452 generation: u64,
453 mut stream: BoxStream<'static, SubUpdate>,
454 tx: Sender<SubEvent>,
455 cancel: oneshot::Receiver<()>,
456 start_seq: u64,
457) -> PumpEnd {
458 // Fuse the cancel receiver: a bare `oneshot::Receiver` reports
459 // `is_terminated()` once its sender drops, and `select_biased!` skips
460 // terminated arms — so the cancel would never fire. `Fuse` keeps the arm
461 // polled until it actually resolves.
462 let mut cancel = cancel.fuse();
463 let mut seq: u64 = start_seq;
464 let mut exhausted = false;
465 loop {
466 // Independent arms, so a direct `select_biased!` is fine here.
467 let update = select_biased! {
468 // Resolves on explicit Unsubscribe (send) or on sender drop.
469 _ = cancel => break,
470 // `BoxStream` is not `FusedStream`, so fuse the per-iteration `next`.
471 next = stream.next().fuse() => match next {
472 Some(update) => update,
473 None => {
474 exhausted = true;
475 break;
476 }
477 },
478 };
479 seq += update.skipped + 1;
480 // Non-blocking: drop on a full funnel (slow-client protection); only a
481 // disconnected funnel ends the pump.
482 match tx.try_send(SubEvent {
483 sub: sub_id.clone(),
484 seq,
485 topic: update.topic,
486 ts: update.ts,
487 data: update.data,
488 }) {
489 Ok(()) => {}
490 Err(e) if e.is_full() => {} // drop on overflow
491 Err(_) => break, // funnel disconnected — connection gone
492 }
493 }
494 PumpEnd {
495 sub_id,
496 generation,
497 exhausted,
498 }
499}
500
501/// Accept connections from `listener` and serve each with [`run_session`],
502/// bounded by [`SessionLimits::max_connections`]. The accept loop and all
503/// per-connection futures share one [`FuturesUnordered`] — spawn-free.
504///
505/// Runs until the listener reports [`TransportError::Closed`] (no more
506/// connections will come) and every open connection has ended, then returns.
507/// A listener that never closes keeps it running.
508pub async fn serve<L, C, D>(mut listener: L, codec: Arc<C>, dispatch: Arc<D>, config: SessionConfig)
509where
510 L: Listener,
511 C: EnvelopeCodec + 'static,
512 // `?Sized` so a caller can serve an `Arc<dyn Dispatch>`.
513 D: Dispatch + 'static + ?Sized,
514{
515 let mut conns: FuturesUnordered<BoxFut<'static, ()>> = FuturesUnordered::new();
516 // Set by a failed accept: the next one yields once before it starts.
517 let mut after_error = false;
518 // Consecutive failed accepts, so a listener that keeps failing logs a
519 // summary now and then instead of one line per attempt.
520 let mut failures = AcceptFailures::default();
521
522 loop {
523 // Extract the accept result first, then act (keeps the `listener` and
524 // `conns` borrows apart).
525 let accept = {
526 // After an error, the next accept first returns `Pending` once, so
527 // this select falls through to the connections: a listener that
528 // fails at once, every time, cannot starve them, and the task
529 // stays cancellable.
530 let mut accept = PendingOnce::new(listener.accept(), after_error).fuse();
531 select_biased! {
532 a = accept => a,
533 // Parks on the empty set, so the accept arm keeps the select alive.
534 () = conns.select_next_some() => continue,
535 }
536 };
537
538 after_error = accept.is_err();
539 match accept {
540 Ok(conn) => {
541 if let Some(event) = failures.on_success() {
542 report(event);
543 }
544 // Soft cap; `len()` counts finished-but-not-yet-reaped futures, so
545 // under an accept flood (the biased `accept` arm starves the reap
546 // arm) it may read high transiently — acceptable for a soft cap.
547 if conns.len() >= config.limits.max_connections {
548 report(SessionEvent::ConnectionLimitReached {
549 limit: config.limits.max_connections,
550 });
551 drop(conn);
552 continue;
553 }
554 let codec = codec.clone();
555 let dispatch = dispatch.clone();
556 let cfg = config.clone();
557 conns.push(Box::pin(async move {
558 run_session(conn, codec.as_ref(), dispatch.as_ref(), &cfg).await;
559 }));
560 }
561 // The listener hands out no more connections: stop accepting, and
562 // serve the open ones to their end. Calling `accept` again would
563 // only fail again, at once — a spin that starves those connections.
564 Err(TransportError::Closed) => {
565 report(SessionEvent::ListenerClosed {
566 open_connections: conns.len(),
567 });
568 while conns.next().await.is_some() {}
569 return;
570 }
571 Err(_e) => {
572 if let Some(event) = failures.on_error(_e) {
573 report(event);
574 }
575 // Keep serving existing connections despite a transient accept
576 // error; the next accept yields first (`after_error`).
577 }
578 }
579 }
580}
581
582/// Counts consecutive failed accepts and decides which of them to log: the
583/// first of a series, then a summary at 10, 100, 1000, … failures, so a
584/// listener that keeps failing grows the log by one line per decade instead
585/// of one per attempt.
586#[derive(Default)]
587struct AcceptFailures {
588 consecutive: u64,
589}
590
591impl AcceptFailures {
592 fn on_error(&mut self, error: TransportError) -> Option<SessionEvent<'static>> {
593 self.consecutive = self.consecutive.saturating_add(1);
594 match self.consecutive {
595 1 => Some(SessionEvent::AcceptFailed { error }),
596 n if is_power_of_ten(n) => {
597 Some(SessionEvent::AcceptStillFailing { attempts: n, error })
598 }
599 _ => None,
600 }
601 }
602
603 /// The length of the series a success ends, if there was one.
604 fn on_success(&mut self) -> Option<SessionEvent<'static>> {
605 let failed = core::mem::take(&mut self.consecutive);
606 (failed > 0).then_some(SessionEvent::AcceptRecovered { after: failed })
607 }
608}
609
610fn is_power_of_ten(mut n: u64) -> bool {
611 while n >= 10 && n.is_multiple_of(10) {
612 n /= 10;
613 }
614 n == 1
615}
616
617/// `inner`, but when `yield_first` is set, its first poll returns `Pending`
618/// (waking itself) without polling `inner`. Runtime-neutral: one turn back to
619/// the executor and to the sibling arms of a select.
620struct PendingOnce<F> {
621 inner: F,
622 yield_first: bool,
623}
624
625impl<F> PendingOnce<F> {
626 fn new(inner: F, yield_first: bool) -> Self {
627 Self { inner, yield_first }
628 }
629}
630
631impl<F: Future + Unpin> Future for PendingOnce<F> {
632 type Output = F::Output;
633
634 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
635 if self.yield_first {
636 self.yield_first = false;
637 cx.waker().wake_by_ref();
638 return Poll::Pending;
639 }
640 Pin::new(&mut self.inner).poll(cx)
641 }
642}
643
644#[cfg(test)]
645mod tests {
646 use super::*;
647
648 #[test]
649 fn a_failing_series_reports_first_then_once_per_decade() {
650 let mut failures = AcceptFailures::default();
651 let reported: Vec<_> = (1..=1000)
652 .filter_map(|n| {
653 failures.on_error(TransportError::Io).map(|event| {
654 assert!(matches!(
655 event,
656 SessionEvent::AcceptFailed {
657 error: TransportError::Io
658 } | SessionEvent::AcceptStillFailing {
659 error: TransportError::Io,
660 ..
661 }
662 ));
663 n
664 })
665 })
666 .collect();
667 assert_eq!(reported, [1, 10, 100, 1000]);
668 assert!(matches!(
669 failures.on_success(),
670 Some(SessionEvent::AcceptRecovered { after: 1000 })
671 ));
672 assert!(failures.on_success().is_none());
673 assert!(matches!(
674 failures.on_error(TransportError::Busy),
675 Some(SessionEvent::AcceptFailed {
676 error: TransportError::Busy
677 })
678 ));
679 }
680
681 #[test]
682 fn failure_count_saturates_without_repeated_summaries() {
683 let mut failures = AcceptFailures {
684 consecutive: u64::MAX - 1,
685 };
686 assert!(failures.on_error(TransportError::Io).is_none());
687 assert!(failures.on_error(TransportError::Io).is_none());
688 assert!(matches!(
689 failures.on_success(),
690 Some(SessionEvent::AcceptRecovered { after: u64::MAX })
691 ));
692 }
693
694 #[test]
695 fn powers_of_ten() {
696 let found: Vec<u64> = (0..=10_000).filter(|&n| is_power_of_ten(n)).collect();
697 assert_eq!(found, [1, 10, 100, 1000, 10_000]);
698 }
699}