server: route Ticket mutation notifications
This commit is contained in:
@@ -20,27 +20,25 @@ use schemars::JsonSchema;
|
||||
use serde::de::DeserializeOwned;
|
||||
use serde_json::json;
|
||||
|
||||
use crate::worker::WorkspaceClient;
|
||||
use crate::worker::{
|
||||
WorkspaceClient, WorkspaceClientError, WorkspaceRequest, WorkspaceRequestMethod,
|
||||
};
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct WorkspaceHttpMemoryBackend {
|
||||
workspace_id: String,
|
||||
base_url: String,
|
||||
client: Arc<dyn WorkspaceClient>,
|
||||
}
|
||||
|
||||
impl WorkspaceHttpMemoryBackend {
|
||||
pub fn new(workspace_id: impl Into<String>, base_url: impl Into<String>) -> Self {
|
||||
Self {
|
||||
workspace_id: workspace_id.into(),
|
||||
base_url: base_url.into(),
|
||||
}
|
||||
pub fn new(client: Arc<dyn WorkspaceClient>) -> Self {
|
||||
Self { client }
|
||||
}
|
||||
|
||||
pub async fn execute_operation(
|
||||
&self,
|
||||
operation: MemoryBackendOperation,
|
||||
) -> Result<MemoryBackendOperationResult, WorkspaceMemoryBackendError> {
|
||||
execute_http_memory_backend(&self.workspace_id, &self.base_url, operation).await
|
||||
execute_memory_backend(self.client.as_ref(), operation).await
|
||||
}
|
||||
|
||||
async fn execute(&self, operation: MemoryBackendOperation) -> Result<ToolOutput, ToolError> {
|
||||
@@ -59,7 +57,7 @@ pub enum WorkspaceMemoryBackendError {
|
||||
#[error("workspace memory backend is unavailable: {reason}")]
|
||||
Unavailable { reason: String },
|
||||
#[error("workspace memory backend request failed: {0}")]
|
||||
Request(#[from] reqwest::Error),
|
||||
Request(#[from] WorkspaceClientError),
|
||||
#[error("workspace memory backend returned HTTP {status}: {body}")]
|
||||
Http {
|
||||
status: reqwest::StatusCode,
|
||||
@@ -71,73 +69,49 @@ pub enum WorkspaceMemoryBackendError {
|
||||
Backend(String),
|
||||
}
|
||||
|
||||
impl WorkspaceClient {
|
||||
impl dyn WorkspaceClient + '_ {
|
||||
pub async fn execute_memory_backend_operation(
|
||||
&self,
|
||||
operation: MemoryBackendOperation,
|
||||
) -> Result<MemoryBackendOperationResult, WorkspaceMemoryBackendError> {
|
||||
match self {
|
||||
WorkspaceClient::Http {
|
||||
workspace_id,
|
||||
base_url,
|
||||
} => execute_http_memory_backend(workspace_id, base_url, operation).await,
|
||||
WorkspaceClient::Available { kind } => Err(WorkspaceMemoryBackendError::Unavailable {
|
||||
reason: format!(
|
||||
"workspace client kind `{kind}` does not expose the Backend Workspace API"
|
||||
),
|
||||
}),
|
||||
WorkspaceClient::Unavailable { reason } => {
|
||||
Err(WorkspaceMemoryBackendError::Unavailable {
|
||||
reason: reason.clone(),
|
||||
})
|
||||
}
|
||||
}
|
||||
execute_memory_backend(self, operation).await
|
||||
}
|
||||
|
||||
pub async fn request_memory_staging_consolidation(
|
||||
&self,
|
||||
operation: MemoryConsolidateStagingOperation,
|
||||
) -> Result<MemoryConsolidationOutput, WorkspaceMemoryBackendError> {
|
||||
match self {
|
||||
WorkspaceClient::Http {
|
||||
workspace_id,
|
||||
base_url,
|
||||
} => execute_http_memory_consolidation(workspace_id, base_url, operation).await,
|
||||
WorkspaceClient::Available { kind } => Err(WorkspaceMemoryBackendError::Unavailable {
|
||||
reason: format!(
|
||||
"workspace client kind `{kind}` does not expose the Backend Workspace API"
|
||||
),
|
||||
}),
|
||||
WorkspaceClient::Unavailable { reason } => {
|
||||
Err(WorkspaceMemoryBackendError::Unavailable {
|
||||
reason: reason.clone(),
|
||||
})
|
||||
}
|
||||
}
|
||||
execute_memory_consolidation(self, operation).await
|
||||
}
|
||||
}
|
||||
|
||||
async fn execute_http_memory_backend(
|
||||
workspace_id: &str,
|
||||
base_url: &str,
|
||||
async fn execute_memory_backend(
|
||||
client: &dyn WorkspaceClient,
|
||||
operation: MemoryBackendOperation,
|
||||
) -> Result<MemoryBackendOperationResult, WorkspaceMemoryBackendError> {
|
||||
let url = format!(
|
||||
"{}/api/w/{}/memory/backend",
|
||||
base_url.trim_end_matches('/'),
|
||||
workspace_id
|
||||
);
|
||||
let response = reqwest::Client::new()
|
||||
.post(url)
|
||||
.json(&operation)
|
||||
.send()
|
||||
.await?;
|
||||
let status = response.status();
|
||||
let body = response.text().await?;
|
||||
if !status.is_success() {
|
||||
return Err(WorkspaceMemoryBackendError::Http { status, body });
|
||||
let workspace_id =
|
||||
client
|
||||
.workspace_id()
|
||||
.ok_or_else(|| WorkspaceMemoryBackendError::Unavailable {
|
||||
reason: format!(
|
||||
"workspace client kind `{}` has no workspace id",
|
||||
client.kind()
|
||||
),
|
||||
})?;
|
||||
let response = client.execute(WorkspaceRequest::json(
|
||||
WorkspaceRequestMethod::Post,
|
||||
format!("/api/w/{workspace_id}/memory/backend"),
|
||||
serde_json::to_string(&operation)?,
|
||||
))?;
|
||||
let status = reqwest::StatusCode::from_u16(response.status)
|
||||
.unwrap_or(reqwest::StatusCode::INTERNAL_SERVER_ERROR);
|
||||
if !response.is_success() {
|
||||
return Err(WorkspaceMemoryBackendError::Http {
|
||||
status,
|
||||
body: response.body,
|
||||
});
|
||||
}
|
||||
match serde_json::from_str::<MemoryBackendHttpResponse>(&body)? {
|
||||
match serde_json::from_str::<MemoryBackendHttpResponse>(&response.body)? {
|
||||
MemoryBackendHttpResponse::Ok { result } => Ok(result),
|
||||
MemoryBackendHttpResponse::Error { message } => {
|
||||
Err(WorkspaceMemoryBackendError::Backend(message))
|
||||
@@ -145,34 +119,37 @@ async fn execute_http_memory_backend(
|
||||
}
|
||||
}
|
||||
|
||||
async fn execute_http_memory_consolidation(
|
||||
workspace_id: &str,
|
||||
base_url: &str,
|
||||
async fn execute_memory_consolidation(
|
||||
client: &dyn WorkspaceClient,
|
||||
operation: MemoryConsolidateStagingOperation,
|
||||
) -> Result<MemoryConsolidationOutput, WorkspaceMemoryBackendError> {
|
||||
let url = format!(
|
||||
"{}/api/w/{}/memory/consolidation",
|
||||
base_url.trim_end_matches('/'),
|
||||
workspace_id
|
||||
);
|
||||
let response = reqwest::Client::new()
|
||||
.post(url)
|
||||
.json(&operation)
|
||||
.send()
|
||||
.await?;
|
||||
let status = response.status();
|
||||
let body = response.text().await?;
|
||||
if !status.is_success() {
|
||||
return Err(WorkspaceMemoryBackendError::Http { status, body });
|
||||
let workspace_id =
|
||||
client
|
||||
.workspace_id()
|
||||
.ok_or_else(|| WorkspaceMemoryBackendError::Unavailable {
|
||||
reason: format!(
|
||||
"workspace client kind `{}` has no workspace id",
|
||||
client.kind()
|
||||
),
|
||||
})?;
|
||||
let response = client.execute(WorkspaceRequest::json(
|
||||
WorkspaceRequestMethod::Post,
|
||||
format!("/api/w/{workspace_id}/memory/consolidation"),
|
||||
serde_json::to_string(&operation)?,
|
||||
))?;
|
||||
let status = reqwest::StatusCode::from_u16(response.status)
|
||||
.unwrap_or(reqwest::StatusCode::INTERNAL_SERVER_ERROR);
|
||||
if !response.is_success() {
|
||||
return Err(WorkspaceMemoryBackendError::Http {
|
||||
status,
|
||||
body: response.body,
|
||||
});
|
||||
}
|
||||
serde_json::from_str::<MemoryConsolidationOutput>(&body).map_err(Into::into)
|
||||
serde_json::from_str::<MemoryConsolidationOutput>(&response.body).map_err(Into::into)
|
||||
}
|
||||
|
||||
pub fn workspace_http_memory_tools(
|
||||
workspace_id: impl Into<String>,
|
||||
base_url: impl Into<String>,
|
||||
) -> Vec<ToolDefinition> {
|
||||
let backend = WorkspaceHttpMemoryBackend::new(workspace_id, base_url);
|
||||
pub fn workspace_http_memory_tools(client: Arc<dyn WorkspaceClient>) -> Vec<ToolDefinition> {
|
||||
let backend = WorkspaceHttpMemoryBackend::new(client);
|
||||
vec![
|
||||
memory_tool(
|
||||
"MemoryReadDocument",
|
||||
@@ -215,13 +192,10 @@ pub fn workspace_http_memory_tools(
|
||||
}
|
||||
|
||||
pub fn workspace_http_memory_consolidation_tools(
|
||||
workspace_id: impl Into<String>,
|
||||
base_url: impl Into<String>,
|
||||
client: Arc<dyn WorkspaceClient>,
|
||||
) -> Vec<ToolDefinition> {
|
||||
let workspace_id = workspace_id.into();
|
||||
let base_url = base_url.into();
|
||||
let mut tools = workspace_http_memory_tools(workspace_id.clone(), base_url.clone());
|
||||
let backend = WorkspaceHttpMemoryBackend::new(workspace_id, base_url);
|
||||
let mut tools = workspace_http_memory_tools(client.clone());
|
||||
let backend = WorkspaceHttpMemoryBackend::new(client);
|
||||
tools.extend([
|
||||
memory_tool(
|
||||
"MemoryStagingList",
|
||||
@@ -370,6 +344,14 @@ mod tests {
|
||||
use super::*;
|
||||
use llm_engine::tool::ToolDefinition;
|
||||
|
||||
fn test_client() -> Arc<dyn WorkspaceClient> {
|
||||
Arc::new(crate::worker::RuntimeWorkspaceHttpClient::new(
|
||||
"workspace",
|
||||
"http://backend",
|
||||
"test-worker",
|
||||
))
|
||||
}
|
||||
|
||||
fn tool_names(definitions: Vec<ToolDefinition>) -> Vec<String> {
|
||||
let mut names = definitions
|
||||
.into_iter()
|
||||
@@ -390,10 +372,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn normal_workspace_memory_tools_do_not_include_staging_tools() {
|
||||
let names = tool_names(workspace_http_memory_tools(
|
||||
"workspace".to_string(),
|
||||
"http://backend".to_string(),
|
||||
));
|
||||
let names = tool_names(workspace_http_memory_tools(test_client()));
|
||||
|
||||
assert!(names.contains(&"MemoryQuery".to_string()));
|
||||
assert!(names.contains(&"MemoryReadDocument".to_string()));
|
||||
@@ -410,7 +389,7 @@ mod tests {
|
||||
#[test]
|
||||
fn document_update_schema_is_edit_like_and_staging_close_has_no_legacy_kinds() {
|
||||
let update_schema = tool_meta(
|
||||
workspace_http_memory_tools("workspace".to_string(), "http://backend".to_string()),
|
||||
workspace_http_memory_tools(test_client()),
|
||||
"MemoryUpdateDocument",
|
||||
);
|
||||
assert_eq!(
|
||||
@@ -423,10 +402,7 @@ mod tests {
|
||||
assert!(update_schema["properties"].get("body_md").is_none());
|
||||
|
||||
let close_schema_text = tool_meta(
|
||||
workspace_http_memory_consolidation_tools(
|
||||
"workspace".to_string(),
|
||||
"http://backend".to_string(),
|
||||
),
|
||||
workspace_http_memory_consolidation_tools(test_client()),
|
||||
"MemoryStagingClose",
|
||||
)
|
||||
.to_string();
|
||||
@@ -440,10 +416,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn consolidation_workspace_memory_tools_include_staging_tools() {
|
||||
let names = tool_names(workspace_http_memory_consolidation_tools(
|
||||
"workspace".to_string(),
|
||||
"http://backend".to_string(),
|
||||
));
|
||||
let names = tool_names(workspace_http_memory_consolidation_tools(test_client()));
|
||||
|
||||
assert!(names.contains(&"MemoryQuery".to_string()));
|
||||
assert!(names.contains(&"MemoryReadDocument".to_string()));
|
||||
|
||||
@@ -14,26 +14,27 @@ use llm_engine::tool::{
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::json;
|
||||
|
||||
use crate::worker::{WorkspaceClient, WorkspaceRequest, WorkspaceRequestMethod};
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct WorkspaceHttpObjectiveBackend {
|
||||
workspace_id: String,
|
||||
base_url: String,
|
||||
client: Arc<dyn WorkspaceClient>,
|
||||
}
|
||||
|
||||
impl WorkspaceHttpObjectiveBackend {
|
||||
pub fn new(workspace_id: impl Into<String>, base_url: impl Into<String>) -> Self {
|
||||
Self {
|
||||
workspace_id: workspace_id.into(),
|
||||
base_url: base_url.into().trim_end_matches('/').to_string(),
|
||||
}
|
||||
pub fn new(client: Arc<dyn WorkspaceClient>) -> Self {
|
||||
Self { client }
|
||||
}
|
||||
|
||||
async fn list(&self, input: ObjectiveListInput) -> Result<ToolOutput, ToolError> {
|
||||
let mut url = format!("{}/api/w/{}/objectives", self.base_url, self.workspace_id);
|
||||
let mut url = format!(
|
||||
"/api/w/{}/objectives",
|
||||
self.client.workspace_id().unwrap_or_default()
|
||||
);
|
||||
if let Some(limit) = input.limit {
|
||||
url.push_str(&format!("?limit={}", limit.min(1000)));
|
||||
}
|
||||
let response = get_json::<ObjectiveListResponse>(&url)
|
||||
let response = get_json::<ObjectiveListResponse>(self.client.as_ref(), &url)
|
||||
.await
|
||||
.map_err(backend_error)?;
|
||||
let count = response.items.len();
|
||||
@@ -46,7 +47,7 @@ impl WorkspaceHttpObjectiveBackend {
|
||||
async fn show(&self, input: ObjectiveShowInput) -> Result<ToolOutput, ToolError> {
|
||||
let id = validate_id(&input.id, "ObjectiveShow")?;
|
||||
let url = self.objective_url(id);
|
||||
let response = get_json::<ObjectiveDetail>(&url)
|
||||
let response = get_json::<ObjectiveDetail>(self.client.as_ref(), &url)
|
||||
.await
|
||||
.map_err(backend_error)?;
|
||||
Ok(objective_output(
|
||||
@@ -61,11 +62,18 @@ impl WorkspaceHttpObjectiveBackend {
|
||||
"ObjectiveCreate requires non-empty title".to_string(),
|
||||
));
|
||||
}
|
||||
let url = format!("{}/api/w/{}/objectives", self.base_url, self.workspace_id);
|
||||
let response =
|
||||
send_json::<ObjectiveCreateInput, ObjectiveDetail>(reqwest::Method::POST, &url, &input)
|
||||
.await
|
||||
.map_err(backend_error)?;
|
||||
let url = format!(
|
||||
"/api/w/{}/objectives",
|
||||
self.client.workspace_id().unwrap_or_default()
|
||||
);
|
||||
let response = send_json::<ObjectiveCreateInput, ObjectiveDetail>(
|
||||
self.client.as_ref(),
|
||||
reqwest::Method::POST,
|
||||
&url,
|
||||
&input,
|
||||
)
|
||||
.await
|
||||
.map_err(backend_error)?;
|
||||
Ok(objective_output(
|
||||
format!("Created objective {}", response.id),
|
||||
response,
|
||||
@@ -86,10 +94,14 @@ impl WorkspaceHttpObjectiveBackend {
|
||||
new_string: input.new_string,
|
||||
replace_all: input.replace_all,
|
||||
};
|
||||
let response =
|
||||
send_json::<ObjectiveEditRequest, ObjectiveDetail>(reqwest::Method::PATCH, &url, &body)
|
||||
.await
|
||||
.map_err(backend_error)?;
|
||||
let response = send_json::<ObjectiveEditRequest, ObjectiveDetail>(
|
||||
self.client.as_ref(),
|
||||
reqwest::Method::PATCH,
|
||||
&url,
|
||||
&body,
|
||||
)
|
||||
.await
|
||||
.map_err(backend_error)?;
|
||||
Ok(objective_output(
|
||||
format!("Edited objective {}", response.id),
|
||||
response,
|
||||
@@ -105,6 +117,7 @@ impl WorkspaceHttpObjectiveBackend {
|
||||
}
|
||||
let url = format!("{}/state", self.objective_url(id));
|
||||
let response = send_json::<ObjectiveSetStateRequest, ObjectiveDetail>(
|
||||
self.client.as_ref(),
|
||||
reqwest::Method::POST,
|
||||
&url,
|
||||
&ObjectiveSetStateRequest { state: input.state },
|
||||
@@ -122,6 +135,7 @@ impl WorkspaceHttpObjectiveBackend {
|
||||
let ticket_id = validate_id(&input.ticket_id, "ObjectiveLinkTicket")?;
|
||||
let url = format!("{}/ticket-links", self.objective_url(id));
|
||||
let response = send_json::<ObjectiveLinkTicketRequest, ObjectiveDetail>(
|
||||
self.client.as_ref(),
|
||||
reqwest::Method::POST,
|
||||
&url,
|
||||
&ObjectiveLinkTicketRequest {
|
||||
@@ -143,7 +157,7 @@ impl WorkspaceHttpObjectiveBackend {
|
||||
let id = validate_id(&input.id, "ObjectiveUnlinkTicket")?;
|
||||
let ticket_id = validate_id(&input.ticket_id, "ObjectiveUnlinkTicket")?;
|
||||
let url = format!("{}/ticket-links/{}", self.objective_url(id), ticket_id);
|
||||
let response = delete_json::<ObjectiveDetail>(&url)
|
||||
let response = delete_json::<ObjectiveDetail>(self.client.as_ref(), &url)
|
||||
.await
|
||||
.map_err(backend_error)?;
|
||||
Ok(objective_output(
|
||||
@@ -153,17 +167,15 @@ impl WorkspaceHttpObjectiveBackend {
|
||||
}
|
||||
|
||||
fn objective_url(&self, id: &str) -> String {
|
||||
format!(
|
||||
"{}/api/w/{}/objectives/{}",
|
||||
self.base_url, self.workspace_id, id
|
||||
)
|
||||
let workspace_id = self.client.workspace_id().unwrap_or_default();
|
||||
format!("/api/w/{workspace_id}/objectives/{id}")
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum WorkspaceObjectiveBackendError {
|
||||
#[error("workspace objective backend request failed: {0}")]
|
||||
Request(#[from] reqwest::Error),
|
||||
Request(#[from] crate::worker::WorkspaceClientError),
|
||||
#[error("workspace objective backend returned HTTP {status}: {body}")]
|
||||
Http {
|
||||
status: reqwest::StatusCode,
|
||||
@@ -182,41 +194,55 @@ fn backend_error(error: WorkspaceObjectiveBackendError) -> ToolError {
|
||||
}
|
||||
|
||||
async fn get_json<T: for<'de> Deserialize<'de>>(
|
||||
url: &str,
|
||||
client: &dyn WorkspaceClient,
|
||||
path: &str,
|
||||
) -> Result<T, WorkspaceObjectiveBackendError> {
|
||||
let response = reqwest::Client::new().get(url).send().await?;
|
||||
decode_response(response).await
|
||||
decode_response(client.execute(WorkspaceRequest::get(path))?)
|
||||
}
|
||||
|
||||
async fn send_json<B: Serialize, T: for<'de> Deserialize<'de>>(
|
||||
client: &dyn WorkspaceClient,
|
||||
method: reqwest::Method,
|
||||
url: &str,
|
||||
path: &str,
|
||||
body: &B,
|
||||
) -> Result<T, WorkspaceObjectiveBackendError> {
|
||||
let response = reqwest::Client::new()
|
||||
.request(method, url)
|
||||
.json(body)
|
||||
.send()
|
||||
.await?;
|
||||
decode_response(response).await
|
||||
let method = match method {
|
||||
reqwest::Method::POST => WorkspaceRequestMethod::Post,
|
||||
reqwest::Method::PUT => WorkspaceRequestMethod::Put,
|
||||
reqwest::Method::PATCH => WorkspaceRequestMethod::Patch,
|
||||
reqwest::Method::DELETE => WorkspaceRequestMethod::Delete,
|
||||
_ => WorkspaceRequestMethod::Get,
|
||||
};
|
||||
decode_response(client.execute(WorkspaceRequest::json(
|
||||
method,
|
||||
path,
|
||||
serde_json::to_string(body)?,
|
||||
))?)
|
||||
}
|
||||
|
||||
async fn delete_json<T: for<'de> Deserialize<'de>>(
|
||||
url: &str,
|
||||
client: &dyn WorkspaceClient,
|
||||
path: &str,
|
||||
) -> Result<T, WorkspaceObjectiveBackendError> {
|
||||
let response = reqwest::Client::new().delete(url).send().await?;
|
||||
decode_response(response).await
|
||||
decode_response(client.execute(WorkspaceRequest {
|
||||
method: WorkspaceRequestMethod::Delete,
|
||||
path: path.to_string(),
|
||||
body: None,
|
||||
})?)
|
||||
}
|
||||
|
||||
async fn decode_response<T: for<'de> Deserialize<'de>>(
|
||||
response: reqwest::Response,
|
||||
fn decode_response<T: for<'de> Deserialize<'de>>(
|
||||
response: crate::worker::WorkspaceResponse,
|
||||
) -> Result<T, WorkspaceObjectiveBackendError> {
|
||||
let status = response.status();
|
||||
let body = response.text().await?;
|
||||
if !status.is_success() {
|
||||
return Err(WorkspaceObjectiveBackendError::Http { status, body });
|
||||
let status = reqwest::StatusCode::from_u16(response.status)
|
||||
.unwrap_or(reqwest::StatusCode::INTERNAL_SERVER_ERROR);
|
||||
if !response.is_success() {
|
||||
return Err(WorkspaceObjectiveBackendError::Http {
|
||||
status,
|
||||
body: response.body,
|
||||
});
|
||||
}
|
||||
serde_json::from_str(&body).map_err(Into::into)
|
||||
serde_json::from_str(&response.body).map_err(Into::into)
|
||||
}
|
||||
|
||||
fn objective_output(summary: String, response: ObjectiveDetail) -> Result<ToolOutput, ToolError> {
|
||||
@@ -236,11 +262,8 @@ fn validate_id<'a>(id: &'a str, tool_name: &str) -> Result<&'a str, ToolError> {
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
pub fn workspace_http_objective_tools(
|
||||
workspace_id: impl Into<String>,
|
||||
base_url: impl Into<String>,
|
||||
) -> Vec<ToolDefinition> {
|
||||
let backend = WorkspaceHttpObjectiveBackend::new(workspace_id, base_url);
|
||||
pub fn workspace_http_objective_tools(client: Arc<dyn WorkspaceClient>) -> Vec<ToolDefinition> {
|
||||
let backend = WorkspaceHttpObjectiveBackend::new(client);
|
||||
vec![
|
||||
objective_tool(
|
||||
"ObjectiveList",
|
||||
@@ -600,10 +623,13 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn workspace_http_objective_tools_include_objective_crud_tools() {
|
||||
let names = tool_names(workspace_http_objective_tools(
|
||||
"workspace".to_string(),
|
||||
"http://backend".to_string(),
|
||||
));
|
||||
let names = tool_names(workspace_http_objective_tools(Arc::new(
|
||||
crate::worker::RuntimeWorkspaceHttpClient::new(
|
||||
"workspace",
|
||||
"http://backend",
|
||||
"test-worker",
|
||||
),
|
||||
)));
|
||||
|
||||
assert_eq!(
|
||||
names,
|
||||
|
||||
@@ -29,7 +29,7 @@ const FINISH_EXTRACTION_DESCRIPTION: &str = "Finish the extract worker run after
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct SessionExploreState {
|
||||
view: Arc<SessionReferenceView>,
|
||||
workspace_client: WorkspaceClient,
|
||||
workspace_client: Arc<dyn WorkspaceClient>,
|
||||
source: SourceRef,
|
||||
extract_run_id: String,
|
||||
staged: Arc<Mutex<Vec<String>>>,
|
||||
@@ -39,7 +39,7 @@ pub(crate) struct SessionExploreState {
|
||||
impl SessionExploreState {
|
||||
pub(crate) fn new(
|
||||
view: SessionReferenceView,
|
||||
workspace_client: WorkspaceClient,
|
||||
workspace_client: Arc<dyn WorkspaceClient>,
|
||||
source: SourceRef,
|
||||
) -> Self {
|
||||
Self {
|
||||
@@ -615,7 +615,7 @@ mod tests {
|
||||
|
||||
fn stub_memory_backend_response(
|
||||
body: &'static str,
|
||||
) -> (WorkspaceClient, mpsc::Receiver<String>) {
|
||||
) -> (Arc<dyn WorkspaceClient>, mpsc::Receiver<String>) {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
let (tx, rx) = mpsc::channel();
|
||||
@@ -659,7 +659,11 @@ mod tests {
|
||||
stream.write_all(response.as_bytes()).unwrap();
|
||||
});
|
||||
(
|
||||
WorkspaceClient::http("test-workspace", format!("http://{addr}")),
|
||||
Arc::new(crate::worker::RuntimeWorkspaceHttpClient::new(
|
||||
"test-workspace",
|
||||
format!("http://{addr}"),
|
||||
"test-worker",
|
||||
)),
|
||||
rx,
|
||||
)
|
||||
}
|
||||
@@ -668,7 +672,7 @@ mod tests {
|
||||
fn descriptor_declares_session_explore_tools() {
|
||||
let state = SessionExploreState::new(
|
||||
SessionReferenceView::new("segment-1", vec![Item::user_message("remember this")]),
|
||||
WorkspaceClient::available("test-backend"),
|
||||
crate::worker::marker_workspace_client(None, "test-backend"),
|
||||
SourceRef {
|
||||
segment_id: "segment-1".to_string(),
|
||||
range: [0, 0],
|
||||
|
||||
@@ -4,7 +4,10 @@
|
||||
//! module only resolves the local backend root, declares the built-in feature,
|
||||
//! and contributes those tools through the normal feature registry path.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::{
|
||||
path::{Path, PathBuf},
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
use ticket::{
|
||||
LocalTicketBackend, MarkdownText, NewOrchestrationPlanRecord, NewTicket, NewTicketEvent,
|
||||
@@ -22,6 +25,7 @@ use crate::feature::{
|
||||
FeatureInstructionContribution, FeatureInstructionDeclaration, FeatureInstructionId,
|
||||
FeatureModule, ToolContribution, ToolDeclaration,
|
||||
};
|
||||
use crate::worker::{WorkspaceClient, WorkspaceRequest, WorkspaceRequestMethod};
|
||||
|
||||
const FEATURE_ID: &str = "ticket";
|
||||
const FEATURE_NAME: &str = "Ticket tools";
|
||||
@@ -183,13 +187,8 @@ const ORCHESTRATION_CONTROL_ADDITIONAL_TOOL_NAMES: &[&str] = &[
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum TicketFeatureBackend {
|
||||
Local {
|
||||
root: PathBuf,
|
||||
},
|
||||
WorkspaceHttp {
|
||||
workspace_id: String,
|
||||
base_url: String,
|
||||
},
|
||||
Local { root: PathBuf },
|
||||
WorkspaceClient(Arc<dyn WorkspaceClient>),
|
||||
}
|
||||
|
||||
impl From<PathBuf> for TicketFeatureBackend {
|
||||
@@ -274,7 +273,7 @@ impl TicketFeature {
|
||||
pub fn backend_root(&self) -> Option<&Path> {
|
||||
match &self.backend {
|
||||
TicketFeatureBackend::Local { root } => Some(root),
|
||||
TicketFeatureBackend::WorkspaceHttp { .. } => None,
|
||||
TicketFeatureBackend::WorkspaceClient(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -321,15 +320,9 @@ impl TicketFeature {
|
||||
.into(),
|
||||
)
|
||||
}
|
||||
TicketFeatureBackend::WorkspaceHttp {
|
||||
workspace_id,
|
||||
base_url,
|
||||
} => Some(
|
||||
TicketToolBackend::new(WorkspaceHttpTicketBackend::new(
|
||||
workspace_id.clone(),
|
||||
base_url.clone(),
|
||||
))
|
||||
.with_record_language(self.record_language.as_deref()),
|
||||
TicketFeatureBackend::WorkspaceClient(client) => Some(
|
||||
TicketToolBackend::new(WorkspaceHttpTicketBackend::new(client.clone()))
|
||||
.with_record_language(self.record_language.as_deref()),
|
||||
),
|
||||
}
|
||||
}
|
||||
@@ -386,22 +379,18 @@ impl FeatureModule for TicketFeature {
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
struct WorkspaceHttpTicketBackend {
|
||||
workspace_id: String,
|
||||
base_url: String,
|
||||
client: Arc<dyn WorkspaceClient>,
|
||||
}
|
||||
|
||||
impl WorkspaceHttpTicketBackend {
|
||||
fn new(workspace_id: String, base_url: String) -> Self {
|
||||
Self {
|
||||
workspace_id,
|
||||
base_url: base_url.trim_end_matches('/').to_string(),
|
||||
}
|
||||
fn new(client: Arc<dyn WorkspaceClient>) -> Self {
|
||||
Self { client }
|
||||
}
|
||||
|
||||
fn endpoint(&self) -> String {
|
||||
format!(
|
||||
"{}/api/w/{}/tickets/backend",
|
||||
self.base_url, self.workspace_id
|
||||
"/api/w/{}/tickets/backend",
|
||||
self.client.workspace_id().unwrap_or_default()
|
||||
)
|
||||
}
|
||||
|
||||
@@ -409,44 +398,44 @@ impl WorkspaceHttpTicketBackend {
|
||||
&self,
|
||||
operation: TicketBackendOperation,
|
||||
) -> TicketResult<TicketBackendOperationResult> {
|
||||
let client = self.client.clone();
|
||||
let endpoint = self.endpoint();
|
||||
if tokio::runtime::Handle::try_current().is_ok() {
|
||||
return std::thread::spawn(move || Self::invoke_http(endpoint, operation))
|
||||
return std::thread::spawn(move || Self::invoke_client(client, endpoint, operation))
|
||||
.join()
|
||||
.map_err(|_| {
|
||||
TicketError::Conflict("ticket backend request thread panicked".to_string())
|
||||
})?;
|
||||
}
|
||||
Self::invoke_http(endpoint, operation)
|
||||
Self::invoke_client(client, endpoint, operation)
|
||||
}
|
||||
|
||||
fn invoke_http(
|
||||
fn invoke_client(
|
||||
client: Arc<dyn WorkspaceClient>,
|
||||
endpoint: String,
|
||||
operation: TicketBackendOperation,
|
||||
) -> TicketResult<TicketBackendOperationResult> {
|
||||
let body = serde_json::to_string(&operation).map_err(|error| {
|
||||
TicketError::Conflict(format!("serialize ticket operation: {error}"))
|
||||
})?;
|
||||
let response = reqwest::blocking::Client::new()
|
||||
.post(endpoint)
|
||||
.header(reqwest::header::CONTENT_TYPE, "application/json")
|
||||
.body(body)
|
||||
.send()
|
||||
let response = client
|
||||
.execute(WorkspaceRequest::json(
|
||||
WorkspaceRequestMethod::Post,
|
||||
endpoint,
|
||||
body,
|
||||
))
|
||||
.map_err(|error| {
|
||||
TicketError::Conflict(format!("ticket backend request failed: {error}"))
|
||||
})?;
|
||||
let status = response.status();
|
||||
let text = response.text().map_err(|error| {
|
||||
TicketError::Conflict(format!("ticket backend response failed: {error}"))
|
||||
})?;
|
||||
if !status.is_success() {
|
||||
if !response.is_success() {
|
||||
return Err(TicketError::Conflict(format!(
|
||||
"ticket backend returned HTTP {status}: {text}"
|
||||
"ticket backend returned HTTP {}: {}",
|
||||
response.status, response.body
|
||||
)));
|
||||
}
|
||||
match serde_json::from_str::<TicketBackendHttpResponse>(&text).map_err(|error| {
|
||||
TicketError::Conflict(format!("decode ticket backend response: {error}"))
|
||||
})? {
|
||||
match serde_json::from_str::<TicketBackendHttpResponse>(&response.body).map_err(
|
||||
|error| TicketError::Conflict(format!("decode ticket backend response: {error}")),
|
||||
)? {
|
||||
TicketBackendHttpResponse::Ok { result } => Ok(result),
|
||||
TicketBackendHttpResponse::Error { message } => Err(TicketError::Conflict(message)),
|
||||
}
|
||||
@@ -1126,8 +1115,13 @@ provider = "github"
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn workspace_http_backend_invoke_is_safe_inside_async_context() {
|
||||
let backend =
|
||||
WorkspaceHttpTicketBackend::new("workspace-a".to_string(), "not-a-url".to_string());
|
||||
let backend = WorkspaceHttpTicketBackend::new(Arc::new(
|
||||
crate::worker::RuntimeWorkspaceHttpClient::new(
|
||||
"workspace-a",
|
||||
"not-a-url",
|
||||
"test-worker",
|
||||
),
|
||||
));
|
||||
|
||||
let error = backend
|
||||
.invoke(TicketBackendOperation::DefaultIntakeReadyStateChangeBody {
|
||||
@@ -1167,7 +1161,9 @@ provider = "github"
|
||||
.unwrap();
|
||||
});
|
||||
|
||||
let backend = WorkspaceHttpTicketBackend::new("workspace-a".to_string(), base_url);
|
||||
let backend = WorkspaceHttpTicketBackend::new(Arc::new(
|
||||
crate::worker::RuntimeWorkspaceHttpClient::new("workspace-a", base_url, "test-worker"),
|
||||
));
|
||||
let created = backend.create(NewTicket::new("HTTP ticket")).unwrap();
|
||||
|
||||
server.join().unwrap();
|
||||
|
||||
Reference in New Issue
Block a user