Compare commits
18 Commits
3984a7d3ba
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 7f24d7657c | |||
| a613fdb99e | |||
| 975581093a | |||
| 00d46ce968 | |||
| 3f6c5b5559 | |||
| d4666fb36e | |||
| cf59455d4a | |||
| c7387a3b28 | |||
| 433021d607 | |||
| 3c32cd20b6 | |||
| a30d7c5d90 | |||
| 9175f9b3a2 | |||
| 71ebfdd276 | |||
| 3d751ae6c6 | |||
| 6599c20c30 | |||
| a2d898c07d | |||
| efb35d5a8a | |||
| 39c2afa0a7 |
@@ -11,6 +11,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
|
|||||||
curl \
|
curl \
|
||||||
git \
|
git \
|
||||||
build-essential \
|
build-essential \
|
||||||
|
libssl-dev \
|
||||||
cmake \
|
cmake \
|
||||||
pkg-config \
|
pkg-config \
|
||||||
clang \
|
clang \
|
||||||
|
|||||||
@@ -0,0 +1,4 @@
|
|||||||
|
target/
|
||||||
|
.env
|
||||||
|
.devcontainer/
|
||||||
|
docs/
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
HTTP_PORT=3000
|
||||||
|
BOT_NAME=Herald
|
||||||
|
|
||||||
|
WEBHOOK_SIG_HEADER_SECRET=
|
||||||
|
|
||||||
|
OPEN_ROUTER_API_KEY=
|
||||||
|
OPEN_ROUTER_MODEL=deepseek/deepseek-v4-flash
|
||||||
|
OPEN_ROUTER_TIMEOUT=120
|
||||||
|
|
||||||
|
BOT_MAX_CONCURRENT=5
|
||||||
|
|
||||||
|
GITEA_URL=https://gitea.example.com
|
||||||
|
GITEA_TOKEN=
|
||||||
|
GITEA_TIMEOUT=30
|
||||||
|
|
||||||
|
# Optional
|
||||||
|
SENTRY_DSN=
|
||||||
|
RUST_LOG=info
|
||||||
|
RUST_BACKTRACE=1
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
when:
|
||||||
|
event:
|
||||||
|
- tag
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: release-docker
|
||||||
|
image: quay.io/buildah/stable
|
||||||
|
privileged: true
|
||||||
|
volumes:
|
||||||
|
- /data/woodpecker-builds:/data
|
||||||
|
commands:
|
||||||
|
- echo $DOCKER_PASSWORD | buildah login docker.io -u $DOCKER_USERNAME --password-stdin
|
||||||
|
- chmod +x scripts/build.sh
|
||||||
|
- bash scripts/build.sh
|
||||||
|
environment:
|
||||||
|
DOCKER_USERNAME:
|
||||||
|
from_secret: docker_username
|
||||||
|
DOCKER_PASSWORD:
|
||||||
|
from_secret: docker_password
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
when:
|
||||||
|
event:
|
||||||
|
- push
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: clippy
|
||||||
|
image: rust:1.96
|
||||||
|
commands:
|
||||||
|
- rustup component add clippy
|
||||||
|
- cargo clippy
|
||||||
|
|
||||||
|
- name: test
|
||||||
|
image: rust:1.96
|
||||||
|
commands:
|
||||||
|
- cargo test
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
{
|
||||||
|
"lsp": {
|
||||||
|
"rust-analyzer": {
|
||||||
|
"initialization_options": {
|
||||||
|
"check": {
|
||||||
|
"command": "clippy"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Generated
+1351
-17
File diff suppressed because it is too large
Load Diff
+11
-2
@@ -1,8 +1,11 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "herald"
|
name = "herald"
|
||||||
version = "0.1.0"
|
version = "1.0.1"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
|
|
||||||
|
[profile.release]
|
||||||
|
debug = 1
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] }
|
reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] }
|
||||||
tokio = { version = "1.52", features = ["full"] }
|
tokio = { version = "1.52", features = ["full"] }
|
||||||
@@ -11,10 +14,16 @@ tokio-util = "0.7"
|
|||||||
futures-util = "0.3"
|
futures-util = "0.3"
|
||||||
serde_json = "1.0"
|
serde_json = "1.0"
|
||||||
serde = { version = "1.0", features = ["derive"] }
|
serde = { version = "1.0", features = ["derive"] }
|
||||||
|
sentry = { version = "0.48", features = ["tower-axum-matched-path"] }
|
||||||
|
sentry-anyhow = { version = "0.48", features = ["backtrace"] }
|
||||||
openrouter-rs = "0.10"
|
openrouter-rs = "0.10"
|
||||||
dotenvy = "0.15"
|
dotenvy = "0.15"
|
||||||
|
tower = "0.5"
|
||||||
|
tower-http = {version = "0.6", features = ["trace"] }
|
||||||
|
tracing = "0.1"
|
||||||
|
tracing-subscriber = { version = "0.3", features=["env-filter"] }
|
||||||
axum = "0.8"
|
axum = "0.8"
|
||||||
anyhow = "1.0"
|
anyhow = { version = "1.0", features = ["backtrace"] }
|
||||||
thiserror = "2.0"
|
thiserror = "2.0"
|
||||||
hmac = "0.13"
|
hmac = "0.13"
|
||||||
sha2 = "0.11"
|
sha2 = "0.11"
|
||||||
|
|||||||
@@ -0,0 +1,12 @@
|
|||||||
|
FROM rust:1.96 as builder
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
COPY . .
|
||||||
|
RUN cargo build --release
|
||||||
|
|
||||||
|
|
||||||
|
FROM debian:trixie-slim
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
COPY --from=builder /app/target/release/herald .
|
||||||
|
CMD [ "./herald" ]
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
# Herald
|
||||||
|
|
||||||
|
Herald is a Gitea bot that performs automated AI-powered code reviews on pull requests using [OpenRouter](https://openrouter.ai/).
|
||||||
|
|
||||||
|
## Features
|
||||||
|
|
||||||
|
- Listens for Gitea webhook events and triggers code reviews on pull request comments
|
||||||
|
- Streams reviews back to Gitea as PR comments
|
||||||
|
- Concurrent review processing with configurable parallelism
|
||||||
|
- Graceful shutdown — in-progress reviews finish before the process exits
|
||||||
|
- Error tracking via Sentry
|
||||||
|
- Tiny memory footprint (~4MB) thanks to Rust
|
||||||
|
|
||||||
|
## Installation
|
||||||
|
|
||||||
|
**Requirements:** Rust toolchain ([rustup.rs](https://rustup.rs))
|
||||||
|
|
||||||
|
```sh
|
||||||
|
cargo build --release
|
||||||
|
./target/release/herald
|
||||||
|
```
|
||||||
|
|
||||||
|
Herald reads its configuration from environment variables (a `.env` file is supported):
|
||||||
|
|
||||||
|
| Variable | Description |
|
||||||
|
|---|---|
|
||||||
|
| `HTTP_PORT` | Port to listen on |
|
||||||
|
| `BOT_NAME` | The bot's Gitea username (used to detect mentions) |
|
||||||
|
| `WEBHOOK_SIG_HEADER_SECRET` | Gitea webhook secret for signature verification |
|
||||||
|
| `OPEN_ROUTER_API_KEY` | OpenRouter API key |
|
||||||
|
| `OPEN_ROUTER_MODEL` | Model to use (e.g. `deepseek/deepseek-v4-flash`) |
|
||||||
|
| `OPEN_ROUTER_TIMEOUT` | OpenRouter request timeout in seconds |
|
||||||
|
| `BOT_MAX_CONCURRENT` | Maximum number of concurrent reviews |
|
||||||
|
| `GITEA_URL` | Base URL of your Gitea instance |
|
||||||
|
| `GITEA_TOKEN` | Gitea API token |
|
||||||
|
| `GITEA_TIMEOUT` | Gitea API request timeout in seconds |
|
||||||
|
| `SENTRY_DSN` | *(optional)* Sentry DSN for error tracking |
|
||||||
|
| `RUST_LOG` | *(optional)* Log level, defaults to `info` |
|
||||||
|
|
||||||
|
## Development
|
||||||
|
|
||||||
|
The easiest way to get started is with the provided [Dev Container](https://containers.dev/) (VS Code or Zed with the dev container extension).
|
||||||
|
|
||||||
|
Open the project and reopen it in the container — the Rust toolchain is pre-installed.
|
||||||
|
|
||||||
|
**Without Dev Container**, you just need a Rust toolchain:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
rustup toolchain install stable
|
||||||
|
cargo run
|
||||||
|
```
|
||||||
|
|
||||||
|
Copy `.env.example` to `.env` and fill in your values before running.
|
||||||
Executable
+22
@@ -0,0 +1,22 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
IMAGE="tintounn/herald"
|
||||||
|
|
||||||
|
if [ -z "${CI_COMMIT_TAG:-}" ]; then
|
||||||
|
echo "Error: CI_COMMIT_TAG is not set" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
TAG="${CI_COMMIT_TAG}"
|
||||||
|
|
||||||
|
echo "Building ${IMAGE}:${TAG}..."
|
||||||
|
buildah build \
|
||||||
|
--file Containerfile \
|
||||||
|
--tag "docker.io/${IMAGE}:${TAG}" \
|
||||||
|
.
|
||||||
|
|
||||||
|
echo "Pushing ${IMAGE}:${TAG}..."
|
||||||
|
buildah push "${IMAGE}:${TAG}"
|
||||||
|
|
||||||
|
echo "Done: ${IMAGE}:${TAG}"
|
||||||
+43
-6
@@ -1,46 +1,72 @@
|
|||||||
use axum::body::{Bytes, to_bytes};
|
use axum::body::{Bytes, to_bytes};
|
||||||
use axum::extract::{FromRef, FromRequest, State};
|
use axum::extract::{FromRef, FromRequest, State};
|
||||||
|
use axum::http::Request;
|
||||||
use axum::response::IntoResponse;
|
use axum::response::IntoResponse;
|
||||||
use axum::routing::{get, post};
|
use axum::routing::{get, post};
|
||||||
use axum::{Json, Router};
|
use axum::{Json, Router};
|
||||||
use hmac::{Hmac, KeyInit, Mac};
|
use hmac::{Hmac, KeyInit, Mac};
|
||||||
use reqwest::StatusCode;
|
use reqwest::StatusCode;
|
||||||
|
use sentry::integrations::tower::{NewSentryLayer, SentryHttpLayer};
|
||||||
use serde_json::Value;
|
use serde_json::Value;
|
||||||
use sha2::Sha256;
|
use sha2::Sha256;
|
||||||
use subtle::ConstantTimeEq;
|
use subtle::ConstantTimeEq;
|
||||||
|
use tower::ServiceBuilder;
|
||||||
|
use tower_http::trace::TraceLayer;
|
||||||
|
use tracing::{info, instrument};
|
||||||
|
|
||||||
|
use tokio_util::sync::CancellationToken;
|
||||||
|
|
||||||
use crate::consts::{GITEA_EVENT_TYPE_HEADER_NAME, GITEA_SIG_HEADER_NAME, MAX_WEBHOOK_BODY_SIZE};
|
use crate::consts::{GITEA_EVENT_TYPE_HEADER_NAME, GITEA_SIG_HEADER_NAME, MAX_WEBHOOK_BODY_SIZE};
|
||||||
use crate::errors::AppError;
|
use crate::errors::AppError;
|
||||||
use crate::gitea::WebhookType;
|
use crate::gitea::WebhookType;
|
||||||
use crate::state::AppState;
|
use crate::state::AppState;
|
||||||
|
|
||||||
pub async fn start(app_state: AppState) -> anyhow::Result<()> {
|
pub async fn start(app_state: AppState, shutdown: CancellationToken) -> anyhow::Result<()> {
|
||||||
let http_port = app_state.config.http_port;
|
let http_port = app_state.config.http_port;
|
||||||
|
|
||||||
let app = Router::new()
|
let app = Router::new()
|
||||||
.route("/", get(root))
|
.route("/", get(root))
|
||||||
.route("/webhook", post(webhook))
|
.route("/webhook", post(webhook))
|
||||||
|
.layer(
|
||||||
|
ServiceBuilder::new()
|
||||||
|
.layer(NewSentryLayer::<Request<_>>::new_from_top())
|
||||||
|
.layer(SentryHttpLayer::new())
|
||||||
|
.layer(TraceLayer::new_for_http()),
|
||||||
|
)
|
||||||
.with_state(app_state);
|
.with_state(app_state);
|
||||||
|
|
||||||
let listener = tokio::net::TcpListener::bind(format!("0.0.0.0:{}", http_port)).await?;
|
let listener = tokio::net::TcpListener::bind(format!("0.0.0.0:{}", http_port)).await?;
|
||||||
|
info!("Listening API on port {}", http_port);
|
||||||
|
|
||||||
axum::serve(listener, app)
|
axum::serve(listener, app)
|
||||||
|
.with_graceful_shutdown(async move { shutdown.cancelled().await })
|
||||||
.await
|
.await
|
||||||
.map_err(anyhow::Error::from)
|
.map_err(anyhow::Error::from)
|
||||||
|
.inspect(|_| info!("API shutting down complete"))?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn root() -> &'static str {
|
async fn root() -> &'static str {
|
||||||
"Hi, i'm Herald :)"
|
"Hi, i'm Herald :)"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[instrument(skip(app_state), fields(webhook_type), err)]
|
||||||
async fn webhook(
|
async fn webhook(
|
||||||
State(app_state): State<AppState>,
|
State(app_state): State<AppState>,
|
||||||
WebhookExtract(wb): WebhookExtract,
|
WebhookExtract(wb): WebhookExtract,
|
||||||
) -> Result<impl IntoResponse, AppError> {
|
) -> Result<impl IntoResponse, AppError> {
|
||||||
app_state
|
tracing::Span::current().record("webhook_type", tracing::field::debug(&wb));
|
||||||
.bot_tx
|
|
||||||
.send(wb)
|
let event_id = wb.event_id();
|
||||||
.await
|
if app_state.bot.check_and_mark(event_id).await {
|
||||||
.map_err(anyhow::Error::from)?;
|
return Err(AppError::AlreadyProcessedErr);
|
||||||
|
}
|
||||||
|
|
||||||
|
if app_state.bot_tx.try_send(wb).is_err() {
|
||||||
|
app_state.bot.unmark(event_id).await;
|
||||||
|
return Err(AppError::ChannelFullErr);
|
||||||
|
}
|
||||||
|
|
||||||
Ok((StatusCode::CREATED, "Task started"))
|
Ok((StatusCode::CREATED, "Task started"))
|
||||||
}
|
}
|
||||||
@@ -54,6 +80,7 @@ where
|
|||||||
{
|
{
|
||||||
type Rejection = AppError;
|
type Rejection = AppError;
|
||||||
|
|
||||||
|
#[instrument(skip(req, state), err)]
|
||||||
async fn from_request(req: axum::extract::Request, state: &S) -> Result<Self, Self::Rejection> {
|
async fn from_request(req: axum::extract::Request, state: &S) -> Result<Self, Self::Rejection> {
|
||||||
let app_state = AppState::from_ref(state);
|
let app_state = AppState::from_ref(state);
|
||||||
let headers = req.headers();
|
let headers = req.headers();
|
||||||
@@ -68,6 +95,16 @@ where
|
|||||||
&body_bytes,
|
&body_bytes,
|
||||||
)?;
|
)?;
|
||||||
|
|
||||||
|
let body_str = String::from_utf8_lossy(&body_bytes).into_owned();
|
||||||
|
sentry::configure_scope(|scope| {
|
||||||
|
scope.add_event_processor(move |mut event| {
|
||||||
|
let mut request = event.request.take().unwrap_or_default();
|
||||||
|
request.data = Some(body_str.clone());
|
||||||
|
event.request = Some(request);
|
||||||
|
Some(event)
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
let webhook = parse_webhook(&type_header, &app_state.config.bot_name, &body_bytes)?;
|
let webhook = parse_webhook(&type_header, &app_state.config.bot_name, &body_bytes)?;
|
||||||
Ok(WebhookExtract(webhook))
|
Ok(WebhookExtract(webhook))
|
||||||
}
|
}
|
||||||
|
|||||||
+139
-45
@@ -1,11 +1,13 @@
|
|||||||
use serde::Deserialize;
|
|
||||||
use std::time::Duration;
|
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
env::EnvConfig,
|
env::EnvConfig,
|
||||||
gitea::{GiteaAPI, WebhookType},
|
gitea::{GiteaAPI, WebhookType},
|
||||||
open_router::OpenRouterClient,
|
open_router::OpenRouterClient,
|
||||||
};
|
};
|
||||||
|
use serde::Deserialize;
|
||||||
|
use std::{collections::HashSet, sync::Arc, time::Duration};
|
||||||
|
use tokio::sync::Mutex;
|
||||||
|
use tokio_util::sync::CancellationToken;
|
||||||
|
use tracing::{error, info, instrument};
|
||||||
|
|
||||||
#[derive(Deserialize, Debug)]
|
#[derive(Deserialize, Debug)]
|
||||||
pub struct ReviewResult {
|
pub struct ReviewResult {
|
||||||
@@ -22,49 +24,14 @@ pub struct ReviewItem {
|
|||||||
pub message: String,
|
pub message: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Map a filename to a markdown language identifier for syntax highlighting.
|
#[derive(Clone)]
|
||||||
fn lang_from_filename(filename: &str) -> &str {
|
|
||||||
match std::path::Path::new(filename)
|
|
||||||
.extension()
|
|
||||||
.and_then(|e| e.to_str())
|
|
||||||
.unwrap_or("")
|
|
||||||
{
|
|
||||||
"rs" => "rust",
|
|
||||||
"py" => "python",
|
|
||||||
"js" | "mjs" => "javascript",
|
|
||||||
"ts" => "typescript",
|
|
||||||
"jsx" => "jsx",
|
|
||||||
"tsx" => "tsx",
|
|
||||||
"go" => "go",
|
|
||||||
"java" => "java",
|
|
||||||
"kt" | "kts" => "kotlin",
|
|
||||||
"scala" => "scala",
|
|
||||||
"c" | "h" => "c",
|
|
||||||
"cpp" | "cc" | "cxx" | "hpp" | "hxx" => "cpp",
|
|
||||||
"rb" => "ruby",
|
|
||||||
"php" => "php",
|
|
||||||
"swift" => "swift",
|
|
||||||
"sh" | "bash" | "zsh" => "bash",
|
|
||||||
"sql" => "sql",
|
|
||||||
"html" | "htm" => "html",
|
|
||||||
"css" => "css",
|
|
||||||
"scss" | "sass" => "scss",
|
|
||||||
"json" => "json",
|
|
||||||
"yaml" | "yml" => "yaml",
|
|
||||||
"xml" => "xml",
|
|
||||||
"toml" => "toml",
|
|
||||||
"md" | "mdx" => "markdown",
|
|
||||||
"dockerfile" | "Dockerfile" => "dockerfile",
|
|
||||||
"Makefile" => "makefile",
|
|
||||||
_ => "",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct Bot {
|
pub struct Bot {
|
||||||
config: EnvConfig,
|
config: EnvConfig,
|
||||||
gitea_api: GiteaAPI,
|
gitea_api: GiteaAPI,
|
||||||
open_router_client: OpenRouterClient,
|
open_router_client: OpenRouterClient,
|
||||||
http_client: reqwest::Client,
|
http_client: reqwest::Client,
|
||||||
|
max_concurrent: usize,
|
||||||
|
actions_handled: Arc<Mutex<HashSet<u64>>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Bot {
|
impl Bot {
|
||||||
@@ -79,7 +46,9 @@ impl Bot {
|
|||||||
&config.open_router_model,
|
&config.open_router_model,
|
||||||
open_router_timeout,
|
open_router_timeout,
|
||||||
)?,
|
)?,
|
||||||
|
max_concurrent: config.bot_max_concurrent,
|
||||||
config,
|
config,
|
||||||
|
actions_handled: Arc::new(Mutex::new(HashSet::new())),
|
||||||
http_client: reqwest::Client::builder()
|
http_client: reqwest::Client::builder()
|
||||||
.timeout(Duration::from_secs(gitea_timeout))
|
.timeout(Duration::from_secs(gitea_timeout))
|
||||||
.build()?,
|
.build()?,
|
||||||
@@ -89,15 +58,54 @@ impl Bot {
|
|||||||
pub async fn start(
|
pub async fn start(
|
||||||
&self,
|
&self,
|
||||||
mut rx: tokio::sync::mpsc::Receiver<WebhookType>,
|
mut rx: tokio::sync::mpsc::Receiver<WebhookType>,
|
||||||
|
shutdown: CancellationToken,
|
||||||
) -> anyhow::Result<()> {
|
) -> anyhow::Result<()> {
|
||||||
while let Some(wb) = rx.recv().await {
|
info!("Bot started");
|
||||||
self.exec(wb).await;
|
|
||||||
|
let sem = Arc::new(tokio::sync::Semaphore::new(self.max_concurrent));
|
||||||
|
let mut tasks = tokio::task::JoinSet::new();
|
||||||
|
|
||||||
|
loop {
|
||||||
|
let wb = tokio::select! {
|
||||||
|
biased;
|
||||||
|
_ = shutdown.cancelled() => break,
|
||||||
|
msg = rx.recv() => match msg {
|
||||||
|
Some(wb) => wb,
|
||||||
|
None => break,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
while let Some(res) = tasks.try_join_next() {
|
||||||
|
if let Err(e) = res {
|
||||||
|
error!("Task panicked: {e}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
info!(queued = rx.len(), active = tasks.len(), "Webhook received");
|
||||||
|
let permit = sem.clone().acquire_owned().await?;
|
||||||
|
let self_clone = self.clone();
|
||||||
|
|
||||||
|
tasks.spawn(async move {
|
||||||
|
self_clone.exec(wb).await;
|
||||||
|
drop(permit);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
tasks.join_all().await;
|
||||||
|
|
||||||
|
info!("Bot shutting down complete");
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[instrument(skip(self, webhook), fields(repo, pr))]
|
||||||
pub async fn exec(&self, webhook: WebhookType) {
|
pub async fn exec(&self, webhook: WebhookType) {
|
||||||
|
match &webhook {
|
||||||
|
WebhookType::Review(p) => {
|
||||||
|
tracing::Span::current().record("repo", &p.repository.full_name);
|
||||||
|
tracing::Span::current().record("pr", p.pull_request.number);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
let exec_result = match webhook {
|
let exec_result = match webhook {
|
||||||
WebhookType::Review(review_payload) => crate::bot_actions::review::exec_review(
|
WebhookType::Review(review_payload) => crate::bot_actions::review::exec_review(
|
||||||
&self.gitea_api,
|
&self.gitea_api,
|
||||||
@@ -110,8 +118,94 @@ impl Bot {
|
|||||||
.await;
|
.await;
|
||||||
|
|
||||||
match exec_result {
|
match exec_result {
|
||||||
Ok(_) => println!("Task completed"),
|
Ok(_) => info!("Task completed"),
|
||||||
Err(err) => println!("{}", err),
|
Err(err) => {
|
||||||
|
error!(%err, "Task error");
|
||||||
|
sentry_anyhow::capture_anyhow(&err);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub async fn check_and_mark(&self, event_id: u64) -> bool {
|
||||||
|
let mut action_handled_lock = self.actions_handled.lock().await;
|
||||||
|
|
||||||
|
!action_handled_lock.insert(event_id)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn unmark(&self, event_id: u64) {
|
||||||
|
let mut action_handled_lock = self.actions_handled.lock().await;
|
||||||
|
|
||||||
|
action_handled_lock.remove(&event_id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn make_actions_handled() -> Arc<Mutex<HashSet<u64>>> {
|
||||||
|
Arc::new(Mutex::new(HashSet::new()))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn check_and_mark(actions_handled: &Arc<Mutex<HashSet<u64>>>, event_id: u64) -> bool {
|
||||||
|
let mut lock = actions_handled.lock().await;
|
||||||
|
!lock.insert(event_id)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn unmark(actions_handled: &Arc<Mutex<HashSet<u64>>>, event_id: u64) {
|
||||||
|
let mut lock = actions_handled.lock().await;
|
||||||
|
lock.remove(&event_id);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn test_check_and_mark_first_call_returns_false() {
|
||||||
|
let actions_handled = make_actions_handled();
|
||||||
|
assert!(!check_and_mark(&actions_handled, 1).await);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn test_check_and_mark_second_call_returns_true() {
|
||||||
|
let actions_handled = make_actions_handled();
|
||||||
|
check_and_mark(&actions_handled, 1).await;
|
||||||
|
assert!(check_and_mark(&actions_handled, 1).await);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn test_check_and_mark_different_ids_are_independent() {
|
||||||
|
let actions_handled = make_actions_handled();
|
||||||
|
check_and_mark(&actions_handled, 1).await;
|
||||||
|
assert!(!check_and_mark(&actions_handled, 2).await);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn test_unmark_allows_reprocessing() {
|
||||||
|
let actions_handled = make_actions_handled();
|
||||||
|
check_and_mark(&actions_handled, 1).await;
|
||||||
|
unmark(&actions_handled, 1).await;
|
||||||
|
assert!(!check_and_mark(&actions_handled, 1).await);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn test_unmark_nonexistent_id_is_noop() {
|
||||||
|
let actions_handled = make_actions_handled();
|
||||||
|
unmark(&actions_handled, 99).await;
|
||||||
|
assert!(!check_and_mark(&actions_handled, 99).await);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn test_check_and_mark_concurrent_same_id() {
|
||||||
|
let actions_handled = make_actions_handled();
|
||||||
|
let actions_handled2 = Arc::clone(&actions_handled);
|
||||||
|
|
||||||
|
let t1 = tokio::spawn(async move { check_and_mark(&actions_handled, 42).await });
|
||||||
|
let t2 = tokio::spawn(async move { check_and_mark(&actions_handled2, 42).await });
|
||||||
|
|
||||||
|
let (r1, r2) = tokio::join!(t1, t2);
|
||||||
|
let results = [r1.unwrap(), r2.unwrap()];
|
||||||
|
|
||||||
|
// exactement un seul des deux doit retourner false (non traité)
|
||||||
|
assert_eq!(results.iter().filter(|&&r| !r).count(), 1);
|
||||||
|
// l'autre doit retourner true (déjà traité)
|
||||||
|
assert_eq!(results.iter().filter(|&&r| r).count(), 1);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+30
-17
@@ -1,22 +1,30 @@
|
|||||||
use futures_util::stream::TryStreamExt;
|
use futures_util::stream::TryStreamExt;
|
||||||
use tokio::io::AsyncReadExt;
|
use tokio::io::AsyncReadExt;
|
||||||
use tokio_util::io::StreamReader;
|
use tokio_util::io::StreamReader;
|
||||||
|
use tracing::instrument;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
bot::ReviewResult,
|
bot::ReviewResult,
|
||||||
consts::{BOT_PROCESS_MSG, MAX_DIFF_SIZE, REVIEW_PROMPT},
|
consts::{BOT_PROCESS_MSG, MAX_DIFF_SIZE, REVIEW_PROMPT},
|
||||||
errors::AppError,
|
|
||||||
gitea::{GiteaAPI, ReviewPayload},
|
gitea::{GiteaAPI, ReviewPayload},
|
||||||
open_router::OpenRouterClient,
|
open_router::OpenRouterClient,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
#[instrument(skip(gitea_api, open_router_client, http_client, review_payload))]
|
||||||
pub async fn exec_review(
|
pub async fn exec_review(
|
||||||
gitea_api: &GiteaAPI,
|
gitea_api: &GiteaAPI,
|
||||||
open_router_client: &OpenRouterClient,
|
open_router_client: &OpenRouterClient,
|
||||||
http_client: &reqwest::Client,
|
http_client: &reqwest::Client,
|
||||||
model: &str,
|
model: &str,
|
||||||
review_payload: ReviewPayload,
|
review_payload: ReviewPayload,
|
||||||
) -> Result<(), AppError> {
|
) -> anyhow::Result<()> {
|
||||||
|
tracing::info!(
|
||||||
|
repo = %review_payload.repository.full_name,
|
||||||
|
pr = review_payload.pull_request.number,
|
||||||
|
action = %review_payload.action,
|
||||||
|
"Starting review"
|
||||||
|
);
|
||||||
|
|
||||||
let new_comment = gitea_api
|
let new_comment = gitea_api
|
||||||
.comment(
|
.comment(
|
||||||
&BOT_PROCESS_MSG.replace("{model}", model),
|
&BOT_PROCESS_MSG.replace("{model}", model),
|
||||||
@@ -27,7 +35,7 @@ pub async fn exec_review(
|
|||||||
|
|
||||||
let bot_result: Result<ReviewResult, anyhow::Error> = async {
|
let bot_result: Result<ReviewResult, anyhow::Error> = async {
|
||||||
let git_diff =
|
let git_diff =
|
||||||
download_git_diff(&http_client, &review_payload.pull_request.diff_url).await?;
|
download_git_diff(http_client, &review_payload.pull_request.diff_url).await?;
|
||||||
|
|
||||||
let diff_for_llm = format_diff_for_review(&git_diff);
|
let diff_for_llm = format_diff_for_review(&git_diff);
|
||||||
|
|
||||||
@@ -41,9 +49,12 @@ pub async fn exec_review(
|
|||||||
|
|
||||||
review_result.cost = chat_result.cost;
|
review_result.cost = chat_result.cost;
|
||||||
|
|
||||||
|
let final_review_markdown = review_result_to_markdown(&review_result);
|
||||||
|
|
||||||
gitea_api
|
gitea_api
|
||||||
.post_pull_request_review(
|
.post_pull_request_review(
|
||||||
&review_result,
|
&review_result,
|
||||||
|
&final_review_markdown,
|
||||||
&review_payload.repository.full_name,
|
&review_payload.repository.full_name,
|
||||||
review_payload.pull_request.number,
|
review_payload.pull_request.number,
|
||||||
)
|
)
|
||||||
@@ -53,20 +64,22 @@ pub async fn exec_review(
|
|||||||
}
|
}
|
||||||
.await;
|
.await;
|
||||||
|
|
||||||
let edit_msg = match bot_result {
|
match bot_result {
|
||||||
Ok(bot_result) => review_result_to_markdown(&bot_result),
|
Ok(_) => {
|
||||||
Err(e) => format!("Error while reviewing: {}", e),
|
gitea_api
|
||||||
};
|
.delete_comment(&review_payload.repository.full_name, new_comment.id)
|
||||||
|
.await
|
||||||
gitea_api
|
}
|
||||||
.edit_comment(
|
Err(e) => {
|
||||||
&edit_msg,
|
gitea_api
|
||||||
&review_payload.repository.full_name,
|
.edit_comment(
|
||||||
new_comment.id,
|
&format!("Error while reviewing: {}", e),
|
||||||
)
|
&review_payload.repository.full_name,
|
||||||
.await?;
|
new_comment.id,
|
||||||
|
)
|
||||||
Ok(())
|
.await
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn review_result_to_markdown(review_result: &ReviewResult) -> String {
|
fn review_result_to_markdown(review_result: &ReviewResult) -> String {
|
||||||
|
|||||||
+38
-7
@@ -1,5 +1,4 @@
|
|||||||
use anyhow::anyhow;
|
use anyhow::anyhow;
|
||||||
use dotenvy::dotenv;
|
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct EnvConfig {
|
pub struct EnvConfig {
|
||||||
@@ -9,20 +8,20 @@ pub struct EnvConfig {
|
|||||||
pub open_router_model: String,
|
pub open_router_model: String,
|
||||||
pub open_router_timeout: u64,
|
pub open_router_timeout: u64,
|
||||||
pub bot_name: String,
|
pub bot_name: String,
|
||||||
|
pub bot_max_concurrent: usize,
|
||||||
pub gitea_url: String,
|
pub gitea_url: String,
|
||||||
pub gitea_token: String,
|
pub gitea_token: String,
|
||||||
pub gitea_timeout: u64,
|
pub gitea_timeout: u64,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn load_config() -> anyhow::Result<EnvConfig> {
|
pub fn load_config() -> anyhow::Result<EnvConfig> {
|
||||||
dotenv().ok();
|
|
||||||
|
|
||||||
let http_port = try_get_env("HTTP_PORT")?.parse()?;
|
let http_port = try_get_env("HTTP_PORT")?.parse()?;
|
||||||
let bot_name = try_get_env("BOT_NAME")?;
|
let bot_name = try_get_env("BOT_NAME")?;
|
||||||
let webhook_secret = try_get_env("WEBHOOK_SIG_HEADER_SECRET")?;
|
let webhook_secret = try_get_env("WEBHOOK_SIG_HEADER_SECRET")?;
|
||||||
let open_router_api_key = try_get_env("OPEN_ROUTER_API_KEY")?;
|
let open_router_api_key = try_get_env("OPEN_ROUTER_API_KEY")?;
|
||||||
let open_router_model = try_get_env("OPEN_ROUTER_MODEL")?;
|
let open_router_model = try_get_env("OPEN_ROUTER_MODEL")?;
|
||||||
let open_router_timeout = try_get_env("OPEN_ROUTER_TIMEOUT")?.parse()?;
|
let open_router_timeout = try_get_env("OPEN_ROUTER_TIMEOUT")?.parse()?;
|
||||||
|
let bot_max_concurrent = try_get_env("BOT_MAX_CONCURRENT")?.parse()?;
|
||||||
let gitea_url = try_get_env("GITEA_URL")?;
|
let gitea_url = try_get_env("GITEA_URL")?;
|
||||||
let gitea_token = try_get_env("GITEA_TOKEN")?;
|
let gitea_token = try_get_env("GITEA_TOKEN")?;
|
||||||
let gitea_timeout = try_get_env("GITEA_TIMEOUT")?.parse()?;
|
let gitea_timeout = try_get_env("GITEA_TIMEOUT")?.parse()?;
|
||||||
@@ -34,18 +33,50 @@ pub fn load_config() -> anyhow::Result<EnvConfig> {
|
|||||||
open_router_api_key,
|
open_router_api_key,
|
||||||
open_router_model,
|
open_router_model,
|
||||||
open_router_timeout,
|
open_router_timeout,
|
||||||
|
bot_max_concurrent,
|
||||||
gitea_url,
|
gitea_url,
|
||||||
gitea_token,
|
gitea_token,
|
||||||
gitea_timeout,
|
gitea_timeout,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
fn try_get_env(key: &str) -> anyhow::Result<String> {
|
pub fn try_get_env(key: &str) -> anyhow::Result<String> {
|
||||||
let env = std::env::var(key)?;
|
let env_value = std::env::var(key).map_err(|e| anyhow::anyhow!("{}: {}", key, e))?;
|
||||||
|
|
||||||
if env.trim().is_empty() {
|
if env_value.trim().is_empty() {
|
||||||
return Err(anyhow!(format!("env var {} is empty", key)));
|
return Err(anyhow!(format!("env var {} is empty", key)));
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(env)
|
Ok(env_value)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_try_get_env_returns_value() {
|
||||||
|
unsafe { std::env::set_var("TEST_ENV_PRESENT", "hello") };
|
||||||
|
assert_eq!(try_get_env("TEST_ENV_PRESENT").unwrap(), "hello");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_try_get_env_missing_var_returns_error() {
|
||||||
|
unsafe { std::env::remove_var("TEST_ENV_MISSING") };
|
||||||
|
assert!(try_get_env("TEST_ENV_MISSING").is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_try_get_env_empty_value_returns_error() {
|
||||||
|
unsafe { std::env::set_var("TEST_ENV_EMPTY", "") };
|
||||||
|
let err = try_get_env("TEST_ENV_EMPTY").unwrap_err();
|
||||||
|
assert!(err.to_string().contains("TEST_ENV_EMPTY"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_try_get_env_whitespace_only_returns_error() {
|
||||||
|
unsafe { std::env::set_var("TEST_ENV_WHITESPACE", " ") };
|
||||||
|
let err = try_get_env("TEST_ENV_WHITESPACE").unwrap_err();
|
||||||
|
assert!(err.to_string().contains("TEST_ENV_WHITESPACE"));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+22
-4
@@ -1,3 +1,4 @@
|
|||||||
|
use anyhow::anyhow;
|
||||||
use axum::response::IntoResponse;
|
use axum::response::IntoResponse;
|
||||||
use reqwest::StatusCode;
|
use reqwest::StatusCode;
|
||||||
|
|
||||||
@@ -21,6 +22,12 @@ pub enum AppError {
|
|||||||
#[error("WebHook have bad action")]
|
#[error("WebHook have bad action")]
|
||||||
InvalidActionErr,
|
InvalidActionErr,
|
||||||
|
|
||||||
|
#[error("Channel full")]
|
||||||
|
ChannelFullErr,
|
||||||
|
|
||||||
|
#[error("Already processed")]
|
||||||
|
AlreadyProcessedErr,
|
||||||
|
|
||||||
#[error(transparent)]
|
#[error(transparent)]
|
||||||
BadJsonStructErr(#[from] serde_json::Error),
|
BadJsonStructErr(#[from] serde_json::Error),
|
||||||
|
|
||||||
@@ -54,10 +61,21 @@ impl IntoResponse for AppError {
|
|||||||
StatusCode::UNAUTHORIZED,
|
StatusCode::UNAUTHORIZED,
|
||||||
"WebHook sig header is invalid".to_string(),
|
"WebHook sig header is invalid".to_string(),
|
||||||
),
|
),
|
||||||
AppError::Other(_) => (
|
AppError::AlreadyProcessedErr => (StatusCode::OK, "Already processed".to_string()),
|
||||||
StatusCode::INTERNAL_SERVER_ERROR,
|
AppError::ChannelFullErr => {
|
||||||
"Internal server error".to_string(),
|
sentry_anyhow::capture_anyhow(&anyhow!("Max concurrent tasks reached"));
|
||||||
),
|
(
|
||||||
|
StatusCode::SERVICE_UNAVAILABLE,
|
||||||
|
"Max concurrent tasks reached".to_string(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
AppError::Other(err) => {
|
||||||
|
sentry_anyhow::capture_anyhow(&err);
|
||||||
|
(
|
||||||
|
StatusCode::INTERNAL_SERVER_ERROR,
|
||||||
|
"Internal server error".to_string(),
|
||||||
|
)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
.into_response()
|
.into_response()
|
||||||
}
|
}
|
||||||
|
|||||||
+74
-19
@@ -2,12 +2,11 @@ use std::time::Duration;
|
|||||||
|
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
use serde_json::{Value, json};
|
use serde_json::{Value, json};
|
||||||
|
use tracing::instrument;
|
||||||
|
|
||||||
use crate::{
|
use crate::{bot::ReviewResult, errors::AppError};
|
||||||
bot::{ReviewItem, ReviewResult},
|
|
||||||
errors::AppError,
|
|
||||||
};
|
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
pub struct GiteaAPI {
|
pub struct GiteaAPI {
|
||||||
base_url: String,
|
base_url: String,
|
||||||
client: reqwest::Client,
|
client: reqwest::Client,
|
||||||
@@ -30,6 +29,7 @@ impl GiteaAPI {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[instrument(skip(self))]
|
||||||
pub async fn comment(
|
pub async fn comment(
|
||||||
&self,
|
&self,
|
||||||
body: &str,
|
body: &str,
|
||||||
@@ -57,6 +57,7 @@ impl GiteaAPI {
|
|||||||
res.json::<Comment>().await.map_err(anyhow::Error::from)
|
res.json::<Comment>().await.map_err(anyhow::Error::from)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[instrument(skip(self))]
|
||||||
pub async fn edit_comment(
|
pub async fn edit_comment(
|
||||||
&self,
|
&self,
|
||||||
body: &str,
|
body: &str,
|
||||||
@@ -84,9 +85,30 @@ impl GiteaAPI {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[instrument(skip(self))]
|
||||||
|
pub async fn delete_comment(&self, full_name: &str, comment_id: u64) -> anyhow::Result<()> {
|
||||||
|
let url = format!(
|
||||||
|
"{}/api/v1/repos/{}/issues/comments/{}",
|
||||||
|
self.base_url, full_name, comment_id
|
||||||
|
);
|
||||||
|
|
||||||
|
let res = self.client.delete(url).send().await?;
|
||||||
|
|
||||||
|
if !res.status().is_success() {
|
||||||
|
return Err(anyhow::anyhow!(
|
||||||
|
"Failed to delete comment: {}",
|
||||||
|
res.status()
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[instrument(skip(self, review_result))]
|
||||||
pub async fn post_pull_request_review(
|
pub async fn post_pull_request_review(
|
||||||
&self,
|
&self,
|
||||||
review_result: &ReviewResult,
|
review_result: &ReviewResult,
|
||||||
|
final_comment: &str,
|
||||||
full_name: &str,
|
full_name: &str,
|
||||||
index: u64,
|
index: u64,
|
||||||
) -> anyhow::Result<()> {
|
) -> anyhow::Result<()> {
|
||||||
@@ -95,7 +117,7 @@ impl GiteaAPI {
|
|||||||
self.base_url, full_name, index
|
self.base_url, full_name, index
|
||||||
);
|
);
|
||||||
|
|
||||||
let comments = &&review_result
|
let comments = &review_result
|
||||||
.reviews
|
.reviews
|
||||||
.iter()
|
.iter()
|
||||||
.filter(|r| r.line.is_some())
|
.filter(|r| r.line.is_some())
|
||||||
@@ -117,7 +139,7 @@ impl GiteaAPI {
|
|||||||
.post(url)
|
.post(url)
|
||||||
.json(&json!({
|
.json(&json!({
|
||||||
"event": "COMMENT",
|
"event": "COMMENT",
|
||||||
"body": review_result.comment,
|
"body": final_comment,
|
||||||
"comments": comments
|
"comments": comments
|
||||||
}))
|
}))
|
||||||
.send()
|
.send()
|
||||||
@@ -136,6 +158,14 @@ pub enum WebhookType {
|
|||||||
Review(ReviewPayload),
|
Review(ReviewPayload),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl WebhookType {
|
||||||
|
pub fn event_id(&self) -> u64 {
|
||||||
|
match self {
|
||||||
|
WebhookType::Review(payload) => payload.comment.id,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Deserialize, Debug)]
|
#[derive(Deserialize, Debug)]
|
||||||
pub struct ReviewPayload {
|
pub struct ReviewPayload {
|
||||||
pub action: String,
|
pub action: String,
|
||||||
@@ -176,14 +206,6 @@ impl WebhookType {
|
|||||||
_ => Err(AppError::UnknownEventErr),
|
_ => Err(AppError::UnknownEventErr),
|
||||||
}?;
|
}?;
|
||||||
|
|
||||||
let pr_body = match &wb {
|
|
||||||
WebhookType::Review(review_payload) => &review_payload.comment.body,
|
|
||||||
};
|
|
||||||
|
|
||||||
if !pr_body.starts_with(&format!("@{}", bot_name)) {
|
|
||||||
return Err(AppError::UnauthorizedUserErr);
|
|
||||||
}
|
|
||||||
|
|
||||||
let action = match &wb {
|
let action = match &wb {
|
||||||
WebhookType::Review(review_payload) => &review_payload.action,
|
WebhookType::Review(review_payload) => &review_payload.action,
|
||||||
};
|
};
|
||||||
@@ -192,6 +214,14 @@ impl WebhookType {
|
|||||||
return Err(AppError::InvalidActionErr);
|
return Err(AppError::InvalidActionErr);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let pr_body = match &wb {
|
||||||
|
WebhookType::Review(review_payload) => &review_payload.comment.body,
|
||||||
|
};
|
||||||
|
|
||||||
|
if !pr_body.starts_with(&format!("@{}", bot_name)) {
|
||||||
|
return Err(AppError::UnauthorizedUserErr);
|
||||||
|
}
|
||||||
|
|
||||||
Ok(wb)
|
Ok(wb)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -207,7 +237,12 @@ mod tests {
|
|||||||
"action": "created",
|
"action": "created",
|
||||||
"pull_request": {
|
"pull_request": {
|
||||||
"id": 42,
|
"id": 42,
|
||||||
"diff_url": "https://mydiff.fr"
|
"diff_url": "https://mydiff.fr",
|
||||||
|
"number": 1,
|
||||||
|
"title": "My PR"
|
||||||
|
},
|
||||||
|
"repository": {
|
||||||
|
"full_name": "owner/repo"
|
||||||
},
|
},
|
||||||
"comment": {
|
"comment": {
|
||||||
"id": 7,
|
"id": 7,
|
||||||
@@ -266,7 +301,12 @@ mod tests {
|
|||||||
"action": "edited",
|
"action": "edited",
|
||||||
"pull_request": {
|
"pull_request": {
|
||||||
"id": 1,
|
"id": 1,
|
||||||
"diff_url": "https://mydiff.fr"
|
"diff_url": "https://mydiff.fr",
|
||||||
|
"number": 1,
|
||||||
|
"title": "My PR"
|
||||||
|
},
|
||||||
|
"repository": {
|
||||||
|
"full_name": "owner/repo"
|
||||||
},
|
},
|
||||||
"comment": {
|
"comment": {
|
||||||
"id": 1,
|
"id": 1,
|
||||||
@@ -292,7 +332,12 @@ mod tests {
|
|||||||
"action": "created",
|
"action": "created",
|
||||||
"pull_request": {
|
"pull_request": {
|
||||||
"id": 99,
|
"id": 99,
|
||||||
"diff_url": "https://mydiff.fr"
|
"diff_url": "https://mydiff.fr",
|
||||||
|
"number": 5,
|
||||||
|
"title": "My PR"
|
||||||
|
},
|
||||||
|
"repository": {
|
||||||
|
"full_name": "owner/repo"
|
||||||
},
|
},
|
||||||
"comment": {
|
"comment": {
|
||||||
"id": 12,
|
"id": 12,
|
||||||
@@ -324,7 +369,12 @@ mod tests {
|
|||||||
"action": "created",
|
"action": "created",
|
||||||
"pull_request": {
|
"pull_request": {
|
||||||
"id": 1,
|
"id": 1,
|
||||||
"diff_url": "https://mydiff.fr"
|
"diff_url": "https://mydiff.fr",
|
||||||
|
"number": 1,
|
||||||
|
"title": "My PR"
|
||||||
|
},
|
||||||
|
"repository": {
|
||||||
|
"full_name": "owner/repo"
|
||||||
},
|
},
|
||||||
"comment": {
|
"comment": {
|
||||||
"id": 1,
|
"id": 1,
|
||||||
@@ -345,7 +395,12 @@ mod tests {
|
|||||||
"action": "created",
|
"action": "created",
|
||||||
"pull_request": {
|
"pull_request": {
|
||||||
"id": 1,
|
"id": 1,
|
||||||
"diff_url": "https://mydiff.fr"
|
"diff_url": "https://mydiff.fr",
|
||||||
|
"number": 1,
|
||||||
|
"title": "My PR"
|
||||||
|
},
|
||||||
|
"repository": {
|
||||||
|
"full_name": "owner/repo"
|
||||||
},
|
},
|
||||||
"comment": {
|
"comment": {
|
||||||
"id": 1,
|
"id": 1,
|
||||||
|
|||||||
+74
-5
@@ -1,5 +1,13 @@
|
|||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
use crate::{bot::Bot, gitea::WebhookType, state::AppState};
|
use crate::{bot::Bot, gitea::WebhookType, state::AppState};
|
||||||
|
|
||||||
|
use dotenvy::dotenv;
|
||||||
|
use tokio::signal::unix::{SignalKind, signal};
|
||||||
|
use tokio_util::sync::CancellationToken;
|
||||||
|
use tracing::{info, warn};
|
||||||
|
use tracing_subscriber::{EnvFilter, fmt, layer::SubscriberExt, util::SubscriberInitExt};
|
||||||
|
|
||||||
mod api;
|
mod api;
|
||||||
mod bot;
|
mod bot;
|
||||||
mod bot_actions;
|
mod bot_actions;
|
||||||
@@ -10,16 +18,77 @@ mod gitea;
|
|||||||
mod open_router;
|
mod open_router;
|
||||||
mod state;
|
mod state;
|
||||||
|
|
||||||
#[tokio::main]
|
fn main() -> anyhow::Result<()> {
|
||||||
async fn main() -> anyhow::Result<()> {
|
dotenv().ok();
|
||||||
|
|
||||||
|
tracing_subscriber::registry()
|
||||||
|
.with(fmt::layer())
|
||||||
|
.with(
|
||||||
|
EnvFilter::try_from_default_env() // lit RUST_LOG depuis l'env
|
||||||
|
.unwrap_or_else(|_| EnvFilter::new("info")),
|
||||||
|
)
|
||||||
|
.init();
|
||||||
|
|
||||||
|
let _sentry_guard = if let Ok(sentry_dsn) = env::try_get_env("SENTRY_DSN") {
|
||||||
|
info!("Initialize sentry");
|
||||||
|
|
||||||
|
Some(sentry::init((
|
||||||
|
sentry_dsn,
|
||||||
|
sentry::ClientOptions {
|
||||||
|
release: sentry::release_name!(),
|
||||||
|
send_default_pii: true,
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
)))
|
||||||
|
} else {
|
||||||
|
warn!("SENTRY_DSN not set, sentry will not be initialized");
|
||||||
|
None
|
||||||
|
};
|
||||||
|
|
||||||
|
tokio::runtime::Runtime::new()?.block_on(run())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn run() -> anyhow::Result<()> {
|
||||||
let config = env::load_config()?;
|
let config = env::load_config()?;
|
||||||
|
|
||||||
|
info!(
|
||||||
|
port = config.http_port,
|
||||||
|
model = %config.open_router_model,
|
||||||
|
gitea_url = %config.gitea_url,
|
||||||
|
bot_name = %config.bot_name,
|
||||||
|
"Starting Herald"
|
||||||
|
);
|
||||||
|
|
||||||
|
let shutdown = CancellationToken::new();
|
||||||
|
|
||||||
let bot = Bot::new(config.clone())?;
|
let bot = Bot::new(config.clone())?;
|
||||||
|
let (tx, rx) = tokio::sync::mpsc::channel::<WebhookType>(config.bot_max_concurrent * 2);
|
||||||
|
let app_state = AppState {
|
||||||
|
bot_tx: tx,
|
||||||
|
bot: bot.clone(),
|
||||||
|
config,
|
||||||
|
};
|
||||||
|
|
||||||
let (tx, rx) = tokio::sync::mpsc::channel::<WebhookType>(1);
|
let signal = async {
|
||||||
|
let mut sigterm = signal(SignalKind::terminate())?;
|
||||||
|
let mut sigint = signal(SignalKind::interrupt())?;
|
||||||
|
tokio::select! {
|
||||||
|
_ = sigterm.recv() => info!("Received SIGTERM"),
|
||||||
|
_ = sigint.recv() => info!("Received SIGINT"),
|
||||||
|
}
|
||||||
|
|
||||||
let app_state = AppState { bot_tx: tx, config };
|
info!("Shutting down...");
|
||||||
|
shutdown.cancel();
|
||||||
|
anyhow::Ok(())
|
||||||
|
};
|
||||||
|
|
||||||
tokio::try_join!(bot.start(rx), api::start(app_state))?;
|
tokio::try_join!(
|
||||||
|
bot.start(rx, shutdown.clone()),
|
||||||
|
api::start(app_state, shutdown.clone()),
|
||||||
|
signal
|
||||||
|
)?;
|
||||||
|
|
||||||
|
info!("Shutdown complete");
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|||||||
+4
-1
@@ -1,12 +1,14 @@
|
|||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
use openrouter_rs::{Message, api::chat::ChatCompletionRequest};
|
use openrouter_rs::{Message, api::chat::ChatCompletionRequest};
|
||||||
|
use tracing::instrument;
|
||||||
|
|
||||||
pub struct ChatResult {
|
pub struct ChatResult {
|
||||||
pub message: String,
|
pub message: String,
|
||||||
pub cost: Option<f64>,
|
pub cost: Option<f64>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
pub struct OpenRouterClient {
|
pub struct OpenRouterClient {
|
||||||
client: openrouter_rs::OpenRouterClient,
|
client: openrouter_rs::OpenRouterClient,
|
||||||
model: String,
|
model: String,
|
||||||
@@ -27,6 +29,7 @@ impl OpenRouterClient {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[instrument(skip(self), err)]
|
||||||
pub async fn chat(&self, msg: &str) -> anyhow::Result<ChatResult> {
|
pub async fn chat(&self, msg: &str) -> anyhow::Result<ChatResult> {
|
||||||
let request = ChatCompletionRequest::builder()
|
let request = ChatCompletionRequest::builder()
|
||||||
.model(&self.model)
|
.model(&self.model)
|
||||||
@@ -39,7 +42,7 @@ impl OpenRouterClient {
|
|||||||
Ok(ChatResult {
|
Ok(ChatResult {
|
||||||
message: response.choices[0]
|
message: response.choices[0]
|
||||||
.content()
|
.content()
|
||||||
.map(|msg| String::from(msg))
|
.map(String::from)
|
||||||
.ok_or(anyhow::anyhow!("No content"))?,
|
.ok_or(anyhow::anyhow!("No content"))?,
|
||||||
cost: response.usage.and_then(|u| u.cost),
|
cost: response.usage.and_then(|u| u.cost),
|
||||||
})
|
})
|
||||||
|
|||||||
+2
-1
@@ -1,7 +1,8 @@
|
|||||||
use crate::{env::EnvConfig, gitea::WebhookType};
|
use crate::{bot::Bot, env::EnvConfig, gitea::WebhookType};
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct AppState {
|
pub struct AppState {
|
||||||
pub bot_tx: tokio::sync::mpsc::Sender<WebhookType>,
|
pub bot_tx: tokio::sync::mpsc::Sender<WebhookType>,
|
||||||
|
pub bot: Bot,
|
||||||
pub config: EnvConfig,
|
pub config: EnvConfig,
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user