Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

21 changes: 20 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,11 +1,24 @@
[workspace]
members = ["crates/database", "crates/logging", "crates/soundboard", "crates/voicevox", "restarter", "seitai"]
members = [
"crates/database",
"crates/logging",
"crates/restarter",
"crates/serenity-utils",
"crates/soundboard",
"crates/voicevox",
"seitai",
]
default-members = ["seitai"]
resolver = "3"

[workspace.dependencies.anyhow]
version = "1.0.96"

[workspace.dependencies.futures]
version = "0.3.31"
default-features =false
features = ["std"]

[workspace.dependencies.http-body-util]
version = "0.1.2"

Expand All @@ -20,6 +33,9 @@ features = ["client", "client-legacy", "http1", "tokio"]
[workspace.dependencies.logging]
path = "crates/logging"

[workspace.dependencies.restarter]
path = "crates/restarter"

[workspace.dependencies.serde]
version = "1.0.218"
features = ["derive"]
Expand All @@ -31,6 +47,9 @@ version = "1.0.139"
version = "0.12.4"
default-features = false

[workspace.dependencies.serenity_utils]
path = "crates/serenity-utils"

[workspace.dependencies.tokio]
version = "1.43.0"
features = ["macros", "net", "rt-multi-thread", "signal"]
Expand Down
15 changes: 0 additions & 15 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -13,28 +13,13 @@ FROM runtime AS development

FROM runtime AS builder
RUN --mount=type=bind,source=crates,target=crates \
--mount=type=bind,source=restarter,target=restarter \
--mount=type=bind,source=seitai,target=seitai \
--mount=type=bind,source=Cargo.toml,target=Cargo.toml \
--mount=type=bind,source=Cargo.lock,target=Cargo.lock \
--mount=type=cache,target=/usr/src/myapp/target \
cargo build --release --workspace \
&& cp target/release/restarter /restarter \
&& cp target/release/seitai /seitai

FROM scratch AS restarter
LABEL io.github.hexium310.seitai.app=restarter
LABEL org.opencontainers.image.source=https://github.com/hexium310/seitai
COPY --from=runtime /etc/ssl/certs/ /etc/ssl/certs/
COPY --from=runtime /lib/x86_64-linux-gnu/libc.so* /lib/x86_64-linux-gnu/
COPY --from=runtime /lib/x86_64-linux-gnu/libcrypto.so* /lib/x86_64-linux-gnu/
COPY --from=runtime /lib/x86_64-linux-gnu/libgcc_s.so* /lib/x86_64-linux-gnu/
COPY --from=runtime /lib/x86_64-linux-gnu/libm.so* /lib/x86_64-linux-gnu/
COPY --from=runtime /lib/x86_64-linux-gnu/libssl.so* /lib/x86_64-linux-gnu/
COPY --from=runtime /lib64/ld-linux-x86-64.so* /lib64/
COPY --from=builder /restarter /
CMD ["/restarter"]

FROM scratch AS seitai
LABEL io.github.hexium310.seitai.app=seitai
LABEL org.opencontainers.image.source=https://github.com/hexium310/seitai
Expand Down
8 changes: 1 addition & 7 deletions compose.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,6 @@ services:
- type: bind
source: seitai
target: /usr/src/myapp/seitai
- type: bind
source: restarter
target: /usr/src/myapp/restarter
command: /bin/sh -c 'cargo run -p seitai'
environment:
DISCORD_TOKEN:
Expand Down Expand Up @@ -53,10 +50,7 @@ services:
- type: bind
source: seitai
target: /usr/src/myapp/seitai
- type: bind
source: restarter
target: /usr/src/myapp/restarter
command: /bin/sh -c 'cargo run -p restarter'
command: /bin/sh -c 'cargo run -- restarter'
environment:
DISCORD_TOKEN:

Expand Down
17 changes: 16 additions & 1 deletion restarter/Cargo.toml → crates/restarter/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,16 @@ name = "restarter"
version = "0.1.7"
edition = "2024"

[lib]
doctest = false

[dependencies]

[dependencies.anyhow]
workspace = true

[dependencies.futures]
version = "0.3.31"
workspace = true

[dependencies.k8s-openapi]
version = "0.24.0"
Expand All @@ -30,3 +35,13 @@ workspace = true
[dependencies.serenity]
workspace = true
features = ["cache", "client", "gateway", "model", "native_tls_backend"]

[dependencies.serenity_utils]
workspace = true

[dev-dependencies.mockall]
version = "0.13.1"

[dev-dependencies.tokio]
workspace = true
features = ["test-util"]
51 changes: 51 additions & 0 deletions crates/restarter/src/client.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
use std::{collections::HashMap, sync::Arc, time::Duration};

use anyhow::Result;
use futures::lock::Mutex;
use serenity::{all::GatewayIntents, Client as SerenityClient};
use tokio::{signal::unix::{self, SignalKind}, task::JoinHandle};

