reifydb-sub-server 0.9.1

Common infrastructure for server subsystems
Documentation
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
// SPDX-License-Identifier: Apache-2.0
// Copyright (c) 2026 ReifyDB

use std::{
	collections::{HashMap, HashSet},
	mem,
	sync::{
		Arc,
		atomic::{AtomicUsize, Ordering},
	},
};

use dashmap::DashMap;
use reifydb_core::{
	interface::{catalog::id::SubscriptionId, change::StagedBatch},
	value::column::columns::Columns,
};
use reifydb_runtime::{
	context::{clock::Clock, rng::Rng},
	sync::mutex::Mutex,
};
use reifydb_subscription::{
	batch::BatchId,
	delivery::{DeliveryResult, SubscriptionDelivery},
};
use reifydb_value::{
	reifydb_assertions,
	value::{diff_type::DiffType, duration::Duration, frame::frame::Frame, uuid::Uuid7},
};
use tokio::sync::Notify;
use tracing::{debug, instrument, trace};

use crate::subscription::wire_sink::WireSink;

pub type ConnectionId = Uuid7;

type PromoteDrain<S> = (Vec<StagedBatch>, Option<BatchId>, <S as WireSink>::Format, S);
type ThrottleReady<S> = (SubscriptionId, Vec<StagedBatch>, <S as WireSink>::Format, S);

#[derive(Debug)]
pub enum PromoteResult {
	Promoted(usize),
	Overflowed,
	NotWarming,
	NotFound,
	Disconnected,
}

struct SubscriptionState<S: WireSink> {
	connection_id: ConnectionId,
	sink: S,
	format: S::Format,
	#[allow(dead_code)]
	query: String,
	batch_id: Option<BatchId>,
	warming: Option<WarmingBuffer>,
	throttle: ThrottleState,
}

struct FlushGate {
	throttle_millis: u64,
	linger_millis: u64,
	first_pending_at: Option<u64>,
	last_sent_at: Option<u64>,
}

impl FlushGate {
	fn new(throttle: Duration, linger: Duration) -> Self {
		Self {
			throttle_millis: throttle.to_std().as_millis() as u64,
			linger_millis: linger.to_std().as_millis() as u64,
			first_pending_at: None,
			last_sent_at: None,
		}
	}

	fn shaping(&self) -> bool {
		self.throttle_millis != 0 || self.linger_millis != 0
	}

	fn on_pending(&mut self, now: u64) {
		if self.first_pending_at.is_none() {
			self.first_pending_at = Some(now);
		}
	}

	fn throttle_ok(&self, now: u64) -> bool {
		match self.last_sent_at {
			None => true,
			Some(prev) => now.saturating_sub(prev) >= self.throttle_millis,
		}
	}

	fn linger_ok(&self, now: u64) -> bool {
		match self.first_pending_at {
			None => false,
			Some(first) => now.saturating_sub(first) >= self.linger_millis,
		}
	}

	fn ready(&self, now: u64) -> bool {
		self.linger_ok(now) && self.throttle_ok(now)
	}

	fn remaining_millis(&self, now: u64) -> u64 {
		let linger_left = match self.first_pending_at {
			None => u64::MAX,
			Some(first) => self.linger_millis.saturating_sub(now.saturating_sub(first)),
		};
		let throttle_left = match self.last_sent_at {
			None => 0,
			Some(prev) => self.throttle_millis.saturating_sub(now.saturating_sub(prev)),
		};
		linger_left.max(throttle_left)
	}

	fn on_flush(&mut self, now: u64) {
		self.first_pending_at = None;
		self.last_sent_at = Some(now);
	}
}

struct ThrottleState {
	gate: FlushGate,
	pending: Vec<StagedBatch>,
}

impl ThrottleState {
	fn new(throttle: Duration, linger: Duration) -> Self {
		Self {
			gate: FlushGate::new(throttle, linger),
			pending: Vec::new(),
		}
	}

	fn enabled(&self) -> bool {
		self.gate.shaping()
	}
}

struct WarmingBuffer {
	buffered: Vec<StagedBatch>,
	cap: usize,
	overflowed: bool,
}

