diff --git a/apps/detail-photocraft/apps/photocraft/build.rs b/apps/detail-photocraft/apps/photocraft/build.rs index b56dc47e..f9e52948 100644 --- a/apps/detail-photocraft/apps/photocraft/build.rs +++ b/apps/detail-photocraft/apps/photocraft/build.rs @@ -1,4 +1,4 @@ -//! Windows only: embed the app icon and version info (VERSIONINFO) into `photocraft.exe`. +//! Windows only: embed the app manifest, icon and version info into `photocraft.exe`. //! //! On every other target this does nothing. A missing resource compiler is a warning, so a //! cross-compile from macOS or Linux still links, unless `PHOTOCRAFT_REQUIRE_WINRES=1` (set by the @@ -52,6 +52,7 @@ fn main() { println!("cargo:rerun-if-changed=build.rs"); println!("cargo:rerun-if-changed=../../assets/jiansun/icon.ico"); + println!("cargo:rerun-if-changed=photocraft.manifest"); println!("cargo:rerun-if-env-changed=PHOTOCRAFT_REQUIRE_WINRES"); if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") { return; @@ -59,7 +60,8 @@ fn main() { let numeric_version = official.split('.').take(3).zip([48, 32, 16]).map(|(part, shift)| u64::from(part.parse::().expect("invalid client version")) << shift).sum(); let mut res = winresource::WindowsResource::new(); - res.set_icon("../../assets/jiansun/icon.ico") + res.set_manifest_file("photocraft.manifest") + .set_icon("../../assets/jiansun/icon.ico") .set("ProductName", "小壹") .set("FileDescription", "小壹客户端") .set("CompanyName", "由壹点品牌中心") @@ -74,6 +76,6 @@ fn main() { if std::env::var_os("PHOTOCRAFT_REQUIRE_WINRES").is_some() { panic!("embedding Windows resources failed: {e}"); } - println!("cargo:warning=photocraft.exe built without icon/version resources: {e}"); + println!("cargo:warning=photocraft.exe built without Windows resources: {e}"); } } diff --git a/apps/detail-photocraft/apps/photocraft/photocraft.manifest b/apps/detail-photocraft/apps/photocraft/photocraft.manifest new file mode 100644 index 00000000..1536e544 --- /dev/null +++ b/apps/detail-photocraft/apps/photocraft/photocraft.manifest @@ -0,0 +1,8 @@ + + + + + true + + + diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_delivery.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_delivery.rs index 3bcbd13b..2224a5a3 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_delivery.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_delivery.rs @@ -4,6 +4,7 @@ use serde_json::{Value, json}; use std::{ collections::{BTreeMap, HashSet}, fs, + io::Read, path::{Path, PathBuf}, sync::{atomic::{AtomicBool, Ordering}, mpsc}, }; @@ -196,7 +197,21 @@ fn file_record(root: &Path, path: &Path, category: &str, size: Option<(u32, u32) fn artifact_size(path: &Path, format: &str) -> R> { let size = match format { - "psd" | "psb" => canvas_workspace::layered_size(&path.to_string_lossy(), &fs::read(path).map_err(disk)?)?, + "psd" | "psb" => { + let mut signature = [0; 6]; + fs::File::open(path).and_then(|mut file| file.read_exact(&mut signature)).map_err(disk)?; + if canvas_workspace::layered_format(&signature)? != format + || path.extension().and_then(|ext| ext.to_str()) != Some(format) + { + return Err("分层文件扩展名与文件头不一致".into()); + } + // Reopen through the file-backed decoder so the encoded PSB and its decoded + // document don't have to occupy memory together. + let imported = photocraft_io::import_file( + &path.to_string_lossy(), path, &Default::default(), &photocraft_raster::Interrupt::NONE, + ).map_err(|error| format!("无法重开分层文件:{error}"))?; + (imported.document.size.width, imported.document.size.height) + } "pcraft" => { transfer::check_pcraft_file(path)?; let doc = photocraft_format::load_path(path).map_err(|error| format!("无法重开成品原稿:{error}"))?; @@ -1387,7 +1402,7 @@ mod tests { fn delivered_long_canvas_reopens_as_layered_psb_with_editable_text() { use photocraft_doc::{Layer, LayerContent, TextLayer, text::{CharStyle, TextRun}}; - let (root, project, local, mut input) = fixture(); + let (_root, project, local, mut input) = fixture(); let policy = transfer::Policy { chat: false, scope: "owner", project: &local }; let mut canvas = Document::new("长详情", Size::new(16, 30_001), ColorMode::Rgb, SampleType::U8); let style = CharStyle { font_family: "Arial".into(), size_pt: 18.0, ..Default::default() }; @@ -1409,10 +1424,12 @@ mod tests { input["total"] = json!(1); let delivered = deliver_production_bundle(&project, &policy, &input, || Ok(())).unwrap(); let final_dir = Path::new(delivered["path"].as_str().unwrap()); - let copy = root.path().join("详情页.psb"); - fs::copy(final_dir.join("PSD/详情页.psb"), ©).unwrap(); - let bytes = fs::read(copy).unwrap(); - let imported = photocraft_io::import("详情页.psb", &bytes).unwrap().document; + let path = final_dir.join("PSD/详情页.psb"); + assert_eq!(artifact_size(&path, "psb").unwrap(), Some((16, 30_001))); + assert_eq!(artifact_size(&path, "psd").unwrap_err(), "分层文件扩展名与文件头不一致"); + let imported = photocraft_io::import_file( + "详情页.psb", &path, &Default::default(), &photocraft_raster::Interrupt::NONE, + ).unwrap().document; assert_eq!(imported.size, canvas.size); let layer = imported.layers.iter().find(|layer| layer.name == "成稿文案").unwrap(); let LayerContent::Text(text) = &layer.content else { panic!("保留可编辑文字图层"); }; @@ -1504,7 +1521,7 @@ mod tests { let (_root, project, local, mut input) = fixture(); let policy = transfer::Policy { chat: false, scope: "owner", project: &local }; let variant = input["published"][0]["variantId"].as_str().unwrap().to_owned(); - let doc = Document::new("浅橡木", Size::new(8, 12), ColorMode::Rgb, SampleType::U8); + let doc = Document::new("浅橡木", Size::new(8, 14), ColorMode::Rgb, SampleType::U8); let receipt = canvas_workspace::receipt_path(&project, &variant, "sku_images"); let mut sku = json!({"workspaceId":input["workspaceId"],"variantId":variant,"outputId":"sku_images"}); canvas_workspace::publish_product_generation( @@ -1524,12 +1541,12 @@ mod tests { assert_eq!(delivered["state"], "bundle_saved"); let bundle = Path::new(delivered["path"].as_str().unwrap()); for relative in [ - "SKU/01 浅橡木/8x4/01/001-Blue.jpg", - "SKU/01 浅橡木/8x4/02/001-Blue.jpg", - "SKU/01 浅橡木/8x6/001-Blue.jpg", + "SKU/8x4/01/001-Blue.jpg", + "SKU/8x4/02/001-Blue.jpg", + "SKU/8x6/001-Blue.jpg", ] { assert!(bundle.join(relative).is_file(), "missing {relative}"); } - assert!(!bundle.join("SKU/01 浅橡木/8x4/001-Blue.jpg").exists()); + assert!(!bundle.join("SKU/8x4/001-Blue.jpg").exists()); } } diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_knowledge_http.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_knowledge_http.rs index ebeba77b..b6cff93b 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_knowledge_http.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_knowledge_http.rs @@ -9,8 +9,8 @@ use std::{ net::{Ipv4Addr, SocketAddrV4, TcpListener, TcpStream}, process::Command, sync::{Arc, LazyLock, Mutex, OnceLock}, - sync::atomic::{AtomicU8, Ordering}, - time::Duration, + sync::atomic::{AtomicBool, AtomicU8, Ordering}, + time::{Duration, Instant}, }; const XIAOYI_CREDENTIAL_NAME: &str = "企业知识库/小壹"; @@ -41,11 +41,16 @@ const TOKEN_PREFIX: &str = "ekb_xiaoyi_session_"; const CREDENTIAL_CACHE_TTL: Duration = Duration::from_secs(15); -#[derive(Clone)] struct CachedCredential { - token: String, - cached_at: std::time::Instant, - expires_at: Option, + token: Arc, + valid_until: Instant, +} + +#[derive(Default)] +struct Credentials { + cached: Mutex>, + refresh: Mutex<()>, + retired: AtomicBool, } #[derive(Clone)] @@ -56,14 +61,28 @@ struct Account { access: super::AccountAccess, http: super::NetworkClient, channel: Arc, - cached: Arc>>, + credentials: Arc, } impl Account { - fn clear_cached(&self) { - if let Ok(mut guard) = self.cached.lock() { - *guard = None; + fn check_access(&self) -> R<()> { + if self.credentials.retired.load(Ordering::Acquire) { + return Err(PORTAL_LOGIN.into()); } + self.access.check().map_err(|_| PORTAL_LOGIN.into()) + } + + fn clear_cached(&self, rejected: Option<&Arc>) { + if let Ok(mut cached) = self.credentials.cached.lock() + && rejected.is_none_or(|token| cached.as_ref().is_some_and(|entry| Arc::ptr_eq(token, &entry.token))) + { + *cached = None; + } + } + + fn retire(&self) { + self.credentials.retired.store(true, Ordering::Release); + self.clear_cached(None); } } @@ -76,16 +95,18 @@ pub(super) fn set_account(backend: &super::Backend) { }; let token = backend.auth["access_token"].as_str().unwrap_or_default(); let account_id = backend.auth["account"]["id"].as_str().unwrap_or_default(); - if token.is_empty() || account_id.is_empty() { - *current = None; - return; - } if current.as_ref().is_some_and(|account| account.origin == backend.origin && account.token == token && account.account_id == account_id && account.access.epoch == backend.access.epoch) { return; } + if let Some(previous) = current.take() { + previous.retire(); + } + if token.is_empty() || account_id.is_empty() { + return; + } *current = Some(Account { origin: backend.origin.clone(), token: token.to_owned(), @@ -93,7 +114,7 @@ pub(super) fn set_account(backend: &super::Backend) { access: backend.access.clone(), http: backend.http.clone(), channel: Arc::new(AtomicU8::new(0)), - cached: Arc::new(Mutex::new(None)), + credentials: Arc::default(), }); } @@ -101,9 +122,11 @@ pub(super) fn clear_account(backend: &super::Backend) { if let Ok(mut current) = ACCOUNT.lock() && current.as_ref().is_some_and(|account| account.origin == backend.origin && backend.auth["access_token"].as_str() == Some(account.token.as_str()) + && backend.auth["account"]["id"].as_str() == Some(account.account_id.as_str()) && account.access.epoch == backend.access.epoch) + && let Some(account) = current.take() { - *current = None; + account.retire(); } } @@ -111,46 +134,45 @@ fn current_account() -> R { ACCOUNT.lock().map_err(|_| PORTAL_UNAVAILABLE)?.clone().ok_or_else(|| PORTAL_LOGIN.into()) } -fn account_credential(account: &Account) -> R { - account.access.check().map_err(|_| PORTAL_LOGIN)?; - if let Ok(guard) = account.cached.lock() - && let Some(entry) = guard.as_ref() - && entry.cached_at.elapsed() < CREDENTIAL_CACHE_TTL - && entry.expires_at.is_none_or(|exp| std::time::Instant::now() + Duration::from_secs(2) < exp) +fn account_credential(account: &Account) -> R> { + // A parallel batch shares one exchange. Retirement and HTTP rejections can still + // clear the cached token while the signer is in flight. + let _refresh = account.credentials.refresh.lock().map_err(|_| PORTAL_UNAVAILABLE)?; + account.check_access()?; { - return Ok(entry.token.clone()); + let mut cached = account.credentials.cached.lock().map_err(|_| PORTAL_UNAVAILABLE)?; + if let Some(entry) = cached.as_ref() + && Instant::now() < entry.valid_until + { + return Ok(Arc::clone(&entry.token)); + } + *cached = None; } // Each uncached exchange uses the current material-library account and role. let request = account.http.get(format!("{}/api/desktop/knowledge/session", account.origin)) .bearer_auth(&account.token).timeout(Duration::from_secs(8)); - let deadline = std::time::Instant::now() + Duration::from_secs(8); + let deadline = Instant::now() + Duration::from_secs(8); let mut misconfigured = false; let mut payload = Ok(Value::Null); let response = account.http.read_with(request, Some(deadline), |response| { let status = response.status().as_u16(); if status == 200 { payload = super::response_json(response, super::MAX_JSON); - return matches!(payload, Err(super::JsonResponseError::Read(_))) && account.access.check().is_ok(); + return matches!(payload, Err(super::JsonResponseError::Read(_))) && account.check_access().is_ok(); } if status == 503 { misconfigured = super::response_json(response, 16 * 1024).is_ok_and(|value| value["code"] == "knowledge_session_misconfigured"); } - knowledge_transient_status(status) && !misconfigured && account.access.check().is_ok() + knowledge_transient_status(status) && !misconfigured && account.check_access().is_ok() }).map_err(|error| if error.is_timeout() { PORTAL_TIMEOUT } else { PORTAL_UNAVAILABLE })?; let status = response.status().as_u16(); - account.access.check().map_err(|_| PORTAL_LOGIN)?; + account.check_access()?; match status { 404 => return Err(SESSION_MISSING.into()), 503 if misconfigured => return Err(SESSION_UNAVAILABLE.into()), - 401 => { - account.clear_cached(); - return Err(PORTAL_LOGIN.into()); - } - 403 => { - account.clear_cached(); - return Err(PORTAL_FORBIDDEN.into()); - } + 401 => return Err(PORTAL_LOGIN.into()), + 403 => return Err(PORTAL_FORBIDDEN.into()), 200 => {} 500..=599 => return Err(PORTAL_SERVER.into()), _ => return Err(AUTOMATIC_INVALID.into()), @@ -160,28 +182,20 @@ fn account_credential(account: &Account) -> R { super::JsonResponseError::Read(_) => PORTAL_UNAVAILABLE, _ => AUTOMATIC_INVALID, })?; - account.access.check().map_err(|_| PORTAL_LOGIN)?; let token = value["token"].as_str().filter(|token| token.starts_with(TOKEN_PREFIX)) .ok_or(AUTOMATIC_INVALID)?; - // The knowledge server checks expiry with its own clock. + // The knowledge server enforces expiry. The local clock only bounds cache reuse. let parsed_expiry = value["expiresAt"].as_str() .and_then(|expiry| chrono::DateTime::parse_from_rfc3339(expiry).ok()) .ok_or(AUTOMATIC_INVALID)?; - let normalized = normalize_key(token).map_err(|_| AUTOMATIC_INVALID)?; - let expires_at = (parsed_expiry.with_timezone(&chrono::Utc) - chrono::Utc::now()) - .to_std() - .ok() - .map(|ttl| std::time::Instant::now() + ttl); - if account.access.check().is_ok() - && let Ok(mut guard) = account.cached.lock() - { - *guard = Some(CachedCredential { - token: normalized.clone(), - cached_at: std::time::Instant::now(), - expires_at, - }); - } - Ok(normalized) + let token: Arc = normalize_key(token).map_err(|_| AUTOMATIC_INVALID)?.into(); + let remaining = (parsed_expiry.with_timezone(&chrono::Utc) - chrono::Utc::now()) + .to_std().unwrap_or_default(); + let ttl = CREDENTIAL_CACHE_TTL.min(remaining.saturating_sub(Duration::from_secs(2))); + let mut cached = account.credentials.cached.lock().map_err(|_| PORTAL_UNAVAILABLE)?; + account.check_access()?; + *cached = (!ttl.is_zero()).then(|| CachedCredential { token: Arc::clone(&token), valid_until: Instant::now() + ttl }); + Ok(token) } fn verify_automatic_key() -> Value { @@ -493,14 +507,14 @@ fn secure_portal(origin: &str) -> bool { fn automatic_response( account: &Account, origin: &str, path: &str, input: &Value, -) -> R<(reqwest::blocking::Response, String)> { +) -> R<(reqwest::blocking::Response, Arc)> { use KnowledgeChannel::{Direct, Portal}; if !allows_xiaoyi_origin(origin) { return Err(XIAOYI_ORIGIN_REQUIRED.into()); } let last = account.channel.load(Ordering::Relaxed); let preferred = if last == Portal as u8 { [Portal, Direct] } else { [Direct, Portal] }; let mut diagnosis = NETWORK; - for channel in preferred { - account.access.check().map_err(|_| PORTAL_LOGIN)?; + 'channels: for channel in preferred { + account.check_access()?; let clients = if is_large(path) { &DOWNLOAD_CLIENT } else { &METADATA_CLIENT }; let (client, address, key) = match channel { Direct => { @@ -516,25 +530,45 @@ fn automatic_response( Portal => { if !secure_portal(&account.origin) { continue; } let address = format!("{}/api/desktop/knowledge/proxy{path}", account.origin); - (account.http.client(&address), address, account.token.clone()) + (account.http.client(&address), address, Arc::from(account.token.as_str())) } }; - account.access.check().map_err(|_| PORTAL_LOGIN)?; - let result = Route::Xiaoyi.request(client, address, input)?.bearer_auth(&key) - .timeout(Duration::from_secs(clients.timeout_seconds)).send(); - let mut response = match result { - Ok(response) => response, - Err(error) => { - diagnosis = if error.is_timeout() { TIMEOUT } else { NETWORK }; - continue; - } + let send = |key: &str| { + account.check_access()?; + let request = Route::Xiaoyi.request(client, address.clone(), input)?.bearer_auth(key) + .timeout(Duration::from_secs(clients.timeout_seconds)); + let result = request.send(); + account.check_access()?; + Ok::<_, String>(result) + }; + let mut key = key; + let mut may_refresh = channel == Direct; + let mut response = loop { + let response = match send(&key)? { + Ok(response) => response, + Err(error) => { + diagnosis = if error.is_timeout() { TIMEOUT } else { NETWORK }; + continue 'channels; + } + }; + let status = response.status().as_u16(); + if !matches!(status, 401 | 403) { + break response; + } + if channel == Portal { + account.clear_cached(None); + break response; + } + account.clear_cached(Some(&key)); + if !may_refresh { + if status == 401 { return Err(AUTOMATIC_INVALID.into()); } + break response; + } + drop(response); + may_refresh = false; + key = account_credential(account)?; }; - account.access.check().map_err(|_| PORTAL_LOGIN)?; let status = response.status().as_u16(); - if matches!(status, 401 | 403) { - account.clear_cached(); - } - if channel == Direct && status == 401 { return Err(AUTOMATIC_INVALID.into()); } if knowledge_transient_status(status) { if status == 503 && let Ok(value) = super::response_json(&mut response, 16 * 1024) { match value["code"].as_str() { @@ -562,7 +596,7 @@ fn automatic_response( fn exchange_automatic(account: &Account, input: &Value, emit: &mut impl FnMut(Value) -> R<()>) -> R<()> { let (response, key) = automatic_response(account, input["origin"].as_str().ok_or(INVALID)?, input["path"].as_str().ok_or(INVALID)?, input)?; - emit_response(response, Some(&key), emit) + emit_response(response, Some(key.as_ref()), emit) } fn exchange_route( @@ -758,40 +792,105 @@ mod tests { #[test] fn jiansun_automatic_knowledge_is_scoped_to_current_login() { const TOKEN: &str = "ekb_xiaoyi_session_test-signature"; + const SIGN: &str = "/api/desktop/knowledge/session"; + const DESKTOP: &str = "synthetic-desktop-session"; + let blob = |index: usize| format!("/api/xiaoyi/v1/blobs/{index:064x}"); let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).unwrap(); let origin = format!("http://{}", listener.local_addr().unwrap()); let server = std::thread::spawn(move || { let expiry = (chrono::Utc::now() + chrono::Duration::seconds(300)).to_rfc3339(); - for (status, body) in [(200, json!({"token":TOKEN,"expiresAt":expiry}).to_string()), - (403, r#"{"code":"account_inactive"}"#.to_owned())] { + let requests = std::iter::once((SIGN.to_owned(), DESKTOP, 200, json!({"token":TOKEN,"expiresAt":expiry}).to_string())) + .chain((0..50).map(|index| (blob(index), TOKEN, 200, String::new()))) + .chain(std::iter::once((SIGN.to_owned(), DESKTOP, 403, r#"{"code":"account_inactive"}"#.to_owned()))); + for (path, key, status, body) in requests { let (mut stream, _) = listener.accept().unwrap(); stream.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); let mut lines = BufReader::new(&mut stream).lines(); - assert_eq!(lines.next().unwrap().unwrap(), "GET /api/desktop/knowledge/session HTTP/1.1"); + assert_eq!(lines.next().unwrap().unwrap(), format!("GET {path} HTTP/1.1")); assert!(lines.map(Result::unwrap).take_while(|line| !line.is_empty()) - .any(|line| line == "authorization: Bearer synthetic-desktop-session")); + .any(|line| line == format!("authorization: Bearer {key}"))); write!(stream, "HTTP/1.1 {status} Fixture\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len()).unwrap(); } }); let access = super::super::AccountAccess::default(); let client = Client::builder().no_proxy().timeout(Duration::from_secs(5)).build().unwrap(); let account = Account { - origin, token: "synthetic-desktop-session".into(), account_id: "test-user".into(), + origin: origin.clone(), token: DESKTOP.into(), account_id: "test-user".into(), access: access.clone(), http: client.into(), - channel: Arc::new(AtomicU8::new(0)), - cached: Arc::new(Mutex::new(None)), + channel: Arc::new(AtomicU8::new(KnowledgeChannel::Direct as u8)), + credentials: Arc::default(), }; - assert!(matches!(account_credential(&account), Ok(token) if token == TOKEN)); - // Within 15s TTL, repeated calls reuse the cached credential without hitting the server. - assert!(matches!(account_credential(&account), Ok(token) if token == TOKEN)); - // Clearing cache (e.g. after upstream 401/403) forces re-exchange on next call. - account.clear_cached(); + std::thread::scope(|scope| { + let account = &account; + for _ in 0..8 { + scope.spawn(move || assert_eq!(&*account_credential(account).unwrap(), TOKEN)); + } + }); + for index in 0..50 { + let (response, _) = automatic_response(&account, &origin, &blob(index), &json!({"headers":{}})).unwrap(); + assert_eq!(response.status().as_u16(), 200); + } + account.credentials.cached.lock().unwrap().as_mut().unwrap().valid_until = Instant::now(); assert!(matches!(account_credential(&account), Err(error) if error == PORTAL_FORBIDDEN)); server.join().unwrap(); access.invalidate(); assert!(matches!(account_credential(&account), Err(error) if error == PORTAL_LOGIN)); } + #[test] + fn jiansun_direct_blob_rejection_refreshes_at_most_once() { + const SIGN: &str = "/api/desktop/knowledge/session"; + const BLOB: &str = "/api/xiaoyi/v1/blobs/test"; + const DESKTOP: &str = "synthetic-desktop-session"; + const FIRST: &str = "ekb_xiaoyi_session_first-fixture"; + const SECOND: &str = "ekb_xiaoyi_session_second-fixture"; + for (rejection, retried) in [(401, 200), (403, 403)] { + let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).unwrap(); + let origin = format!("http://{}", listener.local_addr().unwrap()); + let server = std::thread::spawn(move || { + listener.set_nonblocking(true).unwrap(); + let deadline = Instant::now() + Duration::from_secs(5); + let expiry = (chrono::Utc::now() + chrono::Duration::minutes(5)).to_rfc3339(); + for (path, key, status, body) in [ + (SIGN, DESKTOP, 200, json!({"token":FIRST,"expiresAt":expiry}).to_string()), + (BLOB, FIRST, rejection, String::new()), + (SIGN, DESKTOP, 200, json!({"token":SECOND,"expiresAt":expiry}).to_string()), + (BLOB, SECOND, retried, String::new()), + ] { + let mut stream = loop { + match listener.accept() { + Ok((stream, _)) => break stream, + Err(error) if error.kind() == std::io::ErrorKind::WouldBlock && Instant::now() < deadline => + std::thread::sleep(Duration::from_millis(5)), + Err(error) => panic!("missing fixture request for {path}: {error}"), + } + }; + stream.set_nonblocking(false).unwrap(); + stream.set_read_timeout(Some(Duration::from_secs(2))).unwrap(); + let mut lines = BufReader::new(&mut stream).lines(); + assert_eq!(lines.next().unwrap().unwrap(), format!("GET {path} HTTP/1.1")); + assert!(lines.map(Result::unwrap).take_while(|line| !line.is_empty()) + .any(|line| line == format!("authorization: Bearer {key}"))); + write!(stream, "HTTP/1.1 {status} Fixture\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len()).unwrap(); + } + }); + let account = Account { + origin: origin.clone(), token: DESKTOP.into(), account_id: "test-user".into(), + access: super::super::AccountAccess::default(), http: client(5).unwrap().into(), + channel: Arc::new(AtomicU8::new(KnowledgeChannel::Direct as u8)), + credentials: Arc::default(), + }; + let (response, _) = automatic_response(&account, &origin, BLOB, &json!({"headers":{}})).unwrap(); + assert_eq!(response.status().as_u16(), retried); + assert_eq!(account.credentials.cached.lock().unwrap().is_some(), retried == 200); + let old_account = account.clone(); + account.retire(); + assert!(old_account.credentials.cached.lock().unwrap().is_none()); + assert_eq!(account_credential(&old_account).unwrap_err(), PORTAL_LOGIN); + server.join().unwrap(); + } + } + #[test] fn jiansun_missing_knowledge_signer_returns_http_diagnostics() { for (status, body, code, message) in [ @@ -815,7 +914,7 @@ mod tests { origin, token: "synthetic-desktop-session".into(), account_id: "test-user".into(), access: super::super::AccountAccess::default(), http: client(5).unwrap().into(), channel: Arc::new(AtomicU8::new(0)), - cached: Arc::new(Mutex::new(None)), + credentials: Arc::default(), }; let error = account_credential(&account).unwrap_err(); assert_eq!(error, message); @@ -864,9 +963,9 @@ mod tests { origin, token: "synthetic-desktop-session".into(), account_id: "test-user".into(), access: super::super::AccountAccess::default(), http: super::super::NetworkClient::new(false).unwrap(), channel: Arc::new(AtomicU8::new(0)), - cached: Arc::new(Mutex::new(None)), + credentials: Arc::default(), }; - assert_eq!(account_credential(&account).unwrap(), "ekb_xiaoyi_session_retry-fixture"); + assert_eq!(&*account_credential(&account).unwrap(), "ekb_xiaoyi_session_retry-fixture"); server.join().unwrap(); } @@ -883,7 +982,7 @@ mod tests { token: "synthetic-desktop-portal-session".into(), account_id: "test-user".into(), access: super::super::AccountAccess::default(), http: super::super::NetworkClient::new(false).unwrap(), channel: Arc::new(AtomicU8::new(0)), - cached: Arc::new(Mutex::new(None)), + credentials: Arc::default(), }; const MANIFEST: &str = "/api/xiaoyi/v1/templates/chair/releases/v1/manifest"; const BUNDLE: &str = "/api/xiaoyi/v1/templates/chair/releases/v1/bundle"; diff --git a/apps/detail-photocraft/crates/psd/src/file.rs b/apps/detail-photocraft/crates/psd/src/file.rs index f2aeb902..8083862e 100644 --- a/apps/detail-photocraft/crates/psd/src/file.rs +++ b/apps/detail-photocraft/crates/psd/src/file.rs @@ -290,17 +290,17 @@ impl PsdFile { pub fn to_bytes(&self) -> Result> { let (v, widen) = self.write_form(); let psb = v.is_psb(); - // Reserve the pixel data up front: appending it to an empty Vec reallocates and copies - // repeatedly. Everything else (headers, resources, records) is small by comparison. - let widened = if widen { self.rle_widening()? } else { 0 }; - let hint = self - .layer_info - .as_ref() - .map_or(0, LayerInfo::channel_data_len) - .saturating_add(usize::try_from(self.image_data.encoded_len()).unwrap_or(usize::MAX)) - .saturating_add(usize::try_from(widened).unwrap_or(usize::MAX)); let mut out = Vec::new(); - out.try_reserve(hint).map_err(|_| PsdError::OutOfMemory("not enough memory to serialize the file"))?; + let reserve = if psb { + // A pixel-only estimate leaves no room for the PSB headers or records. + // Growing this buffer can copy the whole encoded document and double capacity. + out.try_reserve_exact(usize::try_from(self.encoded_len()?).unwrap_or(usize::MAX)) + } else { + let pixels = self.layer_info.as_ref().map_or(0, LayerInfo::channel_data_len) + .saturating_add(usize::try_from(self.image_data.encoded_len()).unwrap_or(usize::MAX)); + out.try_reserve(pixels) + }; + reserve.map_err(|_| PsdError::OutOfMemory("not enough memory to serialize the file"))?; if widen { Header { version: v, ..self.header.clone() }.write(&mut out); } else { @@ -610,6 +610,17 @@ mod write_tests { use super::*; use crate::{Compression, testgen}; + #[test] + fn long_psb_serializes_without_growing_the_output_buffer() { + let file = testgen::merged_only(Version::Psb, ColorMode::Rgb, 8, Compression::Raw, 32, 30_001); + let bytes = file.to_bytes().unwrap(); + assert_eq!(bytes.len() as u64, file.encoded_len().unwrap()); + assert!(bytes.capacity() <= bytes.len() + 4096); + let reopened = PsdFile::from_bytes(&bytes).unwrap(); + assert_eq!(reopened.header, file.header); + assert_eq!(reopened.decode_merged().unwrap(), file.decode_merged().unwrap()); + } + /// `encoded_len` is exactly what `to_bytes` writes, for every generated file and both layer /// info placements, with and without padding (#5285). #[test]