DeclarativeRecipeRuntime.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/DeclarativeRecipeRuntime.kt
1package eu.friedcutlet.yokan.services.extensions.recipe23import eu.friedcutlet.yokan.services.catchingNonCancellation4import kotlinx.coroutines.ensureActive5import kotlinx.serialization.json.Json6import kotlinx.serialization.json.JsonArray7import kotlinx.serialization.json.JsonObject8import kotlinx.serialization.json.JsonPrimitive9import kotlinx.serialization.json.JsonElement10import kotlinx.serialization.json.JsonNull11import kotlin.coroutines.coroutineContext12import kotlin.time.TimeSource1314enum class RecipeExecutionErrorCode {15 InvalidBundle, InvalidPolicy, OriginDenied, DocumentBudgetExceeded, BrokerDenied, BrokerHttpFailure,16 BrokerDeadlineExceeded, BrokerFailure, InvalidJsonDocument, JsonPointerNotFound,17}1819data class RecipeExecutionError(val code: RecipeExecutionErrorCode)2021sealed interface RecipeEntrypointInput {22 data class PageIndex(val value: Int) : RecipeEntrypointInput23 /** Derived by the runtime from [PageIndex] for `pageOffset` entrypoints; hosts never supply it. */24 data class PageOffset(val value: Int) : RecipeEntrypointInput25 data class Query(val value: String) : RecipeEntrypointInput26 data class ItemId(val value: String) : RecipeEntrypointInput27 data class EpisodeId(val value: String) : RecipeEntrypointInput28}2930sealed interface RecipeEntrypointResult {31 data class Listing(val items: List<Item>, val pageSize: Int) : RecipeEntrypointResult32 data class Detail(val id: String, val title: String, val thumbnailUrl: String?, val description: String?) : RecipeEntrypointResult33 data class Episodes(val items: List<Episode>) : RecipeEntrypointResult34 data class Media(val items: List<MediaItem>) : RecipeEntrypointResult35 data class Item(val id: String, val title: String, val thumbnailUrl: String?)36 data class Episode(val id: String, val season: String?, val number: String?)37 data class MediaItem(val url: String, val quality: String?)38}3940sealed interface RecipeEntrypointExecutionResult {41 data class Completed(val result: RecipeEntrypointResult) : RecipeEntrypointExecutionResult42 data class Rejected(val error: RecipeExecutionError) : RecipeEntrypointExecutionResult43}4445/** Injectable monotonic source used only to form one invocation-wide deadline. */46fun interface RecipeMonotonicClock {47 fun nowMillis(): Long48}4950private object DefaultRecipeMonotonicClock : RecipeMonotonicClock {51 private val start = TimeSource.Monotonic.markNow()52 override fun nowMillis(): Long = start.elapsedNow().inWholeMilliseconds53}5455/** Host-issued, nonserializable limits. Every limit is aggregate for one execution invocation. */56class RecipeExecutionPolicy(57 grantedOrigins: Map<String, String>,58 val maxReceivedDocumentBytes: Int = 256 * 1024,59 val brokerDeadlineMillis: Long = 15_000,60) {61 val grantedOrigins: Map<String, String> = grantedOrigins.toMap()62}6364/**65 * Host broker contract. The host must enforce destination/public-address policy, redirect/retry/session isolation,66 * streaming decompressed response limits, JSON-only response content, and cancellation. Recipes provide no headers, cookies, methods, or authority.67 */68data class RecipeBrokerRequest(69 val originId: String,70 val origin: String,71 val pathAndQuery: String,72 val maxDocumentBytes: Int,73 /** Remaining time from the single runtime invocation deadline; never a refreshed per-request allowance. */74 val deadlineMillis: Long,75) {76 val url: String get() = origin + pathAndQuery77}7879sealed interface RecipeBrokerResult {80 data class Document(val bytes: ByteArray) : RecipeBrokerResult81 data object OriginDenied : RecipeBrokerResult82 data object HttpFailure : RecipeBrokerResult83 data object ResponseTooLarge : RecipeBrokerResult84 data object Failed : RecipeBrokerResult85}8687interface RecipeCapabilityBroker {88 suspend fun fetch(request: RecipeBrokerRequest): RecipeBrokerResult89}9091class DeclarativeRecipeRuntime(92 private val broker: RecipeCapabilityBroker,93 private val clock: RecipeMonotonicClock = DefaultRecipeMonotonicClock,94) {95 suspend fun executeEntrypoint(bundle: DeclarativeExtensionBundle, entrypoint: String, hostInputs: Map<String, RecipeEntrypointInput>, policy: RecipeExecutionPolicy): RecipeEntrypointExecutionResult {96 coroutineContext.ensureActive()97 val deadline = InvocationDeadline(clock, policy.brokerDeadlineMillis)98 if (!deadline.isActive()) return entryRejected(RecipeExecutionErrorCode.BrokerDeadlineExceeded)99 if (bundle.manifest.formatVersion != RecipeFormatVersion.V21 || RecipeBundleValidator.validate(bundle) !is RecipeBundleDecodeResult.Accepted || !validPolicy(policy)) return entryRejected(RecipeExecutionErrorCode.InvalidBundle)100 val entry = bundle.entrypoints[entrypoint] ?: return entryRejected(RecipeExecutionErrorCode.InvalidBundle)101 val inputs = pageOffsetInputs(entry, hostInputs)102 val expected = entry.inputs.associateWith { it.name.replaceFirstChar { c -> c.lowercase() } }103 if (inputs.keys != expected.values.toSet() || !inputs.all { (key, value) -> expected.entries.any { it.value == key && inputMatches(it.key, value) } }) return entryRejected(RecipeExecutionErrorCode.InvalidPolicy)104 val origin = bundle.manifest.declaredOrigins.firstOrNull { it.id == entry.url.origin.originId } ?: return entryRejected(RecipeExecutionErrorCode.InvalidBundle)105 if (policy.grantedOrigins[origin.id] != origin.origin) return entryRejected(RecipeExecutionErrorCode.OriginDenied)106 val path = entry.url.path.joinToString("") { value -> when (value) { is RecipeV21UrlValue.Literal -> value.text; is RecipeV21UrlValue.HostInput -> percentEncode(inputText(inputs.getValue(expected.getValue(value.input)))) } }107 val query = entry.url.query.entries.sortedBy { it.key }.joinToString("&", prefix = if (entry.url.query.isEmpty()) "" else "?") { (key, value) -> "$key=${percentEncode(when (value) { is RecipeV21UrlValue.Literal -> value.text; is RecipeV21UrlValue.HostInput -> inputText(inputs.getValue(expected.getValue(value.input))) })}" }108 val remaining = deadline.remainingMillis()109 if (remaining <= 0) return entryRejected(RecipeExecutionErrorCode.BrokerDeadlineExceeded)110 val response = catchingNonCancellation { broker.fetch(RecipeBrokerRequest(origin.id, origin.origin, path + query, policy.maxReceivedDocumentBytes, remaining)) }111 .getOrElse { return entryRejected(RecipeExecutionErrorCode.BrokerFailure) }112 val bytes = when (response) {113 is RecipeBrokerResult.Document -> response.bytes114 RecipeBrokerResult.OriginDenied -> return entryRejected(RecipeExecutionErrorCode.BrokerDenied)115 RecipeBrokerResult.HttpFailure -> return entryRejected(RecipeExecutionErrorCode.BrokerHttpFailure)116 RecipeBrokerResult.ResponseTooLarge -> return entryRejected(RecipeExecutionErrorCode.DocumentBudgetExceeded)117 RecipeBrokerResult.Failed -> return entryRejected(RecipeExecutionErrorCode.BrokerFailure)118 }119 if (bytes.size > policy.maxReceivedDocumentBytes || StrictRecipeBundleDecoder.boundedApiResponseJsonPreflight(bytes, policy.maxReceivedDocumentBytes) != null) return entryRejected(RecipeExecutionErrorCode.InvalidJsonDocument)120 // The preflight above already proved the bytes are valid UTF-8 JSON within the structural limits.121 val root = try { strictJson.parseToJsonElement(bytes.decodeToString()) } catch (_: IllegalArgumentException) { return entryRejected(RecipeExecutionErrorCode.InvalidJsonDocument) }122 val selected = jsonPointerElement(root, entry.projection.pointer) ?: return entryRejected(RecipeExecutionErrorCode.JsonPointerNotFound)123 val rows = when (entry.projection.mode) { RecipeV21ProjectionMode.One -> listOf(selected as? JsonObject ?: return entryRejected(RecipeExecutionErrorCode.JsonPointerNotFound)); RecipeV21ProjectionMode.Many -> (selected as? JsonArray)?.takeIf { it.size <= resultLimit(entry.terminal.type) }?.map { it as? JsonObject ?: return entryRejected(RecipeExecutionErrorCode.JsonPointerNotFound) } ?: return entryRejected(RecipeExecutionErrorCode.JsonPointerNotFound) }124 val mapped = rows.map { row ->125 coroutineContext.ensureActive()126 if (!deadline.isActive()) return entryRejected(RecipeExecutionErrorCode.BrokerDeadlineExceeded)127 entry.projection.fields.mapValues { (_, pointers) -> pointers.firstNotNullOfOrNull { jsonPointerScalar(row, it) } }128 }129 if (mapped.any { fields -> entry.projection.fields.any { (name, _) -> fields[name] == null && name in requiredFields(entry.terminal.type) } }) return entryRejected(RecipeExecutionErrorCode.InvalidJsonDocument)130 return mapTerminal(entry.terminal, mapped) ?: entryRejected(RecipeExecutionErrorCode.InvalidJsonDocument)131 }132 private fun validPolicy(policy: RecipeExecutionPolicy): Boolean =133 policy.maxReceivedDocumentBytes >= 0 && policy.brokerDeadlineMillis > 0 &&134 policy.grantedOrigins.all { (id, origin) -> RecipeSyntax.isIdentifier(id) && RecipeSyntax.isNormalizedHttpsOrigin(origin) }135136 private companion object {137 val strictJson = Json { ignoreUnknownKeys = false; isLenient = false; coerceInputValues = false; explicitNulls = false; useAlternativeNames = false }138 }139}140141private class InvocationDeadline(clock: RecipeMonotonicClock, durationMillis: Long) {142 private val clock = clock143 private val expiresAt = clock.nowMillis().let { start -> if (start > Long.MAX_VALUE - durationMillis) Long.MAX_VALUE else start + durationMillis }144 suspend fun isActive(): Boolean {145 coroutineContext.ensureActive()146 return clock.nowMillis() < expiresAt147 }148 suspend fun remainingMillis(): Long {149 coroutineContext.ensureActive()150 return (expiresAt - clock.nowMillis()).coerceAtLeast(0)151 }152}153154private fun jsonPointerScalar(root: JsonElement, pointer: String): String? {155 val rawTokens = when {156 pointer.isEmpty() -> emptyList()157 !pointer.startsWith('/') -> return null158 else -> pointer.substring(1).split('/')159 }160 if (rawTokens.size > RecipeBundleLimits.maxJsonPointerTokens) return null161 var current = root162 for (raw in rawTokens) {163 if (raw.length > RecipeBundleLimits.maxJsonPointerTokenCharacters) return null164 val token = decodePointerToken(raw) ?: return null165 current = when (current) {166 is JsonObject -> current[token] ?: return null167 is JsonArray -> {168 if (token.isEmpty() || (token.length > 1 && token[0] == '0') || token.any { it !in '0'..'9' }) return null169 current.getOrNull(token.toIntOrNull() ?: return null) ?: return null170 }171 else -> return null172 }173 }174 val primitive = current as? JsonPrimitive ?: return null175 return primitive.takeUnless { it is JsonNull }?.content176}177178private fun decodePointerToken(raw: String): String? {179 val decoded = StringBuilder()180 var index = 0181 while (index < raw.length) {182 val char = raw[index++]183 if (char != '~') decoded.append(char) else when (raw.getOrNull(index++)) {184 '0' -> decoded.append('~')185 '1' -> decoded.append('/')186 else -> return null187 }188 }189 return decoded.toString()190}191192private fun inputMatches(expected: RecipeHostInput, value: RecipeEntrypointInput): Boolean = when (expected) {193 RecipeHostInput.PageIndex -> (value as? RecipeEntrypointInput.PageIndex)?.value in 0..999194 RecipeHostInput.PageOffset -> (value as? RecipeEntrypointInput.PageOffset)?.value in 0..999 * 30195 RecipeHostInput.Query -> (value as? RecipeEntrypointInput.Query)?.value?.let { it.length <= 256 && it.none { c -> c.code < 0x20 } } == true196 RecipeHostInput.ItemId -> (value as? RecipeEntrypointInput.ItemId)?.value?.let(::validOpaqueId) == true197 RecipeHostInput.EpisodeId -> (value as? RecipeEntrypointInput.EpisodeId)?.value?.let(::validOpaqueId) == true198}199private fun inputText(value: RecipeEntrypointInput): String = when (value) { is RecipeEntrypointInput.PageIndex -> value.value.toString(); is RecipeEntrypointInput.PageOffset -> value.value.toString(); is RecipeEntrypointInput.Query -> value.value; is RecipeEntrypointInput.ItemId -> value.value; is RecipeEntrypointInput.EpisodeId -> value.value }200201/** A `pageOffset` entrypoint receives the host's zero-based page index as an item offset: `pageIndex × pageSize`. */202private fun pageOffsetInputs(entry: RecipeV21Entrypoint, inputs: Map<String, RecipeEntrypointInput>): Map<String, RecipeEntrypointInput> {203 if (RecipeHostInput.PageOffset !in entry.inputs) return inputs204 val page = inputs["pageIndex"] as? RecipeEntrypointInput.PageIndex ?: return inputs205 val pageSize = entry.terminal.pageSize ?: return inputs206 return inputs - "pageIndex" + ("pageOffset" to RecipeEntrypointInput.PageOffset(page.value * pageSize))207}208private fun validOpaqueId(value: String) = value.length in 1..64 && value.all { it in '0'..'9' || it in 'a'..'z' || it in 'A'..'Z' || it == '-' || it == '_' }209private fun percentEncode(value: String): String = value.encodeToByteArray().joinToString("") { byte -> val n = byte.toInt() and 255; if ((n in 48..57) || (n in 65..90) || (n in 97..122) || n in intArrayOf(45, 46, 95, 126)) n.toChar().toString() else "%${"0123456789ABCDEF"[n ushr 4]}${"0123456789ABCDEF"[n and 15]}" }210private fun jsonPointerElement(root: JsonElement, pointer: String): JsonElement? {211 val tokens = if (pointer.isEmpty()) emptyList() else pointer.takeIf { it.startsWith('/') }?.substring(1)?.split('/') ?: return null212 var current = root213 for (raw in tokens) { val token = decodePointerToken(raw) ?: return null; current = when (current) { is JsonObject -> current[token] ?: return null; is JsonArray -> current.getOrNull(token.toIntOrNull() ?: return null) ?: return null; else -> return null } }214 return current215}216private fun resultLimit(type: RecipeV21TerminalType) = when (type) { RecipeV21TerminalType.Listing -> 30; RecipeV21TerminalType.Detail -> 1; RecipeV21TerminalType.Episodes -> 256; RecipeV21TerminalType.Media -> 16 }217private fun requiredFields(type: RecipeV21TerminalType) = when (type) { RecipeV21TerminalType.Media -> setOf("url"); RecipeV21TerminalType.Episodes -> setOf("id"); else -> setOf("id", "title") }218private fun mapTerminal(terminal: RecipeV21Terminal, rows: List<Map<String, String?>>): RecipeEntrypointExecutionResult.Completed? = when (terminal.type) {219 RecipeV21TerminalType.Listing -> RecipeEntrypointExecutionResult.Completed(RecipeEntrypointResult.Listing(rows.map { RecipeEntrypointResult.Item(it["id"] ?: return null, it["title"] ?: return null, it["thumbnailUrl"]) }, terminal.pageSize ?: return null))220 RecipeV21TerminalType.Detail -> rows.singleOrNull()?.let { RecipeEntrypointExecutionResult.Completed(RecipeEntrypointResult.Detail(it["id"] ?: return null, it["title"] ?: return null, it["thumbnailUrl"], it["description"])) }221 RecipeV21TerminalType.Episodes -> RecipeEntrypointExecutionResult.Completed(RecipeEntrypointResult.Episodes(rows.map { RecipeEntrypointResult.Episode(it["id"] ?: return null, it["season"], it["number"]) }))222 RecipeV21TerminalType.Media -> RecipeEntrypointExecutionResult.Completed(RecipeEntrypointResult.Media(rows.map { val url = it["url"] ?: return null; if (!url.startsWith("https://") || url.length > 2048) return null; RecipeEntrypointResult.MediaItem(url, it["quality"]?.takeIf { q -> q.length <= 128 }) }))223}224private fun entryRejected(code: RecipeExecutionErrorCode) = RecipeEntrypointExecutionResult.Rejected(RecipeExecutionError(code))225