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 May 30, 2023
1 parent bbaed0b commit 101e597
Show file tree
Hide file tree
Showing 9 changed files with 46 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 TrinityCommand 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 TrinityCommand 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 @@ -18,7 +18,7 @@ impl RoomConfig {
struct Component;

impl TrinityCommand 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 TrinityCommand 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 @@ -33,7 +33,7 @@ impl Component {
}

impl TrinityCommand 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 TrinityCommand 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
23 changes: 18 additions & 5 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,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 @@ -49,6 +49,8 @@ pub struct BotConfig {
pub admin_user_id: OwnedUserId,
/// paths where modules can be loaded.
pub modules_paths: Vec<PathBuf>,
/// module specific configuration to forward to corresponding handler.
pub modules_config: Option<HashMap<String, HashMap<String, String>>>,
}

impl BotConfig {
Expand Down Expand Up @@ -123,16 +125,17 @@ impl BotConfig {
admin_user_id,
redb_path,
modules_paths,
modules_config: None,
})
}
}


pub(crate) type ShareableDatabase = Arc<redb::Database>;

struct AppCtx {
modules: WasmModules,
modules_paths: Vec<PathBuf>,
modules_config: HashMap<String, HashMap<String, String>>,
needs_recompile: bool,
admin_user_id: OwnedUserId,
db: ShareableDatabase,
Expand All @@ -146,13 +149,15 @@ impl AppCtx {
pub fn new(
client: Client,
modules_paths: Vec<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_paths)?,
modules: WasmModules::new(db.clone(), &modules_paths, &modules_config)?,
modules_paths,
modules_config,
needs_recompile: false,
admin_user_id,
db,
Expand All @@ -175,7 +180,7 @@ impl AppCtx {
ptr.lock().await
});

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

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

client
.user_id()
.context("impossible state: missing user id for the logged in bot?")?;
Expand All @@ -546,7 +553,13 @@ pub async fn run(config: BotConfig) -> anyhow::Result<()> {
tracing::debug!("setting up app...");
let client_copy = client.clone();
let app_ctx = tokio::task::spawn_blocking(|| {
AppCtx::new(client_copy, config.modules_paths, db, config.admin_user_id)
AppCtx::new(
client_copy,
config.modules_paths,
modules_config,
db,
config.admin_user_id,
)
})
.await??;
let app = App::new(app_ctx);
Expand Down
23 changes: 21 additions & 2 deletions src/wasm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ pub(crate) use module::messaging::Message;
mod apis;

use std::path::PathBuf;
use std::collections::HashMap;

use matrix_sdk::ruma::{RoomId, UserId};
use wasmtime::AsContextMut;
Expand Down Expand Up @@ -85,7 +86,11 @@ impl WasmModules {
/// Create a new collection of wasm modules.
///
/// Must be called from a blocking context.
pub fn new(db: ShareableDatabase, modules_paths: &[PathBuf]) -> anyhow::Result<Self> {
pub fn new(
db: ShareableDatabase,
modules_paths: &[PathBuf],
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 @@ -142,8 +147,22 @@ impl WasmModules {
let (exports, instance) =
module::TrinityModule::instantiate(&mut store, &component, &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.messaging().call_init(&mut store)?;
exports.messaging().call_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 @@ -12,7 +12,7 @@ interface messaging {
react(reaction)
}

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<action>
on-msg: func(content: string, author-id: string, author-name: string, room: string) -> list<action>
Expand Down

0 comments on commit 101e597

Please sign in to comment.