refactor: align project directory architecture

This commit is contained in:
leookun committed 2026-08-29 20:45:51 +08:00
1 parent 88f258f184
commit 279e6bb07c
236 files changed
+1982 -57487

No files matched your search

-56
View File
@@ -1,56 +0,0 @@
use std::sync::Arc;
use tokio_util::sync::CancellationToken;
use crate::{
client::{ClientCommand, ClientPort},
model::PreparedRun,
provider::Provider,
store::Store,
};
use super::{RunEngine, RunOutcome, RunRegistry};
#[derive(Clone)]
pub struct RunActor {
store: Store,
provider: Arc<dyn Provider>,
registry: RunRegistry,
}
impl RunActor {
pub fn new(store: Store, provider: Arc<dyn Provider>, registry: RunRegistry) -> Self {
Self {
store,
provider,
registry,
}
}
pub async fn spawn(
&self,
prepared: PreparedRun,
client: ClientPort,
commands: tokio::sync::mpsc::Sender<ClientCommand>,
cancellation: CancellationToken,
) -> tokio::task::JoinHandle<RunOutcome> {
let run_id = prepared.run_id.clone();
let conversation_id = prepared.conversation_id.clone();
self.registry
.activate(
conversation_id.clone(),
run_id.clone(),
cancellation.clone(),
commands,
)
.await;
let actor = self.clone();
tokio::spawn(async move {
let outcome = RunEngine::new(actor.store, actor.provider)
.run(prepared, client, cancellation)
.await;
actor.registry.release(&conversation_id, &run_id).await;
outcome
})
}
}
+4 -5
View File
@@ -4,10 +4,6 @@ use std::sync::Arc;
use tokio_util::sync::CancellationToken;
use crate::{
client::{
ClientCommand, ClientEvent, ClientPort, CommitBarrier, CommitCause, MessageInsertion,
StateCommitted,
},
model::{
CanonicalMessage, MessageContent, Origin, PreparedRun, Role, RunAction, ToolRoundAssistant,
ToolRoundId, Usage,
@@ -16,7 +12,10 @@ use crate::{
store::{RunStatus, Store},
};
use super::{consume_model_cycle, ModelCycleFailure, RunFailure, RunOutcome};
use super::{
consume_model_cycle, ClientCommand, ClientEvent, ClientPort, CommitBarrier, CommitCause,
MessageInsertion, ModelCycleFailure, RunFailure, RunOutcome, StateCommitted,
};
const COMPACTION_RESERVE_TOKENS: u64 = 10_000;
const COMPACTION_OUTPUT_TOKENS: u64 = 4_096;
-45
View File
@@ -1,45 +0,0 @@
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum RunFailure {
Protocol(String),
Provider(String),
Store(String),
Client(String),
}
impl RunFailure {
pub fn category(&self) -> &'static str {
match self {
Self::Protocol(_) => "protocol",
Self::Provider(_) => "provider",
Self::Store(_) => "store",
Self::Client(_) => "client",
}
}
}
impl From<crate::Error> for RunFailure {
fn from(error: crate::Error) -> Self {
use crate::Error;
match error {
Error::Protocol(message) | Error::Config(message) => Self::Protocol(message),
Error::Provider(message) => Self::Provider(message),
Error::Store(message) => Self::Store(message),
Error::Cancelled => Self::Client("run was cancelled".into()),
Error::Http(error) => Self::Provider(error.to_string()),
Error::Database(error) => Self::Store(error.to_string()),
Error::Migration(error) => Self::Store(error.to_string()),
Error::Io(error) => Self::Store(error.to_string()),
Error::Decode(error) => Self::Protocol(error.to_string()),
Error::Encode(error) => Self::Protocol(error.to_string()),
Error::Json(error) => Self::Protocol(error.to_string()),
Error::RunNotFound(run_id) => Self::Store(format!("run not found: {run_id}")),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum RunOutcome {
Completed,
Cancelled,
Failed(RunFailure),
}
+4 -6
View File
@@ -1,12 +1,10 @@
mod actor;
mod engine;
mod lifecycle;
mod model_cycle;
mod registry;
mod port;
mod runtime;
mod tool_round;
pub use actor::*;
pub use engine::*;
pub use lifecycle::*;
pub use model_cycle::*;
pub use registry::*;
pub use port::*;
pub use runtime::*;
+1 -2
View File
@@ -5,12 +5,11 @@ use tokio::sync::mpsc;
use tokio_util::sync::CancellationToken;
use crate::{
client::ClientEvent,
model::{ProviderReplayState, ToolCall, Usage},
provider::{FinishReason, ModelEvent, ProviderStream},
};
use super::RunFailure;
use super::{ClientEvent, RunFailure};
#[derive(Clone, Debug, PartialEq)]
pub struct ModelCycleResult {
+125
View File
@@ -0,0 +1,125 @@
use std::time::Duration;
use tokio::sync::{mpsc, oneshot};
use crate::model::{
CanonicalMessage, RevisionId, RuntimeEvent, ToolCall, ToolResult, ToolRoundId, Usage,
};
use super::RunOutcome;
#[derive(Debug)]
pub struct MessageInsertion {
pub messages: Vec<CanonicalMessage>,
pub delivered: oneshot::Sender<()>,
}
#[derive(Debug)]
pub enum ClientCommand {
ToolResult(ToolResult),
InterruptWithMessage(CanonicalMessage),
RuntimeEvent(RuntimeEvent),
InsertMessages(MessageInsertion),
ClientClosed { error: String },
Cancel,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum CommitCause {
InitialMessages,
ToolRoundStarted(ToolRoundId),
ToolResult { call_id: String, interrupted: bool },
FinalTurn,
Compaction { summary: String },
RuntimeEvent { event_id: String },
}
#[derive(Debug)]
pub enum CommitBarrier {
None,
BeforeContinue(oneshot::Sender<std::result::Result<(), String>>),
}
impl CommitBarrier {
pub fn before_continue() -> (Self, oneshot::Receiver<std::result::Result<(), String>>) {
let (sender, receiver) = oneshot::channel();
(Self::BeforeContinue(sender), receiver)
}
pub fn is_required(&self) -> bool {
matches!(self, Self::BeforeContinue(_))
}
pub fn complete(self, result: std::result::Result<(), String>) {
if let Self::BeforeContinue(sender) = self {
let _ = sender.send(result);
}
}
}
#[derive(Debug)]
pub struct StateCommitted {
pub revision_id: RevisionId,
pub tool_round_version: u64,
pub cause: CommitCause,
pub barrier: CommitBarrier,
}
#[derive(Debug)]
pub enum ClientEvent {
AutoCompactionStarted,
AutoCompactionCompleted,
TextStart,
TextDelta(String),
TextEnd,
ThinkingStart,
ThinkingDelta(String),
ThinkingEnd {
duration: Duration,
},
ToolCallStart {
index: usize,
call_id: String,
name: String,
model_call_id: String,
},
ToolCallArgumentsDelta {
index: usize,
delta: String,
},
ToolCallEnd {
index: usize,
},
Usage(Usage),
ExecuteToolRound {
round_id: ToolRoundId,
calls: Vec<ToolCall>,
},
StateCommitted(StateCommitted),
Ended(RunOutcome),
}
pub struct ClientPort {
pub commands: mpsc::Receiver<ClientCommand>,
pub events: mpsc::Sender<ClientEvent>,
}
pub struct ClientSession {
pub commands: mpsc::Sender<ClientCommand>,
pub events: mpsc::Receiver<ClientEvent>,
}
pub fn session(capacity: usize) -> (ClientPort, ClientSession) {
let (commands_tx, commands_rx) = mpsc::channel(capacity);
let (events_tx, events_rx) = mpsc::channel(capacity);
(
ClientPort {
commands: commands_rx,
events: events_tx,
},
ClientSession {
commands: commands_tx,
events: events_rx,
},
)
}
-90
View File
@@ -1,90 +0,0 @@
use std::{collections::HashMap, sync::Arc};
use tokio::sync::Mutex;
use tokio_util::sync::CancellationToken;
use crate::{
client::{ClientCommand, MessageInsertion},
model::{CanonicalMessage, ConversationId, RunId},
};
#[derive(Clone, Default)]
pub struct RunRegistry {
active: Arc<Mutex<HashMap<ConversationId, ActiveRun>>>,
}
struct ActiveRun {
run_id: RunId,
cancellation: CancellationToken,
commands: tokio::sync::mpsc::Sender<ClientCommand>,
}
impl RunRegistry {
pub async fn activate(
&self,
conversation_id: ConversationId,
run_id: RunId,
cancellation: CancellationToken,
commands: tokio::sync::mpsc::Sender<ClientCommand>,
) {
let previous = self.active.lock().await.insert(
conversation_id,
ActiveRun {
run_id: run_id.clone(),
cancellation,
commands,
},
);
if let Some(previous) = previous.filter(|previous| previous.run_id != run_id) {
previous.cancellation.cancel();
}
}
pub async fn insert_messages(
&self,
conversation_id: &ConversationId,
messages: Vec<CanonicalMessage>,
) -> bool {
if messages.is_empty() {
return true;
}
let commands = self
.active
.lock()
.await
.get(conversation_id)
.map(|run| run.commands.clone());
let Some(commands) = commands else {
return false;
};
let (delivered, delivery) = tokio::sync::oneshot::channel();
if commands
.send(ClientCommand::InsertMessages(MessageInsertion {
messages,
delivered,
}))
.await
.is_err()
{
return false;
}
delivery.await.is_ok()
}
pub async fn release(&self, conversation_id: &ConversationId, run_id: &RunId) {
let mut active = self.active.lock().await;
if active
.get(conversation_id)
.is_some_and(|current| &current.run_id == run_id)
{
active.remove(conversation_id);
}
}
pub async fn shutdown(&self) {
let active = std::mem::take(&mut *self.active.lock().await);
for run in active.into_values() {
run.cancellation.cancel();
}
}
}
+183
View File
@@ -0,0 +1,183 @@
use std::{collections::HashMap, sync::Arc};
use tokio::sync::Mutex;
use tokio_util::sync::CancellationToken;
use crate::{
model::{CanonicalMessage, ConversationId, PreparedRun, RunId},
provider::Provider,
store::Store,
};
use super::{ClientCommand, ClientPort, MessageInsertion, RunEngine};
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum RunFailure {
Protocol(String),
Provider(String),
Store(String),
Client(String),
}
impl RunFailure {
pub fn category(&self) -> &'static str {
match self {
Self::Protocol(_) => "protocol",
Self::Provider(_) => "provider",
Self::Store(_) => "store",
Self::Client(_) => "client",
}
}
}
impl From<crate::Error> for RunFailure {
fn from(error: crate::Error) -> Self {
use crate::Error;
match error {
Error::Protocol(message) | Error::Config(message) => Self::Protocol(message),
Error::Provider(message) => Self::Provider(message),
Error::Store(message) => Self::Store(message),
Error::Cancelled => Self::Client("run was cancelled".into()),
Error::Http(error) => Self::Provider(error.to_string()),
Error::Database(error) => Self::Store(error.to_string()),
Error::Migration(error) => Self::Store(error.to_string()),
Error::Io(error) => Self::Store(error.to_string()),
Error::Decode(error) => Self::Protocol(error.to_string()),
Error::Encode(error) => Self::Protocol(error.to_string()),
Error::Json(error) => Self::Protocol(error.to_string()),
Error::RunNotFound(run_id) => Self::Store(format!("run not found: {run_id}")),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum RunOutcome {
Completed,
Cancelled,
Failed(RunFailure),
}
#[derive(Clone, Default)]
pub struct RunRegistry {
active: Arc<Mutex<HashMap<ConversationId, ActiveRun>>>,
}
struct ActiveRun {
run_id: RunId,
cancellation: CancellationToken,
commands: tokio::sync::mpsc::Sender<ClientCommand>,
}
impl RunRegistry {
pub async fn activate(
&self,
conversation_id: ConversationId,
run_id: RunId,
cancellation: CancellationToken,
commands: tokio::sync::mpsc::Sender<ClientCommand>,
) {
let previous = self.active.lock().await.insert(
conversation_id,
ActiveRun {
run_id: run_id.clone(),
cancellation,
commands,
},
);
if let Some(previous) = previous.filter(|previous| previous.run_id != run_id) {
previous.cancellation.cancel();
}
}
pub async fn insert_messages(
&self,
conversation_id: &ConversationId,
messages: Vec<CanonicalMessage>,
) -> bool {
if messages.is_empty() {
return true;
}
let commands = self
.active
.lock()
.await
.get(conversation_id)
.map(|run| run.commands.clone());
let Some(commands) = commands else {
return false;
};
let (delivered, delivery) = tokio::sync::oneshot::channel();
if commands
.send(ClientCommand::InsertMessages(MessageInsertion {
messages,
delivered,
}))
.await
.is_err()
{
return false;
}
delivery.await.is_ok()
}
pub async fn release(&self, conversation_id: &ConversationId, run_id: &RunId) {
let mut active = self.active.lock().await;
if active
.get(conversation_id)
.is_some_and(|current| &current.run_id == run_id)
{
active.remove(conversation_id);
}
}
pub async fn shutdown(&self) {
let active = std::mem::take(&mut *self.active.lock().await);
for run in active.into_values() {
run.cancellation.cancel();
}
}
}
#[derive(Clone)]
pub struct RunActor {
store: Store,
provider: Arc<dyn Provider>,
registry: RunRegistry,
}
impl RunActor {
pub fn new(store: Store, provider: Arc<dyn Provider>, registry: RunRegistry) -> Self {
Self {
store,
provider,
registry,
}
}
pub async fn spawn(
&self,
prepared: PreparedRun,
client: ClientPort,
commands: tokio::sync::mpsc::Sender<ClientCommand>,
cancellation: CancellationToken,
) -> tokio::task::JoinHandle<RunOutcome> {
let run_id = prepared.run_id.clone();
let conversation_id = prepared.conversation_id.clone();
self.registry
.activate(
conversation_id.clone(),
run_id.clone(),
cancellation.clone(),
commands,
)
.await;
let actor = self.clone();
tokio::spawn(async move {
let outcome = RunEngine::new(actor.store, actor.provider)
.run(prepared, client, cancellation)
.await;
actor.registry.release(&conversation_id, &run_id).await;
outcome
})
}
}
+4 -5
View File
@@ -3,15 +3,14 @@ use std::collections::HashSet;
use tokio_util::sync::CancellationToken;
use crate::{
client::{
ClientCommand, ClientEvent, ClientPort, CommitBarrier, CommitCause, MessageInsertion,
StateCommitted,
},
model::{PreparedRun, RevisionId, ToolCall, ToolResult, ToolRoundAssistant, ToolRoundId},
store::Store,
};
use super::{RunFailure, RunOutcome};
use super::{
ClientCommand, ClientEvent, ClientPort, CommitBarrier, CommitCause, MessageInsertion,
RunFailure, RunOutcome, StateCommitted,
};
pub(super) struct ToolRound {
pub id: ToolRoundId,