package p.studio.api.execution; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.util.*; /** Bounded immutable input of one compilation, consumed by interactive execution. */ public record ExecutionSources(String buildId, String programSha256, Map sources) { public static final int MAX_FILE_BYTES = 4 * 1024 * 1024; public static final int MAX_FILES = 1024; public static final int MAX_CAPTURE_BYTES = 16 * 1024 * 1024; public static final ExecutionSources EMPTY = new ExecutionSources("", "", Map.of()); public record Source(int fileId, int projectId, String path, String logicalPath, String kind, String sha256, String text) { public Source { if (fileId < 0 || projectId < 0) throw new IllegalArgumentException("Invalid source identity"); Objects.requireNonNull(path); Objects.requireNonNull(logicalPath); Objects.requireNonNull(kind); Objects.requireNonNull(sha256); Objects.requireNonNull(text); if (!Set.of("source","dependency","sdk","generated").contains(kind)) throw new IllegalArgumentException("Invalid execution source kind"); byte[] bytes = text.getBytes(StandardCharsets.UTF_8); if (bytes.length > MAX_FILE_BYTES || !digest(bytes).equals(sha256)) throw new IllegalArgumentException("Invalid execution source size/revision"); } } public ExecutionSources { Objects.requireNonNull(buildId); Objects.requireNonNull(programSha256); Objects.requireNonNull(sources); if (!programSha256.isEmpty() && !programSha256.matches("[0-9a-f]{64}")) throw new IllegalArgumentException("Invalid program identity"); if (sources.size() > MAX_FILES) throw new IllegalArgumentException("Execution source count limit"); long bytes = buildId.getBytes(StandardCharsets.UTF_8).length + programSha256.length() + 16L; if (bytes > MAX_CAPTURE_BYTES) throw new IllegalArgumentException("Execution source capture metadata limit"); for (var e : sources.entrySet()) { var s = Objects.requireNonNull(e.getValue()); if (e.getKey() != s.fileId()) throw new IllegalArgumentException("Mismatched source ID"); bytes += s.text().getBytes(StandardCharsets.UTF_8).length + s.path().getBytes(StandardCharsets.UTF_8).length + s.logicalPath().getBytes(StandardCharsets.UTF_8).length + 128L; if (bytes > MAX_CAPTURE_BYTES) throw new IllegalArgumentException("Execution source capture byte limit"); } sources = Map.copyOf(sources); } public static String digest(byte[] bytes) { try { return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); } catch (java.security.NoSuchAlgorithmException impossible) { throw new IllegalStateException(impossible); } } }