Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions .github/workflows/fh.yml
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
name: Build 🏗️ and Cache ❄️
on:
workflow_dispatch:
pull_request:
push:
branches:
- main
Expand All @@ -12,7 +11,7 @@ on:
- "LICENSE"

concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true

env:
Expand Down
220 changes: 191 additions & 29 deletions src/cache.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,22 @@
use std::collections::HashMap;
use std::sync::{Mutex, MutexGuard};
use std::time::SystemTime;

use datafusion::prelude::DataFrame;
use nu_protocol::{LabeledError, ShellError, Span, shell_error::generic::GenericError};
use chrono::{DateTime, Utc};
use log::trace;
use nu_plugin::EngineInterface;
use nu_protocol::{LabeledError, Span};
use uuid::Uuid;

use crate::plugin::EngineWrapper;
use crate::plugin::{DfPlugin, EngineWrapper};
use crate::values::NuDataFusionObject;

#[derive(Debug, Clone)]
pub struct CacheEntry {
pub df: DataFrame,
pub id: Uuid,
pub value: NuDataFusionObject,
pub created: DateTime<Utc>,
pub span: Span,
pub reference_count: i16,
}

Expand All @@ -18,56 +26,210 @@ pub struct Cache {
}

impl Cache {
fn lock(&self) -> Result<MutexGuard<'_, HashMap<Uuid, CacheEntry>>, ShellError> {
self.inner.lock().map_err(|e| {
ShellError::Generic(GenericError::new_internal(
format!("error acquiring cache lock: {e}"),
"",
))
})
fn lock(&self) -> Result<MutexGuard<'_, HashMap<Uuid, CacheEntry>>, LabeledError> {
self.inner
.lock()
.map_err(|e| LabeledError::new(format!("error acquiring cache lock: {e}")))
}

/// Inserts an item into the plugin cache, disabling plugin GC while
/// any live values exist.
pub fn insert(
&self,
engine: impl EngineWrapper,
id: Uuid,
df: DataFrame,
_span: Span,
) -> Result<(), ShellError> {
value: NuDataFusionObject,
span: Span,
) -> Result<Option<CacheEntry>, LabeledError> {
let mut lock = self.lock()?;
trace!("DataFusion plugin: inserting {id} into cache: {value:?}");
engine.set_gc_disabled(true).map_err(LabeledError::from)?;
lock.insert(
let entry = CacheEntry {
id,
CacheEntry {
df,
reference_count: 1,
},
);
Ok(())
value,
created: SystemTime::now().into(),
span,
reference_count: 1,
};
Ok(lock.insert(id, entry))
}

pub fn get(&self, id: &Uuid) -> Result<Option<DataFrame>, ShellError> {
let lock = self.lock()?;
Ok(lock.get(id).map(|entry| entry.df.clone()))
/// Looks up a cache entry.
///
/// * `increment` - Only pass `true` when handing an existing value back to
/// Nushell without minting a new id. Nushell will send a drop
/// notification for that copy too, so it needs its own reference.
pub fn get(&self, id: &Uuid, increment: bool) -> Result<Option<CacheEntry>, LabeledError> {
let mut lock = self.lock()?;
Ok(lock.get_mut(id).map(|entry| {
if increment {
entry.reference_count += 1;
trace!(
"DataFusion plugin: incremented reference count for {id} to {}",
entry.reference_count
);
}
entry.clone()
}))
}

/// Removes an item from the plugin cache, re-enabling plugin GC once the
/// cache is empty.
///
/// * `force` - Delete even if there are outstanding references
pub fn remove(
&self,
engine: impl EngineWrapper,
id: &Uuid,
force: bool,
) -> Result<(), ShellError> {
) -> Result<Option<CacheEntry>, LabeledError> {
let mut lock = self.lock()?;
let remaining = lock.get_mut(id).map(|entry| {
entry.reference_count -= 1;
entry.reference_count
});
if force || remaining.unwrap_or_default() < 1 {
lock.remove(id);
}

let removed = if force || remaining.unwrap_or_default() < 1 {
let removed = lock.remove(id);
trace!("DataFusion plugin: removed {id} from cache: {removed:?}");
removed
} else {
trace!("DataFusion plugin: decremented reference count for {id}");
None
};

if lock.is_empty() {
trace!("DataFusion plugin: cache is empty, enabling GC");
engine.set_gc_disabled(false).map_err(LabeledError::from)?;
}
Ok(())
Ok(removed)
}
}

