refactor: execute Tier 3 - diagnostics, image fetchers, minter JSON

BootRelayDiagnostics -> commonMain. The concurrency review found it
already fully non-blocking: per-relay atomic counters on the hot
per-message path and get-or-create maps, no locks. Swaps: stdlib
kotlin.concurrent.atomics, quartz ConcurrentMap, TimeUtils.nowMillis,
and the daemon dump thread became a coroutine that completes after the
last scheduled census instead of parking a thread for process lifetime.

Blurhash/Thumbhash/Base64 fetchers -> commonMain over a new
CoilImageBridge expect (PlatformImage.toCoilImage +
base64DataUriToCoilImage; android actual = Bitmap.asImage, jvm/ios
actuals = Skia N32 premul from the ARGB pixel buffer, iOS base64 via
Image.makeFromEncoded). desktopApp deletes its three hand-rolled clone
fetchers and registers the shared ones - the first UI-adjacent
duplication the migration removes outright.

BuzzInviteMinter drops Jackson for kotlinx-serialization but stays
jvmAndroid: its OkHttp pin is load-bearing, since the NIP-98 u tag is
signed over OkHttp's canonical URL string and the transport must not
drift from the canonicalizer. PodcastRemoteContent is reclassified to
the OkHttp tier - the object IS a capped HTTP GET; injecting the fetch
would leave an empty shell.

