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 Jun 6, 2023
1 parent 3edc4a6 commit cbd12e8
Show file tree
Hide file tree
Showing 10 changed files with 74 additions and 17 deletions.
4 changes: 3 additions & 1 deletion modules/horsejs/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::collections::HashMap;

use libcommand::{impl_command, CommandClient, TrinityCommand};
use wit_log as log;
use wit_sync_request;
Expand Down Expand Up @@ -33,7 +35,7 @@ impl Component {
}

impl TrinityCommand for Component {
fn init() {
fn init(_config: HashMap<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
19 changes: 16 additions & 3 deletions modules/libcommand/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,15 @@
//! - Because of that, I've had to put most of the code, including the whole `impl Interface for X`
//! block, in the macro body. It's ugly and not practical for maintainability purposes.

use std::collections::HashMap;

/// Implements a command for a given type, assuming the type implements the `TrinityCommand` trait.
#[macro_export]
macro_rules! impl_command {
($ident:ident) => {
const _: () = {
use std::collections::HashMap;

fn consume_client(client: $crate::CommandClient) -> Vec<bindings::messaging::Action> {
let mut actions = Vec::new();

Expand All @@ -37,8 +41,17 @@ macro_rules! impl_command {
}

impl bindings::messaging::Messaging for $ident {
fn init() {
<Self as $crate::TrinityCommand>::init();
fn init(config: Option<Vec<(String, String)>>) {
// Convert the Vec of tuples to a HashMap for convenience.
let config = match config {
Some(cfg) => cfg
.iter()
.map(|(k, v)| (k.to_string(), v.to_string()))
.collect(),
None => HashMap::new(),
};

<Self as $crate::TrinityCommand>::init(config);
}

fn help(topic: Option<String>) -> String {
Expand Down Expand Up @@ -124,7 +137,7 @@ pub trait TrinityCommand {
/// Code that will be called once during initialization of the command. This is a good time to
/// retrieve settings from the database and cache them locally, if needs be, or run any
/// initialization code that shouldn't run on every message later.
fn init() {}
fn init(_client: HashMap<String, String>) {}

/// Handle a message received in a room where the bot is present.
///
Expand Down
5 changes: 3 additions & 2 deletions modules/linkify/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
use std::collections::{HashMap, HashSet};

use anyhow::Context as _;
use libcommand::{impl_command, CommandClient, TrinityCommand};
use regex::Regex;
use serde::{Deserialize, Serialize};
use shlex;
use std::collections::HashSet;
use textwrap_macros::dedent;

use wit_log as log;
Expand Down Expand Up @@ -165,7 +166,7 @@ impl Component {
}

impl TrinityCommand for Component {
fn init() {
fn init(_config: HashMap<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
4 changes: 3 additions & 1 deletion modules/mastodon/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::collections::HashMap;

use libcommand::{impl_command, CommandClient, TrinityCommand};
use wit_log as log;
use wit_sync_request;
Expand All @@ -18,7 +20,7 @@ impl RoomConfig {
struct Component;

impl TrinityCommand for Component {
fn init() {
fn init(_config: HashMap<String, String>) {
let _ = log::set_boxed_logger(Box::new(crate::log::WitLog::new()));
log::set_max_level(log::LevelFilter::Trace);
}
Expand Down
4 changes: 3 additions & 1 deletion modules/openai/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::collections::HashMap;

use anyhow::Context as _;
use libcommand::{impl_command, CommandClient, TrinityCommand};
use wit_log as log;
Expand Down Expand Up @@ -115,7 +117,7 @@ impl Component {
}

impl TrinityCommand for Component {
fn init() {
fn init(_config: HashMap<String, String>) {
let _ = log::set_boxed_logger(Box::new(crate::log::WitLog::new()));
log::set_max_level(log::LevelFilter::Trace);
}
Expand Down
4 changes: 3 additions & 1 deletion modules/pun/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::collections::HashMap;

use libcommand::*;
use wit_log as log;
use wit_sync_request;
Expand Down Expand Up @@ -33,7 +35,7 @@ impl Component {
}

impl TrinityCommand for Component {
fn init() {
fn init(_config: HashMap<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
4 changes: 3 additions & 1 deletion modules/secret/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
use std::collections::HashMap;

use libcommand::{impl_command, TrinityCommand};
use wit_log as log;

struct Component;

impl TrinityCommand for Component {
fn init() {
fn init(_config: HashMap<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
22 changes: 18 additions & 4 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 @@ -119,6 +121,7 @@ impl BotConfig {
admin_user_id,
redb_path,
modules_paths,
modules_config: None,
})
}
}
Expand All @@ -128,6 +131,7 @@ 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 @@ -141,13 +145,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 @@ -170,7 +176,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 @@ -528,6 +534,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 @@ -541,7 +549,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 @@ -9,6 +9,7 @@ pub(crate) use module::messaging::Message;

mod apis;

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

use matrix_sdk::ruma::{RoomId, UserId};
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 cbd12e8

Please sign in to comment.