package p.studio.app.assets; import com.fasterxml.jackson.databind.*; import p.studio.api.assets.AssetBudgets; import p.studio.api.automation.*; import p.studio.api.project.ProjectLocalStudioSetup; import java.nio.*; import java.nio.channels.FileChannel; import java.nio.file.*; import java.util.*; /** Same admission for headless and desktop: verify qualification, actual cartridge bytes and serialized preload. */ public final class ManagedAssetGuard { private final ObjectMapper json;private final AssetCapacityProfiles profiles; public ManagedAssetGuard(ObjectMapper json){this.json=json;profiles=new AssetCapacityProfiles(json);} public Map require(Path project,Path cartridge,ProjectLocalStudioSetup setup)throws Exception { var selected=profiles.select(setup); if(selected.state()!=AssetBudgets.QualificationState.known)throw failure("ASSET_PROFILE_UNKNOWN",selected.reason()); Path root=cartridge.toRealPath();if(!root.startsWith(project.toRealPath()))throw failure("BUILD_OUTSIDE_PROJECT","Cartridge is outside its project"); Path file=AssetWorkspaceFiles.path(root,"asset-capacity.json"); if(!Files.isRegularFile(file)||Files.size(file)>32*1024*1024)throw failure("ASSET_BUILD_UNQUALIFIED","Rebuild with a compatible selected runtime before managed execution"); var record=json.readTree(file.toFile());var qualification=record.path("snapshot").path("qualification");var profile=qualification.path("profile"); if(record.path("contractVersion").asInt()!=1||!qualification.path("state").asText().equals("known") ||!profile.path("profileId").asText().equals(selected.profile().profileId()) ||!profile.path("executableSha256").asText().equals(selected.selectedExecutableSha256())) throw failure("ASSET_BUILD_PROFILE_CHANGED","Build capacity qualification does not match the selected runtime; rebuild required"); if (!profile.equals(json.valueToTree(selected.profile()))) throw failure("ASSET_BUILD_PROFILE_CHANGED", "Build capacity evidence changed; rebuild required"); if(!record.path("snapshot").path("revision").equals(json.valueToTree(AssetWorkspaceFiles.revision(project)))) throw failure("ASSET_BUILD_INPUTS_CHANGED", "Asset inputs changed since qualification; rebuild required"); var hashes=record.path("files"); for(String name:List.of("manifest.json","program.pbx","assets.pa","asset_table.json","preload.json")) { Path input=AssetWorkspaceFiles.path(root,name); if(!Files.isRegularFile(input)||!AssetWorkspaceFiles.hash(Files.readAllBytes(input)).equals(hashes.path(name).asText())) throw failure("ASSET_BUILD_BYTES_CHANGED","Qualified cartridge bytes changed: "+name); } JsonNode packed=header(root.resolve("assets.pa"));var banks=new HashMap(); for(var bank:packed.path("asset_table")) { int id=integer(bank.path("asset_id"));String type=bank.path("bank_type").asText(); if(banks.put(id,type)!=null)throw failure("ASSET_TOPOLOGY_INVALID","Duplicate cold AssetId"); } var claimed=new HashSet();var required=new TreeMap(); for(var preload:packed.path("preload")) { int id=integer(preload.path("asset_id")),slot=integer(preload.path("slot"));String type=banks.get(id); if(type==null||!claimed.add(type+":"+slot))throw failure("ASSET_TOPOLOGY_INVALID","Unknown preload bank or duplicate runtime slot"); Integer limit=null;for(var entry:selected.profile().limits().entrySet())if(entry.getKey().runtimeTag().equals(type))limit=entry.getValue(); if(limit==null||slot>=limit)throw new AutomationException(new AutomationFailure(AutomationFailure.Code.LIMIT_EXCEEDED,"Managed preload is outside the qualified capacity",Map.of(), p.studio.api.values.ValueMaps.fields("code","PRELOAD_CAPACITY_EXCEEDED","bankType",type,"slot",slot,"assetId",id,"limit",limit,"profileId",selected.profile().profileId()))); required.merge(type,slot+1,Math::max); } return Map.of("profileId",selected.profile().profileId(),"selectedExecutableSha256",selected.selectedExecutableSha256(),"requiredSlots",required,"inputRevision",record.path("snapshot").path("revision").path("sha256").asText()); } private JsonNode header(Path path)throws Exception { try(var file=FileChannel.open(path,StandardOpenOption.READ)) { var prelude=ByteBuffer.allocate(32).order(ByteOrder.LITTLE_ENDIAN);read(file,prelude);prelude.flip(); if(prelude.get()!='A'||prelude.get()!='S'||prelude.get()!='P'||prelude.get()!='A'||prelude.getInt()!=1)throw failure("ASSET_HEADER_INVALID","Unsupported packed asset header"); int size=prelude.getInt();long payload=prelude.getLong(); if(size<2||size>32*1024*1024||payload!=32L+size||payload>file.size())throw failure("ASSET_HEADER_INVALID","Invalid packed asset header bounds"); var bytes=ByteBuffer.allocate(size);read(file,bytes);var header=json.readTree(bytes.array()); if(!header.path("asset_table").isArray()||!header.path("preload").isArray())throw failure("ASSET_HEADER_INVALID","Expected asset table and preload arrays"); return header; } } private static void read(FileChannel source,ByteBuffer target)throws Exception{while(target.hasRemaining())if(source.read(target)<0)throw new java.io.EOFException("Truncated assets.pa header");} private static int integer(JsonNode node){if(!node.isIntegralNumber()||!node.canConvertToInt()||node.intValue()<0)throw failure("ASSET_TOPOLOGY_INVALID","Expected a nonnegative lossless cold ID or slot");return node.intValue();} private static AutomationException failure(String code,String message){return new AutomationException(new AutomationFailure(AutomationFailure.Code.RUNTIME_INCOMPATIBLE,message,Map.of(),Map.of("code",code)));} }