Verified: verifyKmpPurity, JVM, iosArm64 compile + test-compile,
Android, desktop, and the quartz/commons/cli test suites.

Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011S1vbFWVVAMFDT8PTgdibV
This commit is contained in:
Claude
2026-08-31 22:19:16 +00:00
parent 33c87b4935
commit a9fc0184d4
13 changed files with 270 additions and 346 deletions
@@ -0,0 +1,32 @@
/*
* Copyright (c) 2025 Vitor Pamplona
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.vitorpamplona.amethyst.commons.service.image
import coil3.Image
import coil3.asImage
import com.vitorpamplona.amethyst.commons.base64Image.toBitmap
import com.vitorpamplona.amethyst.commons.blurhash.PlatformImage
import com.vitorpamplona.amethyst.commons.blurhash.toAndroidBitmap
import com.vitorpamplona.amethyst.commons.richtext.Base64Image
actual fun PlatformImage.toCoilImage(): Image = toAndroidBitmap().asImage(true)
actual fun base64DataUriToCoilImage(dataUri: String): Image = Base64Image.toBitmap(dataUri).asImage(true)
@@ -33,10 +33,16 @@ import com.vitorpamplona.quartz.nip01Core.relay.commands.toRelay.Command
import com.vitorpamplona.quartz.nip01Core.relay.commands.toRelay.ReqCmd
import com.vitorpamplona.quartz.nip01Core.relay.normalizer.NormalizedRelayUrl
import com.vitorpamplona.quartz.utils.Log
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.atomic.AtomicInteger
import java.util.concurrent.atomic.AtomicLong
import kotlin.concurrent.thread
import com.vitorpamplona.quartz.utils.TimeUtils
import com.vitorpamplona.quartz.utils.concurrent.ConcurrentMap
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlin.concurrent.atomics.AtomicInt
import kotlin.concurrent.atomics.AtomicLong
import kotlin.concurrent.atomics.ExperimentalAtomicApi
/**
* Debug-only cold-start census: what every relay in the pool actually did, and why the ones
@@ -54,6 +60,7 @@ import kotlin.concurrent.thread
*
* Attach only in debug builds; it holds one small record per relay for the process lifetime.
*/
@OptIn(ExperimentalAtomicApi::class)
class BootRelayDiagnostics(
val client: INostrClient,
// 5s first: the pool is assembled and dialling well before 20s, and the early datapoint is what
@@ -85,41 +92,41 @@ class BootRelayDiagnostics(
}
class RelayRecord {
val tentatives = AtomicInteger()
val opens = AtomicInteger()
val disconnects = AtomicInteger()
val reqsSent = AtomicInteger()
val authsSent = AtomicInteger()
val events = AtomicInteger()
val eoses = AtomicInteger()
val notices = AtomicInteger()
val tentatives = AtomicInt(0)
val opens = AtomicInt(0)
val disconnects = AtomicInt(0)
val reqsSent = AtomicInt(0)
val authsSent = AtomicInt(0)
val events = AtomicInt(0)
val eoses = AtomicInt(0)
val notices = AtomicInt(0)
/** failure cause -> count, see [classify]. */
val failures = ConcurrentHashMap<String, AtomicInteger>()
val failures = ConcurrentMap<String, AtomicInt>()
/** CLOSED machine-readable prefix (or "unprefixed") -> count. */
val closed = ConcurrentHashMap<String, AtomicInteger>()
val closed = ConcurrentMap<String, AtomicInt>()
val firstOpenAtMs = AtomicLong(0)
val firstEoseAtMs = AtomicLong(0)
val firstOpenAtMs = AtomicLong(0L)
val firstEoseAtMs = AtomicLong(0L)
fun bump(
map: ConcurrentHashMap<String, AtomicInteger>,
map: ConcurrentMap<String, AtomicInt>,
key: String,
) = map.computeIfAbsent(key) { AtomicInteger() }.incrementAndGet()
) = map.getOrPut(key) { AtomicInt(0) }.addAndFetch(1)
}
private val records = ConcurrentHashMap<NormalizedRelayUrl, RelayRecord>()
private val startedAtMs = System.currentTimeMillis()
private val records = ConcurrentMap<NormalizedRelayUrl, RelayRecord>()
private val startedAtMs = TimeUtils.nowMillis()
private fun record(url: NormalizedRelayUrl) = records.computeIfAbsent(url) { RelayRecord() }
private fun record(url: NormalizedRelayUrl) = records.getOrPut(url) { RelayRecord() }
private fun elapsed() = System.currentTimeMillis() - startedAtMs
private fun elapsed() = TimeUtils.nowMillis() - startedAtMs
private val listener =
object : RelayConnectionListener {
override fun onConnecting(relay: IRelayClient) {
record(relay.url).tentatives.incrementAndGet()
record(relay.url).tentatives.addAndFetch(1)
}
override fun onConnected(
@@ -128,8 +135,8 @@ class BootRelayDiagnostics(
compressed: Boolean,
) {
val r = record(relay.url)
r.opens.incrementAndGet()
r.firstOpenAtMs.compareAndSet(0, elapsed())
r.opens.addAndFetch(1)
r.firstOpenAtMs.compareAndSet(0L, elapsed())
}
override fun onCannotConnect(
@@ -141,7 +148,7 @@ class BootRelayDiagnostics(
}
override fun onDisconnected(relay: IRelayClient) {
record(relay.url).disconnects.incrementAndGet()
record(relay.url).disconnects.addAndFetch(1)
}
override fun onSent(
@@ -152,8 +159,8 @@ class BootRelayDiagnostics(
) {
val r = record(relay.url)
when (cmd) {
is ReqCmd -> r.reqsSent.incrementAndGet()
is AuthCmd -> r.authsSent.incrementAndGet()
is ReqCmd -> r.reqsSent.addAndFetch(1)
is AuthCmd -> r.authsSent.addAndFetch(1)
else -> Unit
}
}
@@ -165,12 +172,12 @@ class BootRelayDiagnostics(
) {
val r = record(relay.url)
when (msg) {
is EventMessage -> r.events.incrementAndGet()
is EventMessage -> r.events.addAndFetch(1)
is EoseMessage -> {
r.eoses.incrementAndGet()
r.firstEoseAtMs.compareAndSet(0, elapsed())
r.eoses.addAndFetch(1)
r.firstEoseAtMs.compareAndSet(0L, elapsed())
}
is NoticeMessage -> r.notices.incrementAndGet()
is NoticeMessage -> r.notices.addAndFetch(1)
is ClosedMessage -> r.bump(r.closed, prefixOf(msg.message))
else -> Unit
}
@@ -187,10 +194,12 @@ class BootRelayDiagnostics(
init {
client.addConnectionListener(listener)
thread(isDaemon = true, name = TAG) {
// A coroutine instead of a daemon thread: KMP-portable and finishes after
// the last scheduled census instead of holding a parked thread.
CoroutineScope(Dispatchers.Default + SupervisorJob()).launch {
var last = 0L
dumpAtSeconds.forEach { at ->
Thread.sleep((at - last) * 1000)
delay((at - last) * 1000)
last = at
dump(at)
}
@@ -209,26 +218,26 @@ class BootRelayDiagnostics(
* relay, too long (up to 45 lines a census) to sit in the default log.
*/
fun dump(atSeconds: Long) {
val snapshot = records.toMap()
val snapshot = records.snapshot()
val served = snapshot.filter { it.value.events.get() > 0 }
val opened = snapshot.filter { it.value.opens.get() > 0 }
val neverOpened = snapshot.filter { it.value.opens.get() == 0 }
val served = snapshot.filter { it.value.events.load() > 0 }
val opened = snapshot.filter { it.value.opens.load() > 0 }
val neverOpened = snapshot.filter { it.value.opens.load() == 0 }
val causeTotals = mutableMapOf<String, Int>()
val closedTotals = mutableMapOf<String, Int>()
snapshot.values.forEach { r ->
r.failures.forEach { (k, v) -> causeTotals[k] = (causeTotals[k] ?: 0) + v.get() }
r.closed.forEach { (k, v) -> closedTotals[k] = (closedTotals[k] ?: 0) + v.get() }
r.failures.snapshot().forEach { (k, v) -> causeTotals[k] = (causeTotals[k] ?: 0) + v.load() }
r.closed.snapshot().forEach { (k, v) -> closedTotals[k] = (closedTotals[k] ?: 0) + v.load() }
}
Log.d(TAG) { "===== boot census @${atSeconds}s =====" }
Log.i(TAG) {
"census @${atSeconds}s pool=${snapshot.size} opened=${opened.size} served_events=${served.size} never_opened=${neverOpened.size} " +
"dials=${snapshot.values.sumOf { it.tentatives.get() }} " +
"events=${snapshot.values.sumOf { it.events.get() }} " +
"reqs=${snapshot.values.sumOf { it.reqsSent.get() }} " +
"auths=${snapshot.values.sumOf { it.authsSent.get() }}"
"dials=${snapshot.values.sumOf { it.tentatives.load() }} " +
"events=${snapshot.values.sumOf { it.events.load() }} " +
"reqs=${snapshot.values.sumOf { it.reqsSent.load() }} " +
"auths=${snapshot.values.sumOf { it.authsSent.load() }}"
}
Log.i(TAG) { "census @${atSeconds}s failures_by_cause=${causeTotals.byCountDesc()}" }
Log.i(TAG) { "census @${atSeconds}s closed_by_prefix=${closedTotals.byCountDesc()}" }
@@ -236,16 +245,16 @@ class BootRelayDiagnostics(
// Relays that cost us dials and gave nothing back, worst first: the wasted-effort list.
Log.d(TAG, "--- top wasted dials (no events received) ---")
snapshot
.filter { it.value.events.get() == 0 }
.filter { it.value.events.load() == 0 }
.entries
.sortedByDescending { it.value.tentatives.get() }
.sortedByDescending { it.value.tentatives.load() }
.take(25)
.forEach { (url, r) ->
Log.d(TAG) {
"WASTE ${url.url} dials=${r.tentatives.get()} opens=${r.opens.get()} " +
"fail=[${r.failures.entries.joinToString { "${it.key}:${it.value.get()}" }}] " +
"closed=[${r.closed.entries.joinToString { "${it.key}:${it.value.get()}" }}] " +
"reqs=${r.reqsSent.get()} eose=${r.eoses.get()}"
"WASTE ${url.url} dials=${r.tentatives.load()} opens=${r.opens.load()} " +
"fail=[${r.failures.snapshot().entries.joinToString { "${it.key}:${it.value.load()}" }}] " +
"closed=[${r.closed.snapshot().entries.joinToString { "${it.key}:${it.value.load()}" }}] " +
"reqs=${r.reqsSent.load()} eose=${r.eoses.load()}"
}
}
@@ -253,12 +262,12 @@ class BootRelayDiagnostics(
// coverage loss rather than just CLOSED reduction.
Log.d(TAG, "--- top event providers ---")
served.entries
.sortedByDescending { it.value.events.get() }
.sortedByDescending { it.value.events.load() }
.take(20)
.forEach { (url, r) ->
Log.d(TAG) {
"SERVE ${url.url} events=${r.events.get()} reqs=${r.reqsSent.get()} eose=${r.eoses.get()} " +
"openMs=${r.firstOpenAtMs.get()} eoseMs=${r.firstEoseAtMs.get()} dials=${r.tentatives.get()}"
"SERVE ${url.url} events=${r.events.load()} reqs=${r.reqsSent.load()} eose=${r.eoses.load()} " +
"openMs=${r.firstOpenAtMs.load()} eoseMs=${r.firstEoseAtMs.load()} dials=${r.tentatives.load()}"
}
}
Log.d(TAG) { "===== end census @${atSeconds}s =====" }
@@ -23,15 +23,12 @@ package com.vitorpamplona.amethyst.commons.service.image
import androidx.compose.runtime.Stable
import coil3.ImageLoader
import coil3.Uri
import coil3.asImage
import coil3.decode.DataSource
import coil3.fetch.FetchResult
import coil3.fetch.Fetcher
import coil3.fetch.ImageFetchResult
import coil3.key.Keyer
import coil3.request.Options
import com.vitorpamplona.amethyst.commons.base64Image.toBitmap
import com.vitorpamplona.amethyst.commons.richtext.Base64Image
import com.vitorpamplona.quartz.nip01Core.core.toHexKey
import com.vitorpamplona.quartz.utils.sha256.sha256
@@ -43,7 +40,7 @@ class Base64Fetcher(
override suspend fun fetch(): FetchResult? =
runCatching {
ImageFetchResult(
image = Base64Image.toBitmap(data.toString()).asImage(true),
image = base64DataUriToCoilImage(data.toString()),
isSampled = false,
dataSource = DataSource.MEMORY,
)
@@ -68,7 +65,7 @@ class Base64Fetcher(
options: Options,
): String? =
if (data.scheme == "data") {
sha256(data.toString().toByteArray()).toHexKey()
sha256(data.toString().encodeToByteArray()).toHexKey()
} else {
null
}
@@ -22,7 +22,6 @@ package com.vitorpamplona.amethyst.commons.service.image
import androidx.compose.runtime.Stable
import coil3.ImageLoader
import coil3.asImage
import coil3.decode.DataSource
import coil3.fetch.FetchResult
import coil3.fetch.Fetcher
@@ -30,7 +29,6 @@ import coil3.fetch.ImageFetchResult
import coil3.key.Keyer
import coil3.request.Options
import com.vitorpamplona.amethyst.commons.blurhash.BlurHashDecoder
import com.vitorpamplona.amethyst.commons.blurhash.toAndroidBitmap
data class BlurhashWrapper(
val blurhash: String,
@@ -47,7 +45,7 @@ class BlurHashFetcher(
val platformImage = BlurHashDecoder.decodeKeepAspectRatio(hash, 25) ?: return null
return ImageFetchResult(
image = platformImage.toAndroidBitmap().asImage(true),
image = platformImage.toCoilImage(),
isSampled = false,
dataSource = DataSource.MEMORY,
)
@@ -0,0 +1,30 @@
/*
* Copyright (c) 2025 Vitor Pamplona
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.vitorpamplona.amethyst.commons.service.image
import coil3.Image
import com.vitorpamplona.amethyst.commons.blurhash.PlatformImage
/** Converts a decoded [PlatformImage] (blurhash/thumbhash output) into a Coil image. */
expect fun PlatformImage.toCoilImage(): Image
/** Decodes a base64 `data:` image URI into a Coil image; throws on malformed input. */
expect fun base64DataUriToCoilImage(dataUri: String): Image
@@ -22,14 +22,12 @@ package com.vitorpamplona.amethyst.commons.service.image
import androidx.compose.runtime.Stable
import coil3.ImageLoader
import coil3.asImage
import coil3.decode.DataSource
import coil3.fetch.FetchResult
import coil3.fetch.Fetcher
import coil3.fetch.ImageFetchResult
import coil3.key.Keyer
import coil3.request.Options
import com.vitorpamplona.amethyst.commons.blurhash.toAndroidBitmap
import com.vitorpamplona.amethyst.commons.thumbhash.ThumbHashDecoder
data class ThumbhashWrapper(
@@ -45,7 +43,7 @@ class ThumbHashFetcher(
val hash = data.thumbhash
val platformImage = ThumbHashDecoder.decodeKeepAspectRatio(hash, 25) ?: return null
return ImageFetchResult(
image = platformImage.toAndroidBitmap().asImage(true),
image = platformImage.toCoilImage(),
isSampled = false,
dataSource = DataSource.MEMORY,
)
@@ -0,0 +1,63 @@
/*
* Copyright (c) 2025 Vitor Pamplona
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.vitorpamplona.amethyst.commons.service.image
import coil3.Image
import coil3.asImage
import com.vitorpamplona.amethyst.commons.blurhash.PlatformImage
import org.jetbrains.skia.Bitmap
import org.jetbrains.skia.ColorAlphaType
import org.jetbrains.skia.ImageInfo
import kotlin.io.encoding.Base64
import kotlin.io.encoding.ExperimentalEncodingApi
import org.jetbrains.skia.Image as SkiaImage
actual fun PlatformImage.toCoilImage(): Image = toSkiaBitmap().asImage(true)
@OptIn(ExperimentalEncodingApi::class)
actual fun base64DataUriToCoilImage(dataUri: String): Image {
val payload = dataUri.substringAfter("base64,")
val encoded = SkiaImage.makeFromEncoded(Base64.decode(payload))
return Bitmap.makeFromImage(encoded).asImage(true)
}
/**
* ARGB int pixels -> N32 premul Skia bitmap. Blurhash/thumbhash output is opaque
* (alpha 255), so straight-alpha channel reordering is also valid premul data.
*/
private fun PlatformImage.toSkiaBitmap(): Bitmap {
val pixels = IntArray(width * height)
getPixels(pixels, 0, width, 0, 0, width, height)
val bytes = ByteArray(pixels.size * 4)
for (i in pixels.indices) {
val argb = pixels[i]
val offset = i * 4
bytes[offset] = (argb and 0xFF).toByte()
bytes[offset + 1] = ((argb shr 8) and 0xFF).toByte()
bytes[offset + 2] = ((argb shr 16) and 0xFF).toByte()
bytes[offset + 3] = ((argb shr 24) and 0xFF).toByte()
}
val bitmap = Bitmap()
bitmap.allocPixels(ImageInfo.makeN32(width, height, ColorAlphaType.PREMUL))
bitmap.installPixels(bytes)
bitmap.setImmutable()
return bitmap
}
@@ -20,11 +20,14 @@
*/
package com.vitorpamplona.amethyst.commons.actions
import com.fasterxml.jackson.databind.ObjectMapper
import com.vitorpamplona.quartz.nip01Core.relay.normalizer.NormalizedRelayUrl
import com.vitorpamplona.quartz.nip98HttpAuth.HTTPAuthorizationEvent
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.jsonObject
import okhttp3.HttpUrl.Companion.toHttpUrl
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
@@ -42,8 +45,6 @@ import okhttp3.coroutines.executeAsync
* `crates/buzz-relay/src/api/invites.rs`.
*/
object BuzzInviteMinter {
private val json = ObjectMapper()
/** A freshly minted invite: the opaque [code], the shareable [url], and its [expiresAt] (secs). */
data class MintedInvite(
val code: String,
@@ -89,18 +90,22 @@ object BuzzInviteMinter {
okHttpClient(url).newCall(request).executeAsync().use { response ->
val payload = response.body.string()
val tree = runCatching { json.readTree(payload) }.getOrNull()
val tree = runCatching { Json.parseToJsonElement(payload).jsonObject }.getOrNull()
if (!response.isSuccessful) {
val slug = tree?.get("error")?.asText() ?: "HTTP ${response.code}"
val slug = tree?.get("error")?.stringOrNull() ?: "HTTP ${response.code}"
throw IllegalStateException(slug)
}
MintedInvite(
code = tree?.get("code")?.asText().orEmpty(),
url = tree?.get("url")?.asText().orEmpty(),
expiresAt = tree?.get("expires_at")?.asLong() ?: 0L,
code = tree?.get("code")?.stringOrNull().orEmpty(),
url = tree?.get("url")?.stringOrNull().orEmpty(),
expiresAt = tree?.get("expires_at")?.longOrNull() ?: 0L,
)
}
}
}
private fun JsonElement.stringOrNull(): String? = (this as? JsonPrimitive)?.takeIf { it.isString }?.content
private fun JsonElement.longOrNull(): Long? = (this as? JsonPrimitive)?.content?.toLongOrNull()
@@ -0,0 +1,57 @@
/*
* Copyright (c) 2025 Vitor Pamplona
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.vitorpamplona.amethyst.commons.service.image
import coil3.Image
import coil3.asImage
import com.vitorpamplona.amethyst.commons.base64Image.toPlatformImage
import com.vitorpamplona.amethyst.commons.blurhash.PlatformImage
import com.vitorpamplona.amethyst.commons.richtext.Base64Image
import org.jetbrains.skia.Bitmap
import org.jetbrains.skia.ColorAlphaType
import org.jetbrains.skia.ImageInfo
actual fun PlatformImage.toCoilImage(): Image = toSkiaBitmap().asImage(true)
actual fun base64DataUriToCoilImage(dataUri: String): Image = Base64Image.toPlatformImage(dataUri).toCoilImage()
/**
* ARGB int pixels -> N32 premul Skia bitmap. Blurhash/thumbhash output is opaque
* (alpha 255), so straight-alpha channel reordering is also valid premul data.
*/
private fun PlatformImage.toSkiaBitmap(): Bitmap {
val pixels = IntArray(width * height)
getPixels(pixels, 0, width, 0, 0, width, height)
val bytes = ByteArray(pixels.size * 4)
for (i in pixels.indices) {
val argb = pixels[i]
val offset = i * 4
bytes[offset] = (argb and 0xFF).toByte()
bytes[offset + 1] = ((argb shr 8) and 0xFF).toByte()
bytes[offset + 2] = ((argb shr 16) and 0xFF).toByte()
bytes[offset + 3] = ((argb shr 24) and 0xFF).toByte()
}
val bitmap = Bitmap()
bitmap.allocPixels(ImageInfo.makeN32(width, height, ColorAlphaType.PREMUL))
bitmap.installPixels(bytes)
bitmap.setImmutable()
return bitmap
}
@@ -1,95 +0,0 @@
/*
* Copyright (c) 2025 Vitor Pamplona
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.vitorpamplona.amethyst.desktop.service.images
import androidx.compose.runtime.Stable
import coil3.ImageLoader
import coil3.Uri
import coil3.asImage
import coil3.decode.DataSource
import coil3.fetch.FetchResult
import coil3.fetch.Fetcher
import coil3.fetch.ImageFetchResult
import coil3.key.Keyer
import coil3.request.Options
import com.vitorpamplona.amethyst.commons.base64Image.toPlatformImage
import com.vitorpamplona.amethyst.commons.blurhash.toBufferedImage
import com.vitorpamplona.amethyst.commons.richtext.Base64Image
import com.vitorpamplona.quartz.nip01Core.core.toHexKey
import com.vitorpamplona.quartz.utils.sha256.sha256
import org.jetbrains.skia.Bitmap
import org.jetbrains.skia.ColorAlphaType
import org.jetbrains.skia.ImageInfo
import java.awt.image.BufferedImage
@Stable
class DesktopBase64Fetcher(
private val data: Uri,
) : Fetcher {
override suspend fun fetch(): FetchResult? =
runCatching {
val platformImage = Base64Image.toPlatformImage(data.toString())
val bufferedImage = platformImage.toBufferedImage()
val bitmap = bufferedImageToSkiaBitmap(bufferedImage)
ImageFetchResult(
image = bitmap.asImage(true),
isSampled = false,
dataSource = DataSource.MEMORY,
)
}.getOrNull()
object Factory : Fetcher.Factory<Uri> {
override fun create(
data: Uri,
options: Options,
imageLoader: ImageLoader,
): Fetcher? =
if (data.scheme == "data") {
DesktopBase64Fetcher(data)
} else {
null
}
}
object BKeyer : Keyer<Uri> {
override fun key(
data: Uri,
options: Options,
): String? =
if (data.scheme == "data") {
sha256(data.toString().toByteArray()).toHexKey()
} else {
null
}
}
}
internal fun bufferedImageToSkiaBitmap(bi: BufferedImage): Bitmap {
val w = bi.width
val h = bi.height
val pixels = IntArray(w * h)
bi.getRGB(0, 0, w, h, pixels, 0, w)
val bitmap = Bitmap()
bitmap.allocPixels(ImageInfo.makeN32(w, h, ColorAlphaType.PREMUL))
bitmap.installPixels(convertArgbToBgra(pixels))
bitmap.setImmutable()
return bitmap
}
@@ -1,87 +0,0 @@
/*
* Copyright (c) 2025 Vitor Pamplona
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.vitorpamplona.amethyst.desktop.service.images
import androidx.compose.runtime.Stable
import coil3.ImageLoader
import coil3.asImage
import coil3.decode.DataSource
import coil3.fetch.FetchResult
import coil3.fetch.Fetcher
import coil3.fetch.ImageFetchResult
import coil3.key.Keyer
import coil3.request.Options
import com.vitorpamplona.amethyst.commons.blurhash.BlurHashDecoder
import com.vitorpamplona.amethyst.commons.blurhash.toBufferedImage
data class BlurhashWrapper(
val blurhash: String,
)
@Stable
class DesktopBlurHashFetcher(
private val data: BlurhashWrapper,
) : Fetcher {
override suspend fun fetch(): FetchResult? {
val hash = data.blurhash
val platformImage = BlurHashDecoder.decodeKeepAspectRatio(hash, 25) ?: return null
val bufferedImage = platformImage.toBufferedImage()
val bitmap = bufferedImageToSkiaBitmap(bufferedImage)
return ImageFetchResult(
image = bitmap.asImage(true),
isSampled = false,
dataSource = DataSource.MEMORY,
)
}
object Factory : Fetcher.Factory<BlurhashWrapper> {
override fun create(
data: BlurhashWrapper,
options: Options,
imageLoader: ImageLoader,
): Fetcher = DesktopBlurHashFetcher(data)
}
object BKeyer : Keyer<BlurhashWrapper> {
override fun key(
data: BlurhashWrapper,
options: Options,
): String = data.blurhash
}
}
internal fun convertArgbToBgra(pixels: IntArray): ByteArray {
val bytes = ByteArray(pixels.size * 4)
for (i in pixels.indices) {
val argb = pixels[i]
val a = (argb shr 24) and 0xFF
val r = (argb shr 16) and 0xFF
val g = (argb shr 8) and 0xFF
val b = argb and 0xFF
val offset = i * 4
bytes[offset] = b.toByte()
bytes[offset + 1] = g.toByte()
bytes[offset + 2] = r.toByte()
bytes[offset + 3] = a.toByte()
}
return bytes
}
@@ -37,6 +37,9 @@ import coil3.network.okhttp.asNetworkClient
import coil3.request.Options
import coil3.size.Precision
import coil3.svg.SvgDecoder
import com.vitorpamplona.amethyst.commons.service.image.Base64Fetcher
import com.vitorpamplona.amethyst.commons.service.image.BlurHashFetcher
import com.vitorpamplona.amethyst.commons.service.image.ThumbHashFetcher
import com.vitorpamplona.amethyst.desktop.network.DesktopHttpClient
import okhttp3.Call
import okio.Path.Companion.toOkioPath
@@ -58,12 +61,12 @@ object DesktopImageLoaderSetup {
add(TorAwareOkHttpFactory { DesktopHttpClient.currentClient() })
add(SvgDecoder.Factory())
add(SkiaGifDecoder.Factory())
add(DesktopBase64Fetcher.Factory)
add(DesktopBlurHashFetcher.Factory)
add(DesktopThumbHashFetcher.Factory)
add(DesktopBase64Fetcher.BKeyer)
add(DesktopBlurHashFetcher.BKeyer)
add(DesktopThumbHashFetcher.TKeyer)
add(Base64Fetcher.Factory)
add(BlurHashFetcher.Factory)
add(ThumbHashFetcher.Factory)
add(Base64Fetcher.BKeyer)
add(BlurHashFetcher.BKeyer)
add(ThumbHashFetcher.TKeyer)
}.build()
private fun newMemoryCache(): MemoryCache {
@@ -1,86 +0,0 @@
/*
* Copyright (c) 2025 Vitor Pamplona
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.vitorpamplona.amethyst.desktop.service.images
import androidx.compose.runtime.Stable
import coil3.ImageLoader
import coil3.asImage
import coil3.decode.DataSource
import coil3.fetch.FetchResult
import coil3.fetch.Fetcher
import coil3.fetch.ImageFetchResult
import coil3.key.Keyer
import coil3.request.Options
import com.vitorpamplona.amethyst.commons.blurhash.toBufferedImage
import com.vitorpamplona.amethyst.commons.thumbhash.ThumbHashDecoder
data class ThumbhashWrapper(
val thumbhash: String,
)
@Stable
class DesktopThumbHashFetcher(
private val data: ThumbhashWrapper,
) : Fetcher {
override suspend fun fetch(): FetchResult? {
val hash = data.thumbhash
val platformImage = ThumbHashDecoder.decodeKeepAspectRatio(hash, 25) ?: return null
val bufferedImage = platformImage.toBufferedImage()
val bitmap = bufferedImageToSkiaBitmap(bufferedImage)
return ImageFetchResult(
image = bitmap.asImage(true),
isSampled = false,
dataSource = DataSource.MEMORY,
)
}
object Factory : Fetcher.Factory<ThumbhashWrapper> {
override fun create(
data: ThumbhashWrapper,
options: Options,
imageLoader: ImageLoader,
): Fetcher = DesktopThumbHashFetcher(data)
}
object TKeyer : Keyer<ThumbhashWrapper> {
override fun key(
data: ThumbhashWrapper,
options: Options,
): String = data.thumbhash
}
}
/**
* Pick the best Coil model for a media placeholder on Desktop.
*
* Prefers [ThumbhashWrapper] when a thumbhash is available (better quality, preserves aspect ratio
* and alpha) and falls back to [BlurhashWrapper] when only a blurhash is present.
*/
fun placeholderModel(
thumbhash: String?,
blurhash: String?,
): Any? =
when {
!thumbhash.isNullOrEmpty() -> ThumbhashWrapper(thumbhash)
!blurhash.isNullOrEmpty() -> BlurhashWrapper(blurhash)
else -> null
}