impl WarmingBuffer {
	fn new(cap: usize) -> Self {
		Self {
			buffered: Vec::new(),
			cap,
			overflowed: false,
		}
	}

	fn push(&mut self, batch: StagedBatch) {
		if self.overflowed {
			return;
		}
		if self.buffered.len() >= self.cap {
			self.overflowed = true;
			self.buffered.clear();
			return;
		}
		self.buffered.push(batch);
	}
}

struct MemberPending {
	frames: Vec<Frame>,
	gate: FlushGate,
}

impl MemberPending {
	fn new(linger: Duration, throttle: Duration) -> Self {
		Self {
			frames: Vec::new(),
			gate: FlushGate::new(throttle, linger),
		}
	}

	fn push(&mut self, frame: Frame, now: u64) {
		self.gate.on_pending(now);
		self.frames.push(frame);
	}

	fn ready(&self, now: u64) -> bool {
		!self.frames.is_empty() && self.gate.ready(now)
	}

	fn remaining_millis(&self, now: u64) -> u64 {
		self.gate.remaining_millis(now)
	}
}

struct BatchState<S: WireSink> {
	connection_id: ConnectionId,
	sink: S,
	format: S::Format,
	member_ids: Vec<SubscriptionId>,
	pending: DashMap<SubscriptionId, MemberPending>,
	lingers: HashMap<SubscriptionId, Duration>,
	throttles: HashMap<SubscriptionId, Duration>,
}

pub struct SubscriptionRegistry<S: WireSink> {
	subscriptions: DashMap<SubscriptionId, SubscriptionState<S>>,
	connections: DashMap<ConnectionId, Vec<SubscriptionId>>,
	batches: DashMap<BatchId, BatchState<S>>,
	connection_batches: DashMap<ConnectionId, Vec<BatchId>>,
	clock: Clock,
	throttle_pending: AtomicUsize,
	wakers: Mutex<Vec<Arc<Notify>>>,
}

impl<S: WireSink> SubscriptionRegistry<S> {
	pub fn new(clock: Clock) -> Self {
		Self {
			subscriptions: DashMap::new(),
			connections: DashMap::new(),
			batches: DashMap::new(),
			connection_batches: DashMap::new(),
			clock,
			throttle_pending: AtomicUsize::new(0),
			wakers: Mutex::new(Vec::new()),
		}
	}

	#[allow(clippy::too_many_arguments)]
	pub fn subscribe(
		&self,
		subscription_id: SubscriptionId,
		connection_id: ConnectionId,
		query: String,
		sink: S,
		format: S::Format,
		warming_cap: Option<usize>,
		throttle: Duration,
		linger: Duration,
	) {
		self.subscriptions.insert(
			subscription_id,
			SubscriptionState {
				connection_id,
				sink,
				format,
				query,
				batch_id: None,
				warming: warming_cap.map(WarmingBuffer::new),
				throttle: ThrottleState::new(throttle, linger),
			},
		);

		self.connections.entry(connection_id).or_default().push(subscription_id);

		debug!(
			"Registered subscription {} for connection {} (warming_cap={:?})",
			subscription_id, connection_id, warming_cap
		);
	}

	pub fn promote_to_live(&self, subscription_id: SubscriptionId) -> PromoteResult {
		let mut state = match self.subscriptions.get_mut(&subscription_id) {
			Some(s) => s,
			None => return PromoteResult::NotFound,
		};
		let (buffered, batch_id, format, sink) = match self.drain_warming(&mut state) {
			Ok(drain) => drain,
			Err(result) => return result,
		};
		drop(state);

		let count = buffered.len();
		match batch_id {
			Some(batch_id) => self.flush_buffered_to_batch(batch_id, subscription_id, buffered, count),
			None => self.flush_buffered_to_sink(subscription_id, buffered, format, sink, count),
		}
	}

