统一采用图产物读取并验证三类交付来源

This commit is contained in:
WuYongJie 2026-11-28 23:30:45 +08:00
parent 478d9412bd
commit 199cb9d528
3 changed files with 81 additions and 38 deletions

View File

@ -4,6 +4,7 @@ use super::{json, Path, Value, R, Uuid, PathBuf, hash, original_project_present,
use photocraft_ui_egui::jiansun::production_facts::{screen_area, screen_fingerprint, screen_overlay_layers};
use photocraft_ui_egui::jiansun::BridgeFailure;
use super::transfer;
use template_slots::candidate_pixels;
#[path = "jiansun_image_transform.rs"]
mod jiansun_image_transform;
@ -2552,22 +2553,6 @@ impl Backend {
}
}
pub(super) fn candidate_pixels(dir: &Path, artifact: &Value) -> R<Vec<u8>> {
use std::io::Read;
let task = uuid(&artifact["taskId"], "候选原任务")?;
let relative = format!("image-jobs/{task}/generated.png");
if artifact["path"] != relative { return Err("原图片路径无效".into()); }
let path = dir.join(relative);
let mut bytes = Vec::new();
fs::File::open(path).map_err(|_| "原候选图片不可读取")?.take(20 * 1024 * 1024 + 1)
.read_to_end(&mut bytes).map_err(|_| "原候选图片不可读取")?;
if bytes.is_empty() || bytes.len() > 20 * 1024 * 1024 { return Err("候选图片大小无效".into()); }
if artifact["sha256"] != format!("{:x}", Sha256::digest(&bytes)) {
return Err("候选像素已变化,未采纳".into());
}
Ok(bytes)
}
fn matches_placed_candidate(dir: &Path, artifact: &Value, embedded: &[u8]) -> bool {
if embedded.is_empty() { return false; }
if artifact["sha256"] == format!("{:x}", Sha256::digest(embedded)) { return true; }
@ -2717,7 +2702,13 @@ fn candidate_export_source(dir: &Path, record: &Value) -> Value {
if task.is_some() {
source["taskRecord"] = json!(task_record);
}
if record["sourceType"] == "archived-candidate" {
if record["canvasTransform"].is_object() {
source["kind"] = json!("transform");
source["requestId"] = record["sourceRequestId"].clone();
if record["reusedFrom"].is_object() {
source["reusedFrom"] = record["reusedFrom"].clone();
}
} else if record["sourceType"] == "archived-candidate" {
source["kind"] = json!("reused");
source["reusedFrom"] = record["reusedFrom"].clone();
source["requestId"] = record["sourceRequestId"].clone();
@ -5738,11 +5729,17 @@ mod tests {
doc.metadata.text.retain(|(key, _)| key != MAPPING);
doc.metadata.text.push((MAPPING.into(), meta.to_string()));
let fields: Vec<_> = page_fields(&meta).flat_map(|(_, fields)| fields).collect();
let pixels = photocraft_codecs::Image::from_u8(8, 8, photocraft_codecs::ChannelLayout::Rgba, [200, 40, 20, 255].repeat(64)).unwrap();
let bytes = photocraft_codecs::encode(&pixels, photocraft_codecs::Format::Png, &Default::default()).unwrap();
let kinds = ["product-reference", "transform", "generation"];
let sources = kinds.map(|kind| {
let red = match kind { "product-reference" => 100, "transform" => 150, _ => 200 };
let pixels = photocraft_codecs::Image::from_u8(8, 8, photocraft_codecs::ChannelLayout::Rgba, [red, 40, 20, 255].repeat(64)).unwrap();
photocraft_codecs::encode(&pixels, photocraft_codecs::Format::Png, &Default::default()).unwrap()
});
let mut session = photocraft_engine::Session::new();
session.add_document(doc, None);
let adopt = |session: &mut photocraft_engine::Session, field: &Value| {
let adopt = |session: &mut photocraft_engine::Session, index: usize, field: &Value| {
let kind = kinds[index % kinds.len()];
let bytes = &sources[index % sources.len()];
let slot = field["slotId"].as_str().unwrap();
let id = Uuid::new_v4().to_string();
let mut record = candidate(&fixture.dir, "complete");
@ -5752,13 +5749,27 @@ mod tests {
record["binding"]["slotId"] = json!(slot);
record["binding"]["templateHash"] = pack["contentHash"].clone();
record["inputHash"] = Value::Null;
record["artifact"]["sha256"] = json!(format!("{:x}", Sha256::digest(&bytes)));
match kind {
"product-reference" => record["sourceType"] = json!("product-reference"),
"transform" => {
record["sourceType"] = json!("archived-candidate");
record["canvasTransform"] = json!({"transform":{"flipX":true}});
record["sourceRequestId"] = json!("upstream-original");
}
_ => record["requestId"] = json!("upstream-generated"),
}
let task = json!({"id":id,"phase":"complete","slotBinding":record["binding"],
"requestId":record["requestId"],"sha256":format!("{:x}", Sha256::digest(bytes))});
let job = dir.join("image-jobs").join(&id);
write_json(&job.join("task.json"), &task).unwrap();
fs::write(job.join("generated.png"), bytes).unwrap();
record["artifact"] = template_slots::artifact(&dir, &id, &task).unwrap();
write_json(&candidate_path(&dir, &id).unwrap(), &record).unwrap();
let layer = LayerId(field["nativeLayerId"].as_u64().unwrap());
photocraft_engine::smart_cmds::replace_instance_bytes_fit(session, layer, "candidate.png", bytes.clone(), true).unwrap();
(format!("jiansun.adopted.{variant}.{slot}"), id)
};
let mut markers: Vec<_> = fields[..10].iter().map(|field| adopt(&mut session, field)).collect();
let mut markers: Vec<_> = fields[..10].iter().enumerate().map(|(index, field)| adopt(&mut session, index, field)).collect();
let snapshot = |session: &photocraft_engine::Session, markers: &[(String, String)]| {
let mut doc = session.active().unwrap().doc.as_ref().clone();
doc.metadata.text.extend_from_slice(markers);
@ -5778,7 +5789,21 @@ mod tests {
let copy_images = |receipt: &Value, count: usize| {
let bundle = tempfile::tempdir().unwrap();
let mut files = Vec::new();
super::super::delivery::copy_generation(bundle.path(), &dir, &input, receipt, Path::new("01"), None, &mut files).unwrap();
let evidence = super::super::delivery::copy_generation(bundle.path(), &dir, &input, receipt, Path::new("01"), None, &mut files).unwrap();
assert_eq!(evidence["reopenVerification"]["consistent"], true);
let adopted = evidence["adoptedImages"].as_array().unwrap();
assert_eq!(adopted.len(), count);
for (index, row) in adopted.iter().enumerate() {
let kind = kinds[index % kinds.len()];
let bytes = &sources[index % sources.len()];
let source = &receipt["imageSources"][index];
assert_eq!(row["kind"], kind);
assert_eq!(row["candidateId"], source["candidateId"]);
assert_eq!(row["requestId"], source["requestId"]);
assert_eq!(row["sha256"], format!("{:x}", Sha256::digest(bytes)));
assert_eq!(fs::read(bundle.path().join(row["relativePath"].as_str().unwrap())).unwrap(), *bytes);
}
assert_eq!(adopted[1]["requestId"], "upstream-original");
let images: Vec<_> = files.iter().filter(|file| file["category"] == "主图").collect();
assert_eq!(images.len(), count);
assert_eq!(images.iter().filter(|image| image["height"] == 16).count(), count - 10);
@ -5787,7 +5812,7 @@ mod tests {
fs::remove_file(settings).unwrap();
assert_eq!(remaining_stages(&dir, &state, &square["briefRevision"], true).len(), 1);
markers.extend(fields[10..].iter().map(|field| adopt(&mut session, field)));
markers.extend(fields.iter().enumerate().skip(10).map(|(index, field)| adopt(&mut session, index, field)));
let both = save(&snapshot(&session, &markers));
assert_eq!(both["productionDelivery"]["outputState"], "exported");
copy_images(&both, 16);

View File

@ -144,7 +144,7 @@ pub(super) fn copy_generation(root: &Path, project: &Path, input: &Value, output
}
let mut adopted = Vec::new();
for (index, source) in data["imageSources"].as_array().into_iter().flatten().enumerate() {
let bytes = canvas_workspace::candidate_pixels(project, &source["candidateArtifact"])?;
let bytes = super::template_slots::candidate_pixels(project, &source["candidateArtifact"])?;
let parent = root.join("采用图").join(folder).join(label);
fs::create_dir_all(&parent).map_err(disk)?;
let path = parent.join(format!("{:02}.png", index + 1));
@ -152,7 +152,7 @@ pub(super) fn copy_generation(root: &Path, project: &Path, input: &Value, output
let size = artifact_size(&path, "png")?;
let file = file_record(root, &path, "采用图", size)?;
adopted.push(json!({"pageId":source["pageId"],"fieldId":source["fieldId"],
"slotId":source["slotId"],"candidateId":source["candidateId"],"prompt":source["prompt"],
"slotId":source["slotId"],"candidateId":source["candidateId"],"kind":source["kind"],"prompt":source["prompt"],
"requestId":source["requestId"],"relativePath":file["relativePath"],"sha256":file["sha256"]}));
files.push(file);
}

View File

@ -1,7 +1,7 @@
//! Versioned template fields and explicit A/B selection. This module performs no
//! network operation: a reserved UUID is passed to the existing image journal.
//! Reserving, selecting and applying are separate durable user decisions.
use super::{json, Value, R, hash, Read, Digest, Path, original_project_present, read_json, write_json, sync, Uuid, now, fs, Sha256};
use super::{json, Value, R, hash, Read, Digest, Path, PathBuf, original_project_present, read_json, write_json, sync, Uuid, now, fs, Sha256};
const FILE: &str = "template-slots.json";
@ -304,25 +304,30 @@ pub(super) fn validate_journal_binding(dir: &Path, task: &Value) -> R<()> {
Ok(())
}
pub(super) fn artifact(dir: &Path, task: &str, journal: &Value) -> R<Value> {
let task = Uuid::parse_str(task).map_err(|_| "候选原任务身份无效")?.to_string();
fn checked_artifact_path(dir: &Path, task: &str) -> R<PathBuf> {
let relative = format!("image-jobs/{task}/generated.png");
let path = dir.join(&relative);
for part in [dir.join("image-jobs"), dir.join("image-jobs").join(&task), path.clone()] {
for part in [dir.join("image-jobs"), dir.join("image-jobs").join(task), path.clone()] {
if part.symlink_metadata().map_err(|_| "候选图片或目录不可读取")?.file_type().is_symlink() {
return Err("候选图片路径含链接,未读取其他任务文件".into());
}
}
let actual = fs::canonicalize(&path).map_err(|_| "候选图片缺失,原结果保留")?;
let expected_dir = fs::canonicalize(dir.join("image-jobs").join(&task)).map_err(|_| "候选图片目录缺失")?;
let expected_dir = fs::canonicalize(dir.join("image-jobs").join(task)).map_err(|_| "候选图片目录缺失")?;
let project = fs::canonicalize(dir).map_err(|_| "原项目目录不可读取")?;
if !actual.starts_with(&project)
|| actual.parent() != Some(expected_dir.as_path())
|| !expected_dir.starts_with(&project)
|| path.symlink_metadata().map_err(|_| "候选图片不可读取")?.file_type().is_symlink()
{
return Err("候选图片不属于原项目任务".into());
}
Ok(actual)
}
pub(super) fn artifact(dir: &Path, task: &str, journal: &Value) -> R<Value> {
let task = Uuid::parse_str(task).map_err(|_| "候选原任务身份无效")?.to_string();
let relative = format!("image-jobs/{task}/generated.png");
let actual = checked_artifact_path(dir, &task)?;
if let Some(declared) = journal["artifact"].as_str() {
let declared = Path::new(declared);
let same_project_task = dir.file_name().is_some_and(|project| {
@ -336,20 +341,33 @@ pub(super) fn artifact(dir: &Path, task: &str, journal: &Value) -> R<Value> {
return Err("候选图片与原任务文件不一致".into());
}
}
let meta = fs::metadata(&actual).map_err(|_| "候选图片不可读取")?;
read_artifact_pixels(&actual, &journal["sha256"])?;
Ok(json!({"taskId":task,"path":relative,"sha256":journal["sha256"]}))
}
fn read_artifact_pixels(path: &Path, expected: &Value) -> R<Vec<u8>> {
let meta = fs::metadata(path).map_err(|_| "候选图片不可读取")?;
if meta.len() == 0 || meta.len() > 20 * 1024 * 1024 {
return Err("候选图片大小无效".into());
}
let mut bytes = Vec::new();
fs::File::open(actual).map_err(|_| "候选图片读取失败")?.take(20 * 1024 * 1024 + 1).read_to_end(&mut bytes).map_err(|_| "候选图片读取中断")?;
if bytes.len() > 20 * 1024 * 1024 {
return Err("候选图片读取时超出20MiB,未回填".into());
fs::File::open(path).map_err(|_| "候选图片读取失败")?.take(20 * 1024 * 1024 + 1).read_to_end(&mut bytes).map_err(|_| "候选图片读取中断")?;
if bytes.is_empty() || bytes.len() > 20 * 1024 * 1024 {
return Err("候选图片大小无效".into());
}
let digest = format!("{:x}", Sha256::digest(&bytes));
if !hex(&journal["sha256"]) || journal["sha256"] != digest {
if expected.as_str() != Some(digest.as_str()) {
return Err("候选图片校验失败,未回填".into());
}
Ok(json!({"taskId":task,"path":relative,"sha256":digest}))
Ok(bytes)
}
pub(super) fn candidate_pixels(dir: &Path, artifact: &Value) -> R<Vec<u8>> {
let task = artifact["taskId"].as_str().and_then(|task| Uuid::parse_str(task).ok())
.ok_or("候选原任务编号无效")?.to_string();
let relative = format!("image-jobs/{task}/generated.png");
if artifact["path"] != relative { return Err("原图片路径无效".into()); }
read_artifact_pixels(&checked_artifact_path(dir, &task)?, &artifact["sha256"])
}
/// Feed the durable original task journal after dispatch or GET-only recovery.