稳定小壹生图原请求恢复并压缩传输体积
- 线路契约声明压缩出图格式且背景为不透明时,出图改用 JPEG/WebP,契约声明 output_compression 时取 95;R3 所用线路只声明 png/gif 并禁用 output_compression,保持 PNG - 线路接受 JPEG 参考图时,不透明参考图以 JPEG q95 上传;带透明像素的参考图和实拍合成的模板底图保持 PNG。编码由保存的文件扩展名决定,旧请求的规格哈希不变 - 恢复重查改用结构化等待原因(processing、unresolved、running、network),不再按错误文案判断 - 原幂等键查询为 unresolved 时,从首次观测起计 180 秒恢复预算,用完仍为 unresolved 即记为 expired,图位可以另备新请求;410 与 failed 的处理不变,结果有留存时仍按原请求号取回 - 同步 reconcile_image_slots 工具说明与 JIANSUN.md
This commit is contained in:
parent
6b37fae127
commit
04889a4f1e
@ -109,7 +109,7 @@ export const productionOperationTools = [
|
||||
})],
|
||||
['adopt_production_image','采用你选择的候选,返回画布修订和覆盖该图位的模板叠层。尺寸线、虚线、引线、文字和装饰角标的错位或数值是否匹配本款,可用 read_output_screen 查看整屏合成画面。',obj({slotId:slotRef,candidateId:text,fit:optional(fit)})],
|
||||
['retire_production_image','清理你已判为失败的当前图位候选,保留原因、提示词和原请求记录。返工需要旧图时,先让子代理读取再清理。若该图已在画布上,回执会给出应替换的图层。',obj({slotId:slotRef,candidateId:text,reason:text})],
|
||||
['reconcile_image_slots','按已保存的原操作或原候选号核查结果。未绑定画布时核查本轮项目输出,可用完整图位 id 缩小范围。unknown 继续核查原号;expired 表示原结果已过期,可以为同图位另备新请求。',obj({slotIds:optional(ids)})],
|
||||
['reconcile_image_slots','按已保存的原操作或原候选号核查结果。未绑定画布时核查本轮项目输出,可用完整图位 id 缩小范围。unknown 继续核查原号,结果有留存时按原号取回,不重新付费。expired 表示原结果已不可取回:网关确认结果过期(HTTP 410),或原请求在 180 秒恢复预算用完后仍是 unresolved。expired 可以为同图位另备新请求;已派发的原请求仍计入该图位的生图次数上限。',obj({slotIds:optional(ids)})],
|
||||
['read_output_screen',`读取整屏合成画面的实际像素和 overlayLayers。page 指定单屏,pages 可按需查看 2–4 屏,屏号从 0 开始。后续新读图时自动释放较早的截图并保留文字元数据。${COPY_IMAGE_SCREEN_GUIDANCE}`,obj({
|
||||
page:optional(page),pages:optional(Type.Array(page)),
|
||||
})],
|
||||
|
||||
@ -63,9 +63,13 @@ cargo xtask wasm
|
||||
不会转为新的生成请求。缺少请求号、且没有已保存原响应或异步任务号时,使用原幂等键调用
|
||||
`GET /api/external/requests/by-idempotency-key`。只有明确成功、结果可取回、请求号有效,且
|
||||
结果路径精确为该请求的相对公开接口时,才先把请求号保存到两份原任务记录,再 GET 原结果。
|
||||
查询失败、运行中、不可取回或状态不明仍保留待核查,不转换为生成重试。人工补充原请求号
|
||||
查询失败、运行中、不可取回或状态不明仍保留待核查,不转换为生成重试。原幂等键查询为
|
||||
`unresolved` 时,从首次看到它起计 180 秒恢复预算;预算用完仍为 `unresolved` 的原请求记为
|
||||
`expired`,图位可以另备新请求。人工补充原请求号
|
||||
也须通过原 Key 校验,不能覆盖已有的不同请求号。98k 留存接口的原始响应直接解析,另支持
|
||||
明确的 `data` 对象封装。
|
||||
明确的 `data` 对象封装。参考图按线路契约传输:线路接受时,不透明参考图以 JPEG 上传,
|
||||
带透明像素的参考图和实拍合成的模板底图保持 PNG。线路声明压缩出图格式且背景为不透明时,
|
||||
出图请求使用该格式。
|
||||
|
||||
启动后按原账户扫描本机未决任务,只使用原 Key 核查。处理中或临时网络失败按逐渐延长的
|
||||
间隔继续 GET,本次启动共用最多 180 秒恢复窗口;404、410、无法确认归属或结果不可取回
|
||||
|
||||
@ -5634,6 +5634,29 @@ mod tests {
|
||||
assert_eq!(pending_summary(&fixture.dir).unwrap()[0]["id"], next["id"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unresolved_original_releases_its_slot_once_the_recovery_budget_is_spent() {
|
||||
let fixture = fixture();
|
||||
let original = candidate(&fixture.dir, "dispatched");
|
||||
let next = candidate(&fixture.dir, "dispatched");
|
||||
reserve(&fixture.dir, load(&fixture.dir).unwrap(), &original).unwrap();
|
||||
let request_id = Uuid::new_v4().to_string();
|
||||
let mut task = json!({"id":original["id"],"slotBinding":original["binding"],"phase":"unknown","requestId":request_id});
|
||||
let first = 1_795_781_555;
|
||||
super::super::images::settle_unresolved(&mut task, first);
|
||||
reconcile_candidate(&fixture.dir, &task).unwrap();
|
||||
assert!(reserve(&fixture.dir, load(&fixture.dir).unwrap(), &next).is_err(), "inside its budget the original keeps the slot");
|
||||
super::super::images::settle_unresolved(&mut task, first + super::super::images::IMAGE_REQUEST_TIMEOUT.as_secs());
|
||||
assert_eq!(reconcile_candidate(&fixture.dir, &task).unwrap()["phase"], "expired");
|
||||
assert!(pending_summary(&fixture.dir).unwrap().is_empty());
|
||||
reserve(&fixture.dir, load(&fixture.dir).unwrap(), &next).unwrap();
|
||||
let receipt = candidate_receipt(&read_candidate(&fixture.dir, original["id"].as_str().unwrap()).unwrap());
|
||||
assert_eq!(receipt["status"], "expired");
|
||||
assert_eq!(receipt["retryable"], false);
|
||||
assert_eq!(receipt["requestId"], request_id);
|
||||
assert_eq!(receipt["resultExpiry"]["source"], "unresolved");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn distinct_frozen_requests_can_reserve_the_same_slot_while_the_first_is_pending() {
|
||||
let fixture = fixture();
|
||||
|
||||
@ -2,6 +2,9 @@
|
||||
//! inline private references, and no model-name-specific transport guesses.
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// Quality used when a route declares a compressed result format.
|
||||
pub(super) const OUTPUT_COMPRESSION: u8 = 95;
|
||||
|
||||
fn parts(s: &Value, depth: usize) -> Vec<&Value> {
|
||||
if depth > 5 {
|
||||
return vec![];
|
||||
@ -269,14 +272,38 @@ pub fn select_model(m: &Value) -> Result<Value, String> {
|
||||
params.remove(name);
|
||||
}
|
||||
}
|
||||
let mut body = Value::Object(params.clone());
|
||||
body["model"] = json!(model);
|
||||
body["prompt"] = json!("product scene");
|
||||
body[field] = json!(["data:image/png;base64,AA=="]);
|
||||
if !multipart && !accepts(&body, schema, 0) {
|
||||
let admitted = |params: &serde_json::Map<String, Value>| {
|
||||
let mut body = Value::Object(params.clone());
|
||||
body["model"] = json!(model);
|
||||
body["prompt"] = json!("product scene");
|
||||
body[field] = json!(["data:image/png;base64,AA=="]);
|
||||
multipart || accepts(&body, schema, 0)
|
||||
};
|
||||
if !admitted(¶ms) {
|
||||
continue;
|
||||
}
|
||||
found.push(json!({"path":path,"route":id,"field":field,"multipart":multipart,"probe":probe,"maxImages":max,"schema":schema,"parameters":params}));
|
||||
let declared = |name: &str, value: &Value| {
|
||||
let rules: Vec<_> = nodes.iter().filter_map(|n| n["properties"].get(name)).collect();
|
||||
!rules.is_empty() && rules.iter().all(|rule| accepts(value, rule, 0))
|
||||
};
|
||||
// An opaque result may come back as a compressed raster when the route
|
||||
// declares one. The smaller success body stays within the retained-result limit.
|
||||
if params.get("background") == Some(&json!("opaque"))
|
||||
&& let Some(format) = ["jpeg", "webp"].into_iter().find(|format| declared("output_format", &json!(format)))
|
||||
{
|
||||
let mut compressed = params.clone();
|
||||
compressed.insert("output_format".into(), json!(format));
|
||||
if declared("output_compression", &json!(OUTPUT_COMPRESSION)) {
|
||||
compressed.insert("output_compression".into(), json!(OUTPUT_COMPRESSION));
|
||||
}
|
||||
if admitted(&compressed) {
|
||||
params = compressed;
|
||||
}
|
||||
}
|
||||
// Multipart files carry their own type; an inline field must accept a JPEG data URL.
|
||||
let jpeg_references = multipart || nodes.iter().all(|n| accepts(&json!(["data:image/jpeg;base64,AA=="]), &n["properties"][field], 0));
|
||||
found.push(json!({"path":path,"route":id,"field":field,"multipart":multipart,"probe":probe,"maxImages":max,"schema":schema,
|
||||
"parameters":params,"jpegReferences":jpeg_references}));
|
||||
}
|
||||
}
|
||||
found.sort_by_key(|p| (p["probe"] == true, p["path"] != "/extensions/v1/tasks", p["multipart"] == true));
|
||||
@ -328,6 +355,66 @@ mod tests {
|
||||
assert_eq!(p["maxImages"], 8);
|
||||
assert_eq!(p["parameters"], json!({"n":1,"response_format":"b64_json"}));
|
||||
}
|
||||
fn route(path: &str, content_type: &str, schema: Value) -> Result<Value, String> {
|
||||
let mut c = catalog();
|
||||
let invocation = &mut c["data"]["sections"][0]["models"][0]["service_offers"][0]["route_options"][0]["invocation"];
|
||||
invocation["path"] = json!(path);
|
||||
invocation["content_type"] = json!(content_type);
|
||||
invocation["input_schema"] = schema;
|
||||
select(&c, "test-image")
|
||||
}
|
||||
fn edit_schema(output_format: Value, output_compression: Option<Value>, background: &str) -> Value {
|
||||
let mut schema = json!({"type":"object","additionalProperties":true,"properties":{"model":{"type":"string"},"prompt":{"type":"string"},
|
||||
"image[]":{},"n":{"type":"integer"},"response_format":{"enum":["url","b64_json"]},
|
||||
"background":{"enum":["opaque","auto","transparent"],"default":background},"output_format":output_format}});
|
||||
if let Some(rule) = output_compression {
|
||||
schema["properties"]["output_compression"] = rule;
|
||||
}
|
||||
schema
|
||||
}
|
||||
#[test]
|
||||
fn opaque_results_use_only_a_compressed_format_the_route_declares() {
|
||||
let edits = |schema| route("/v1/images/edits", "multipart/form-data", schema).unwrap()["parameters"].clone();
|
||||
let png_or_jpeg = json!({"enum":["png","jpeg","webp"],"default":"png"});
|
||||
let compression = json!({"type":["integer","null"],"minimum":0,"maximum":100});
|
||||
let declared = edits(edit_schema(png_or_jpeg.clone(), Some(compression.clone()), "opaque"));
|
||||
assert_eq!(declared["output_format"], "jpeg");
|
||||
assert_eq!(declared["output_compression"], OUTPUT_COMPRESSION);
|
||||
assert_eq!(declared["background"], "opaque");
|
||||
assert_eq!(edits(edit_schema(json!({"enum":["png","webp"],"default":"png"}), Some(compression.clone()), "opaque"))["output_format"], "webp");
|
||||
let uncontrolled = edits(edit_schema(png_or_jpeg.clone(), None, "opaque"));
|
||||
assert_eq!(uncontrolled["output_format"], "jpeg");
|
||||
assert!(uncontrolled.get("output_compression").is_none(), "an undeclared compression control is never sent");
|
||||
// The R3 route publishes PNG/GIF only and disables output_compression.
|
||||
let png_only = edits(edit_schema(json!({"enum":["png","gif"],"type":"string","default":"png"}), Some(json!(false)), "opaque"));
|
||||
assert_eq!(png_only["output_format"], "png");
|
||||
assert!(png_only.get("output_compression").is_none());
|
||||
for background in ["auto", "transparent"] {
|
||||
let kept = edits(edit_schema(png_or_jpeg.clone(), Some(compression.clone()), background));
|
||||
assert_eq!(kept["output_format"], "png", "{background} results keep their lossless format");
|
||||
assert!(kept.get("output_compression").is_none());
|
||||
}
|
||||
// A JSON route whose whole contract refuses the compressed body keeps the original choice.
|
||||
let mut strict = edit_schema(png_or_jpeg, Some(compression), "opaque");
|
||||
strict["properties"]["images"] = json!({"type":"array","items":{"type":"string","pattern":"^data:image/"}});
|
||||
strict["not"] = json!({"required":["output_compression"]});
|
||||
let kept = route("/v1/images/edits", "application/json", strict).unwrap();
|
||||
assert_eq!(kept["field"], "images");
|
||||
assert_eq!(kept["parameters"]["output_format"], "png");
|
||||
}
|
||||
#[test]
|
||||
fn references_compress_only_where_the_route_accepts_a_jpeg_reference() {
|
||||
let multipart = route("/v1/images/edits", "multipart/form-data", edit_schema(json!({"enum":["png"]}), None, "opaque")).unwrap();
|
||||
assert_eq!(multipart["jpegReferences"], true, "multipart files declare their own type");
|
||||
let schema = |pattern: &str| json!({"type":"object","additionalProperties":true,"properties":{"model":{"type":"string"},
|
||||
"prompt":{"type":"string"},"images":{"type":"array","items":{"type":"string","pattern":pattern}}}});
|
||||
let png_only = route("/v1/images/edits", "application/json", schema("^data:image/png;base64,")).unwrap();
|
||||
assert_eq!(png_only["field"], "images");
|
||||
assert_eq!(png_only["jpegReferences"], false);
|
||||
let any_image = route("/v1/images/edits", "application/json", schema("^data:image/[^;,]+;base64,")).unwrap();
|
||||
assert_eq!(any_image["jpegReferences"], true);
|
||||
assert_eq!(select(&catalog(), "test-image").unwrap()["jpegReferences"], true, "an open probe field is unrestricted");
|
||||
}
|
||||
#[test]
|
||||
fn explicit_reference_denial_and_nondefault_scopes_are_not_probed() {
|
||||
let mut c = catalog();
|
||||
|
||||
@ -5,6 +5,7 @@ use photocraft_doc::{LayerContent, LayerId};
|
||||
use crate::jiansun_image_protocol as protocol;
|
||||
const IMAGE_BYTES: u64 = 20 * 1024 * 1024;
|
||||
const RESPONSE_BYTES: u64 = 40 * 1024 * 1024;
|
||||
const REFERENCE_JPEG_QUALITY: u8 = 95;
|
||||
pub(super) const IMAGE_REQUEST_TIMEOUT: Duration = Duration::from_secs(180);
|
||||
// New POSTs may wait for a synchronous image result. GET recovery retains its
|
||||
// separate bounded 180s window and never inherits this larger request budget.
|
||||
@ -64,10 +65,19 @@ pub(super) fn read_image_request(dir: &Path, id: &str) -> R<Value> {
|
||||
Ok(request)
|
||||
}
|
||||
|
||||
/// A saved reference names its own wire encoding by its file extension.
|
||||
fn reference_mime(reference: &Value) -> Option<&'static str> {
|
||||
match Path::new(reference["path"].as_str()?).extension()?.to_str()? {
|
||||
"png" => Some("image/png"),
|
||||
"jpg" => Some("image/jpeg"),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn image_spec(task: &Value) -> Value {
|
||||
let references: Vec<_> = task["references"].as_array().into_iter().flatten().map(|reference|
|
||||
json!({"position":reference["position"],"source":reference["source"],"sourceSha256":reference["sourceSha256"],
|
||||
"role":reference["role"],"sha256":reference["sha256"],"size":reference["size"],"encoding":"image/png"})).collect();
|
||||
"role":reference["role"],"sha256":reference["sha256"],"size":reference["size"],"encoding":reference_mime(reference)})).collect();
|
||||
json!({"prompt":task["prompt"],"promptHash":hash(task["prompt"].as_str().unwrap_or("")),"modelId":task["modelId"],
|
||||
"route":task["protocol"]["route"],"protocolPath":task["protocol"]["path"],"parameters":task["protocol"]["parameters"],
|
||||
"encoding":if task["protocol"]["multipart"] == true {"multipart"}else{"json"},
|
||||
@ -101,13 +111,36 @@ fn image_payload(task: &Value, files: &[Vec<u8>]) -> R<Value> {
|
||||
payload["model"] = task["modelId"].clone();
|
||||
payload["prompt"] = task["prompt"].clone();
|
||||
let field = protocol["field"].as_str().ok_or("参考图契约无效")?;
|
||||
payload[field] = json!(files.iter().map(|bytes| format!("data:image/png;base64,{}", STANDARD.encode(bytes))).collect::<Vec<_>>());
|
||||
let references = task["references"].as_array().ok_or("参考图记录无效")?;
|
||||
payload[field] = json!(files.iter().zip(references).map(|(bytes, reference)| {
|
||||
Ok(format!("data:{};base64,{}", reference_mime(reference).ok_or("参考图格式无效")?, STANDARD.encode(bytes)))
|
||||
}).collect::<R<Vec<_>>>()?);
|
||||
if protocol["multipart"] != true && !protocol::accepts(&payload, &protocol["schema"], 0) {
|
||||
return Err("当前参数不满足98k公开契约,未提交".into());
|
||||
}
|
||||
Ok(payload)
|
||||
}
|
||||
|
||||
fn multipart_form(task: &Value, files: Vec<Vec<u8>>) -> R<reqwest::blocking::multipart::Form> {
|
||||
let protocol = &task["protocol"];
|
||||
let field = protocol["field"].as_str().ok_or("参考图契约无效")?;
|
||||
let mut form = reqwest::blocking::multipart::Form::new()
|
||||
.text("model", task["modelId"].as_str().unwrap_or("").to_owned())
|
||||
.text("prompt", task["prompt"].as_str().unwrap_or("").to_owned());
|
||||
for (k, v) in protocol["parameters"].as_object().ok_or("参数记录无效")? {
|
||||
form = form.text(k.clone(), v.as_str().map(str::to_owned).unwrap_or_else(|| v.to_string()));
|
||||
}
|
||||
let references = task["references"].as_array().ok_or("参考图记录无效")?;
|
||||
for (bytes, reference) in files.into_iter().zip(references) {
|
||||
let name = Path::new(reference["path"].as_str().ok_or("参考图记录无效")?).file_name()
|
||||
.and_then(|name| name.to_str()).ok_or("参考图记录无效")?.to_owned();
|
||||
let part = reqwest::blocking::multipart::Part::bytes(bytes).file_name(name)
|
||||
.mime_str(reference_mime(reference).ok_or("参考图格式无效")?).map_err(|_| "参考图类型无效")?;
|
||||
form = form.part(field.to_owned(), part);
|
||||
}
|
||||
Ok(form)
|
||||
}
|
||||
|
||||
pub(super) fn validate_frozen_spec(dir: &Path, task: &Value) -> R<()> {
|
||||
if task["requestSpecHash"] != hash(&image_spec(task).to_string()) {
|
||||
return Err("生图请求内容已变化,请重新准备".into());
|
||||
@ -175,7 +208,7 @@ fn slot_post<T>(dir: &Path, task: &Value, post: impl FnOnce() -> R<T>) -> R<T> {
|
||||
}
|
||||
post()
|
||||
}
|
||||
fn png(bytes: &[u8]) -> R<Vec<u8>> {
|
||||
fn model_raster(bytes: &[u8]) -> R<photocraft_codecs::Image> {
|
||||
let image = photocraft_codecs::decode_with(
|
||||
bytes,
|
||||
&photocraft_codecs::DecodeOptions {
|
||||
@ -187,19 +220,26 @@ fn png(bytes: &[u8]) -> R<Vec<u8>> {
|
||||
let mut image = image.convert(photocraft_codecs::ChannelLayout::Rgba, photocraft_codecs::SampleType::U8);
|
||||
// Model reference copies carry pixels, never camera/location metadata.
|
||||
image.meta = Default::default();
|
||||
let out = photocraft_codecs::encode(&image, photocraft_codecs::Format::Png, &Default::default()).map_err(|_| "图片无法转为PNG")?;
|
||||
Ok(image)
|
||||
}
|
||||
fn encoded(image: &photocraft_codecs::Image, format: photocraft_codecs::Format) -> R<Vec<u8>> {
|
||||
let options = photocraft_codecs::EncodeOptions { jpeg_quality: REFERENCE_JPEG_QUALITY, ..Default::default() };
|
||||
let out = photocraft_codecs::encode(image, format, &options).map_err(|_| "图片无法转码")?;
|
||||
if out.len() as u64 > IMAGE_BYTES {
|
||||
return Err("转码后的图片超过20MiB,请先缩小图片".into());
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
fn png(bytes: &[u8]) -> R<Vec<u8>> {
|
||||
encoded(&model_raster(bytes)?, photocraft_codecs::Format::Png)
|
||||
}
|
||||
// Native Edit Contents/Convert to Smart Object retains a layered .pcraft or
|
||||
// PSD source. Decode that declared native format, then render its own canvas;
|
||||
// a source document is never modified or mistaken for a flat image response.
|
||||
fn reference_png(name: &str, bytes: &[u8]) -> R<Vec<u8>> {
|
||||
fn reference_raster(name: &str, bytes: &[u8]) -> R<photocraft_codecs::Image> {
|
||||
let native = Path::new(name).extension().and_then(|s| s.to_str()).is_some_and(|ext| ext.eq_ignore_ascii_case("pcraft"))
|
||||
|| photocraft_io::is_psd(bytes);
|
||||
if !native { return png(bytes); }
|
||||
if !native { return model_raster(bytes); }
|
||||
let source = photocraft_engine::smart_cmds::decode_source(name, bytes).map_err(|_| "原生智能对象内容无法读取,未提交生图")?;
|
||||
if source.size.width == 0 || source.size.height == 0 || source.size.width > 8192 || source.size.height > 8192
|
||||
|| source.size.width.checked_mul(source.size.height).is_none_or(|pixels| pixels > 24_000_000)
|
||||
@ -207,7 +247,16 @@ fn reference_png(name: &str, bytes: &[u8]) -> R<Vec<u8>> {
|
||||
let rendered = photocraft_io::export(&source, "png", &photocraft_io::ExportOptions { xmp: photocraft_io::XmpEmbed::None, ..Default::default() })
|
||||
.map_err(|_| "原生智能对象参考图无法合成,未提交生图")?;
|
||||
// Same bounded RGBA conversion and metadata removal as ordinary references.
|
||||
png(&rendered.bytes)
|
||||
model_raster(&rendered.bytes)
|
||||
}
|
||||
/// An opaque reference travels as high-quality JPEG when the route accepts it.
|
||||
/// Translucent pixels and a lossless local composite base stay PNG.
|
||||
fn reference_upload(image: &photocraft_codecs::Image, compressed: bool) -> R<(Vec<u8>, &'static str)> {
|
||||
if compressed && !image.has_translucency() {
|
||||
Ok((encoded(image, photocraft_codecs::Format::Jpeg)?, "jpg"))
|
||||
} else {
|
||||
Ok((encoded(image, photocraft_codecs::Format::Png)?, "png"))
|
||||
}
|
||||
}
|
||||
pub(super) fn job_save(dir: &Path, t: &Value) -> R<()> {
|
||||
let _guard = sync::context_guard();
|
||||
@ -577,6 +626,76 @@ fn checked_original_response(
|
||||
}
|
||||
}
|
||||
|
||||
/// Why an unknown original merits another GET within the bounded recovery window.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(super) enum RecoveryWait {
|
||||
/// The original lookup reports the request as still processing.
|
||||
Processing,
|
||||
/// The original lookup has no confirmed outcome (`unresolved`).
|
||||
Unresolved,
|
||||
/// The deferred upstream task is still queued, running or finalizing.
|
||||
Running,
|
||||
/// A GET did not deliver a readable response or met a temporary gateway status.
|
||||
Network,
|
||||
}
|
||||
|
||||
impl RecoveryWait {
|
||||
fn name(self) -> &'static str {
|
||||
match self {
|
||||
Self::Processing => "processing",
|
||||
Self::Unresolved => "unresolved",
|
||||
Self::Running => "running",
|
||||
Self::Network => "network",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn query_kind(path: &str, idempotency: Option<&str>) -> &'static str {
|
||||
if idempotency.is_some() {
|
||||
"lookup"
|
||||
} else if path.starts_with("/extensions/v1/tasks/") {
|
||||
if path.ends_with("/result") { "task-result" } else { "task-status" }
|
||||
} else {
|
||||
"result"
|
||||
}
|
||||
}
|
||||
|
||||
/// The wait a received recovery response reports, from its HTTP status and the
|
||||
/// structured lookup or task status only.
|
||||
fn observed_wait(kind: &str, code: u16, body: &Value) -> Option<RecoveryWait> {
|
||||
match (kind, code) {
|
||||
(_, 502..=504) => Some(RecoveryWait::Network),
|
||||
("lookup", 200) => match body["status"].as_str() {
|
||||
Some("processing") => Some(RecoveryWait::Processing),
|
||||
Some("unresolved") => Some(RecoveryWait::Unresolved),
|
||||
_ => None,
|
||||
},
|
||||
("task-status", 200) => matches!(body["status"].as_str(), Some("queued" | "in_progress" | "finalizing" | "pending_review"))
|
||||
.then_some(RecoveryWait::Running),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// An `unresolved` lookup has no confirmed result. Once it stays unresolved for
|
||||
/// the whole recovery budget, the original is settled as expired and its slot
|
||||
/// may prepare a new request. The first observation is kept durably, so every
|
||||
/// recovery path measures the same budget.
|
||||
pub(super) fn settle_unresolved(task: &mut Value, now: u64) {
|
||||
let since = match task["unresolvedSince"].as_u64() {
|
||||
Some(since) => since,
|
||||
None => {
|
||||
task["unresolvedSince"] = json!(now);
|
||||
now
|
||||
}
|
||||
};
|
||||
if now.saturating_sub(since) >= IMAGE_REQUEST_TIMEOUT.as_secs() {
|
||||
task["phase"] = json!("expired");
|
||||
task["resultExpiry"] = json!({"source":"unresolved","unresolvedSince":since,"observedAt":now,
|
||||
"requestId":task["requestId"],"upstreamTaskId":task["upstreamTaskId"]});
|
||||
task["message"] = json!("原请求在恢复预算内始终未确认结果(unresolved),按已过期处理;可为此图位准备新请求");
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn retry_original_queries(
|
||||
mut query: impl FnMut(Duration) -> R<Value>,
|
||||
mut wait: impl FnMut(Duration),
|
||||
@ -590,21 +709,10 @@ pub(super) fn retry_original_queries(
|
||||
return Err("本次恢复查询窗口已结束,原请求保留待核查;不会重发".into());
|
||||
}
|
||||
let result = query(budget);
|
||||
let message = match &result {
|
||||
Ok(v) if v["phase"] == "unknown" || v["phase"] == "running" => v["reply"].as_str().unwrap_or(""),
|
||||
Err(e) => e,
|
||||
_ => return result,
|
||||
};
|
||||
let transient = message.contains("processing")
|
||||
|| message.contains("unresolved")
|
||||
|| message.contains("原任务仍在生成")
|
||||
|| message.contains("HTTP 202")
|
||||
|| message.contains("连接中断")
|
||||
|| message.contains("HTTP 502")
|
||||
|| message.contains("HTTP 503")
|
||||
|| message.contains("HTTP 504");
|
||||
// Only a pending original with a structured wait earns another GET.
|
||||
let pending = result.as_ref().is_ok_and(|v| matches!(v["phase"].as_str(), Some("unknown" | "running")) && v["recoveryWait"].is_string());
|
||||
let remaining = IMAGE_REQUEST_TIMEOUT.saturating_sub(elapsed());
|
||||
if !transient || message.contains("HTTP 410") || remaining.is_zero() {
|
||||
if !pending || remaining.is_zero() {
|
||||
return result;
|
||||
}
|
||||
let delay = Duration::from_secs(*backoff.get(attempt).unwrap_or(&30));
|
||||
@ -621,6 +729,9 @@ pub(super) fn public(t: &Value, doc: u64, account: &Value, origin: &str) -> Valu
|
||||
receipt["retryable"] = json!(false);
|
||||
receipt["resultExpiry"] = t["resultExpiry"].clone();
|
||||
}
|
||||
if receipt["unknown"] == true {
|
||||
receipt["recoveryWait"] = t["recoveryWait"].clone();
|
||||
}
|
||||
receipt
|
||||
}
|
||||
fn settled_recovery(task: &Value, doc: u64, account: &Value, origin: &str) -> Option<Value> {
|
||||
@ -870,23 +981,22 @@ impl Backend {
|
||||
return Err("参考图超过20MiB,请先缩小图片".into());
|
||||
}
|
||||
let source_hash = preparing.then(|| format!("{:x}", Sha256::digest(bytes.as_slice())));
|
||||
let bytes = reference_png(&name, &bytes)?;
|
||||
let raster = reference_raster(&name, &bytes)?;
|
||||
let (width, height) = (raster.width(), raster.height());
|
||||
if scene.is_some() {
|
||||
let (width, height) = image::ImageReader::with_format(std::io::Cursor::new(&bytes), image::ImageFormat::Png)
|
||||
.into_dimensions().map_err(|_| "模板场景画幅无法读取,未提交擦除")?;
|
||||
protocol::frame(&mut contract, u64::from(width), u64::from(height), false)?;
|
||||
}
|
||||
// The scene composite reuses its template base locally, so it stays lossless.
|
||||
let (bytes, extension) = reference_upload(&raster, scene.is_none() && contract["jpegReferences"] == true)?;
|
||||
total = total.saturating_add(bytes.len());
|
||||
if bytes.len() > 10 * 1024 * 1024 || total > 24 * 1024 * 1024 {
|
||||
return Err("参考图总量过大,请减少图片".into());
|
||||
}
|
||||
let path = files.join(format!("reference-{i}.png"));
|
||||
let path = files.join(format!("reference-{i}.{extension}"));
|
||||
check()?;
|
||||
job_bytes(&dir, &path, &bytes, || Ok(())).map_err(|_| "参考图保存失败,未提交")?;
|
||||
let mut reference = json!({"layer":layer.0,"name":name,"path":path.to_string_lossy(),"sha256":format!("{:x}",Sha256::digest(&bytes))});
|
||||
if preparing {
|
||||
let [width,height] = image::ImageReader::with_format(std::io::Cursor::new(&bytes), image::ImageFormat::Png)
|
||||
.into_dimensions().map(|(w,h)| [w,h]).map_err(|_| "参考图尺寸无法读取")?;
|
||||
reference["position"] = json!(i + 1);
|
||||
reference["source"] = input["referenceOrigins"][i]["source"].clone();
|
||||
reference["role"] = input["referenceOrigins"][i]["purpose"].clone();
|
||||
@ -950,6 +1060,8 @@ impl Backend {
|
||||
let _ = tx.send(Event::Json("image-progress".into(), Ok(v)));
|
||||
ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
};
|
||||
// The structured reason this attempt leaves the original pending, if any.
|
||||
let wait = std::cell::Cell::new(None::<RecoveryWait>);
|
||||
let result = (|| -> R<()> {
|
||||
let raw_file = taskdir.join("response.json");
|
||||
let mut deferred_result_ready = false;
|
||||
@ -972,10 +1084,7 @@ impl Backend {
|
||||
progress(if idempotency.is_some() { "正在定位原请求…" } else { "正在核查原请求…" }, false);
|
||||
let diagnostic_file = taskdir.join("recovery-http.json");
|
||||
let mut diagnostic = if diagnostic_file.exists() { read_json(&diagnostic_file)? } else { json!({"attempts":[]}) };
|
||||
let kind = if idempotency.is_some() { "lookup" }
|
||||
else if path.starts_with("/extensions/v1/tasks/") {
|
||||
if path.ends_with("/result") { "task-result" } else { "task-status" }
|
||||
} else { "result" };
|
||||
let kind = query_kind(path, idempotency);
|
||||
let attempt = json!({"session":session,"kind":kind,"method":"GET","at":now(),"status":null});
|
||||
let rows = diagnostic["attempts"].as_array_mut().ok_or("恢复诊断记录无效")?;
|
||||
if rows.len() >= 256 {
|
||||
@ -989,7 +1098,10 @@ impl Backend {
|
||||
request = request.header("Idempotency-Key", id);
|
||||
}
|
||||
check()?;
|
||||
let response = request.send().map_err(|_| "原请求只读查询连接中断,保留待核查;不会重发")?;
|
||||
let response = request.send().map_err(|_| {
|
||||
wait.set(Some(RecoveryWait::Network));
|
||||
"原请求只读查询连接中断,保留待核查;不会重发"
|
||||
})?;
|
||||
check()?;
|
||||
if let Some(last) = diagnostic["attempts"].as_array_mut().and_then(|a| a.last_mut()) {
|
||||
last["status"] = json!(response.status().as_u16());
|
||||
@ -999,7 +1111,11 @@ impl Backend {
|
||||
return Ok((410, Value::Null));
|
||||
}
|
||||
self.check_model_authority(&response, key)?;
|
||||
let decoded = body(response, if matches!(kind, "lookup" | "task-status") { 64 * 1024 } else { RESPONSE_BYTES })?;
|
||||
let decoded = body(response, if matches!(kind, "lookup" | "task-status") { 64 * 1024 } else { RESPONSE_BYTES })
|
||||
.inspect_err(|_| wait.set(Some(RecoveryWait::Network)))?;
|
||||
if let Some(observed) = observed_wait(kind, decoded.0, &decoded.1) {
|
||||
wait.set(Some(observed));
|
||||
}
|
||||
check()?;
|
||||
if let Some(last) = diagnostic["attempts"].as_array_mut().and_then(|a| a.last_mut()) {
|
||||
match kind {
|
||||
@ -1033,7 +1149,6 @@ impl Backend {
|
||||
let p = t["protocol"].clone();
|
||||
let files = verified_reference_bytes(&t)?;
|
||||
let payload = image_payload(&t, &files)?;
|
||||
let field = p["field"].as_str().ok_or("参考图契约无效")?;
|
||||
let mut req = self
|
||||
.http
|
||||
.post(format!("{UPSTREAM}{}", p["path"].as_str().ok_or("模型路径无效")?))
|
||||
@ -1042,22 +1157,7 @@ impl Backend {
|
||||
.header("Idempotency-Key", t["id"].as_str().ok_or("任务身份无效")?)
|
||||
.header("X-Relay-Route-Option", p["route"].as_str().ok_or("线路身份无效")?);
|
||||
if p["multipart"] == true {
|
||||
let mut form = reqwest::blocking::multipart::Form::new()
|
||||
.text("model", t["modelId"].as_str().unwrap_or("").to_owned())
|
||||
.text("prompt", t["prompt"].as_str().unwrap_or("").to_owned());
|
||||
for (k, v) in p["parameters"].as_object().ok_or("参数记录无效")? {
|
||||
form = form.text(k.clone(), v.as_str().map(str::to_owned).unwrap_or_else(|| v.to_string()));
|
||||
}
|
||||
for (i, b) in files.into_iter().enumerate() {
|
||||
form = form.part(
|
||||
field.to_owned(),
|
||||
reqwest::blocking::multipart::Part::bytes(b)
|
||||
.file_name(format!("reference-{i}.png"))
|
||||
.mime_str("image/png")
|
||||
.map_err(|_| "参考图类型无效")?,
|
||||
);
|
||||
}
|
||||
req = req.multipart(form);
|
||||
req = req.multipart(multipart_form(&t, files)?);
|
||||
} else {
|
||||
req = req.json(&payload);
|
||||
}
|
||||
@ -1111,18 +1211,25 @@ impl Backend {
|
||||
.bearer_auth(key)
|
||||
.timeout(recovery_timeout(deadline, Duration::from_secs(30))?)
|
||||
.send()
|
||||
.map_err(|_| "任务查询连接中断")?;
|
||||
.map_err(|_| {
|
||||
wait.set(Some(RecoveryWait::Network));
|
||||
"任务查询连接中断"
|
||||
})?;
|
||||
check()?;
|
||||
if response.status() == reqwest::StatusCode::GONE {
|
||||
retain_result_expiry(&mut t, "task-result");
|
||||
return Ok(());
|
||||
}
|
||||
self.check_model_authority(&response, key)?;
|
||||
let (code, v) = body(response, RESPONSE_BYTES)?;
|
||||
let (code, v) = body(response, RESPONSE_BYTES).inspect_err(|_| wait.set(Some(RecoveryWait::Network)))?;
|
||||
if code == 202 && v["ready"] == false {
|
||||
wait.set(Some(RecoveryWait::Running));
|
||||
return Err("原任务仍在生成,可继续查询进度".into());
|
||||
}
|
||||
if code != 200 {
|
||||
if let Some(observed) = observed_wait("task-result", code, &v) {
|
||||
wait.set(Some(observed));
|
||||
}
|
||||
return Err(format!("原任务查询 HTTP {code},继续保留任务"));
|
||||
}
|
||||
if v["ready"] == true && v["status"] == "failed" {
|
||||
@ -1162,16 +1269,25 @@ impl Backend {
|
||||
.bearer_auth(key)
|
||||
.timeout(recovery_timeout(deadline, Duration::from_secs(30))?)
|
||||
.send()
|
||||
.map_err(|_| "图片下载连接中断,保留原结果后可重取")?;
|
||||
.map_err(|_| {
|
||||
wait.set(Some(RecoveryWait::Network));
|
||||
"图片下载连接中断,保留原结果后可重取"
|
||||
})?;
|
||||
if r.status() == reqwest::StatusCode::GONE {
|
||||
retain_result_expiry(&mut t, "image-asset");
|
||||
return Ok(());
|
||||
}
|
||||
if !r.status().is_success() {
|
||||
if let Some(observed) = observed_wait("asset", r.status().as_u16(), &Value::Null) {
|
||||
wait.set(Some(observed));
|
||||
}
|
||||
return Err(format!("98k图片下载 HTTP {},原结果已保留", r.status().as_u16()));
|
||||
}
|
||||
let mut b = Vec::new();
|
||||
r.take(IMAGE_BYTES + 1).read_to_end(&mut b).map_err(|_| "图片下载中断")?;
|
||||
r.take(IMAGE_BYTES + 1).read_to_end(&mut b).map_err(|_| {
|
||||
wait.set(Some(RecoveryWait::Network));
|
||||
"图片下载中断"
|
||||
})?;
|
||||
b
|
||||
};
|
||||
if bytes.len() as u64 > IMAGE_BYTES {
|
||||
@ -1199,14 +1315,25 @@ impl Backend {
|
||||
t["message"] = json!("图片已生成");
|
||||
Ok(())
|
||||
})();
|
||||
if let Err(reason) = result {
|
||||
if t["phase"] == "prepared" {
|
||||
return Err(reason);
|
||||
match result {
|
||||
Err(reason) => {
|
||||
if t["phase"] == "prepared" {
|
||||
return Err(reason);
|
||||
}
|
||||
if t["phase"] != "failed" {
|
||||
t["phase"] = json!("unknown");
|
||||
}
|
||||
t["message"] = json!(reason);
|
||||
t["recoveryWait"] = json!(wait.get().map(RecoveryWait::name));
|
||||
if recover && t["phase"] == "unknown" && wait.get() == Some(RecoveryWait::Unresolved) {
|
||||
settle_unresolved(&mut t, now());
|
||||
}
|
||||
}
|
||||
if t["phase"] != "failed" {
|
||||
t["phase"] = json!("unknown");
|
||||
Ok(()) => {
|
||||
if let Some(fields) = t.as_object_mut() {
|
||||
fields.remove("recoveryWait");
|
||||
}
|
||||
}
|
||||
t["message"] = json!(reason);
|
||||
}
|
||||
persist(&t)?;
|
||||
// Concurrent late GETs may have settled a stronger terminal outcome.
|
||||
@ -1324,18 +1451,91 @@ mod tests {
|
||||
("edited.pcraft", bytes),
|
||||
("edited.psd", photocraft_io::export(doc, "psd", &Default::default()).unwrap().bytes),
|
||||
] {
|
||||
let output = reference_png(name, &input).unwrap();
|
||||
let image = photocraft_codecs::decode(&output).unwrap();
|
||||
let image = reference_raster(name, &input).unwrap();
|
||||
assert_eq!((image.width(), image.height()), (3, 2));
|
||||
assert_eq!(image.data(), [255, 0, 0, 255].repeat(6));
|
||||
}
|
||||
assert_eq!(photocraft_engine::smart_cmds::encode_source(doc).unwrap(), before);
|
||||
assert!(reference_png("broken.pcraft", b"broken").is_err());
|
||||
assert!(reference_raster("broken.pcraft", b"broken").is_err());
|
||||
// Ordinary model outputs still require an image, not a layered file.
|
||||
assert!(png(&before).is_err());
|
||||
session.execute("file.new", json!({"width":8193,"height":1})).unwrap();
|
||||
let oversized = photocraft_engine::smart_cmds::encode_source(&session.active().unwrap().doc).unwrap();
|
||||
assert!(reference_png("oversized.pcraft", &oversized).unwrap_err().contains("8192"));
|
||||
assert!(reference_raster("oversized.pcraft", &oversized).unwrap_err().contains("8192"));
|
||||
}
|
||||
|
||||
fn photo(width: u32, height: u32, alpha: u8) -> photocraft_codecs::Image {
|
||||
let mut pixels = Vec::new();
|
||||
for y in 0..height {
|
||||
for x in 0..width {
|
||||
pixels.extend([(x * 255 / width) as u8, (y * 255 / height) as u8, ((x + y) % 256) as u8, if x == 0 && y == 0 { alpha } else { 255 }]);
|
||||
}
|
||||
}
|
||||
photocraft_codecs::Image::from_raw(width, height, photocraft_codecs::ChannelLayout::Rgba, photocraft_codecs::SampleType::U8, pixels).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opaque_references_upload_as_high_quality_jpeg_while_translucent_or_lossless_bases_stay_png() {
|
||||
let opaque = photo(64, 48, 255);
|
||||
let (jpeg, extension) = reference_upload(&opaque, true).unwrap();
|
||||
assert_eq!(extension, "jpg");
|
||||
assert!(jpeg.starts_with(&[0xff, 0xd8, 0xff]), "a compressed reference is a JPEG stream");
|
||||
let decoded = photocraft_codecs::decode(&jpeg).unwrap();
|
||||
assert_eq!((decoded.width(), decoded.height()), (64, 48));
|
||||
let (png, extension) = reference_upload(&opaque, false).unwrap();
|
||||
assert_eq!(extension, "png");
|
||||
assert!(png.starts_with(b"\x89PNG"));
|
||||
assert_eq!(photocraft_codecs::decode(&png).unwrap().data(), opaque.data(), "the lossless base keeps its exact pixels");
|
||||
let (cutout, extension) = reference_upload(&photo(64, 48, 0), true).unwrap();
|
||||
assert_eq!(extension, "png", "transparent pixels never travel as JPEG");
|
||||
assert_eq!(photocraft_codecs::decode(&cutout).unwrap().data()[3], 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inline_and_multipart_references_carry_the_encoding_of_their_saved_file() {
|
||||
use std::net::TcpListener;
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let jpeg = dir.path().join("reference-0.jpg");
|
||||
let png = dir.path().join("reference-1.png");
|
||||
fs::write(&jpeg, [0xff, 0xd8, 0xff, 0x01]).unwrap();
|
||||
fs::write(&png, b"\x89PNG").unwrap();
|
||||
let task = json!({"modelId":"fixture-image","prompt":"保留原样",
|
||||
"protocol":{"field":"image[]","multipart":true,"parameters":{"output_format":"jpeg","output_compression":95}},
|
||||
"references":[{"path":jpeg,"sha256":format!("{:x}",Sha256::digest([0xff, 0xd8, 0xff, 0x01]))},
|
||||
{"path":png,"sha256":format!("{:x}",Sha256::digest(b"\x89PNG"))}]});
|
||||
let files = verified_reference_bytes(&task).unwrap();
|
||||
let payload = image_payload(&task, &files).unwrap();
|
||||
assert_eq!(payload["image[]"], json!([format!("data:image/jpeg;base64,{}", STANDARD.encode([0xff, 0xd8, 0xff, 0x01])),
|
||||
format!("data:image/png;base64,{}", STANDARD.encode(b"\x89PNG"))]));
|
||||
assert_eq!(payload["output_format"], "jpeg");
|
||||
assert_eq!(payload["output_compression"], 95);
|
||||
// A legacy PNG reference keeps the encoding its frozen request was hashed with.
|
||||
assert_eq!(image_spec(&task)["references"], json!([
|
||||
{"position":null,"source":null,"sourceSha256":null,"role":null,"sha256":task["references"][0]["sha256"],"size":null,"encoding":"image/jpeg"},
|
||||
{"position":null,"source":null,"sourceSha256":null,"role":null,"sha256":task["references"][1]["sha256"],"size":null,"encoding":"image/png"}]));
|
||||
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let address = listener.local_addr().unwrap();
|
||||
let server = std::thread::spawn(move || {
|
||||
let (mut socket, _) = listener.accept().unwrap();
|
||||
socket.set_read_timeout(Some(Duration::from_secs(2))).unwrap();
|
||||
let mut request = Vec::new();
|
||||
let mut chunk = [0u8; 4096];
|
||||
while !String::from_utf8_lossy(&request).contains("--\r\n") {
|
||||
let read = socket.read(&mut chunk).unwrap();
|
||||
assert!(read > 0, "multipart body ended early");
|
||||
request.extend(&chunk[..read]);
|
||||
}
|
||||
write!(socket, "HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\n{{}}").unwrap();
|
||||
String::from_utf8_lossy(&request).into_owned()
|
||||
});
|
||||
let client = Client::builder().no_proxy().timeout(Duration::from_secs(2)).build().unwrap();
|
||||
client.post(format!("http://{address}/local-image-dispatch")).multipart(multipart_form(&task, files).unwrap()).send().unwrap();
|
||||
let wire = server.join().unwrap();
|
||||
assert!(wire.contains("name=\"image[]\"; filename=\"reference-0.jpg\"\r\nContent-Type: image/jpeg"), "{wire}");
|
||||
assert!(wire.contains("name=\"image[]\"; filename=\"reference-1.png\"\r\nContent-Type: image/png"), "{wire}");
|
||||
assert!(wire.contains("name=\"output_format\"\r\n\r\njpeg\r\n"));
|
||||
assert!(wire.contains("name=\"output_compression\"\r\n\r\n95\r\n"));
|
||||
}
|
||||
struct CanvasPostFixture {
|
||||
dir: PathBuf,
|
||||
@ -1431,6 +1631,7 @@ mod tests {
|
||||
task["prompt"] = json!(prompt);
|
||||
task["protocol"] = json!({"parameters":{"quality":"high","size":"1536x2048"},"field":"images",
|
||||
"multipart":true});
|
||||
task["references"] = json!([{"path":"reference-0.png"},{"path":"reference-1.png"}]);
|
||||
let payload = image_payload(&task, &references).unwrap();
|
||||
let post = || -> R<Response> {
|
||||
client.post(format!("http://{address}/local-image-dispatch")).json(&payload).send().map_err(|error| error.to_string())
|
||||
@ -1828,7 +2029,25 @@ mod tests {
|
||||
assert!(!dir.join("image-task.json").exists(), "repair must not recreate a retired current pointer");
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
fn mock_recovery_http(lookup_code: u16, lookup: Value, result_code: u16) -> (R<Value>, Vec<String>, usize) {
|
||||
/// One recovery attempt as `run_image_job` reports it: each GET outcome is
|
||||
/// observed structurally and an unsettled original becomes an unknown receipt.
|
||||
fn attempt_receipt(outcome: R<Value>, wait: Option<RecoveryWait>) -> R<Value> {
|
||||
Ok(outcome.unwrap_or_else(|reason| json!({"phase":"unknown","reply":reason,"recoveryWait":wait.map(RecoveryWait::name)})))
|
||||
}
|
||||
fn observing<'a>(wait: &'a std::cell::Cell<Option<RecoveryWait>>, mut get: impl FnMut(&str, Option<&str>) -> R<(u16, Value)> + 'a)
|
||||
-> impl FnMut(&str, Option<&str>) -> R<(u16, Value)> + 'a {
|
||||
move |path, key| {
|
||||
let response = get(path, key);
|
||||
match &response {
|
||||
Err(_) => wait.set(Some(RecoveryWait::Network)),
|
||||
Ok((code, body)) => if let Some(observed) = observed_wait(query_kind(path, key), *code, body) {
|
||||
wait.set(Some(observed));
|
||||
},
|
||||
}
|
||||
response
|
||||
}
|
||||
}
|
||||
fn mock_recovery_http(lookup_code: u16, lookup: Value, result_code: u16) -> (R<Value>, Vec<String>, usize, Option<RecoveryWait>) {
|
||||
use std::net::{TcpListener, TcpStream};
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
@ -1874,9 +2093,10 @@ mod tests {
|
||||
methods
|
||||
});
|
||||
let mut task = json!({"id":"42e84e04-4738-48c0-b3c0-31ee097b7a35","phase":"unknown","requestId":null});
|
||||
let wait = std::cell::Cell::new(None);
|
||||
let result = original_response(
|
||||
&mut task,
|
||||
|path, key| {
|
||||
observing(&wait, |path, key| {
|
||||
let mut socket = TcpStream::connect(address).map_err(|e| e.to_string())?;
|
||||
socket.set_read_timeout(Some(Duration::from_secs(1))).map_err(|e| e.to_string())?;
|
||||
write!(socket, "GET {path} HTTP/1.1\r\nHost: {address}\r\nIdempotency-Key: {}\r\nConnection: close\r\n\r\n", key.unwrap_or(""))
|
||||
@ -1886,7 +2106,7 @@ mod tests {
|
||||
let (header, body) = response.split_once("\r\n\r\n").ok_or("原请求只读查询连接中断")?;
|
||||
let code = header.split_whitespace().nth(1).ok_or("missing HTTP status")?.parse::<u16>().map_err(|e| e.to_string())?;
|
||||
Ok((code, serde_json::from_str(body).map_err(|e| e.to_string())?))
|
||||
},
|
||||
}),
|
||||
|_| {
|
||||
durable.fetch_add(1, Ordering::SeqCst);
|
||||
Ok(())
|
||||
@ -1899,13 +2119,14 @@ mod tests {
|
||||
});
|
||||
assert_eq!(task["id"], "42e84e04-4738-48c0-b3c0-31ee097b7a35");
|
||||
assert_eq!(task["phase"], "unknown");
|
||||
(result, server.join().unwrap(), durable.load(Ordering::SeqCst))
|
||||
(result, server.join().unwrap(), durable.load(Ordering::SeqCst), wait.get())
|
||||
}
|
||||
#[test]
|
||||
fn restart_http_recovery_uses_only_two_original_gets_with_durable_binding() {
|
||||
let lookup = json!({"request_id":"cc6a9ed9-863b-419f-bd1a-b126833227fb","status":"succeeded","result_available":true,"result_path":"/api/external/requests/cc6a9ed9-863b-419f-bd1a-b126833227fb/result"});
|
||||
let (result, calls, writes) = mock_recovery_http(200, lookup, 200);
|
||||
assert!(result.is_ok());
|
||||
let (result, calls, writes, wait) = mock_recovery_http(200, lookup, 200);
|
||||
assert_eq!(result.unwrap(), json!({"data":[{"b64_json":"original-image"}]}), "the retained original is returned");
|
||||
assert_eq!(wait, None);
|
||||
assert_eq!(writes, 1);
|
||||
assert_eq!(calls.len(), 2);
|
||||
assert!(calls.iter().all(|v| v.starts_with("GET ")));
|
||||
@ -2038,16 +2259,23 @@ mod tests {
|
||||
let mut lookup = original.clone();
|
||||
lookup["status"] = json!(status);
|
||||
lookup["result_available"] = json!(available);
|
||||
let (result, calls, _) = mock_recovery_http(code, lookup, result_code);
|
||||
let (result, calls, _, wait) = mock_recovery_http(code, lookup, result_code);
|
||||
assert!(result.is_err());
|
||||
assert_eq!(calls.len(), expected);
|
||||
assert!(calls.iter().all(|v| v.starts_with("GET ")));
|
||||
// Only a pending lookup state is a reason to query again in this window.
|
||||
assert_eq!(wait, match status {
|
||||
"processing" => Some(RecoveryWait::Processing),
|
||||
"unresolved" => Some(RecoveryWait::Unresolved),
|
||||
_ => None,
|
||||
}, "{code} {status} {result_code}");
|
||||
}
|
||||
let mut foreign = original;
|
||||
foreign["result_path"] = json!("https://other.invalid/result");
|
||||
let (result, calls, _) = mock_recovery_http(200, foreign, 200);
|
||||
let (result, calls, _, wait) = mock_recovery_http(200, foreign, 200);
|
||||
assert!(result.is_err());
|
||||
assert_eq!(calls.len(), 1);
|
||||
assert_eq!(wait, None);
|
||||
}
|
||||
#[test]
|
||||
fn old_recovery_cannot_replace_the_current_project_task() {
|
||||
@ -2079,30 +2307,61 @@ mod tests {
|
||||
lookup["status"] = json!(first_status);
|
||||
lookup["result_available"] = json!(false);
|
||||
}
|
||||
let (result, actual, _) = mock_recovery_http(if invocation == 1 { first_code } else { 200 }, lookup, 200);
|
||||
let (result, actual, _, wait) = mock_recovery_http(if invocation == 1 { first_code } else { 200 }, lookup, 200);
|
||||
calls.extend(actual);
|
||||
result
|
||||
attempt_receipt(result, wait)
|
||||
},
|
||||
|delay| waits.push(delay),
|
||||
|| Duration::ZERO,
|
||||
);
|
||||
assert!(result.is_ok());
|
||||
// The retained result is fetched with the bound original request ID.
|
||||
assert_eq!(result.unwrap(), json!({"data":[{"b64_json":"original-image"}]}));
|
||||
assert_eq!(invocation, 2);
|
||||
assert_eq!(waits, [Duration::from_secs(3)]);
|
||||
assert_eq!(calls.len(), 3);
|
||||
assert!(calls.iter().all(|v| v.starts_with("GET ")));
|
||||
assert!(calls[2].contains("cc6a9ed9-863b-419f-bd1a-b126833227fb/result"));
|
||||
}
|
||||
// Message text alone never earns another GET, whatever it says.
|
||||
for receipt in [
|
||||
Err::<Value, String>("原请求只读查询连接中断(processing,unresolved,HTTP 503)".into()),
|
||||
Ok(json!({"phase":"unknown","reply":"原请求结果待上游确认(unresolved),保留待核查;不会重发","recoveryWait":null})),
|
||||
Ok(json!({"phase":"unknown","reply":"原结果尚未取回(HTTP 410);不会重发"})),
|
||||
] {
|
||||
let mut count = 0;
|
||||
let result = retry_original_queries(
|
||||
|_| {
|
||||
count += 1;
|
||||
receipt.clone()
|
||||
},
|
||||
|_| panic!("an original without a structured wait must not be polled"),
|
||||
|| Duration::ZERO,
|
||||
);
|
||||
assert_eq!(result, receipt);
|
||||
assert_eq!(count, 1);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn received_statuses_map_to_structured_waits_only() {
|
||||
for (kind, code, body, expected) in [
|
||||
("lookup", 200, json!({"status":"processing"}), Some(RecoveryWait::Processing)),
|
||||
("lookup", 200, json!({"status":"unresolved"}), Some(RecoveryWait::Unresolved)),
|
||||
("lookup", 200, json!({"status":"succeeded"}), None),
|
||||
("lookup", 200, json!({"status":"failed"}), None),
|
||||
("lookup", 404, json!({"status":"processing"}), None),
|
||||
("task-status", 200, json!({"status":"in_progress"}), Some(RecoveryWait::Running)),
|
||||
("task-status", 200, json!({"status":"pending_review"}), Some(RecoveryWait::Running)),
|
||||
("task-status", 200, json!({"status":"failed"}), None),
|
||||
("result", 200, json!({"status":"processing"}), None),
|
||||
("result", 409, json!({}), None),
|
||||
("result", 503, json!({}), Some(RecoveryWait::Network)),
|
||||
("asset", 502, Value::Null, Some(RecoveryWait::Network)),
|
||||
("task-result", 410, Value::Null, None),
|
||||
("lookup", 200, json!({"error":"processing unresolved"}), None),
|
||||
] {
|
||||
assert_eq!(observed_wait(kind, code, &body), expected, "{kind} {code} {body}");
|
||||
}
|
||||
let mut count = 0;
|
||||
let result = retry_original_queries(
|
||||
|_| {
|
||||
count += 1;
|
||||
Err("原结果尚未取回(HTTP 410);不会重发".into())
|
||||
},
|
||||
|_| panic!("expired result must not be polled"),
|
||||
|| Duration::ZERO,
|
||||
);
|
||||
assert!(result.is_err());
|
||||
assert_eq!(count, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@ -2121,7 +2380,8 @@ mod tests {
|
||||
let result = retry_original_queries(
|
||||
|budget| {
|
||||
assert_eq!(budget, IMAGE_REQUEST_TIMEOUT - elapsed.get());
|
||||
original_response(&mut task, |path, key| {
|
||||
let wait = std::cell::Cell::new(None);
|
||||
let outcome = original_response(&mut task, observing(&wait, |path, key| {
|
||||
calls.push((path.to_owned(), key.map(str::to_owned)));
|
||||
if path == result_path {
|
||||
assert_eq!(key, None);
|
||||
@ -2132,7 +2392,7 @@ mod tests {
|
||||
let status = if elapsed.get() < Duration::from_secs(8) { "unresolved" } else { terminal };
|
||||
Ok((200, json!({"request_id":request_id,"status":status,"result_available":false,
|
||||
"result_path":result_path,"result_expires_at":null})))
|
||||
}, |saved| {
|
||||
}), |saved| {
|
||||
persists += 1;
|
||||
assert_eq!(saved["requestId"], request_id);
|
||||
Ok(())
|
||||
@ -2140,7 +2400,8 @@ mod tests {
|
||||
OriginalResponse::TerminalFailure(_) => json!({"phase":"failed"}),
|
||||
OriginalResponse::Expired(_) => json!({"phase":"expired"}),
|
||||
_ => panic!("expected terminal original"),
|
||||
})
|
||||
});
|
||||
attempt_receipt(outcome, wait.get())
|
||||
},
|
||||
|delay| elapsed.set(elapsed.get() + delay),
|
||||
|| elapsed.get(),
|
||||
@ -2168,7 +2429,8 @@ mod tests {
|
||||
|budget| {
|
||||
polls += 1;
|
||||
assert!(budget <= IMAGE_REQUEST_TIMEOUT);
|
||||
Ok(if elapsed.get() > Duration::from_secs(2) { json!({"phase":"complete"}) } else { json!({"phase":"unknown","reply":"processing"}) })
|
||||
Ok(if elapsed.get() > Duration::from_secs(2) { json!({"phase":"complete"}) }
|
||||
else { json!({"phase":"unknown","recoveryWait":"processing"}) })
|
||||
},
|
||||
|delay| elapsed.set(elapsed.get() + delay),
|
||||
|| elapsed.get(),
|
||||
@ -2182,7 +2444,7 @@ mod tests {
|
||||
|budget| {
|
||||
polls += 1;
|
||||
assert!(budget > Duration::ZERO);
|
||||
Ok(json!({"phase":"unknown","reply":"原请求结果待上游确认(unresolved),保留待核查;不会重发"}))
|
||||
Ok(json!({"phase":"unknown","recoveryWait":"unresolved"}))
|
||||
},
|
||||
|delay| elapsed.set(elapsed.get() + delay),
|
||||
|| elapsed.get(),
|
||||
@ -2191,6 +2453,76 @@ mod tests {
|
||||
assert_eq!(elapsed.get(), IMAGE_REQUEST_TIMEOUT);
|
||||
assert_eq!(polls, 10);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unresolved_original_expires_once_it_outlasts_the_recovery_budget() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
write_json(&dir.path().join("context.json"), &json!({})).unwrap();
|
||||
let mut task = unknown_image();
|
||||
task["requestId"] = json!(FAILURE_REQUEST);
|
||||
let original = task.clone();
|
||||
let first = 1_795_781_555;
|
||||
let budget = IMAGE_REQUEST_TIMEOUT.as_secs();
|
||||
settle_unresolved(&mut task, first);
|
||||
settle_unresolved(&mut task, first + budget - 1);
|
||||
assert_eq!(task["phase"], "unknown", "the budget counts from the first unresolved observation");
|
||||
assert_eq!(task["unresolvedSince"], first);
|
||||
job_save(dir.path(), &task).unwrap();
|
||||
assert!(pending(dir.path()).unwrap(), "an unresolved original inside its budget is still checked by its original ID");
|
||||
|
||||
settle_unresolved(&mut task, first + budget);
|
||||
assert_eq!(task["phase"], "expired");
|
||||
assert_eq!(task["resultExpiry"], json!({"source":"unresolved","unresolvedSince":first,"observedAt":first + budget,
|
||||
"requestId":FAILURE_REQUEST,"upstreamTaskId":null}));
|
||||
for key in ["id", "requestId", "slotBinding", "prompt", "references", "modelId", "keyFingerprint"] {
|
||||
assert_eq!(task[key], original[key], "expiry changed {key}");
|
||||
}
|
||||
job_save(dir.path(), &task).unwrap();
|
||||
assert!(!pending(dir.path()).unwrap());
|
||||
let mut late = original.clone();
|
||||
late["message"] = json!("late unresolved GET");
|
||||
job_save(dir.path(), &late).unwrap();
|
||||
let stored = read_json(&dir.path().join("image-task.json")).unwrap();
|
||||
assert_eq!(stored, task, "a late unknown copy cannot reopen the expired original");
|
||||
let receipt = settled_recovery(&stored, 1, &json!({"id":"owner"}), "origin").unwrap();
|
||||
assert_eq!(receipt["phase"], "expired");
|
||||
assert_eq!(receipt["unknown"], false);
|
||||
assert_eq!(receipt["retryable"], false);
|
||||
assert_eq!(receipt["resultExpiry"]["source"], "unresolved");
|
||||
assert!(receipt.get("recoveryWait").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_later_recovery_round_settles_the_original_that_stayed_unresolved_for_the_budget() {
|
||||
// The first round starts at the first unresolved lookup and ends with the
|
||||
// original still unknown; the next round finds the budget spent.
|
||||
let first = 1_795_781_555;
|
||||
let clock = std::cell::Cell::new(Duration::ZERO);
|
||||
let mut task = unknown_image();
|
||||
task["requestId"] = json!(FAILURE_REQUEST);
|
||||
let first_round = retry_original_queries(
|
||||
|_| {
|
||||
settle_unresolved(&mut task, first + clock.get().as_secs());
|
||||
Ok(json!({"phase":task["phase"],"recoveryWait":"unresolved"}))
|
||||
},
|
||||
|delay| clock.set(clock.get() + delay),
|
||||
|| clock.get(),
|
||||
);
|
||||
assert_eq!(first_round.unwrap()["phase"], "unknown");
|
||||
assert_eq!(clock.get(), IMAGE_REQUEST_TIMEOUT);
|
||||
assert_eq!(task["unresolvedSince"], first);
|
||||
clock.set(IMAGE_REQUEST_TIMEOUT + Duration::from_secs(8));
|
||||
let settled = retry_original_queries(
|
||||
|_| {
|
||||
settle_unresolved(&mut task, first + clock.get().as_secs());
|
||||
Ok(json!({"phase":task["phase"],"recoveryWait":"unresolved"}))
|
||||
},
|
||||
|_| panic!("an expired original is not polled again"),
|
||||
|| Duration::ZERO,
|
||||
).unwrap();
|
||||
assert_eq!(settled["phase"], "expired");
|
||||
assert_eq!(task["resultExpiry"]["source"], "unresolved");
|
||||
}
|
||||
#[test]
|
||||
fn image_recovery_binds_original_request_without_changing_task_or_phase() {
|
||||
let dir = std::env::temp_dir().join(format!("jiansun-image-bind-{}", Uuid::new_v4()));
|
||||
|
||||
@ -35,7 +35,7 @@ fn project_entry(relative: &Path) -> bool {
|
||||
|| root == "product-exports" && matches!(relative.extension().and_then(|ext| ext.to_str()), Some("psd" | "psb")),
|
||||
"image-jobs" => relative.file_name().and_then(|name| name.to_str()).is_some_and(|name|
|
||||
matches!(name, "canvas-candidate.json" | "task.json" | "generated.png" | "failure.json" | "scene-product.png")
|
||||
|| name.starts_with("reference-") && name.ends_with(".png")),
|
||||
|| name.starts_with("reference-") && (name.ends_with(".png") || name.ends_with(".jpg"))),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user