	#[inline]
	fn drain_warming(&self, state: &mut SubscriptionState<S>) -> Result<PromoteDrain<S>, PromoteResult> {
		let warming = match state.warming.as_ref() {
			Some(w) => w,
			None => return Err(PromoteResult::NotWarming),
		};
		if warming.overflowed {
			state.warming = None;
			return Err(PromoteResult::Overflowed);
		}
		let buffered = state.warming.take().expect("warming present").buffered;
		let batch_id = state.batch_id;
		let format = state.format;
		let sink = state.sink.clone();
		Ok((buffered, batch_id, format, sink))
	}

	#[inline]
	fn flush_buffered_to_batch(
		&self,
		batch_id: BatchId,
		subscription_id: SubscriptionId,
		buffered: Vec<StagedBatch>,
		count: usize,
	) -> PromoteResult {
		let Some(batch) = self.batches.get(&batch_id) else {
			return PromoteResult::Disconnected;
		};
		{
			let now = self.clock.now().to_millis();
			let linger = batch.lingers.get(&subscription_id).copied().unwrap_or(Duration::zero());
			let throttle = batch.throttles.get(&subscription_id).copied().unwrap_or(Duration::zero());
			let mut entry = batch
				.pending
				.entry(subscription_id)
				.or_insert_with(|| MemberPending::new(linger, throttle));
			for (op, columns) in buffered {
				entry.push(Frame::from(columns).with_op(op), now);
			}
		}
		for waker in self.wakers.lock().iter() {
			waker.notify_one();
		}
		PromoteResult::Promoted(count)
	}

	#[inline]
	fn flush_buffered_to_sink(
		&self,
		subscription_id: SubscriptionId,
		buffered: Vec<StagedBatch>,
		format: S::Format,
		sink: S,
		count: usize,
	) -> PromoteResult {
		for (op, columns) in buffered {
			match sink.send_change(subscription_id, op, columns, format) {
				DeliveryResult::Delivered => {}
				DeliveryResult::Disconnected => return PromoteResult::Disconnected,
			}
		}
		PromoteResult::Promoted(count)
	}

	#[allow(clippy::too_many_arguments)]
	pub fn register_batch(
		&self,
		connection_id: ConnectionId,
		members: Vec<(SubscriptionId, Duration)>,
		sink: S,
		format: S::Format,
		clock: &Clock,
		rng: &Rng,
	) -> BatchId {
		let batch_id = BatchId(Uuid7::generate(clock, rng));

		let member_ids: Vec<SubscriptionId> = members.iter().map(|(id, _)| *id).collect();
		let lingers: HashMap<SubscriptionId, Duration> = members.into_iter().collect();
		let mut throttles: HashMap<SubscriptionId, Duration> = HashMap::new();

		for member_id in &member_ids {
			if let Some(mut state) = self.subscriptions.get_mut(member_id) {
				state.batch_id = Some(batch_id);
				let throttle_millis = state.throttle.gate.throttle_millis;
				if throttle_millis != 0 {
					throttles.insert(
						*member_id,
						Duration::from_milliseconds(throttle_millis as i64).unwrap(),
					);
				}
			}
		}

		self.batches.insert(
			batch_id,
			BatchState {
				connection_id,
				sink,
				format,
				member_ids: member_ids.clone(),
				pending: DashMap::new(),
				lingers,
				throttles,
			},
		);

		self.connection_batches.entry(connection_id).or_default().push(batch_id);

		debug!(
			"Registered batch {} with {} members for connection {}",
			batch_id,
			member_ids.len(),
			connection_id
		);
		batch_id
	}

	pub fn unsubscribe_batch(&self, batch_id: BatchId) -> Option<Vec<SubscriptionId>> {
		let (_, state) = self.batches.remove(&batch_id)?;
		let connection_id = state.connection_id;
		let members = state.member_ids.clone();

		self.remove_batch_members(&members);
		self.prune_empty_connection(connection_id);
		self.prune_empty_connection_batches(connection_id, batch_id);

		debug!("Unsubscribed batch {} ({} members)", batch_id, members.len());
		Some(members)
	}