/// A value that can be stored in the plugin cache.
pub trait Cacheable: Sized + Clone {
fn cache_id(&self) -> &Uuid;

fn to_cache_value(&self) -> NuDataFusionObject;

fn from_cache_value(value: NuDataFusionObject) -> Result<Self, LabeledError>;

fn cache(
self,
plugin: &DfPlugin,
engine: &EngineInterface,
span: Span,
) -> Result<Self, LabeledError> {
plugin
.cache
.insert(engine, *self.cache_id(), self.to_cache_value(), span)?;
Ok(self)
}

fn get_cached(plugin: &DfPlugin, id: &Uuid) -> Result<Option<Self>, LabeledError> {
plugin
.cache
.get(id, false)?
.map(|entry| Self::from_cache_value(entry.value))
.transpose()
}
}

#[cfg(test)]
mod tests {
use std::cell::Cell;

use datafusion::prelude::SessionContext;
use nu_protocol::ShellError;

use super::*;
use crate::values::NuDataFrame;

struct MockEngine {
gc_enabled: Cell<bool>,
}

impl MockEngine {
fn new() -> Self {
Self {
gc_enabled: Cell::new(true),
}
}
}

impl EngineWrapper for &MockEngine {
fn set_gc_disabled(&self, disabled: bool) -> Result<(), ShellError> {
self.gc_enabled.set(!disabled);
Ok(())
}
}

fn test_object() -> NuDataFusionObject {
let df = SessionContext::new()
.read_empty()
.expect("should create empty dataframe");
NuDataFusionObject::DataFrame(NuDataFrame::new(df))
}

fn insert(cache: &Cache, engine: &MockEngine) -> Uuid {
let id = Uuid::new_v4();
cache
.insert(engine, id, test_object(), Span::test_data())
.expect("should insert");
id
}

#[test]
fn gc_disabled_until_cache_empty() {
let engine = MockEngine::new();
let cache = Cache::default();
let a = insert(&cache, &engine);
let b = insert(&cache, &engine);
assert!(!engine.gc_enabled.get());

cache.remove(&engine, &a, false).expect("should remove a");
assert!(!engine.gc_enabled.get());

cache.remove(&engine, &b, false).expect("should remove b");
assert!(engine.gc_enabled.get());
}

#[test]
fn get_without_increment_does_not_leak() {
let engine = MockEngine::new();
let cache = Cache::default();
let id = insert(&cache, &engine);

for _ in 0..3 {
cache.get(&id, false).expect("should get");
}

let removed = cache.remove(&engine, &id, false).expect("should remove");
assert!(removed.is_some());
assert!(cache.get(&id, false).expect("should get").is_none());
}

#[test]
fn get_with_increment_needs_extra_remove() {
let engine = MockEngine::new();
let cache = Cache::default();
let id = insert(&cache, &engine);

let entry = cache.get(&id, true).expect("should get").expect("exists");
assert_eq!(entry.reference_count, 2);

assert!(cache.remove(&engine, &id, false).expect("ok").is_none());
assert!(cache.remove(&engine, &id, false).expect("ok").is_some());
}

#[test]
fn force_remove_ignores_references() {
let engine = MockEngine::new();
let cache = Cache::default();
let id = insert(&cache, &engine);
cache.get(&id, true).expect("should get");

assert!(cache.remove(&engine, &id, true).expect("ok").is_some());
assert!(engine.gc_enabled.get());
}
}
11 changes: 7 additions & 4 deletions src/commands/aggregate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use crate::error::from_datafusion;
use crate::expr::parse_sql_expr;
use crate::input::resolve_df;
use crate::plugin::DfPlugin;
use crate::values::{cache_and_value, dataframe_type};
use crate::values::{CustomValueSupport, NuDataFrame, NuDataFusionType};

pub struct Aggregate;

