Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: AsyncHelperDef WIP #513

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 2 additions & 0 deletions Cargo.toml
Expand Up @@ -31,6 +31,7 @@ serde_json = "1.0.39"
walkdir = { version = "2.2.3", optional = true }
rhai = { version = "1.6", optional = true, features = ["sync", "serde"] }
rust-embed = { version = "6.3.0", optional = true }
async-trait = { version = "0.1", optional = true }

[dev-dependencies]
env_logger = "0.9"
Expand All @@ -48,6 +49,7 @@ dir_source = ["walkdir"]
script_helper = ["rhai"]
no_logging = []
default = []
async_helper = ["async-trait"]

[badges]
maintenance = { status = "actively-developed" }
Expand Down
68 changes: 68 additions & 0 deletions src/async_render.rs
@@ -0,0 +1,68 @@
use async_trait::async_trait;

use crate::context::Context;
use crate::error::RenderError;
use crate::output::Output;
use crate::registry::Registry;
use crate::render::{Helper, RenderContext};
use crate::template::HelperTemplate;

async fn async_render_helper<'reg: 'rc, 'rc>(
ht: &'reg HelperTemplate,
registry: &'reg Registry<'reg>,
ctx: &'rc Context,
rc: &mut RenderContext<'reg, 'rc>,
out: &mut (dyn Output + Send + Sync),
) -> Result<(), RenderError> {
let h = Helper::try_from_template(ht, registry, ctx, rc)?;
debug!(
"Rendering helper: {:?}, params: {:?}, hash: {:?}",
h.name(),
h.params(),
h.hash()
);
if let Some(ref d) = rc.get_local_helper(h.name()) {
d.call(&h, registry, ctx, rc, out)
} else {
if let Some(ah) = registry.async_helpers.get(h.name()) {
ah.call(&h, registry, ctx, out).await
} else {
let mut helper = registry.get_or_load_helper(h.name())?;

if helper.is_none() {
helper = registry.get_or_load_helper(if ht.block {
BLOCK_HELPER_MISSING
} else {
HELPER_MISSING
})?;
}

helper
.ok_or_else(|| RenderError::new(format!("Helper not defined: {:?}", h.name())))
.and_then(|d| d.call(&h, registry, ctx, rc, out))
}
}
}

#[async_trait]
pub trait AsyncRenderable {
async fn async_render<'reg: 'rc, 'rc>(
&'reg self,
registry: &'reg Registry<'reg>,
ctx: &'rc Context,
rc: Arc<Mutex<RenderContext<'reg, 'rc>>>,
out: &mut dyn Output,
) -> Result<(), RenderError>;
}

#[async_trait]
pub trait AsyncHelperDef {
async fn call<'reg: 'rc, 'rc>(
&self,
h: &Helper<'reg, 'rc>,
r: &'reg Registry<'reg>,
ctx: &'rc Context,
// rc: &mut RenderContext<'reg, 'rc>,
out: &mut (dyn Output + Send + Sync),
) -> HelperResult;
}
3 changes: 3 additions & 0 deletions src/helpers/mod.rs
@@ -1,3 +1,6 @@
#[cfg(feature = "async_helper")]
use async_trait::async_trait;

use crate::context::Context;
use crate::error::RenderError;
use crate::json::value::ScopedJson;
Expand Down
2 changes: 2 additions & 0 deletions src/lib.rs
Expand Up @@ -402,6 +402,8 @@ pub use self::serde_json::Value as JsonValue;

#[macro_use]
mod macros;
#[cfg(feature = "async_helper")]
mod async_render;
mod block;
mod context;
mod decorators;
Expand Down
26 changes: 19 additions & 7 deletions src/registry.rs
Expand Up @@ -12,6 +12,8 @@ use crate::decorators::{self, DecoratorDef};
#[cfg(feature = "script_helper")]
use crate::error::ScriptError;
use crate::error::{RenderError, TemplateError};
#[cfg(feature = "async_helper")]
use crate::helpers::AsyncHelperDef;
use crate::helpers::{self, HelperDef};
use crate::output::{Output, StringOutput, WriteOutput};
use crate::render::{RenderContext, Renderable};
Expand Down Expand Up @@ -59,6 +61,8 @@ pub struct Registry<'reg> {

helpers: HashMap<String, Arc<dyn HelperDef + Send + Sync + 'reg>>,
decorators: HashMap<String, Arc<dyn DecoratorDef + Send + Sync + 'reg>>,
#[cfg(feature = "async_helper")]
pub async_helpers: HashMap<String, Arc<dyn AsyncHelperDef + Send + Sync + 'reg>>,

escape_fn: EscapeFn,
strict_mode: bool,
Expand Down Expand Up @@ -100,18 +104,12 @@ fn rhai_engine() -> Engine {
impl<'reg> Registry<'reg> {
pub fn new() -> Registry<'reg> {
let r = Registry {
templates: HashMap::new(),
template_sources: HashMap::new(),
helpers: HashMap::new(),
decorators: HashMap::new(),
escape_fn: Arc::new(html_escape),
strict_mode: false,
dev_mode: false,
prevent_indent: false,
#[cfg(feature = "script_helper")]
engine: Arc::new(rhai_engine()),
#[cfg(feature = "script_helper")]
script_sources: HashMap::new(),
..Default::default()
};

r.setup_builtins()
Expand Down Expand Up @@ -614,6 +612,20 @@ impl<'reg> Registry<'reg> {
output.into_string().map_err(RenderError::from)
}

#[cfg(feature = "async_helper")]
pub async fn render_async<T>(&self, name: &str, data: &T) -> Result<String, RenderError>
where
T: Serialize,
{
let mut output = StringOutput::new();
let ctx = Context::wraps(&data)?;
self.get_or_load_template(name).and_then(|t| {
let mut render_context = RenderContext::new(t.name.as_ref());
t.render(self, &ctx, &mut render_context, &mut output)
})?;
output.into_string().map_err(RenderError::from)
}

/// Render a registered template with reused context
pub fn render_with_context(&self, name: &str, ctx: &Context) -> Result<String, RenderError> {
let mut output = StringOutput::new();
Expand Down