	#[inline]
	fn remove_batch_members(&self, members: &[SubscriptionId]) {
		let mut removed_by_conn: HashMap<ConnectionId, HashSet<SubscriptionId>> = HashMap::new();
		for member_id in members {
			if let Some((_, sub_state)) = self.subscriptions.remove(member_id) {
				removed_by_conn.entry(sub_state.connection_id).or_default().insert(*member_id);
			}
		}
		for (conn_id, removed) in removed_by_conn {
			if let Some(mut subs) = self.connections.get_mut(&conn_id) {
				subs.retain(|id| !removed.contains(id));
			}
		}
	}

	#[inline]
	fn prune_empty_connection(&self, connection_id: ConnectionId) {
		let remove_connection =
			self.connections.get(&connection_id).map(|subs| subs.is_empty()).unwrap_or(false);
		if remove_connection {
			self.connections.remove(&connection_id);
		}
	}

	#[inline]
	fn prune_empty_connection_batches(&self, connection_id: ConnectionId, batch_id: BatchId) {
		let batches_empty = {
			if let Some(mut batches) = self.connection_batches.get_mut(&connection_id) {
				batches.retain(|id| *id != batch_id);
				batches.is_empty()
			} else {
				false
			}
		};
		if batches_empty {
			self.connection_batches.remove(&connection_id);
		}
	}

	pub fn batch_for(&self, subscription_id: &SubscriptionId) -> Option<BatchId> {
		self.subscriptions.get(subscription_id).and_then(|state| state.batch_id)
	}

	pub fn batch_count(&self) -> usize {
		self.batches.len()
	}

	pub fn push_batch_frames(
		&self,
		batch_id: BatchId,
		subscription_id: SubscriptionId,
		frames: Vec<Frame>,
	) -> bool {
		let Some(batch) = self.batches.get(&batch_id) else {
			return false;
		};
		{
			let now = self.clock.now().to_millis();
			let linger = batch.lingers.get(&subscription_id).copied().unwrap_or(Duration::zero());
			let throttle = batch.throttles.get(&subscription_id).copied().unwrap_or(Duration::zero());
			let mut entry = batch
				.pending
				.entry(subscription_id)
				.or_insert_with(|| MemberPending::new(linger, throttle));
			for frame in frames {
				entry.push(frame, now);
			}
		}
		for waker in self.wakers.lock().iter() {
			waker.notify_one();
		}
		true
	}

	pub fn emit_batch_member_closed(&self, batch_id: BatchId, subscription_id: SubscriptionId) -> bool {
		let Some(batch) = self.batches.get(&batch_id) else {
			return false;
		};
		matches!(batch.sink.send_batch_member_closed(batch_id, subscription_id), DeliveryResult::Delivered)
	}

	pub fn unsubscribe(&self, subscription_id: SubscriptionId) -> bool {
		if let Some((_, state)) = self.subscriptions.remove(&subscription_id) {
			if !state.throttle.pending.is_empty() {
				self.throttle_pending.fetch_sub(1, Ordering::AcqRel);
			}
			let connection_id = state.connection_id;

			let should_remove_connection = {
				if let Some(mut subs) = self.connections.get_mut(&connection_id) {
					subs.retain(|id| *id != subscription_id);
					subs.is_empty()
				} else {
					false
				}
			};

			if should_remove_connection {
				self.connections.remove(&connection_id);
			}

			debug!("Unsubscribed subscription {}", subscription_id);
			true
		} else {
			false
		}
	}

	pub fn cleanup_connection(&self, connection_id: ConnectionId) -> Vec<SubscriptionId> {
		if let Some((_, batch_ids)) = self.connection_batches.remove(&connection_id) {
			for batch_id in &batch_ids {
				self.batches.remove(batch_id);
			}
		}

		if let Some((_, subscription_ids)) = self.connections.remove(&connection_id) {
			for sub_id in &subscription_ids {
				self.subscriptions.remove(sub_id);
			}
			debug!("Cleaned up subscriptions for disconnected connection {}", connection_id);
			subscription_ids
		} else {
			Vec::new()
		}
	}

	pub fn close_all(&self) {
		self.subscriptions.clear();
		self.batches.clear();
		self.connections.clear();
		self.connection_batches.clear();
		self.throttle_pending.store(0, Ordering::Release);
	}

