AppState (app/state.rs) is now lifecycle + EngineLink (client port, control channel, worker status, pool, queue timeout) + HttpPolicy (api key, CORS, trusted origins) + ModelView (name, aliases, tokenizer, template, vision port, prefix-cache and memory views) + Services (response store, monitor, MCP port, settings, clock, started_at). Field uses were rewritten mechanically (state.worker -> state.engine.worker, ...); no handler logic changed. The old impl_default_for_appstate.rs, which held the route table and the admin handlers, is app/routes.rs, app/admin_routes.rs and app/readiness.rs. main.rs (1156 lines: an 840-line argument match, the serve function, two helpers) is now 8 lines. The argument match is split into command groups under src/cli/ (operations, model_fetch, model_inspect, model_ensure, model_prepare, kar_inspect, kar_verify, kar_overlay, model_text; each owns its arms in their old order and answers Ok(false) for a line it does not own), serve() and shutdown_signal() are src/serve.rs (the composition root), the usage text is cli/usage.rs. The binary name and every command line are unchanged. Architecture gate: control-plane/src/main.rs leaves the oversize list (1156 -> 8). --allow-increase was used because the type change forces the AppState struct literals in seven already-oversize test/example files to nest by group: cp_replay.rs +7, responses/tests.rs +11, backend_worker_http.rs +14, mcp_hub.rs +3, memory_gate_http.rs +7, vision_http.rs +6, desktop-core api_over_runtime.rs +6 (55 lines in all, against 1148 lines removed from main.rs). Test outcomes are unchanged (597 ok / 2 ignored before and after, 14 new tests from S16).
190 lines
6.8 KiB
Rust
190 lines
6.8 KiB
Rust
//! Moved out of the parent module by STRA-338: fn resource_query_error, fn retrieve, impl InputItemsQuery, impl StoredResponse, fn input_items, fn delete ....
|
|
|
|
#[allow(unused_imports)]
|
|
use super::*;
|
|
|
|
pub(super) fn resource_query_error(query: Option<String>) -> Option<Response> {
|
|
query.filter(|value| !value.is_empty()).map(|_| {
|
|
api_error(
|
|
StatusCode::BAD_REQUEST,
|
|
"invalid_request_error",
|
|
"unsupported_query",
|
|
None,
|
|
"stored response query options and stream resumption are not supported",
|
|
)
|
|
})
|
|
}
|
|
|
|
pub async fn retrieve(
|
|
State(state): State<AppState>,
|
|
Path(id): Path<String>,
|
|
RawQuery(query): RawQuery,
|
|
) -> Response {
|
|
if let Some(error) = resource_query_error(query) {
|
|
return error;
|
|
}
|
|
match state.services.responses.response(&id).await {
|
|
Some(response) => Json(response).into_response(),
|
|
None => resource_not_found(),
|
|
}
|
|
}
|
|
|
|
impl InputItemsQuery {
|
|
pub(super) fn parse(query: Option<&str>) -> Result<Self, &'static str> {
|
|
let uri = format!("/?{}", query.unwrap_or(""))
|
|
.parse::<axum::http::Uri>()
|
|
.map_err(|_| "invalid input-items query")?;
|
|
let Query(options) = Query::<Self>::try_from_uri(&uri)
|
|
.map_err(|_| "only single after, limit and order query parameters are supported")?;
|
|
if options.limit.is_some_and(|n| !(1..=100).contains(&n))
|
|
|| options
|
|
.order
|
|
.as_deref()
|
|
.is_some_and(|s| s != "asc" && s != "desc")
|
|
|| options
|
|
.after
|
|
.as_ref()
|
|
.is_some_and(|s| s.is_empty() || s.len() > 256)
|
|
{
|
|
return Err("limit must be 1..100, order asc|desc and after a nonempty item ID");
|
|
}
|
|
Ok(options)
|
|
}
|
|
}
|
|
|
|
impl StoredResponse {
|
|
pub(super) fn input_page(
|
|
&self,
|
|
id: &str,
|
|
options: &InputItemsQuery,
|
|
) -> Result<Value, &'static str> {
|
|
let descending = options.order.as_deref().unwrap_or("desc") == "desc";
|
|
let prefix = format!("input_{id}_");
|
|
let start = match options.after.as_deref() {
|
|
None => 0,
|
|
Some(cursor) => {
|
|
let index = cursor
|
|
.strip_prefix(&prefix)
|
|
.and_then(|s| s.parse::<usize>().ok())
|
|
.filter(|i| *i < self.input_len && format!("{prefix}{i}") == cursor)
|
|
.ok_or("after does not identify an input item of this response")?;
|
|
if descending {
|
|
self.input_len - index
|
|
} else {
|
|
index + 1
|
|
}
|
|
}
|
|
};
|
|
let limit = options.limit.unwrap_or(20);
|
|
let count = self.input_len.saturating_sub(start).min(limit);
|
|
let mut data = Vec::with_capacity(count);
|
|
for position in start..start + count {
|
|
let index = if descending {
|
|
self.input_len - 1 - position
|
|
} else {
|
|
position
|
|
};
|
|
// Project rather than mutate the transcript used for prompt replay.
|
|
// IDs identify occurrences in this response, so repeated client IDs
|
|
// cannot make a pagination cursor ambiguous. call_id stays intact.
|
|
let mut item = self.transcript[index].clone();
|
|
item.as_object_mut()
|
|
.ok_or("stored input item is not an object")?
|
|
.insert("id".into(), json!(format!("{prefix}{index}")));
|
|
if item.get("role").is_some()
|
|
&& (item.get("type").is_none() || item["type"] == "message")
|
|
{
|
|
item["type"] = json!("message");
|
|
if let Some(text) = item["content"].as_str() {
|
|
item["content"] = if item["role"] == "assistant" {
|
|
json!([{"type":"output_text","text":text,"annotations":[]}])
|
|
} else {
|
|
json!([{"type":"input_text","text":text}])
|
|
};
|
|
}
|
|
let assistant = item["role"] == "assistant";
|
|
if let Some(parts) = item["content"].as_array_mut() {
|
|
for part in parts {
|
|
if part["type"] == "input_text" || part["type"] == "output_text" {
|
|
part["type"] = json!(if assistant {
|
|
"output_text"
|
|
} else {
|
|
"input_text"
|
|
});
|
|
if assistant && part.get("annotations").is_none() {
|
|
part["annotations"] = json!([]);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
if item.get("status").is_none() {
|
|
item["status"] = json!("completed");
|
|
}
|
|
}
|
|
data.push(item);
|
|
}
|
|
Ok(
|
|
json!({"object":"list", "first_id":data.first().map(|item| &item["id"]),
|
|
"last_id":data.last().map(|item| &item["id"]),
|
|
"has_more":self.input_len.saturating_sub(start) > count,"data":data}),
|
|
)
|
|
}
|
|
}
|
|
|
|
pub async fn input_items(
|
|
State(state): State<AppState>,
|
|
Path(id): Path<String>,
|
|
RawQuery(query): RawQuery,
|
|
) -> Response {
|
|
let invalid = |message| {
|
|
api_error(
|
|
StatusCode::BAD_REQUEST,
|
|
"invalid_request_error",
|
|
"invalid_input_items_query",
|
|
None,
|
|
message,
|
|
)
|
|
};
|
|
let options = match InputItemsQuery::parse(query.as_deref()) {
|
|
Ok(options) => options,
|
|
Err(message) => return invalid(message),
|
|
};
|
|
match state.services.responses.input_page(&id, &options).await {
|
|
None => resource_not_found(),
|
|
Some(Ok(page)) => Json(page).into_response(),
|
|
Some(Err(message)) => invalid(message),
|
|
}
|
|
}
|
|
|
|
pub async fn delete(
|
|
State(state): State<AppState>,
|
|
Path(id): Path<String>,
|
|
RawQuery(query): RawQuery,
|
|
) -> Response {
|
|
if let Some(error) = resource_query_error(query) {
|
|
return error;
|
|
}
|
|
match state.services.responses.delete(&id).await {
|
|
Ok(true) => (),
|
|
Ok(false) => return resource_not_found(),
|
|
Err(_) => {
|
|
return api_error(
|
|
StatusCode::INSUFFICIENT_STORAGE,
|
|
"server_error",
|
|
"response_storage_failed",
|
|
None,
|
|
"cannot commit response deletion; inspect storage and restart",
|
|
);
|
|
}
|
|
}
|
|
Json(json!({"id":id,"object":"response.deleted","deleted":true})).into_response()
|
|
}
|
|
|
|
pub(super) fn append_input(transcript: &mut Vec<Value>, input: &Value) {
|
|
if let Some(items) = input.as_array() {
|
|
transcript.extend(items.iter().cloned());
|
|
} else if let Some(text) = input.as_str() {
|
|
transcript.push(json!({"role":"user","content":text}));
|
|
}
|
|
}
|