Skip to content

Commit

Permalink
feat: support per-module configuration
Browse files Browse the repository at this point in the history
Issue: bnjbvr#26
  • Loading branch information
ahal committed Mar 20, 2023
1 parent 069c6d4 commit 14e3e86
Show file tree
Hide file tree
Showing 10 changed files with 41 additions and 14 deletions.
2 changes: 1 addition & 1 deletion modules/horsejs/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ impl Component {
}

impl interface::Interface for Component {
fn init() {
fn init(_config: Option<Vec<(String, String)>>) {
let _ = log::set_boxed_logger(Box::new(crate::log::WitLog::new()));
log::set_max_level(log::LevelFilter::Trace);
log::trace!("Called the init() method \\o/");
Expand Down
2 changes: 1 addition & 1 deletion modules/linkify/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,7 @@ impl Component {
}

impl interface::Interface for Component {
fn init() {
fn init(_config: Option<Vec<(String, String)>>) {
let _ = log::set_boxed_logger(Box::new(log::WitLog::new()));
log::set_max_level(log::LevelFilter::Trace);
log::trace!("Called the init() method \\o/");
Expand Down
2 changes: 1 addition & 1 deletion modules/mastodon/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ impl Component {
}

impl interface::Interface for Component {
fn init() {
fn init(_config: Option<Vec<(String, String)>>) {
let _ = log::set_boxed_logger(Box::new(crate::log::WitLog::new()));
log::set_max_level(log::LevelFilter::Trace);
}
Expand Down
2 changes: 1 addition & 1 deletion modules/openai/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ impl Component {
}

impl interface::Interface for Component {
fn init() {
fn init(_config: Option<Vec<(String, String)>>) {
let _ = log::set_boxed_logger(Box::new(crate::log::WitLog::new()));
log::set_max_level(log::LevelFilter::Trace);
}
Expand Down
2 changes: 1 addition & 1 deletion modules/pun/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ impl Component {
}

impl interface::Interface for Component {
fn init() {
fn init(_config: Option<Vec<(String, String)>>) {
let _ = log::set_boxed_logger(Box::new(log::WitLog::new()));
log::set_max_level(log::LevelFilter::Trace);
log::trace!("Called the init() method \\o/");
Expand Down
2 changes: 1 addition & 1 deletion modules/secret/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use wit_log as log;
struct Component;

impl interface::Interface for Component {
fn init() {
fn init(_config: Option<Vec<(String, String)>>) {
let _ = log::set_boxed_logger(Box::new(log::WitLog::new()));
log::set_max_level(log::LevelFilter::Trace);
log::trace!("Called the init() method \\o/");
Expand Down
2 changes: 1 addition & 1 deletion modules/uuid/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use bindings::interface;
struct Component;

impl interface::Interface for Component {
fn init() {}
fn init(_config: Option<Vec<(String, String)>>){}

fn help(_topic: Option<String>) -> String {
"Simple uuid generator".to_owned()
Expand Down
15 changes: 12 additions & 3 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ use matrix_sdk::{
use notify::{RecursiveMode, Watcher};
use room_resolver::RoomResolver;
use serde::Deserialize;
use std::{env, fs, path::PathBuf, sync::Arc};
use std::{collections::HashMap, env, fs, path::PathBuf, sync::Arc};
use tokio::{
sync::Mutex,
time::{sleep, Duration},
Expand All @@ -43,6 +43,8 @@ pub struct BotConfig {
pub redb_path: String,
/// the admin user id for the bot.
pub admin_user_id: OwnedUserId,
/// module specific configuration to forward to corresponding handler.
pub modules: Option<HashMap<String, HashMap<String, String>>>,
}

impl BotConfig {
Expand Down Expand Up @@ -98,6 +100,7 @@ impl BotConfig {
matrix_store_path,
admin_user_id,
redb_path,
modules: None,
})
}
}
Expand All @@ -108,6 +111,7 @@ pub(crate) type ShareableDatabase = Arc<redb::Database>;
struct AppCtx {
modules: WasmModules,
modules_path: PathBuf,
modules_config: HashMap<String, HashMap<String, String>>,
needs_recompile: bool,
admin_user_id: OwnedUserId,
db: ShareableDatabase,
Expand All @@ -121,13 +125,15 @@ impl AppCtx {
pub fn new(
client: Client,
modules_path: PathBuf,
modules_config: HashMap<String, HashMap<String, String>>,
db: ShareableDatabase,
admin_user_id: OwnedUserId,
) -> anyhow::Result<Self> {
let room_resolver = RoomResolver::new(client);
Ok(Self {
modules: WasmModules::new(db.clone(), &modules_path)?,
modules: WasmModules::new(db.clone(), &modules_path, &modules_config)?,
modules_path,
modules_config,
needs_recompile: false,
admin_user_id,
db,
Expand All @@ -150,7 +156,7 @@ impl AppCtx {
ptr.lock().await
});

match WasmModules::new(ptr.db.clone(), &ptr.modules_path) {
match WasmModules::new(ptr.db.clone(), &ptr.modules_path, &ptr.modules_config) {
Ok(modules) => {
ptr.modules = modules;
tracing::info!("successful hot reload!");
Expand Down Expand Up @@ -468,6 +474,8 @@ pub async fn run(config: BotConfig) -> anyhow::Result<()> {
.context("writing new device_id into the database")?;
}

let modules_config = config.modules.unwrap_or(HashMap::new());

client
.user_id()
.context("impossible state: missing user id for the logged in bot?")?;
Expand All @@ -484,6 +492,7 @@ pub async fn run(config: BotConfig) -> anyhow::Result<()> {
AppCtx::new(
client_copy,
"./modules/target/wasm32-unknown-unknown/release/".into(),
modules_config,
db,
config.admin_user_id,
)
Expand Down
24 changes: 21 additions & 3 deletions src/wasm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ mod module {

mod apis;

use std::path::Path;
use std::{collections::HashMap, path::Path};

use matrix_sdk::ruma::{RoomId, UserId};
use wasmtime::AsContextMut;
Expand Down Expand Up @@ -81,7 +81,11 @@ impl WasmModules {
/// Create a new collection of wasm modules.
///
/// Must be called from a blocking context.
pub fn new(db: ShareableDatabase, modules_path: &Path) -> anyhow::Result<Self> {
pub fn new(
db: ShareableDatabase,
modules_path: &Path,
modules_config: &HashMap<String, HashMap<String, String>>,
) -> anyhow::Result<Self> {
tracing::debug!("setting up wasm context...");

let mut config = wasmtime::Config::new();
Expand Down Expand Up @@ -133,8 +137,22 @@ impl WasmModules {
let (exports, instance) =
module::Interface::instantiate(&mut store, &component, &mut linker)?;

// Convert the module config to Vec of tuples to satisfy wasm interface types.
let mc = modules_config.get(&name);
let mut module_config_list = Vec::new();
if mc.is_some() {
for (key, value) in mc.unwrap().iter() {
module_config_list.push((key.as_ref(), value.as_ref()))
}
};

let mut init_config = None;
if module_config_list.len() > 0 {
init_config = Some(module_config_list.as_slice());
}

tracing::debug!("calling module's init function...");
exports.init(&mut store)?;
exports.init(&mut store, init_config)?;

tracing::debug!("great success!");
compiled_modules.push(Module {
Expand Down
2 changes: 1 addition & 1 deletion wit/trinity-module.wit
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ record message {
to: string
}

init: func()
init: func(config: option<list<tuple<string, string>>>)
help: func(topic: option<string>) -> string
admin: func(cmd: string, author-id: string, room: string) -> list<message>
on-msg: func(content: string, author-id: string, author-name: string, room: string) -> list<message>

0 comments on commit 14e3e86

Please sign in to comment.