Expand Down Expand Up @@ -36,8 +36,11 @@ impl PluginCommand for Aggregate {
"SQL aggregates, e.g. [\"sum(amount) as total\" \"count(*) as n\"]",
Some('a'),
)
.input_output_type(dataframe_type(), dataframe_type())
.input_output_type(Type::table(), dataframe_type())
.input_output_type(
NuDataFusionType::DataFrame.nu_type(),
NuDataFusionType::DataFrame.nu_type(),
)
.input_output_type(Type::table(), NuDataFusionType::DataFrame.nu_type())
.category(category())
}

Expand Down Expand Up @@ -69,7 +72,7 @@ impl PluginCommand for Aggregate {
.aggregate(group_expr, agg_expr)
.map_err(|e| from_datafusion(e, span))?;
Ok(PipelineData::value(
cache_and_value(plugin, engine, out, span)?,
NuDataFrame::new(out).cache_and_to_value(plugin, engine, span)?,
None,
))
}
Expand Down
11 changes: 7 additions & 4 deletions src/commands/cast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use crate::convert::parse_arrow_type;
use crate::error::{from_datafusion, shell};
use crate::input::resolve_df;
use crate::plugin::DfPlugin;
use crate::values::{cache_and_value, dataframe_type};
use crate::values::{CustomValueSupport, NuDataFrame, NuDataFusionType};

pub struct Cast;

Expand All @@ -26,8 +26,11 @@ impl PluginCommand for Cast {
Signature::build(self.name())
.required("column", SyntaxShape::String, "Column to cast")
.required("type", SyntaxShape::String, "Arrow type name")
.input_output_type(dataframe_type(), dataframe_type())
.input_output_type(Type::table(), dataframe_type())
.input_output_type(
NuDataFusionType::DataFrame.nu_type(),
NuDataFusionType::DataFrame.nu_type(),
)
.input_output_type(Type::table(), NuDataFusionType::DataFrame.nu_type())
.category(category())
}

Expand Down Expand Up @@ -62,7 +65,7 @@ impl PluginCommand for Cast {
.with_column(&column, expr)
.map_err(|e| from_datafusion(e, span))?;
Ok(PipelineData::value(
cache_and_value(plugin, engine, out, span)?,
NuDataFrame::new(out).cache_and_to_value(plugin, engine, span)?,
None,
))
}
Expand Down
4 changes: 2 additions & 2 deletions src/commands/collect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use crate::commands::category;
use crate::convert::collect_to_nu;
use crate::input::resolve_df;
use crate::plugin::DfPlugin;
use crate::values::{COLLECT_DEFAULT, dataframe_type};
use crate::values::{COLLECT_DEFAULT, NuDataFusionType};

pub struct Collect;

Expand Down Expand Up @@ -40,7 +40,7 @@ impl PluginCommand for Collect {
"Collect every row (can lock up the shell)",
Some('a'),
)
.input_output_type(dataframe_type(), Type::table())
.input_output_type(NuDataFusionType::DataFrame.nu_type(), Type::table())
.input_output_type(Type::table(), Type::table())
.category(category())
}
Expand Down
4 changes: 2 additions & 2 deletions src/commands/count.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use nu_protocol::{Example, LabeledError, PipelineData, Signature, Type, Value};
use crate::commands::category;
use crate::input::resolve_df;
use crate::plugin::DfPlugin;
use crate::values::dataframe_type;
use crate::values::NuDataFusionType;

pub struct Count;

Expand All @@ -21,7 +21,7 @@ impl PluginCommand for Count {

fn signature(&self) -> Signature {
Signature::build(self.name())
.input_output_type(dataframe_type(), Type::Int)
.input_output_type(NuDataFusionType::DataFrame.nu_type(), Type::Int)
.input_output_type(Type::table(), Type::Int)
.category(category())
}
Expand Down
4 changes: 2 additions & 2 deletions src/commands/describe.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use crate::commands::category;
use crate::convert::collect_to_nu;
use crate::input::resolve_df;
use crate::plugin::DfPlugin;
use crate::values::dataframe_type;
use crate::values::NuDataFusionType;

pub struct Describe;

Expand All @@ -22,7 +22,7 @@ impl PluginCommand for Describe {

fn signature(&self) -> Signature {
Signature::build(self.name())
.input_output_type(dataframe_type(), Type::table())
.input_output_type(NuDataFusionType::DataFrame.nu_type(), Type::table())
.input_output_type(Type::table(), Type::table())
.category(category())
}
Expand Down
Loading