	#[allow(dead_code)]
	pub fn subscription_count(&self) -> usize {
		self.subscriptions.len()
	}

	#[allow(dead_code)]
	pub fn connection_count(&self) -> usize {
		self.connections.len()
	}

	#[allow(dead_code)]
	pub fn log_stats(&self) {
		trace!(
			"Registry stats: {} subscriptions, {} connections",
			self.subscriptions.len(),
			self.connections.len()
		);
	}

	#[inline]
	fn deliver_to_batch_member(
		&self,
		batch_id: BatchId,
		subscription_id: &SubscriptionId,
		op: DiffType,
		columns: Columns,
	) -> DeliveryResult {
		let Some(batch) = self.batches.get(&batch_id) else {
			return DeliveryResult::Disconnected;
		};
		let now = self.clock.now().to_millis();
		let linger = batch.lingers.get(subscription_id).copied().unwrap_or(Duration::zero());
		let throttle = batch.throttles.get(subscription_id).copied().unwrap_or(Duration::zero());
		batch.pending
			.entry(*subscription_id)
			.or_insert_with(|| MemberPending::new(linger, throttle))
			.push(Frame::from(columns).with_op(op), now);
		DeliveryResult::Delivered
	}

	#[inline]
	fn send_now_and_mark(
		&self,
		subscription_id: &SubscriptionId,
		op: DiffType,
		columns: Columns,
		format: S::Format,
		sink: S,
		now: u64,
	) -> DeliveryResult {
		match sink.send_change(*subscription_id, op, columns, format) {
			DeliveryResult::Delivered => {
				if let Some(mut s) = self.subscriptions.get_mut(subscription_id) {
					s.throttle.gate.last_sent_at = Some(now);
				}
				DeliveryResult::Delivered
			}
			DeliveryResult::Disconnected => DeliveryResult::Disconnected,
		}
	}

	#[inline]
	fn queue_throttled(&self, state: &mut SubscriptionState<S>, op: DiffType, columns: Columns) -> DeliveryResult {
		let was_empty = state.throttle.pending.is_empty();
		state.throttle.pending.push((op, columns));
		state.throttle.gate.on_pending(self.clock.now().to_millis());
		if was_empty {
			self.throttle_pending.fetch_add(1, Ordering::AcqRel);
		}
		DeliveryResult::Delivered
	}

	#[inline]
	fn flush_ready_throttled(&self, now: u64, next_deadline: &mut Option<u64>) {
		if self.throttle_pending.load(Ordering::Acquire) == 0 {
			return;
		}

		let mut throttle_ready: Vec<ThrottleReady<S>> = Vec::new();
		for mut entry in self.subscriptions.iter_mut() {
			let sub_id = *entry.key();
			let state = entry.value_mut();
			if state.batch_id.is_some() || state.warming.is_some() {
				continue;
			}
			if !state.throttle.enabled() || state.throttle.pending.is_empty() {
				continue;
			}
			if !state.throttle.gate.ready(now) {
				let rem = state.throttle.gate.remaining_millis(now);
				*next_deadline = Some(next_deadline.map_or(rem, |d| d.min(rem)));
				continue;
			}
			let drained = mem::take(&mut state.throttle.pending);
			reifydb_assertions! {
				let counted = self.throttle_pending.load(Ordering::Acquire);
				assert!(
					counted > 0,
					"throttle_pending counter is {counted} while draining a subscription with \
					 non-empty pending; queue_throttled must increment once per empty->non-empty \
					 transition, so an underflowing fetch_sub here wraps the counter and the \
					 flush gate `load() > 0` would then fire forever, scanning every subscription \
					 on every flush even when nothing is pending"
				);
			}
			self.throttle_pending.fetch_sub(1, Ordering::AcqRel);
			state.throttle.gate.on_flush(now);
			throttle_ready.push((sub_id, drained, state.format, state.sink.clone()));
		}

		let mut dead_subs: Vec<SubscriptionId> = Vec::new();
		for (sub_id, drained, format, sink) in throttle_ready {
			for (op, columns) in drained {
				match sink.send_change(sub_id, op, columns, format) {
					DeliveryResult::Delivered => {}
					DeliveryResult::Disconnected => {
						dead_subs.push(sub_id);
						break;
					}
				}
			}
		}
		for sub_id in dead_subs {
			self.unsubscribe(sub_id);
		}
	}

