mirror of
https://wget.la/https://github.com/leookun/cursor-byok
synced 2026-12-01 01:05:10 +08:00
new plan
This commit is contained in:
1 parent
279e6bb07c
commit
d200b3791d
204 files changed
+710
-440
No files matched your search
@@ -0,0 +1,209 @@
|
||||
//! Advertisement service contract and desktop HTTP handler.
|
||||
|
||||
use axum::{
|
||||
extract::{Path, State},
|
||||
http::{HeaderMap, StatusCode},
|
||||
Json,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use url::Url;
|
||||
|
||||
use crate::{Error, Result};
|
||||
|
||||
use super::ControlService;
|
||||
|
||||
// 此广告拉取不涉及用户隐私,用户id随机产生
|
||||
// 开源项目广告为作者唯一收入来源,PR时请勿去除此广告
|
||||
|
||||
pub(super) const ADS_ENDPOINT: &str = "https://tab.leokun.cn/api/v1/ads?placement=menu";
|
||||
pub(super) const DEVICE_ID_HEADER: &str = "X-Cursor-Assistant-Device-ID";
|
||||
pub(super) const OS_HEADER: &str = "X-Cursor-Assistant-OS";
|
||||
pub(super) const APP_VERSION_HEADER: &str = "X-Cursor-Assistant-Version";
|
||||
pub(super) const DISABLED_AD_IDS_HEADER: &str = "disable-ad-ids";
|
||||
pub(super) const LANGUAGE_HEADER: &str = "accept-language";
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||
pub struct AdRuntime {
|
||||
pub slots: Vec<AdSlot>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AdSlot {
|
||||
pub id: String,
|
||||
pub enabled: bool,
|
||||
pub placement: AdPlacement,
|
||||
pub target: AdTarget,
|
||||
pub content: AdContent,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum AdPlacement {
|
||||
Menu,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AdTarget {
|
||||
pub title: String,
|
||||
pub description: String,
|
||||
pub image_url: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AdContent {
|
||||
pub title: String,
|
||||
pub description: String,
|
||||
pub image_url: String,
|
||||
pub details: Vec<AdDetail>,
|
||||
pub button: AdButton,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||
pub struct AdDetail {
|
||||
pub label: String,
|
||||
pub value: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||
pub struct AdButton {
|
||||
pub label: String,
|
||||
pub action: AdAction,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||
pub struct AdAction {
|
||||
#[serde(rename = "type")]
|
||||
pub action_type: AdActionType,
|
||||
pub url: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||
pub struct AdDismissalInput {
|
||||
pub reason: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum AdActionType {
|
||||
OpenBrowser,
|
||||
}
|
||||
|
||||
impl AdRuntime {
|
||||
pub(super) fn into_menu_slots(mut self) -> Result<Self> {
|
||||
self.slots
|
||||
.retain(|slot| slot.enabled && slot.placement == AdPlacement::Menu);
|
||||
for slot in &self.slots {
|
||||
validate_http_url(&slot.target.image_url, "target.imageUrl")?;
|
||||
validate_http_url(&slot.content.image_url, "content.imageUrl")?;
|
||||
validate_http_url(&slot.content.button.action.url, "content.button.action.url")?;
|
||||
}
|
||||
Ok(self)
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_http_url(value: &str, field: &str) -> Result<()> {
|
||||
let url = Url::parse(value)
|
||||
.map_err(|error| Error::Provider(format!("advertisement {field} is invalid: {error}")))?;
|
||||
if !matches!(url.scheme(), "http" | "https") || url.host_str().is_none() {
|
||||
return Err(Error::Provider(format!(
|
||||
"advertisement {field} must be an absolute HTTP or HTTPS URL"
|
||||
)));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn get(
|
||||
State(service): State<ControlService>,
|
||||
headers: HeaderMap,
|
||||
) -> Result<Json<AdRuntime>> {
|
||||
let disabled_ad_ids = headers
|
||||
.get(DISABLED_AD_IDS_HEADER)
|
||||
.and_then(|value| value.to_str().ok());
|
||||
Ok(Json(
|
||||
service.ads(disabled_ad_ids, ad_language(&headers)).await?,
|
||||
))
|
||||
}
|
||||
|
||||
fn ad_language(headers: &HeaderMap) -> &'static str {
|
||||
match headers
|
||||
.get(LANGUAGE_HEADER)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
{
|
||||
Some(value) if value.eq_ignore_ascii_case("zh-CN") => "zh-CN",
|
||||
_ => "en-US",
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn dismiss(
|
||||
State(service): State<ControlService>,
|
||||
Path(ad_id): Path<String>,
|
||||
Json(input): Json<AdDismissalInput>,
|
||||
) -> Result<StatusCode> {
|
||||
service.dismiss_ad(&ad_id, &input).await?;
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn accepts_supported_ad_language_and_falls_back_to_english() {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(LANGUAGE_HEADER, "zh-CN".parse().unwrap());
|
||||
assert_eq!(ad_language(&headers), "zh-CN");
|
||||
|
||||
headers.insert(LANGUAGE_HEADER, "fr-FR".parse().unwrap());
|
||||
assert_eq!(ad_language(&headers), "en-US");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn filters_disabled_slots_without_limiting_menu_ads() {
|
||||
let slot = |id: &str, enabled| AdSlot {
|
||||
id: id.into(),
|
||||
enabled,
|
||||
placement: AdPlacement::Menu,
|
||||
target: AdTarget {
|
||||
title: id.into(),
|
||||
description: String::new(),
|
||||
image_url: "https://example.com/target.png".into(),
|
||||
},
|
||||
content: AdContent {
|
||||
title: id.into(),
|
||||
description: String::new(),
|
||||
image_url: "https://example.com/content.png".into(),
|
||||
details: Vec::new(),
|
||||
button: AdButton {
|
||||
label: "Open".into(),
|
||||
action: AdAction {
|
||||
action_type: AdActionType::OpenBrowser,
|
||||
url: "https://example.com".into(),
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
let runtime = AdRuntime {
|
||||
slots: vec![
|
||||
slot("one", true),
|
||||
slot("disabled", false),
|
||||
slot("two", true),
|
||||
slot("three", true),
|
||||
slot("four", true),
|
||||
],
|
||||
}
|
||||
.into_menu_slots()
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
runtime
|
||||
.slots
|
||||
.iter()
|
||||
.map(|slot| slot.id.as_str())
|
||||
.collect::<Vec<_>>(),
|
||||
["one", "two", "three", "four"]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
use axum::{
|
||||
extract::{Path, Query, State},
|
||||
Json,
|
||||
};
|
||||
use serde::Deserialize;
|
||||
|
||||
use crate::Result;
|
||||
|
||||
use super::{CallDetail, CallSummary, ControlService};
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct CallQuery {
|
||||
#[serde(default = "default_limit")]
|
||||
limit: i64,
|
||||
}
|
||||
|
||||
pub async fn list(
|
||||
State(service): State<ControlService>,
|
||||
Query(query): Query<CallQuery>,
|
||||
) -> Result<Json<Vec<CallSummary>>> {
|
||||
Ok(Json(service.calls(query.limit).await?))
|
||||
}
|
||||
|
||||
pub async fn detail(
|
||||
State(service): State<ControlService>,
|
||||
Path(call_id): Path<String>,
|
||||
) -> Result<Json<CallDetail>> {
|
||||
Ok(Json(service.call(&call_id).await?))
|
||||
}
|
||||
|
||||
fn default_limit() -> i64 {
|
||||
100
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
use axum::{extract::State, Json};
|
||||
|
||||
use crate::{
|
||||
harness::{CursorHarnessStatus, SetEnabled},
|
||||
Result,
|
||||
};
|
||||
|
||||
use super::ControlService;
|
||||
|
||||
pub async fn status(State(service): State<ControlService>) -> Result<Json<CursorHarnessStatus>> {
|
||||
Ok(Json(service.cursor_harness().status().await?))
|
||||
}
|
||||
|
||||
pub async fn initialize_ca(
|
||||
State(service): State<ControlService>,
|
||||
) -> Result<Json<CursorHarnessStatus>> {
|
||||
Ok(Json(service.cursor_harness().initialize_ca().await?))
|
||||
}
|
||||
|
||||
pub async fn set_enabled(
|
||||
State(service): State<ControlService>,
|
||||
Json(input): Json<SetEnabled>,
|
||||
) -> Result<Json<CursorHarnessStatus>> {
|
||||
Ok(Json(
|
||||
service.cursor_harness().set_enabled(input.enabled).await?,
|
||||
))
|
||||
}
|
||||
@@ -0,0 +1,338 @@
|
||||
mod ads;
|
||||
mod calls;
|
||||
mod harness;
|
||||
mod models;
|
||||
mod overview;
|
||||
mod service;
|
||||
mod settings;
|
||||
|
||||
use axum::{
|
||||
body::{to_bytes, Body},
|
||||
extract::State,
|
||||
http::{header, header::CONTENT_TYPE, HeaderValue, Method, Request, Response, StatusCode},
|
||||
routing::{any, get, post, put},
|
||||
Router,
|
||||
};
|
||||
use tower_http::{
|
||||
cors::{AllowOrigin, CorsLayer},
|
||||
services::ServeDir,
|
||||
};
|
||||
use url::{Host, Url};
|
||||
|
||||
pub use service::{
|
||||
CallDetail, CallSummary, ControlService, DiscoveredModels, LegacyModelImportPreview,
|
||||
LegacyModelImportResult, ModelConnectivityResult, ModelDiscoveryInput, ObservabilitySettings,
|
||||
};
|
||||
|
||||
pub fn web_router(service: ControlService, assets: impl AsRef<std::path::Path>) -> Router {
|
||||
Router::new()
|
||||
.nest_service(
|
||||
"/__byok-api__",
|
||||
ServeDir::new(assets).append_index_html_on_directories(true),
|
||||
)
|
||||
.merge(api_router(service))
|
||||
}
|
||||
|
||||
pub fn proxy_web_router(service: ControlService, target: Url) -> Router {
|
||||
frontend_proxy_router(target).merge(api_router(service))
|
||||
}
|
||||
|
||||
fn frontend_proxy_router(target: Url) -> Router {
|
||||
let state = FrontendProxy {
|
||||
client: reqwest::Client::new(),
|
||||
target: target.as_str().trim_end_matches('/').to_string(),
|
||||
};
|
||||
Router::new()
|
||||
.route("/__byok-api__/", any(proxy_frontend))
|
||||
.route("/__byok-api__/{*path}", any(proxy_frontend))
|
||||
.with_state(state)
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct FrontendProxy {
|
||||
client: reqwest::Client,
|
||||
target: String,
|
||||
}
|
||||
|
||||
async fn proxy_frontend(
|
||||
State(proxy): State<FrontendProxy>,
|
||||
request: Request<Body>,
|
||||
) -> Response<Body> {
|
||||
let (parts, body) = request.into_parts();
|
||||
let path = parts
|
||||
.uri
|
||||
.path_and_query()
|
||||
.map(|value| value.as_str())
|
||||
.unwrap_or("/__byok-api__/");
|
||||
let mut upstream = proxy
|
||||
.client
|
||||
.request(parts.method, format!("{}{path}", proxy.target));
|
||||
for (name, value) in &parts.headers {
|
||||
if name != header::HOST && name != header::CONNECTION {
|
||||
upstream = upstream.header(name, value);
|
||||
}
|
||||
}
|
||||
let body = match to_bytes(body, 64 * 1024 * 1024).await {
|
||||
Ok(body) => body,
|
||||
Err(error) => return proxy_error(error),
|
||||
};
|
||||
let upstream = match upstream.body(body).send().await {
|
||||
Ok(response) => response,
|
||||
Err(error) => return proxy_error(error),
|
||||
};
|
||||
let status = upstream.status();
|
||||
let headers = upstream.headers().clone();
|
||||
let body = match upstream.bytes().await {
|
||||
Ok(body) => body,
|
||||
Err(error) => return proxy_error(error),
|
||||
};
|
||||
let mut response = Response::new(Body::from(body));
|
||||
*response.status_mut() = status;
|
||||
for (name, value) in &headers {
|
||||
if name != header::CONNECTION
|
||||
&& name != header::TRANSFER_ENCODING
|
||||
&& name != header::CONTENT_LENGTH
|
||||
{
|
||||
response.headers_mut().insert(name, value.clone());
|
||||
}
|
||||
}
|
||||
response
|
||||
}
|
||||
|
||||
fn proxy_error(error: impl std::fmt::Display) -> Response<Body> {
|
||||
tracing::warn!(%error, "frontend development proxy failed");
|
||||
Response::builder()
|
||||
.status(StatusCode::BAD_GATEWAY)
|
||||
.body(Body::from("frontend development server is unavailable"))
|
||||
.expect("static proxy error response")
|
||||
}
|
||||
|
||||
pub fn api_router(service: ControlService) -> Router {
|
||||
Router::new()
|
||||
.route("/__byok-api__/api/ads", get(ads::get))
|
||||
.route(
|
||||
"/__byok-api__/api/ads/{ad_id}/dismissals",
|
||||
post(ads::dismiss),
|
||||
)
|
||||
.route(
|
||||
"/__byok-api__/api/models",
|
||||
get(models::list).post(models::create),
|
||||
)
|
||||
.route("/__byok-api__/api/models/discover", post(models::discover))
|
||||
.route(
|
||||
"/__byok-api__/api/models/import-v0049",
|
||||
get(models::preview_v0049).post(models::import_v0049),
|
||||
)
|
||||
.route("/__byok-api__/api/models/order", put(models::reorder))
|
||||
.route("/__byok-api__/api/overview", get(overview::get))
|
||||
.route(
|
||||
"/__byok-api__/api/models/{model_hash}",
|
||||
put(models::update).delete(models::remove),
|
||||
)
|
||||
.route(
|
||||
"/__byok-api__/api/models/{model_hash}/test/{test_id}",
|
||||
post(models::test).delete(models::cancel),
|
||||
)
|
||||
.route("/__byok-api__/api/llm-calls", get(calls::list))
|
||||
.route("/__byok-api__/api/llm-calls/{call_id}", get(calls::detail))
|
||||
.route(
|
||||
"/__byok-api__/api/settings/observability",
|
||||
get(settings::get).put(settings::update),
|
||||
)
|
||||
.route(
|
||||
"/__byok-api__/api/settings/ports",
|
||||
get(settings::get_ports).put(settings::update_ports),
|
||||
)
|
||||
.route(
|
||||
"/__byok-api__/api/settings/storage/statistics",
|
||||
get(settings::get_storage).delete(settings::clear_storage),
|
||||
)
|
||||
.route(
|
||||
"/__byok-api__/api/settings/proxy",
|
||||
get(settings::get_proxy).put(settings::update_proxy),
|
||||
)
|
||||
.route(
|
||||
"/__byok-api__/api/settings/tab",
|
||||
get(settings::get_tab).put(settings::update_tab),
|
||||
)
|
||||
.route(
|
||||
"/__byok-api__/api/settings/desktop",
|
||||
get(settings::get_desktop).put(settings::update_desktop),
|
||||
)
|
||||
.route(
|
||||
"/__byok-api__/api/harness/cursor/status",
|
||||
get(harness::status),
|
||||
)
|
||||
.route(
|
||||
"/__byok-api__/api/harness/cursor/ca/initialize",
|
||||
post(harness::initialize_ca),
|
||||
)
|
||||
.route(
|
||||
"/__byok-api__/api/harness/cursor/enabled",
|
||||
put(harness::set_enabled),
|
||||
)
|
||||
.with_state(service)
|
||||
.layer(desktop_cors())
|
||||
}
|
||||
|
||||
fn desktop_cors() -> CorsLayer {
|
||||
CorsLayer::new()
|
||||
.allow_origin(AllowOrigin::predicate(|origin, _| local_origin(origin)))
|
||||
.allow_methods([Method::GET, Method::POST, Method::PUT, Method::DELETE])
|
||||
.allow_headers([
|
||||
CONTENT_TYPE,
|
||||
header::ACCEPT_LANGUAGE,
|
||||
header::HeaderName::from_static("disable-ad-ids"),
|
||||
])
|
||||
}
|
||||
|
||||
fn local_origin(origin: &HeaderValue) -> bool {
|
||||
let Ok(origin) = origin.to_str() else {
|
||||
return false;
|
||||
};
|
||||
if origin.eq_ignore_ascii_case("tauri://localhost") {
|
||||
return true;
|
||||
}
|
||||
let Ok(origin) = Url::parse(origin) else {
|
||||
return false;
|
||||
};
|
||||
if !matches!(origin.scheme(), "http" | "https")
|
||||
|| !origin.username().is_empty()
|
||||
|| origin.password().is_some()
|
||||
|| origin.path() != "/"
|
||||
|| origin.query().is_some()
|
||||
|| origin.fragment().is_some()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
match origin.host() {
|
||||
Some(Host::Domain(host)) => {
|
||||
host.eq_ignore_ascii_case("localhost") || host.eq_ignore_ascii_case("tauri.localhost")
|
||||
}
|
||||
Some(Host::Ipv4(address)) => {
|
||||
address.is_loopback() || address.is_private() || address.is_link_local()
|
||||
}
|
||||
Some(Host::Ipv6(address)) => {
|
||||
address.is_loopback() || address.is_unique_local() || address.is_unicast_link_local()
|
||||
}
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use axum::{
|
||||
body::Body,
|
||||
http::{header, HeaderValue, Request},
|
||||
};
|
||||
use tower::ServiceExt;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn control_routes_only_exist_below_the_reserved_namespace() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let store = crate::store::Store::connect(&format!(
|
||||
"sqlite://{}",
|
||||
directory.path().join("control.db").display()
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
let provider = std::sync::Arc::new(crate::provider::ProviderRouter::new(
|
||||
store.clone(),
|
||||
std::time::Duration::from_secs(300),
|
||||
));
|
||||
let router = api_router(ControlService::new(store, provider).unwrap());
|
||||
|
||||
let response = router
|
||||
.clone()
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.uri("/__byok-api__/api/models")
|
||||
.header(header::ORIGIN, "tauri://localhost")
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), axum::http::StatusCode::OK);
|
||||
assert_eq!(
|
||||
response.headers().get(header::ACCESS_CONTROL_ALLOW_ORIGIN),
|
||||
Some(&HeaderValue::from_static("tauri://localhost"))
|
||||
);
|
||||
|
||||
let response = router
|
||||
.clone()
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.uri("/__byok-api__/api/overview")
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), axum::http::StatusCode::OK);
|
||||
|
||||
let response = router
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.uri("/api/models")
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), axum::http::StatusCode::NOT_FOUND);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn development_frontend_proxy_preserves_the_reserved_path_and_query() {
|
||||
let upstream = Router::new().route(
|
||||
"/__byok-api__/{*path}",
|
||||
get(|request: Request<Body>| async move {
|
||||
request.uri().path_and_query().unwrap().as_str().to_string()
|
||||
}),
|
||||
);
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let address = listener.local_addr().unwrap();
|
||||
let task = tokio::spawn(async move { axum::serve(listener, upstream).await.unwrap() });
|
||||
let router = frontend_proxy_router(format!("http://{address}").parse().unwrap());
|
||||
|
||||
let response = router
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.uri("/__byok-api__/src/index.tsx?direct=1")
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
|
||||
assert_eq!(body, "/__byok-api__/src/index.tsx?direct=1");
|
||||
task.abort();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cors_only_allows_tauri_loopback_and_private_network_origins() {
|
||||
for origin in [
|
||||
"tauri://localhost",
|
||||
"http://tauri.localhost",
|
||||
"http://localhost:1420",
|
||||
"http://127.0.0.1:1420",
|
||||
"https://192.168.1.20:8443",
|
||||
"http://[::1]:1420",
|
||||
"http://[fd00::20]:1420",
|
||||
] {
|
||||
assert!(local_origin(&origin.parse().unwrap()), "{origin}");
|
||||
}
|
||||
for origin in [
|
||||
"https://example.com",
|
||||
"https://8.8.8.8",
|
||||
"https://localhost.example.com",
|
||||
"null",
|
||||
] {
|
||||
assert!(!local_origin(&origin.parse().unwrap()), "{origin}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
use axum::{
|
||||
extract::{Path, State},
|
||||
http::StatusCode,
|
||||
Json,
|
||||
};
|
||||
use serde::Deserialize;
|
||||
|
||||
use crate::{
|
||||
model::{ModelConfig, ModelConfigInput},
|
||||
Result,
|
||||
};
|
||||
|
||||
use super::{
|
||||
ControlService, DiscoveredModels, LegacyModelImportPreview, LegacyModelImportResult,
|
||||
ModelConnectivityResult, ModelDiscoveryInput,
|
||||
};
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct SaveModels {
|
||||
pub models: Vec<ModelConfigInput>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct ModelOrder {
|
||||
pub model_hashes: Vec<String>,
|
||||
}
|
||||
|
||||
pub async fn list(State(service): State<ControlService>) -> Result<Json<Vec<ModelConfig>>> {
|
||||
Ok(Json(service.models().await?))
|
||||
}
|
||||
|
||||
pub async fn create(
|
||||
State(service): State<ControlService>,
|
||||
Json(input): Json<SaveModels>,
|
||||
) -> Result<(StatusCode, Json<Vec<ModelConfig>>)> {
|
||||
Ok((
|
||||
StatusCode::CREATED,
|
||||
Json(service.create_models(&input.models).await?),
|
||||
))
|
||||
}
|
||||
|
||||
pub async fn reorder(
|
||||
State(service): State<ControlService>,
|
||||
Json(input): Json<ModelOrder>,
|
||||
) -> Result<Json<Vec<ModelConfig>>> {
|
||||
Ok(Json(service.reorder_models(&input.model_hashes).await?))
|
||||
}
|
||||
|
||||
pub async fn remove(
|
||||
State(service): State<ControlService>,
|
||||
Path(model_hash): Path<String>,
|
||||
) -> Result<StatusCode> {
|
||||
service.delete_model(&model_hash).await?;
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
pub async fn update(
|
||||
State(service): State<ControlService>,
|
||||
Path(model_hash): Path<String>,
|
||||
Json(input): Json<ModelConfigInput>,
|
||||
) -> Result<Json<ModelConfig>> {
|
||||
Ok(Json(service.update_model(&model_hash, &input).await?))
|
||||
}
|
||||
|
||||
pub async fn test(
|
||||
State(service): State<ControlService>,
|
||||
Path((model_hash, test_id)): Path<(String, String)>,
|
||||
) -> Result<Json<ModelConnectivityResult>> {
|
||||
Ok(Json(service.test_model(&model_hash, &test_id).await?))
|
||||
}
|
||||
|
||||
pub async fn cancel(
|
||||
State(service): State<ControlService>,
|
||||
Path((_model_hash, test_id)): Path<(String, String)>,
|
||||
) -> Result<StatusCode> {
|
||||
service.cancel_model_test(&test_id);
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
pub async fn discover(
|
||||
State(service): State<ControlService>,
|
||||
Json(input): Json<ModelDiscoveryInput>,
|
||||
) -> Result<Json<DiscoveredModels>> {
|
||||
Ok(Json(service.discover_models(&input).await?))
|
||||
}
|
||||
|
||||
pub async fn import_v0049(
|
||||
State(service): State<ControlService>,
|
||||
) -> Result<Json<LegacyModelImportResult>> {
|
||||
Ok(Json(service.import_v0049_models().await?))
|
||||
}
|
||||
|
||||
pub async fn preview_v0049(
|
||||
State(service): State<ControlService>,
|
||||
) -> Result<Json<LegacyModelImportPreview>> {
|
||||
Ok(Json(service.preview_v0049_models().await?))
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
//! HTTP handler for the desktop overview aggregates.
|
||||
|
||||
use axum::{
|
||||
extract::{Query, State},
|
||||
Json,
|
||||
};
|
||||
use serde::Deserialize;
|
||||
|
||||
use crate::{model::Overview, Result};
|
||||
|
||||
use super::ControlService;
|
||||
|
||||
#[derive(Debug, Default, Deserialize)]
|
||||
pub struct OverviewRange {
|
||||
start_ms: Option<i64>,
|
||||
end_ms: Option<i64>,
|
||||
model_hashes: Option<String>,
|
||||
}
|
||||
|
||||
pub async fn get(
|
||||
State(service): State<ControlService>,
|
||||
Query(range): Query<OverviewRange>,
|
||||
) -> Result<Json<Overview>> {
|
||||
Ok(Json(
|
||||
service
|
||||
.overview(range.start_ms, range.end_ms, range.model_hashes.as_deref())
|
||||
.await?,
|
||||
))
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,88 @@
|
||||
use crate::Result;
|
||||
use axum::{extract::State, Json};
|
||||
use serde::Deserialize;
|
||||
|
||||
use crate::store::{
|
||||
DesktopSettings, PortSettings, ProxySettings, ProxySettingsInput, StatisticsStorage,
|
||||
StatisticsStorageScope, TabSettings,
|
||||
};
|
||||
|
||||
use super::{ControlService, ObservabilitySettings};
|
||||
|
||||
pub async fn get(State(service): State<ControlService>) -> Result<Json<ObservabilitySettings>> {
|
||||
Ok(Json(service.observability().await?))
|
||||
}
|
||||
|
||||
pub async fn update(
|
||||
State(service): State<ControlService>,
|
||||
Json(settings): Json<ObservabilitySettings>,
|
||||
) -> Result<Json<ObservabilitySettings>> {
|
||||
Ok(Json(service.set_observability(settings).await?))
|
||||
}
|
||||
|
||||
pub async fn get_ports(State(service): State<ControlService>) -> Result<Json<PortSettings>> {
|
||||
Ok(Json(service.ports().await?))
|
||||
}
|
||||
|
||||
pub async fn update_ports(
|
||||
State(service): State<ControlService>,
|
||||
Json(settings): Json<PortSettings>,
|
||||
) -> Result<Json<PortSettings>> {
|
||||
Ok(Json(service.set_ports(settings).await?))
|
||||
}
|
||||
|
||||
pub async fn get_storage(State(service): State<ControlService>) -> Result<Json<StatisticsStorage>> {
|
||||
Ok(Json(service.statistics_storage().await?))
|
||||
}
|
||||
|
||||
pub async fn clear_storage(
|
||||
State(service): State<ControlService>,
|
||||
input: Option<Json<ClearStorageInput>>,
|
||||
) -> Result<Json<StatisticsStorage>> {
|
||||
let scope = input.map(|Json(input)| input.scope).unwrap_or_default();
|
||||
let storage = match scope {
|
||||
StatisticsStorageScope::Details => service.clear_statistics_storage().await?,
|
||||
StatisticsStorageScope::All => service.clear_all_statistics_storage().await?,
|
||||
};
|
||||
Ok(Json(storage))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct ClearStorageInput {
|
||||
#[serde(default)]
|
||||
pub scope: StatisticsStorageScope,
|
||||
}
|
||||
|
||||
pub async fn get_proxy(State(service): State<ControlService>) -> Result<Json<ProxySettings>> {
|
||||
Ok(Json(service.proxy_settings().await?))
|
||||
}
|
||||
|
||||
pub async fn update_proxy(
|
||||
State(service): State<ControlService>,
|
||||
Json(settings): Json<ProxySettingsInput>,
|
||||
) -> Result<Json<ProxySettings>> {
|
||||
Ok(Json(service.set_proxy_settings(settings).await?))
|
||||
}
|
||||
|
||||
pub async fn get_tab(State(service): State<ControlService>) -> Result<Json<TabSettings>> {
|
||||
Ok(Json(service.tab_settings().await?))
|
||||
}
|
||||
|
||||
pub async fn update_tab(
|
||||
State(service): State<ControlService>,
|
||||
Json(settings): Json<TabSettings>,
|
||||
) -> Result<Json<TabSettings>> {
|
||||
Ok(Json(service.set_tab_settings(settings).await?))
|
||||
}
|
||||
|
||||
pub async fn get_desktop(State(service): State<ControlService>) -> Result<Json<DesktopSettings>> {
|
||||
Ok(Json(service.desktop_settings().await?))
|
||||
}
|
||||
|
||||
pub async fn update_desktop(
|
||||
State(service): State<ControlService>,
|
||||
Json(settings): Json<DesktopSettings>,
|
||||
) -> Result<Json<DesktopSettings>> {
|
||||
service.set_desktop_settings(settings).await?;
|
||||
get_desktop(State(service)).await
|
||||
}
|
||||
Reference in new issue
Block a user