Skip to content

Commit

Permalink
change to use function pointer and remove trait
Browse files Browse the repository at this point in the history
  • Loading branch information
darwin67 committed Jul 21, 2024
1 parent b6cda52 commit 15fe7fe
Show file tree
Hide file tree
Showing 4 changed files with 58 additions and 75 deletions.
18 changes: 9 additions & 9 deletions inngest/examples/axum/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use axum::{
Router,
};
use inngest::{
function::{create_function, FunctionOps, Input, ServableFunction, Trigger},
function::{create_function, FunctionOps, Input, ServableFn, Trigger},
router::{axum as inngest_axum, Handler},
};
use serde::{Deserialize, Serialize};
Expand Down Expand Up @@ -38,46 +38,46 @@ struct TestData {
data: u8,
}

fn dummy_fn() -> Box<dyn ServableFunction + Sync + Send> {
fn dummy_fn() -> ServableFn<TestData> {
create_function(
FunctionOps {
name: "Dummy func".to_string(),
id: "Dummy func".to_string(),
..Default::default()
},
Trigger::EventTrigger {
event: "test/event".to_string(),
expression: None,
},
Box::new(|input: Input<TestData>| {
|input: Input<TestData>| {
println!("In dummy function");

let evt = input.event;
println!("Event: {}", evt.name);
// println!("Data: {:?}", evt.data);

Ok(Box::new("test result".to_string()))
}),
},
)
}

fn hello_fn() -> Box<dyn ServableFunction + Sync + Send> {
fn hello_fn() -> ServableFn<TestData> {
create_function(
FunctionOps {
name: "Hello func".to_string(),
id: "Hello func".to_string(),
..Default::default()
},
Trigger::EventTrigger {
event: "test/hello".to_string(),
expression: None,
},
Box::new(|input: Input<TestData>| {
|input: Input<TestData>| {
println!("In hello function");

let evt = input.event;
println!("Event: {}", evt.name);
// println!("Data: {:?}", evt.data());

Ok(Box::new("test hello".to_string()))
}),
},
)
}
52 changes: 14 additions & 38 deletions inngest/src/function.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,22 +3,6 @@ use serde::{Deserialize, Serialize};
use slug::slugify;
use std::{any::Any, collections::HashMap, fmt::Debug};

pub trait ServableFunction {
fn slug(&self) -> String;
fn name(&self) -> String;
fn trigger(&self) -> Trigger;
}

impl Debug for dyn ServableFunction + Send + Sync {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ServableFn")
.field("name", &self.name())
.field("slug", &self.slug())
.field("trigger", &self.trigger())
.finish()
}
}

#[derive(Deserialize)]
pub struct Input<T>
where
Expand All @@ -38,16 +22,16 @@ pub struct InputCtx {

#[derive(Debug, Clone)]
pub struct FunctionOps {
pub id: Option<String>,
pub name: String,
pub id: String,
pub name: Option<String>,
pub retries: u8,
}

impl Default for FunctionOps {
fn default() -> Self {
FunctionOps {
id: None,
name: String::new(),
id: String::new(),
name: None,
retries: 3,
}
}
Expand All @@ -59,25 +43,19 @@ where
{
pub opts: FunctionOps,
pub trigger: Trigger,
pub func: Box<dyn Fn(Input<T>) -> Result<Box<dyn Any>, String> + Send + Sync>,
pub func: fn(Input<T>) -> Result<Box<dyn Any>, String>,
}

impl<T> ServableFunction for ServableFn<T>
impl<T> ServableFn<T>
where
T: Serialize + for<'a> Deserialize<'a> + 'static,
{
fn slug(&self) -> String {
match &self.opts.id {
Some(id) => id.clone(),
None => slugify(self.name()),
}
}

fn name(&self) -> String {
self.opts.name.clone()
// TODO: prepend app_id
pub fn slug(&self) -> String {
slugify(self.opts.id.clone())
}

fn trigger(&self) -> Trigger {
pub fn trigger(&self) -> Trigger {
self.trigger.clone()
}
}
Expand Down Expand Up @@ -125,13 +103,11 @@ pub enum Trigger {
pub fn create_function<T: Serialize + for<'a> Deserialize<'a> + 'static>(
opts: FunctionOps,
trigger: Trigger,
func: Box<dyn Fn(Input<T>) -> Result<Box<dyn Any>, String> + Send + Sync>,
) -> Box<dyn ServableFunction + Sync + Send> {
let servable = ServableFn {
func: fn(Input<T>) -> Result<Box<dyn Any>, String>,
) -> ServableFn<T> {
ServableFn {
opts,
trigger,
func,
};

Box::new(servable)
}
}
29 changes: 19 additions & 10 deletions inngest/src/router/axum.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use axum::{
extract::{Query, State},
Json,
};
use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::{
Expand All @@ -14,7 +15,9 @@ use std::{collections::HashMap, default::Default, sync::Arc};

use super::InvokeQuery;

pub async fn register(State(handler): State<Arc<Handler>>) -> Result<(), String> {
pub async fn register<T: Serialize + for<'a> Deserialize<'a> + 'static>(
State(handler): State<Arc<Handler<T>>>
) -> Result<(), String> {
let funcs: Vec<Function> = handler
.funcs
.iter()
Expand All @@ -36,7 +39,7 @@ pub async fn register(State(handler): State<Arc<Handler>>) -> Result<(), String>

Function {
id: f.slug(),
name: f.name(),
name: f.slug(), // TODO: use the proper name
triggers: vec![f.trigger()],
steps,
}
Expand All @@ -52,32 +55,38 @@ pub async fn register(State(handler): State<Arc<Handler>>) -> Result<(), String>

let client = reqwest::Client::new();

match client
client
.post("http://127.0.0.1:8288/fn/register")
.json(&req)
.send()
.await
{
Ok(_) => Ok(()),
Err(_) => Err("error".to_string()),
}
.map(|_| ())
.map_err(|_| "error".to_string())
}

pub async fn invoke(
pub async fn invoke<T: Serialize + for<'a> Deserialize<'a> + 'static>(
Query(query): Query<InvokeQuery>,
State(handler): State<Arc<Handler>>,
State(handler): State<Arc<Handler<T>>>,
Json(body): Json<Value>,
) -> Result<(), String> {
println!("Body: {:#?}", body);

match handler.funcs.iter().find(|f| f.slug() == query.fn_id) {
None => Err(format!("no function registered as ID: {}", query.fn_id)),
Some(func) => {
println!("Name: {}", func.name());
println!("Slug: {}", func.slug());
println!("Trigger: {:?}", func.trigger());
// println!("Event: {:?}", func.event());

// match (func.func)() {
// Ok(_) => {
// println!("OK!!");
// }
// Err(err) => {
// println!("{:?}", err)
// }
// }

Ok(())
// match serde_json::from_value::<InvokeBody<F::T>>(body) {
// Ok(body) => {
Expand Down
34 changes: 16 additions & 18 deletions inngest/src/router/mod.rs
Original file line number Diff line number Diff line change
@@ -1,25 +1,32 @@
pub mod axum;

use crate::function::ServableFunction;
use serde::Deserialize;
use std::default::Default;
use crate::function::ServableFn;
use serde::{Deserialize, Serialize};

#[derive(Debug)]
pub struct Handler {
pub struct Handler<T>
where
T: Serialize + for<'a> Deserialize<'a> + 'static,
{
app_name: String,
funcs: Vec<Box<dyn ServableFunction + Sync + Send>>,
funcs: Vec<ServableFn<T>>,
}

impl Handler {
impl<T> Handler<T>
where
T: Serialize + for<'a> Deserialize<'a> + 'static,
{
pub fn new() -> Self {
Self::default()
Handler {
app_name: "RustDev".to_string(),
funcs: vec![],
}
}

pub fn set_name(&mut self, name: &str) {
self.app_name = name.to_string()
}

pub fn register_fn(&mut self, func: Box<dyn ServableFunction + Sync + Send>) {
pub fn register_fn(&mut self, func: ServableFn<T>) {
self.funcs.push(func);
}

Expand All @@ -28,15 +35,6 @@ impl Handler {
// }
}

impl Default for Handler {
fn default() -> Self {
Handler {
app_name: "InngestApp".to_string(),
funcs: vec![],
}
}
}

#[derive(Deserialize)]
pub struct InvokeQuery {
#[serde(rename = "fnId")]
Expand Down

0 comments on commit 15fe7fe

Please sign in to comment.