	#[inline]
	fn flush_due_batches(&self, now: u64, next_deadline: &mut Option<u64>) {
		let mut dead_batches: Vec<BatchId> = Vec::new();
		for entry in self.batches.iter() {
			let batch_id = *entry.key();
			let batch = entry.value();

			let mut due: Vec<(SubscriptionId, Vec<Frame>)> = Vec::new();
			for mut e in batch.pending.iter_mut() {
				let key = *e.key();
				let member = e.value_mut();
				if member.frames.is_empty() {
					continue;
				}
				if member.ready(now) {
					let frames = mem::take(&mut member.frames);
					member.gate.on_flush(now);
					due.push((key, frames));
				} else {
					let rem = member.remaining_millis(now);
					*next_deadline = Some(next_deadline.map_or(rem, |d| d.min(rem)));
				}
			}
			if due.is_empty() {
				continue;
			}

			match batch.sink.send_batch_envelope(batch_id, batch.format, due) {
				DeliveryResult::Delivered => {}
				DeliveryResult::Disconnected => dead_batches.push(batch_id),
			}
		}

		for batch_id in dead_batches {
			if let Some(members) = self.unsubscribe_batch(batch_id) {
				debug!("Batch {} push channel closed; cascaded {} members", batch_id, members.len());
			}
		}
	}
}

impl<S: WireSink> SubscriptionDelivery for SubscriptionRegistry<S> {
	fn try_deliver(&self, subscription_id: &SubscriptionId, op: DiffType, columns: Columns) -> DeliveryResult {
		if let Some(batch_id) = self.batch_for(subscription_id) {
			return self.deliver_to_batch_member(batch_id, subscription_id, op, columns);
		}

		let mut state = match self.subscriptions.get_mut(subscription_id) {
			Some(s) => s,
			None => return DeliveryResult::Disconnected,
		};

		if let Some(buffer) = state.warming.as_mut() {
			buffer.push((op, columns));
			return DeliveryResult::Delivered;
		}

		if state.throttle.enabled() {
			let now = self.clock.now().to_millis();
			if state.throttle.gate.linger_millis == 0
				&& state.throttle.gate.throttle_ok(now)
				&& state.throttle.pending.is_empty()
			{
				let format = state.format;
				let sink = state.sink.clone();
				drop(state);
				self.send_now_and_mark(subscription_id, op, columns, format, sink, now)
			} else {
				self.queue_throttled(&mut state, op, columns)
			}
		} else {
			let format = state.format;
			let sink = state.sink.clone();
			drop(state);
			sink.send_change(*subscription_id, op, columns, format)
		}
	}

	fn active_subscriptions(&self) -> Vec<SubscriptionId> {
		self.subscriptions.iter().map(|entry| *entry.key()).collect()
	}

	fn active_subscriptions_into(&self, out: &mut Vec<SubscriptionId>) {
		out.extend(self.subscriptions.iter().map(|entry| *entry.key()));
	}

	fn register_waker(&self, waker: Arc<Notify>) {
		self.wakers.lock().push(waker);
	}

	fn simulated_clock(&self) -> bool {
		self.clock.is_mock()
	}

	#[instrument(name = "server::flush", level = "debug", skip_all)]
	fn flush(&self) -> Option<Duration> {
		let now = self.clock.now().to_millis();
		let mut next_deadline: Option<u64> = None;

		self.flush_ready_throttled(now, &mut next_deadline);

		if self.batches.is_empty() {
			return next_deadline.map(|ms| Duration::from_milliseconds(ms as i64).unwrap());
		}

		self.flush_due_batches(now, &mut next_deadline);

		next_deadline.map(|ms| Duration::from_milliseconds(ms as i64).unwrap())
	}
}