use crate::{event_handler::Handler, restarter::{KubeRestarter, Restarter}};

pub struct Client;

impl Client {
#[tracing::instrument(skip_all)]
pub async fn start(token: String, restart_duration: u64) -> Result<()> {
enable_graceful_shutdown();

let intents = GatewayIntents::GUILDS | GatewayIntents::GUILD_VOICE_STATES;
let mut client = SerenityClient::builder(token, intents)
.event_handler(Handler {
connected_channels: Arc::new(Mutex::new(HashMap::new())),
restarter: Restarter::new(Duration::from_secs(restart_duration), KubeRestarter),
})
.await?;

tracing::debug!("restarter client starts");
if let Err(err) = client.start().await {
tracing::error!("failed to start client\nError: {err:?}");
return Err(err.into());
}

Ok(())
}
}

fn enable_graceful_shutdown() -> JoinHandle<Result<()>> {
tokio::spawn(async move {
let mut sigint = unix::signal(SignalKind::interrupt())?;
let mut sigterm = unix::signal(SignalKind::terminate())?;

tokio::select! {
_ = sigint.recv() => {
tracing::info!("received SIGINT, shutting down");
std::process::exit(130);
},
_ = sigterm.recv() => {
tracing::info!("received SIGTERM, shutting down");
std::process::exit(143);
},
}
})
}
52 changes: 52 additions & 0 deletions crates/restarter/src/event_handler.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
use std::{collections::HashMap, pin::Pin, sync::Arc};

use futures::{lock::Mutex, FutureExt};
use serenity::{
all::{ChannelId, GuildId, VoiceState},
client::{Context, EventHandler},
model::gateway::Ready,
};
use tracing::instrument;

use crate::{event_handler, restarter::Restarter};

mod ready;
mod voice_state_update;

pub(crate) struct Handler {
pub(crate) connected_channels: Arc<Mutex<HashMap<GuildId, ChannelId>>>,
pub(crate) restarter: Restarter,
}

impl EventHandler for Handler {
#[instrument(skip_all)]
fn ready<'s, 'async_trait>(&'s self, ctx: Context, ready: Ready) -> Pin<Box<(dyn Future<Output = ()> + Send + 'async_trait)>>
where
Self: 'async_trait,
's: 'async_trait,
{
async move {
if let Err(err) = event_handler::ready::handle(self, ctx, ready).await {
tracing::error!("failed to handle ready event\nError: {err:?}");
}
}.boxed()
}

#[instrument(skip_all)]
fn voice_state_update<'s, 'async_trait>(
&'s self,
context: Context,
old_state: Option<VoiceState>,
new_state: VoiceState,
) -> Pin<Box<(dyn Future<Output = ()> + Send + 'async_trait)>>
where
Self: 'async_trait,
's: 'async_trait,
{
async move {
if let Err(err) = event_handler::voice_state_update::handle(self, context, old_state, new_state).await {
tracing::error!("failed to handle voice state update event\nError: {err:?}");
}
}.boxed()
}
}
10 changes: 10 additions & 0 deletions crates/restarter/src/event_handler/ready.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
use anyhow::Result;
use serenity::all::{Context, Ready};

use super::Handler;

pub(crate) async fn handle(_handler: &Handler, _ctx: Context, ready: Ready) -> Result<()> {
tracing::info!("{} is ready", ready.user.name);

Ok(())
}
41 changes: 41 additions & 0 deletions crates/restarter/src/event_handler/voice_state_update.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
use anyhow::Result;
use serenity::all::{Context, VoiceState};
use serenity_utils::voice_state::{VoiceStateAction, VoiceStateConnection};

use super::Handler;

pub(crate) async fn handle(handler: &Handler, ctx: Context, old_state: Option<VoiceState>, new_state: VoiceState) -> Result<()> {
let Some(guild_id) = new_state.guild_id else {
return Ok(());
};

let bot_id = ctx.http.get_current_user().await?.id;
let action = VoiceStateAction::new(old_state, new_state);

if !action.is_bot_action(bot_id) {
return Ok(());
}

match action.connection() {
VoiceStateConnection::Joined(channel_id) => {
let mut connected_channels = handler.connected_channels.lock().await;
connected_channels.insert(guild_id, channel_id);

handler.restarter.set_connection_count(connected_channels.len()).await;
},
VoiceStateConnection::Left(_) => {
let mut connected_channels = handler.connected_channels.lock().await;
connected_channels.remove(&guild_id);

let count = connected_channels.len();
handler.restarter.set_connection_count(count).await;

if count == 0 {
handler.restarter.schedule_restart().await;
}
},
VoiceStateConnection::Moved(..) | VoiceStateConnection::NoAction => (),
}

Ok(())
}
5 changes: 5 additions & 0 deletions crates/restarter/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
pub use client::Client;

mod event_handler;
mod client;
mod restarter;
Loading