mod queue;
use std::{collections::VecDeque, future::Future, sync::Arc, time::Duration};
use gpui_kit::{App, BackgroundExecutor, Task};
use parking_lot::Mutex;
use rustc_hash::{FxBuildHasher, FxHashMap, FxHashSet};
use web_time::Instant;
pub use queue::WriteCoalescing;
use crate::{
highlight::{HighlightPolicy, RowChange, RowStamps, SparseStamps, Stamp},
model::{ColumnIx, ColumnSet, GridColumns, GridRow},
};
use queue::{QueueCounters, WriteQueue};
pub const PAGE_SIZE: usize = 1024;
pub(crate) const SNAPSHOT_INTERVAL: Duration = Duration::from_millis(8);
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum PinnedEdge {
Top,
Bottom,
}
impl PinnedEdge {
const fn ix(self) -> usize {
match self {
Self::Top => 0,
Self::Bottom => 1,
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct GridProgress {
fraction: Option<f32>,
label: Option<Arc<str>>,
}
impl GridProgress {
pub fn indeterminate() -> Self {
Self {
fraction: None,
label: None,
}
}
pub fn new(fraction: f32) -> Self {
Self {
fraction: (!fraction.is_nan()).then(|| fraction.clamp(0.0, 1.0)),
label: None,
}
}
pub fn with_label(mut self, label: impl Into<Arc<str>>) -> Self {
self.label = Some(label.into());
self
}
pub fn fraction(&self) -> Option<f32> {
self.fraction
}
pub fn label(&self) -> Option<&str> {
self.label.as_deref()
}
pub fn is_indeterminate(&self) -> bool {
self.fraction.is_none()
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct RowId {
ix: u32,
generation: u32,
}
impl RowId {
pub fn ix(self) -> usize {
self.ix as usize
}
}
struct Slot<R> {
row: Option<Arc<R>>,
generation: u32,
seq: u64,
stamps: Option<SparseStamps>,
}
impl<R> Clone for Slot<R> {
fn clone(&self) -> Self {
Self {
row: self.row.clone(),
generation: self.generation,
seq: self.seq,
stamps: self.stamps.clone(),
}
}
}
impl<R> Default for Slot<R> {
fn default() -> Self {
Self {
row: None,
generation: 0,
seq: 0,
stamps: None,
}
}
}
struct Page<R> {
slots: Vec<Slot<R>>,
}
impl<R> Clone for Page<R> {
fn clone(&self) -> Self {
Self {
slots: self.slots.clone(),
}
}
}
struct PinnedBand<R> {
rows: Vec<Arc<R>>,
stamps: Vec<Option<SparseStamps>>,
}
impl<R> Clone for PinnedBand<R> {
fn clone(&self) -> Self {
Self {
rows: self.rows.clone(),
stamps: self.stamps.clone(),
}
}
}
impl<R> Default for PinnedBand<R> {
fn default() -> Self {
Self {
rows: Vec::new(),
stamps: Vec::new(),
}
}
}
pub trait Clock: Send + Sync + 'static {
fn now(&self) -> Instant;
}
impl Clock for BackgroundExecutor {
fn now(&self) -> Instant {
BackgroundExecutor::now(self)
}
}
pub trait ReloadPolicy<R: GridRow>: Send + 'static {
fn resolve(&mut self, snapshot: Vec<Arc<R>>, live: Vec<Op<R>>) -> Vec<Op<R>>;
}
#[derive(Clone, Copy, Debug, Default)]
pub struct ReplayLive;
impl<R: GridRow> ReloadPolicy<R> for ReplayLive {
fn resolve(&mut self, snapshot: Vec<Arc<R>>, mut live: Vec<Op<R>>) -> Vec<Op<R>> {
let mut ops = Vec::with_capacity(live.len() + 1);
ops.push(Op::ReplaceAll(snapshot));
ops.append(&mut live);
ops
}
}
#[non_exhaustive]
pub enum Op<R: GridRow> {
Upsert(Arc<R>),
UpsertSilent(Arc<R>),
MarkChanged(R::Key, ColumnSet),
Remove(R::Key),
ReplaceAll(Vec<Arc<R>>),
Clear,
FinishReload {
snapshot: Vec<Arc<R>>,
live: Vec<Op<R>>,
},
SetPinnedRows {
edge: PinnedEdge,
rows: Vec<Arc<R>>,
},
SetProgress(Option<GridProgress>),
}
type KeyIndex<K> =
imbl::GenericHashMap<K, RowId, FxBuildHasher, imbl::shared_ptr::DefaultSharedPtr>;
struct FadingRow<R> {
row: Arc<R>,
removed: Stamp,
seq: u64,
}
impl<R> Clone for FadingRow<R> {
fn clone(&self) -> Self {
Self {
row: self.row.clone(),
removed: self.removed,
seq: self.seq,
}
}
}
type FadingMap<R> =
imbl::GenericHashMap<RowId, FadingRow<R>, FxBuildHasher, imbl::shared_ptr::DefaultSharedPtr>;
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct ChangeSet {
inserted: usize,
removed: Vec<RowId>,
faded: Vec<RowId>,
updated: Vec<RowId>,
columns: ColumnSet,
reset: bool,
parent: bool,
pinned: bool,
progress: bool,
}
impl ChangeSet {
pub fn merge(&mut self, other: &ChangeSet) {
self.inserted += other.inserted;
self.removed.extend_from_slice(&other.removed);
self.faded.extend_from_slice(&other.faded);
self.updated.extend_from_slice(&other.updated);
self.columns.union_with(other.columns);
self.reset |= other.reset;
self.parent |= other.parent;
self.pinned |= other.pinned;
self.progress |= other.progress;
}
pub fn has_structure_change(&self) -> bool {
self.inserted > 0 || !self.removed.is_empty() || self.reset
}
pub fn has_insertions_or_reset(&self) -> bool {
self.inserted > 0 || self.reset
}
pub fn is_reset(&self) -> bool {
self.reset
}
pub fn inserted(&self) -> usize {
self.inserted
}
pub fn removed(&self) -> &[RowId] {
&self.removed
}
pub fn faded(&self) -> &[RowId] {
&self.faded
}
pub fn has_parent_change(&self) -> bool {
self.parent
}
pub fn columns(&self) -> ColumnSet {
self.columns
}
pub fn updated(&self) -> &[RowId] {
&self.updated
}
pub fn has_pinned_change(&self) -> bool {
self.pinned
}
pub fn has_progress_change(&self) -> bool {
self.progress
}
pub fn is_empty(&self) -> bool {
self.inserted == 0
&& self.removed.is_empty()
&& self.faded.is_empty()
&& self.updated.is_empty()
&& self.columns.is_empty()
&& !self.reset
&& !self.parent
&& !self.pinned
&& !self.progress
}
}
pub struct StoreSnapshot<R: GridRow> {
version: u64,
pages: Vec<Arc<Page<R>>>,
index: KeyIndex<R::Key>,
capacity: usize,
len: usize,
epoch: Instant,
pinned: [Arc<PinnedBand<R>>; 2],
progress: Option<GridProgress>,
fading: FadingMap<R>,
}
impl<R: GridRow> StoreSnapshot<R> {
pub fn version(&self) -> u64 {
self.version
}
pub fn len(&self) -> usize {
self.len
}
pub fn is_empty(&self) -> bool {
self.len == 0
}
pub fn capacity(&self) -> usize {
self.capacity
}
pub fn epoch(&self) -> Instant {
self.epoch
}
fn slot(&self, ix: usize) -> Option<&Slot<R>> {
if ix >= self.capacity {
return None;
}
self.pages
.get(ix / PAGE_SIZE)
.and_then(|page| page.slots.get(ix % PAGE_SIZE))
}
fn live_slot(&self, id: RowId) -> Option<&Slot<R>> {
self.slot(id.ix())
.filter(|slot| slot.generation == id.generation && slot.row.is_some())
}
pub fn row(&self, id: RowId) -> Option<&Arc<R>> {
self.live_slot(id).and_then(|slot| slot.row.as_ref())
}
pub fn row_id(&self, key: &R::Key) -> Option<RowId> {
self.index.get(key).copied()
}
pub fn get(&self, key: &R::Key) -> Option<&Arc<R>> {
self.row_id(key).and_then(|id| self.row(id))
}
pub fn stamps(&self, id: RowId) -> Option<RowStamps<'_>> {
self.live_slot(id)
.and_then(|slot| slot.stamps.as_ref())
.map(SparseStamps::view)
}
pub fn seq(&self, id: RowId) -> u64 {
self.live_slot(id).map_or(0, |slot| slot.seq)
}
pub fn iter(&self) -> impl Iterator<Item = (RowId, &Arc<R>)> {
self.pages.iter().enumerate().flat_map(|(page_ix, page)| {
page.slots
.iter()
.enumerate()
.filter_map(move |(slot_ix, slot)| {
slot.row.as_ref().map(|row| {
let id = RowId {
ix: (page_ix * PAGE_SIZE + slot_ix) as u32,
generation: slot.generation,
};
(id, row)
})
})
})
}
pub fn pinned_rows(&self, edge: PinnedEdge) -> &[Arc<R>] {
&self.pinned[edge.ix()].rows
}
pub fn pinned_stamps(&self, edge: PinnedEdge, ix: usize) -> Option<RowStamps<'_>> {
self.pinned[edge.ix()]
.stamps
.get(ix)?
.as_ref()
.map(SparseStamps::view)
}
pub fn progress(&self) -> Option<&GridProgress> {
self.progress.as_ref()
}
pub fn fading_row(&self, id: RowId) -> Option<(&Arc<R>, Stamp)> {
self.fading
.get(&id)
.map(|fading| (&fading.row, fading.removed))
}
pub fn fading_rows(&self) -> impl Iterator<Item = (RowId, &Arc<R>, Stamp, u64)> {
self.fading
.iter()
.map(|(id, fading)| (*id, &fading.row, fading.removed, fading.seq))
}
pub fn stamp_bytes(&self) -> usize {
self.pages
.iter()
.flat_map(|page| page.slots.iter())
.filter_map(|slot| slot.stamps.as_ref())
.map(SparseStamps::heap_bytes)
.sum()
}
}
pub struct Ingest<R: GridRow> {
pages: Vec<Arc<Page<R>>>,
capacity: usize,
index: FxHashMap<R::Key, RowId>,
published_index: KeyIndex<R::Key>,
free: Vec<u32>,
next_seq: u64,
version: u64,
hot: FxHashSet<u32>,
epoch: Instant,
policy: HighlightPolicy,
reload: Box<dyn ReloadPolicy<R>>,
every: ColumnSet,
last_sweep_ms: u32,
pinned: [Arc<PinnedBand<R>>; 2],
progress: Option<GridProgress>,
fading: FadingMap<R>,
fading_keys: FxHashMap<R::Key, RowId>,
fade_queue: VecDeque<(RowId, Stamp)>,
}
impl<R: GridRow> Ingest<R> {
pub fn new(policy: HighlightPolicy, epoch: Instant) -> Self {
Self::with_reload_policy(policy, epoch, Box::new(ReplayLive))
}
pub fn with_reload_policy(
policy: HighlightPolicy,
epoch: Instant,
reload: Box<dyn ReloadPolicy<R>>,
) -> Self {
Self {
pages: Vec::new(),
capacity: 0,
index: FxHashMap::default(),
published_index: KeyIndex::default(),
free: Vec::new(),
next_seq: 0,
version: 0,
hot: FxHashSet::default(),
epoch,
policy,
reload,
every: ColumnSet::first(R::Column::all().len()),
last_sweep_ms: 0,
pinned: Default::default(),
progress: None,
fading: FadingMap::default(),
fading_keys: FxHashMap::default(),
fade_queue: VecDeque::new(),
}
}
pub fn len(&self) -> usize {
self.index.len()
}
pub fn is_empty(&self) -> bool {
self.index.is_empty()
}
pub fn hot_rows(&self) -> usize {
self.hot.len()
}
fn now_ms(&self, now: Instant) -> u32 {
now.saturating_duration_since(self.epoch).as_millis() as u32
}
fn slot_mut(&mut self, ix: usize) -> &mut Slot<R> {
let page = Arc::make_mut(&mut self.pages[ix / PAGE_SIZE]);
&mut page.slots[ix % PAGE_SIZE]
}
fn allocate(&mut self) -> usize {
if let Some(ix) = self.free.pop() {
return ix as usize;
}
let ix = self.capacity;
if ix % PAGE_SIZE == 0 {
let mut slots = Vec::with_capacity(PAGE_SIZE);
slots.resize_with(PAGE_SIZE, Slot::default);
self.pages.push(Arc::new(Page { slots }));
}
self.capacity += 1;
ix
}
pub fn apply(&mut self, ops: impl IntoIterator<Item = Op<R>>, now: Instant) -> ChangeSet {
let now_ms = self.now_ms(now);
let mut changes = ChangeSet::default();
for op in ops {
self.apply_op(op, now_ms, &mut changes);
}
self.finish_batch(now_ms, changes)
}
fn finish_batch(&mut self, now_ms: u32, mut changes: ChangeSet) -> ChangeSet {
self.drop_faded(now_ms, &mut changes);
if !changes.is_empty() {
self.version += 1;
}
changes
}
fn apply_op(&mut self, op: Op<R>, now_ms: u32, changes: &mut ChangeSet) {
{
match op {
Op::Upsert(row) => self.upsert(row, now_ms, true, changes),
Op::UpsertSilent(row) => self.upsert(row, now_ms, false, changes),
Op::MarkChanged(key, columns) => {
if let Some(&id) = self.index.get(&key) {
let stamp = Stamp::new(now_ms, RowChange::Updated);
self.stamp(id.ix(), columns, now_ms, |_| stamp);
changes.columns.union_with(columns);
changes.updated.push(id);
}
}
Op::Remove(key) => self.remove(key, now_ms, changes),
Op::ReplaceAll(rows) => {
self.reset(changes);
for row in rows {
self.upsert(row, now_ms, false, changes);
}
}
Op::Clear => self.reset(changes),
Op::FinishReload { snapshot, live } => {
for op in self.reload.resolve(snapshot, live) {
if !matches!(op, Op::FinishReload { .. }) {
self.apply_op(op, now_ms, changes);
}
}
}
Op::SetPinnedRows { edge, rows } => {
self.set_pinned_rows(edge, rows, now_ms, changes);
}
Op::SetProgress(progress) => {
if self.progress != progress {
self.progress = progress;
changes.progress = true;
}
}
}
}
}
fn set_pinned_rows(
&mut self,
edge: PinnedEdge,
rows: Vec<Arc<R>>,
now_ms: u32,
changes: &mut ChangeSet,
) {
let written = rows.len();
let rows = keep_last_of_each_key(rows);
if cfg!(debug_assertions) && rows.len() < written {
log::warn!(
"gpui-kit-grid: {} rows pinned at {edge:?} repeat a key; the last row of each key is kept",
written - rows.len()
);
}
let previous = self.pinned[edge.ix()].clone();
let previous_ix: FxHashMap<&R::Key, usize> = previous
.rows
.iter()
.enumerate()
.map(|(ix, row)| (row.key(), ix))
.collect();
let first_fill = previous.rows.is_empty();
let mut changed = rows.len() != previous.rows.len();
let (policy, every) = (self.policy, self.every);
let columns_of = R::Column::all();
let stamps = rows
.iter()
.enumerate()
.map(|(ix, row)| {
let Some(&old_ix) = previous_ix.get(row.key()) else {
changed = true;
let flash = Stamp::new(now_ms, RowChange::Inserted);
return (!first_fill).then(|| SparseStamps::whole_row(flash));
};
let old = &previous.rows[old_ix];
let mut columns = ColumnSet::EMPTY;
let replaced = !Arc::ptr_eq(old, row);
if replaced {
row.changed_columns(old, &mut columns);
}
changed |= replaced || old_ix != ix;
let carried = &previous.stamps[old_ix];
if columns.is_empty() {
return carried.clone();
}
SparseStamps::written(
carried.as_ref(),
columns,
every,
|stamp| !policy.is_highlight_over(stamp, now_ms),
|column| updated::<R>(now_ms, row, old, columns_of[column.get()]),
)
})
.collect();
self.pinned[edge.ix()] = Arc::new(PinnedBand { rows, stamps });
changes.pinned |= changed;
}
fn remove(&mut self, key: R::Key, now_ms: u32, changes: &mut ChangeSet) {
let Some(id) = self.index.remove(&key) else {
return;
};
self.published_index.remove(&key);
let slot = self.slot_mut(id.ix());
let row = slot.row.take();
let seq = slot.seq;
slot.stamps = None;
slot.generation = slot.generation.wrapping_add(1);
self.free.push(id.ix);
self.hot.remove(&id.ix);
changes.removed.push(id);
if let Some(row) = row
&& self.policy.has_removal_fade()
{
let removed = Stamp::removal(now_ms);
self.fading.insert(id, FadingRow { row, removed, seq });
self.fading_keys.insert(key, id);
self.fade_queue.push_back((id, removed));
}
}
fn drop_fading_key(&mut self, key: &R::Key, changes: &mut ChangeSet) {
if let Some(id) = self.fading_keys.remove(key) {
self.fading.remove(&id);
changes.faded.push(id);
}
}
fn drop_faded(&mut self, now_ms: u32, changes: &mut ChangeSet) {
while let Some(&(id, removed)) = self.fade_queue.front() {
if !self.policy.is_removal_over(removed, now_ms) {
break;
}
self.fade_queue.pop_front();
if let Some(fading) = self.fading.remove(&id) {
self.fading_keys.remove(fading.row.key());
changes.faded.push(id);
}
}
}
fn reset(&mut self, changes: &mut ChangeSet) {
changes.reset = true;
if !self.fading.is_empty() {
changes.faded.extend(self.fading.keys().copied());
self.fading = FadingMap::default();
self.fading_keys.clear();
}
self.fade_queue.clear();
for ix in 0..self.capacity {
let slot = self.slot_mut(ix);
if slot.row.is_some() {
slot.generation = slot.generation.wrapping_add(1);
}
slot.row = None;
slot.stamps = None;
}
self.free = (0..self.capacity as u32).rev().collect();
self.index.clear();
self.published_index = KeyIndex::default();
self.hot.clear();
}
fn upsert(&mut self, row: Arc<R>, now_ms: u32, highlight: bool, changes: &mut ChangeSet) {
if let Some(&id) = self.index.get(row.key()) {
let ix = id.ix();
let current = self.pages[ix / PAGE_SIZE].slots[ix % PAGE_SIZE]
.row
.as_ref();
if current.is_some_and(|current| Arc::ptr_eq(current, &row)) {
return;
}
let slot = self.slot_mut(ix);
let Some(previous) = slot.row.replace(row.clone()) else {
return;
};
let mut columns = ColumnSet::EMPTY;
row.changed_columns(&previous, &mut columns);
changes.parent |= row.parent_key() != previous.parent_key();
changes.updated.push(id);
if columns.is_empty() {
return;
}
changes.columns.union_with(columns);
if highlight {
let all = R::Column::all();
self.stamp(ix, columns, now_ms, |column| {
updated::<R>(now_ms, &row, &previous, all[column.get()])
});
}
return;
}
if !self.fading_keys.is_empty() {
self.drop_fading_key(row.key(), changes);
}
let ix = self.allocate();
let seq = self.next_seq;
self.next_seq += 1;
let key = row.key().clone();
let slot = self.slot_mut(ix);
slot.row = Some(row);
slot.seq = seq;
slot.stamps = None;
let id = RowId {
ix: ix as u32,
generation: slot.generation,
};
self.published_index.insert(key.clone(), id);
self.index.insert(key, id);
changes.inserted += 1;
if highlight {
let flash = SparseStamps::whole_row(Stamp::new(now_ms, RowChange::Inserted));
self.slot_mut(ix).stamps = Some(flash);
self.hot.insert(ix as u32);
}
}
fn stamp(
&mut self,
ix: usize,
columns: ColumnSet,
now_ms: u32,
stamp: impl FnMut(ColumnIx) -> Stamp,
) {
let (policy, every) = (self.policy, self.every);
let slot = self.slot_mut(ix);
slot.stamps = SparseStamps::written(
slot.stamps.as_ref(),
columns,
every,
|stamp| !policy.is_highlight_over(stamp, now_ms),
stamp,
);
if slot.stamps.is_some() {
self.hot.insert(ix as u32);
}
}
pub fn sweep(&mut self, now: Instant) {
let now_ms = self.now_ms(now);
if now_ms.saturating_sub(self.last_sweep_ms) < self.policy.duration_ms() / 2 {
return;
}
self.last_sweep_ms = now_ms;
let policy = self.policy;
let is_hot = |stamp| !policy.is_highlight_over(stamp, now_ms);
let expired: Vec<u32> = self
.hot
.iter()
.copied()
.filter(|&ix| {
let page = &self.pages[ix as usize / PAGE_SIZE];
page.slots[ix as usize % PAGE_SIZE]
.stamps
.as_ref()
.is_none_or(|stamps| stamps.is_cold(is_hot))
})
.collect();
for ix in expired {
self.slot_mut(ix as usize).stamps = None;
self.hot.remove(&ix);
}
let expired = |stamps: &Option<SparseStamps>| {
stamps.as_ref().is_some_and(|stamps| stamps.is_cold(is_hot))
};
for band in &mut self.pinned {
if band.stamps.iter().any(expired) {
for stamps in &mut Arc::make_mut(band).stamps {
if expired(stamps) {
*stamps = None;
}
}
}
}
}
pub fn snapshot(&self) -> Arc<StoreSnapshot<R>> {
Arc::new(StoreSnapshot {
version: self.version,
pages: self.pages.clone(),
index: self.published_index.clone(),
capacity: self.capacity,
len: self.index.len(),
epoch: self.epoch,
pinned: self.pinned.clone(),
progress: self.progress.clone(),
fading: self.fading.clone(),
})
}
}
#[inline]
fn updated<R: GridRow>(now_ms: u32, row: &R, previous: &R, column: R::Column) -> Stamp {
let direction = row.change_direction(previous, column);
Stamp::with_direction(now_ms, RowChange::Updated, direction)
}
fn keep_last_of_each_key<R: GridRow>(rows: Vec<Arc<R>>) -> Vec<Arc<R>> {
if rows.len() < 2 {
return rows;
}
let mut last_ix: FxHashMap<&R::Key, usize> =
FxHashMap::with_capacity_and_hasher(rows.len(), FxBuildHasher);
for (ix, row) in rows.iter().enumerate() {
last_ix.insert(row.key(), ix);
}
if last_ix.len() == rows.len() {
return rows;
}
rows.iter()
.enumerate()
.filter(|(ix, row)| last_ix[row.key()] == *ix)
.map(|(_, row)| row.clone())
.collect()
}
struct Shared<R: GridRow> {
pending: Mutex<Pending<R>>,
wake: async_channel::Sender<()>,
}
impl<R: GridRow> Shared<R> {
fn wake(&self) {
let _ = self.wake.try_send(());
}
}
struct Pending<R: GridRow> {
queue: WriteQueue<R>,
reload: Option<ReloadBuffer<R>>,
next_reload: u64,
flushes: Vec<async_channel::Sender<u64>>,
closed: bool,
}
struct ReloadBuffer<R: GridRow> {
id: u64,
live: Vec<Op<R>>,
}
impl<R: GridRow> Pending<R> {
fn new(coalescing: WriteCoalescing) -> Self {
Self {
queue: WriteQueue::new(coalescing),
reload: None,
next_reload: 0,
flushes: Vec::new(),
closed: false,
}
}
fn write(&mut self, op: Op<R>) -> bool {
match &mut self.reload {
Some(reload) if !matches!(op, Op::SetProgress(_)) => {
self.queue.count_buffered();
reload.live.push(op);
false
}
_ => {
self.queue.push(op);
true
}
}
}
fn finish_reload(&mut self, id: u64, snapshot: Vec<Arc<R>>) -> bool {
let Some(reload) = self.reload.take_if(|reload| reload.id == id) else {
return false;
};
self.queue.push_finished_reload(snapshot, reload.live);
true
}
}
struct IngestGuard<R: GridRow>(Arc<Shared<R>>);
impl<R: GridRow> Drop for IngestGuard<R> {
fn drop(&mut self) {
let flushes = {
let mut pending = self.0.pending.lock();
pending.closed = true;
std::mem::take(&mut pending.flushes)
};
drop(flushes);
}
}
pub struct GridWriter<R: GridRow> {
shared: Arc<Shared<R>>,
hub: Arc<Mutex<Hub<R>>>,
}
impl<R: GridRow> Clone for GridWriter<R> {
fn clone(&self) -> Self {
Self {
shared: self.shared.clone(),
hub: self.hub.clone(),
}
}
}
impl<R: GridRow> GridWriter<R> {
fn push(&self, op: Op<R>) {
let queued = self.shared.pending.lock().write(op);
if queued {
self.shared.wake();
}
}
pub fn batch(&self, write: impl FnOnce(&mut WriteBatch<R>)) {
let mut batch = WriteBatch {
shared: self.shared.clone(),
writes: Vec::new(),
};
write(&mut batch);
if batch.writes.is_empty() {
return;
}
let mut pending = self.shared.pending.lock();
let mut queued = false;
for write in batch.writes {
queued |= match write {
BatchWrite::Op(op) => pending.write(op),
BatchWrite::FinishReload(mut reload, snapshot) => {
reload.finished = true;
pending.finish_reload(reload.id, snapshot)
}
};
}
drop(pending);
if queued {
self.shared.wake();
}
}
pub fn begin_reload(&self) -> Reload<R> {
let mut pending = self.shared.pending.lock();
let id = pending.next_reload;
pending.next_reload += 1;
let live = pending
.reload
.take()
.map(|reload| reload.live)
.unwrap_or_default();
pending.reload = Some(ReloadBuffer { id, live });
Reload {
shared: self.shared.clone(),
id,
finished: false,
}
}
pub fn upsert(&self, row: impl Into<Arc<R>>) {
self.push(Op::Upsert(row.into()));
}
pub fn upsert_silent(&self, row: impl Into<Arc<R>>) {
self.push(Op::UpsertSilent(row.into()));
}
pub fn mark_changed(&self, key: R::Key, columns: ColumnSet) {
self.push(Op::MarkChanged(key, columns));
}
pub fn remove(&self, key: R::Key) {
self.push(Op::Remove(key));
}
pub fn replace_all(&self, rows: impl IntoIterator<Item = Arc<R>>) {
self.push(Op::ReplaceAll(rows.into_iter().collect()));
}
pub fn clear(&self) {
self.push(Op::Clear);
}
pub fn set_pinned_rows(&self, edge: PinnedEdge, rows: impl IntoIterator<Item = Arc<R>>) {
self.push(Op::SetPinnedRows {
edge,
rows: rows.into_iter().collect(),
});
}
pub fn set_progress(&self, progress: Option<GridProgress>) {
self.push(Op::SetProgress(progress));
}
pub fn flush(&self) -> impl Future<Output = Option<u64>> + Send + 'static {
let (done, resolved) = async_channel::bounded(1);
let mut pending = self.shared.pending.lock();
if !pending.closed {
pending.flushes.push(done);
}
drop(pending);
self.shared.wake();
async move { resolved.recv().await.ok() }
}
pub fn is_closed(&self) -> bool {
self.shared.wake.is_closed()
}
pub fn snapshot(&self) -> Arc<StoreSnapshot<R>> {
self.hub.lock().snapshot.clone()
}
}
pub struct Reload<R: GridRow> {
shared: Arc<Shared<R>>,
id: u64,
finished: bool,
}
impl<R: GridRow> Reload<R> {
pub fn finish(mut self, snapshot: impl IntoIterator<Item = Arc<R>>) {
self.finished = true;
let snapshot = snapshot.into_iter().collect();
let queued = self.shared.pending.lock().finish_reload(self.id, snapshot);
if queued {
self.shared.wake();
}
}
}
impl<R: GridRow> Drop for Reload<R> {
fn drop(&mut self) {
if self.finished {
return;
}
let mut pending = self.shared.pending.lock();
if pending
.reload
.as_ref()
.is_some_and(|reload| reload.id == self.id)
{
let live = pending
.reload
.take()
.map(|reload| reload.live)
.unwrap_or_default();
pending.queue.push_cancelled_reload(live);
drop(pending);
self.shared.wake();
}
}
}
pub struct WriteBatch<R: GridRow> {
shared: Arc<Shared<R>>,
writes: Vec<BatchWrite<R>>,
}
enum BatchWrite<R: GridRow> {
Op(Op<R>),
FinishReload(Reload<R>, Vec<Arc<R>>),
}
impl<R: GridRow> WriteBatch<R> {
fn push(&mut self, op: Op<R>) {
self.writes.push(BatchWrite::Op(op));
}
pub fn upsert(&mut self, row: impl Into<Arc<R>>) {
self.push(Op::Upsert(row.into()));
}
pub fn upsert_silent(&mut self, row: impl Into<Arc<R>>) {
self.push(Op::UpsertSilent(row.into()));
}
pub fn mark_changed(&mut self, key: R::Key, columns: ColumnSet) {
self.push(Op::MarkChanged(key, columns));
}
pub fn remove(&mut self, key: R::Key) {
self.push(Op::Remove(key));
}
pub fn replace_all(&mut self, rows: impl IntoIterator<Item = Arc<R>>) {
self.push(Op::ReplaceAll(rows.into_iter().collect()));
}
pub fn clear(&mut self) {
self.push(Op::Clear);
}
pub fn set_pinned_rows(&mut self, edge: PinnedEdge, rows: impl IntoIterator<Item = Arc<R>>) {
self.push(Op::SetPinnedRows {
edge,
rows: rows.into_iter().collect(),
});
}
pub fn set_progress(&mut self, progress: Option<GridProgress>) {
self.push(Op::SetProgress(progress));
}
pub fn finish_reload(&mut self, reload: Reload<R>, snapshot: impl IntoIterator<Item = Arc<R>>) {
if !Arc::ptr_eq(&reload.shared, &self.shared) {
reload.finish(snapshot);
return;
}
let snapshot = snapshot.into_iter().collect();
self.writes.push(BatchWrite::FinishReload(reload, snapshot));
}
}
struct Subscriber {
id: u64,
changes: ChangeSet,
wake: async_channel::Sender<()>,
}
struct Hub<R: GridRow> {
snapshot: Arc<StoreSnapshot<R>>,
subscribers: Vec<Subscriber>,
next_subscriber: u64,
batches: BatchCounters,
}
#[derive(Clone, Copy, Debug, Default)]
struct BatchCounters {
count: u64,
last: Duration,
max: Duration,
}
#[derive(Clone, Copy, Debug, Default)]
pub struct StoreStats {
queue: QueueCounters,
batches: BatchCounters,
}
impl StoreStats {
pub fn writes(&self) -> u64 {
self.queue.writes
}
pub fn coalesced_writes(&self) -> u64 {
self.queue.coalesced
}
pub fn applied_writes(&self) -> u64 {
self.queue.applied
}
pub fn pending(&self) -> usize {
self.queue.pending
}
pub fn peak_pending(&self) -> usize {
self.queue.peak_pending
}
pub fn batches(&self) -> u64 {
self.batches.count
}
pub fn last_batch(&self) -> Duration {
self.batches.last
}
pub fn max_batch(&self) -> Duration {
self.batches.max
}
}
#[derive(Clone, Copy, Debug)]
pub struct StoreOptions {
highlight: HighlightPolicy,
publish_interval: Duration,
write_coalescing: WriteCoalescing,
}
impl Default for StoreOptions {
fn default() -> Self {
Self {
highlight: HighlightPolicy::default(),
publish_interval: SNAPSHOT_INTERVAL,
write_coalescing: WriteCoalescing::default(),
}
}
}
impl StoreOptions {
pub fn with_highlight(mut self, highlight: HighlightPolicy) -> Self {
self.highlight = highlight;
self
}
pub fn with_publish_interval(mut self, interval: Duration) -> Self {
self.publish_interval = interval;
self
}
pub fn with_write_coalescing(mut self, coalescing: WriteCoalescing) -> Self {
self.write_coalescing = coalescing;
self
}
pub fn highlight(&self) -> HighlightPolicy {
self.highlight
}
pub fn write_coalescing(&self) -> WriteCoalescing {
self.write_coalescing
}
pub fn publish_interval(&self) -> Duration {
self.publish_interval
}
}
struct StoreInner<R: GridRow> {
shared: Arc<Shared<R>>,
hub: Arc<Mutex<Hub<R>>>,
options: StoreOptions,
clock: Arc<dyn Clock>,
_ingest: Task<()>,
}
impl<R: GridRow> Drop for StoreInner<R> {
fn drop(&mut self) {
self.hub.lock().subscribers.clear();
}
}
pub struct GridStore<R: GridRow> {
inner: Arc<StoreInner<R>>,
}
impl<R: GridRow> Clone for GridStore<R> {
fn clone(&self) -> Self {
Self {
inner: self.inner.clone(),
}
}
}
impl<R: GridRow> GridStore<R> {
pub fn new(options: StoreOptions, cx: &App) -> Self {
Self::builder(options).build(cx)
}
pub fn builder(options: StoreOptions) -> GridStoreBuilder<R> {
GridStoreBuilder {
options,
clock: None,
reload: Box::new(ReplayLive),
}
}
pub fn now(&self) -> Instant {
self.inner.clock.now()
}
pub fn writer(&self) -> GridWriter<R> {
GridWriter {
shared: self.inner.shared.clone(),
hub: self.inner.hub.clone(),
}
}
pub fn snapshot(&self) -> Arc<StoreSnapshot<R>> {
self.inner.hub.lock().snapshot.clone()
}
pub fn options(&self) -> StoreOptions {
self.inner.options
}
pub fn stats(&self) -> StoreStats {
let queue = self.inner.shared.pending.lock().queue.counters();
let batches = self.inner.hub.lock().batches;
StoreStats { queue, batches }
}
pub fn subscribe(&self) -> StoreSubscription<R> {
let (wake, rx) = async_channel::bounded(1);
let mut hub = self.inner.hub.lock();
let id = hub.next_subscriber;
hub.next_subscriber += 1;
hub.subscribers.push(Subscriber {
id,
changes: ChangeSet::default(),
wake,
});
StoreSubscription {
hub: self.inner.hub.clone(),
id,
rx,
}
}
}
pub struct GridStoreBuilder<R: GridRow> {
options: StoreOptions,
clock: Option<Arc<dyn Clock>>,
reload: Box<dyn ReloadPolicy<R>>,
}
impl<R: GridRow> GridStoreBuilder<R> {
pub fn with_clock(mut self, clock: Arc<dyn Clock>) -> Self {
self.clock = Some(clock);
self
}
pub fn with_reload_policy(mut self, policy: impl ReloadPolicy<R>) -> Self {
self.reload = Box::new(policy);
self
}
pub fn build(self, cx: &App) -> GridStore<R> {
self.build_on(cx.background_executor().clone())
}
pub fn build_on(self, executor: BackgroundExecutor) -> GridStore<R> {
let Self {
options,
clock,
reload,
} = self;
let clock: Arc<dyn Clock> = clock.unwrap_or_else(|| Arc::new(executor.clone()));
let (wake, wake_rx) = async_channel::bounded(1);
let shared = Arc::new(Shared {
pending: Mutex::new(Pending::new(options.write_coalescing)),
wake,
});
let mut ingest = Ingest::<R>::with_reload_policy(options.highlight, clock.now(), reload);
let hub = Arc::new(Mutex::new(Hub {
snapshot: ingest.snapshot(),
subscribers: Vec::new(),
next_subscriber: 0,
batches: BatchCounters::default(),
}));
let task = executor.spawn({
let shared = shared.clone();
let hub = hub.clone();
let clock = clock.clone();
let timer = executor.clone();
let guard = IngestGuard(shared.clone());
async move {
let _guard = guard;
while wake_rx.recv().await.is_ok() {
let (writes, flushes) = {
let mut pending = shared.pending.lock();
let writes = pending.queue.take();
(writes, std::mem::take(&mut pending.flushes))
};
let started = Instant::now();
let now = clock.now();
let changes = ingest.apply_writes(writes, now);
ingest.sweep(now);
let publish = !changes.is_empty();
if publish {
let snapshot = ingest.snapshot();
let elapsed = started.elapsed();
let previous = {
let mut hub = hub.lock();
let batches = &mut hub.batches;
batches.count += 1;
batches.last = elapsed;
batches.max = batches.max.max(elapsed);
let previous = std::mem::replace(&mut hub.snapshot, snapshot);
for subscriber in &mut hub.subscribers {
subscriber.changes.merge(&changes);
let _ = subscriber.wake.try_send(());
}
previous
};
drop(previous);
}
for flush in flushes {
let _ = flush.try_send(ingest.version);
}
if publish {
timer.timer(options.publish_interval).await;
}
}
}
});
GridStore {
inner: Arc::new(StoreInner {
shared,
hub,
options,
clock,
_ingest: task,
}),
}
}
}
pub struct StoreSubscription<R: GridRow> {
hub: Arc<Mutex<Hub<R>>>,
id: u64,
rx: async_channel::Receiver<()>,
}
impl<R: GridRow> StoreSubscription<R> {
pub async fn changed(&self) -> bool {
self.rx.recv().await.is_ok()
}
pub fn take(&self) -> (Arc<StoreSnapshot<R>>, ChangeSet) {
let mut hub = self.hub.lock();
let snapshot = hub.snapshot.clone();
let changes = hub
.subscribers
.iter_mut()
.find(|subscriber| subscriber.id == self.id)
.map(|subscriber| std::mem::take(&mut subscriber.changes))
.unwrap_or_default();
(snapshot, changes)
}
}
impl<R: GridRow> Drop for StoreSubscription<R> {
fn drop(&mut self) {
let id = self.id;
self.hub
.lock()
.subscribers
.retain(|subscriber| subscriber.id != id);
}
}