Compare commits

..

No commits in common. "ff816c4fdcd8d90bcfc2d65e424efe0ccec9b40f" and "d442cccebea4cc83ce9f6bd88664626a038b489b" have entirely different histories.

7 changed files with 76 additions and 41 deletions

13
Cargo.lock generated
View File

@ -897,12 +897,6 @@ version = "0.31.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "07e28edb80900c19c28f1072f2e8aeca7fa06b23cd4169cefe1af5aa3260783f" checksum = "07e28edb80900c19c28f1072f2e8aeca7fa06b23cd4169cefe1af5aa3260783f"
[[package]]
name = "git-const"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aa4f63cc0cd93d91bcc11b46f61db771bc36c405d96043506ae40facd87b31f7"
[[package]] [[package]]
name = "glob" name = "glob"
version = "0.3.2" version = "0.3.2"
@ -921,7 +915,6 @@ dependencies = [
"enum_stringify", "enum_stringify",
"envconfig", "envconfig",
"futures", "futures",
"git-const",
"itertools 0.14.0", "itertools 0.14.0",
"lazy_static", "lazy_static",
"log", "log",
@ -1470,7 +1463,8 @@ dependencies = [
[[package]] [[package]]
name = "libquickjs-ng-sys" name = "libquickjs-ng-sys"
version = "0.9.0" version = "0.9.0"
source = "git+https://github.com/akulij/quickjs-rusty.git?rev=549f830#549f8308b737006098293b2f0a5ff8ed420442b5" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3c98c1ad542ec61348faba7ce5386fef9060e35fbeea19dda64ce41862084e0a"
dependencies = [ dependencies = [
"bindgen", "bindgen",
"cc", "cc",
@ -2015,7 +2009,8 @@ dependencies = [
[[package]] [[package]]
name = "quickjs-rusty" name = "quickjs-rusty"
version = "0.9.0" version = "0.9.0"
source = "git+https://github.com/akulij/quickjs-rusty.git?rev=549f830#549f8308b737006098293b2f0a5ff8ed420442b5" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b3b4d659d1bc37e9112a14ad9a7727d182b0fb12216eb6684bdbada3e9991a22"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"chrono", "chrono",

View File

@ -14,13 +14,12 @@ dotenvy = "0.15.7"
enum_stringify = "0.6.3" enum_stringify = "0.6.3"
envconfig = "0.11.0" envconfig = "0.11.0"
futures = "0.3.31" futures = "0.3.31"
git-const = "1.1.0"
itertools = "0.14.0" itertools = "0.14.0"
lazy_static = "1.5.0" lazy_static = "1.5.0"
log = "0.4.27" log = "0.4.27"
mongodb = "3.2.3" mongodb = "3.2.3"
pretty_env_logger = "0.5.0" pretty_env_logger = "0.5.0"
quickjs-rusty = { git = "https://github.com/akulij/quickjs-rusty.git", rev = "549f830" } quickjs-rusty = "0.9.0"
serde = { version = "1.0.219", features = ["derive", "serde_derive"] } serde = { version = "1.0.219", features = ["derive", "serde_derive"] }
serde_json = "1.0.140" serde_json = "1.0.140"
teloxide = { version = "0.14.0", features = ["macros", "postgres-storage-nativetls"] } teloxide = { version = "0.14.0", features = ["macros", "postgres-storage-nativetls"] }

View File

@ -43,6 +43,7 @@ const dialog = {
function leave_application(user) { function leave_application(user) {
print("point of reach") print("point of reach")
print(JSON.stringify(user))
user_application(user) user_application(user)
return false return false

View File

@ -1,4 +1,3 @@
use git_const::git_hash;
use itertools::Itertools; use itertools::Itertools;
use teloxide::{ use teloxide::{
prelude::*, prelude::*,
@ -45,8 +44,6 @@ pub enum AdminCommands {
Cancel, Cancel,
/// Create new instance of telegram bot /// Create new instance of telegram bot
Deploy { token: String }, Deploy { token: String },
/// Get commit hash of this bot
Commit,
} }
pub async fn admin_command_handler( pub async fn admin_command_handler(
@ -192,12 +189,6 @@ pub async fn admin_command_handler(
.await?; .await?;
Ok(()) Ok(())
} }
AdminCommands::Commit => {
let hash = git_hash!();
bot.send_message(msg.chat.id, format!("Commit: {hash}"))
.await?;
Ok(())
}
} }
} }

View File

@ -2,7 +2,7 @@ use log::{error, info};
use quickjs_rusty::serde::to_js; use quickjs_rusty::serde::to_js;
use std::{ use std::{
str::FromStr, str::FromStr,
sync::{Arc, Mutex, RwLock}, sync::{Arc, RwLock},
}; };
use teloxide::{ use teloxide::{
dispatching::{dialogue::GetChatId, UpdateFilterExt}, dispatching::{dialogue::GetChatId, UpdateFilterExt},
@ -23,7 +23,7 @@ use crate::{
pub type BotHandler = pub type BotHandler =
Handler<'static, DependencyMap, BotResult<()>, teloxide::dispatching::DpHandlerDescription>; Handler<'static, DependencyMap, BotResult<()>, teloxide::dispatching::DpHandlerDescription>;
pub fn script_handler(r: Arc<Mutex<BotRuntime>>) -> BotHandler { pub fn script_handler(r: Arc<BotRuntime>) -> BotHandler {
let cr = r.clone(); let cr = r.clone();
dptree::entry() dptree::entry()
.branch( .branch(
@ -35,8 +35,7 @@ pub fn script_handler(r: Arc<Mutex<BotRuntime>>) -> BotHandler {
let r = std::sync::Arc::clone(&r); let r = std::sync::Arc::clone(&r);
let command = bc.command(); let command = bc.command();
let r = r.lock().expect("RwLock lock on commands map failed"); let rc = r.rc.lock().expect("RwLock lock on commands map failed");
let rc = &r.rc;
rc.get_command_message(command) rc.get_command_message(command)
}) })
@ -47,8 +46,7 @@ pub fn script_handler(r: Arc<Mutex<BotRuntime>>) -> BotHandler {
.filter_map(move |q: CallbackQuery| { .filter_map(move |q: CallbackQuery| {
q.data.and_then(|data| { q.data.and_then(|data| {
let r = std::sync::Arc::clone(&cr); let r = std::sync::Arc::clone(&cr);
let r = r.lock().expect("RwLock lock on commands map failed"); let rc = r.rc.lock().expect("RwLock lock on commands map failed");
let rc = &r.rc;
rc.get_callback_message(&data) rc.get_callback_message(&data)
}) })
@ -157,9 +155,9 @@ async fn handle_callback(bot: Bot, mut db: DB, bm: BotMessage, q: CallbackQuery)
handler, handler,
bm.literal() bm.literal()
); );
match handler.call_args(vec![jsuser]) { match handler.call_args(vec![]) {
Ok(v) => { Ok(v) => {
println!("Ok branch, got value: {v:?}"); println!("Ok branch, value: {:?}", v.js_to_string());
if v.is_bool() { if v.is_bool() {
v.to_bool().unwrap_or(true) v.to_bool().unwrap_or(true)
} else if v.is_int() { } else if v.is_int() {

View File

@ -1,7 +1,7 @@
use std::{ use std::{
collections::HashMap, collections::HashMap,
future::Future, future::Future,
sync::{Arc, Mutex, RwLock}, sync::{Arc, RwLock},
thread::JoinHandle, thread::JoinHandle,
time::Duration, time::Duration,
}; };
@ -14,7 +14,6 @@ use teloxide::{
prelude::{Dispatcher, Requester}, prelude::{Dispatcher, Requester},
Bot, Bot,
}; };
use tokio::runtime::Handle;
use crate::{ use crate::{
bot_handler::{script_handler, BotHandler}, bot_handler::{script_handler, BotHandler},
@ -29,11 +28,18 @@ pub struct BotRunner {
thread: Option<JoinHandle<BotResult<()>>>, thread: Option<JoinHandle<BotResult<()>>>,
} }
unsafe impl Sync for BotRunner {}
unsafe impl Send for BotRunner {}
#[derive(Clone)] #[derive(Clone)]
pub struct BotInfo { pub struct BotInfo {
pub name: String, pub name: String,
} }
lazy_static! {
static ref BOT_POOL: RwLock<HashMap<String, BotRunner>> = RwLock::new(HashMap::new());
}
pub static DEFAULT_SCRIPT: &str = pub static DEFAULT_SCRIPT: &str =
include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/default_script.js")); include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/default_script.js"));
@ -165,10 +171,7 @@ where
} }
} }
async fn script_handler_gen( async fn script_handler_gen(r: Arc<BotRuntime>, plug_handlers: Vec<BotHandler>) -> BotHandler {
r: Arc<Mutex<BotRuntime>>,
plug_handlers: Vec<BotHandler>,
) -> BotHandler {
let handler = script_handler(r.clone()); let handler = script_handler(r.clone());
// each handler will be added to dptree::entry() // each handler will be added to dptree::entry()
let handler = plug_handlers let handler = plug_handlers
@ -179,6 +182,48 @@ async fn script_handler_gen(
handler handler
} }
pub async fn start_bot(
bi: BotInstance,
db: &mut DB,
plug_handlers: Vec<BotHandler>,
) -> BotResult<BotInfo> {
let db = db.clone().with_name(bi.name.clone());
let controller = BotController::with_db(db.clone(), &bi.token, &bi.script).await?;
let handler = script_handler(controller.runtime.clone());
// each handler will be added to dptree::entry()
let handler = plug_handlers
.into_iter()
// as well as the script handler at the end
.chain(std::iter::once(handler))
.fold(dptree::entry(), |h, plug| h.branch(plug));
let thread = spawn_bot_thread(controller.bot.clone(), controller.db.clone(), handler).await?;
let info = BotInfo {
name: bi.name.clone(),
};
let runner = BotRunner {
controller,
info: info.clone(),
thread: Some(thread),
};
BOT_POOL
.write()
.map_or_else(
|err| {
Err(BotError::RwLockError(format!(
"Failed to lock BOT_POOL because previous thread paniced, err: {err}"
)))
},
Ok,
)?
.insert(bi.name.clone(), runner);
Ok(info)
}
pub async fn spawn_bot_thread( pub async fn spawn_bot_thread(
bot: Bot, bot: Bot,
mut db: DB, mut db: DB,
@ -190,10 +235,9 @@ pub async fn spawn_bot_thread(
let thread = std::thread::spawn(move || -> BotResult<()> { let thread = std::thread::spawn(move || -> BotResult<()> {
let state_mgr = state_mgr; let state_mgr = state_mgr;
// let rt = tokio::runtime::Builder::new_current_thread() let rt = tokio::runtime::Builder::new_current_thread()
// .enable_all() .enable_all()
// .build()?; .build()?;
let rt = tokio::runtime::Runtime::new().unwrap();
rt.block_on( rt.block_on(
Dispatcher::builder(bot, handler) Dispatcher::builder(bot, handler)

View File

@ -104,14 +104,16 @@ type CallbackStore = CallbackInfo<Callback>;
pub struct BotController { pub struct BotController {
pub bot: Bot, pub bot: Bot,
pub db: DB, pub db: DB,
pub runtime: Arc<Mutex<BotRuntime>>, pub runtime: Arc<BotRuntime>,
} }
pub struct BotRuntime { pub struct BotRuntime {
pub rc: RunnerConfig, pub rc: Mutex<RunnerConfig>,
pub runner: Runner, pub runner: Runner,
} }
unsafe impl Send for BotRuntime {} unsafe impl Send for BotRuntime {}
unsafe impl Sync for BotRuntime {}
impl Drop for BotController { impl Drop for BotController {
fn drop(&mut self) { fn drop(&mut self) {
@ -119,6 +121,8 @@ impl Drop for BotController {
} }
} }
unsafe impl Send for BotController {}
const MAIN_BOT_SCRIPT: &str = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/mainbot.js")); const MAIN_BOT_SCRIPT: &str = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/mainbot.js"));
impl BotController { impl BotController {
@ -144,7 +148,10 @@ impl BotController {
let mut runner = Runner::init_with_db(&mut db)?; let mut runner = Runner::init_with_db(&mut db)?;
runner.call_attacher(|c, o| attach_user_application(c, o, &db, &bot))??; runner.call_attacher(|c, o| attach_user_application(c, o, &db, &bot))??;
let rc = runner.init_config(script)?; let rc = runner.init_config(script)?;
let runtime = Arc::new(Mutex::new(BotRuntime { rc, runner })); let runtime = Arc::new(BotRuntime {
rc: Mutex::new(rc),
runner,
});
Ok(Self { bot, db, runtime }) Ok(Self { bot, db, runtime })
} }