mirror of
https://github.com/debpalash/VoiceStudio.git
synced 2026-12-04 01:18:16 +00:00
feat(diagnostics): deliver native phone failures through app intake
This commit is contained in:
1 parent
a9544ef387
commit
24c4789871
19 files changed
+1186
-85
No files matched your search
+1
-1
@@ -31,7 +31,7 @@ native/**/target*/
|
||||
.env
|
||||
.env.local
|
||||
.env.*.local
|
||||
/config/supermetry-app.generated.json
|
||||
**/supermetry-app.generated.json
|
||||
|
||||
# ─────────────────────────────────────────────────────────────────────────
|
||||
# OS junk
|
||||
|
||||
@@ -42,6 +42,7 @@ import com.voicestudio.mobile.features.dictate.DictateScreen
|
||||
import com.voicestudio.mobile.features.settings.SettingsScreen
|
||||
import com.voicestudio.mobile.network.ContentReportClient
|
||||
import com.voicestudio.mobile.data.AutomaticDiagnostics
|
||||
import com.voicestudio.mobile.data.AutomaticDiagnosticState
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
@@ -76,6 +77,20 @@ class MainActivity:ComponentActivity() {
|
||||
/** Reports go to VoiceStudio's app API: the dev server for debug builds, production for release. */
|
||||
fun contentReportClient()=ContentReportClient(BuildConfig.CONTENT_REPORTS_URL,BuildConfig.VERSION_NAME)
|
||||
|
||||
/** Local retry feedback remains available after a declined choice closes its prompt. */
|
||||
@Composable internal fun DiagnosticSaveFailureNotice(state:AutomaticDiagnosticState,snackbars:SnackbarHostState,onRetry:()->Unit) {
|
||||
val message=tr("diagnostics.save_failed");val retry=tr("common.retry")
|
||||
val retryChoice by rememberUpdatedState(onRetry)
|
||||
LaunchedEffect(state.saveFailed,state.saving,snackbars,message,retry) {
|
||||
if(state.saveFailed && !state.saving) {
|
||||
// A failed Keep off remains OFF and does not reopen the question or
|
||||
// block other app actions. Retry saves the same desired choice.
|
||||
val result=snackbars.showSnackbar(message,actionLabel=retry,withDismissAction=true,duration=SnackbarDuration.Indefinite)
|
||||
if(result==SnackbarResult.ActionPerformed)retryChoice()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable fun StudioApp(vm:StudioViewModel = viewModel(), reportClient:ContentReportClient? = remember {contentReportClient()},incomingIntent: Intent?=null,onIncomingConsumed: ()->Unit={}) {
|
||||
val prefs by vm.preferences.collectAsStateWithLifecycle()
|
||||
val state by vm.state.collectAsStateWithLifecycle()
|
||||
@@ -97,6 +112,7 @@ fun contentReportClient()=ContentReportClient(BuildConfig.CONTENT_REPORTS_URL,Bu
|
||||
val snackbars=remember {SnackbarHostState()}
|
||||
CompositionLocalProvider(LocalL10n provides l,LocalLayoutDirection provides direction,LocalContentReportClient provides reportClient) {
|
||||
VoiceStudioTheme(ThemePreferences(prefs.mode,prefs.lightPalette,prefs.darkPalette)) {
|
||||
DiagnosticSaveFailureNotice(diagnostics,snackbars,AutomaticDiagnostics::retryConsent)
|
||||
CompositionLocalProvider(LocalScreenTitleProvided provides true) {
|
||||
key(state.connectionId) {
|
||||
val initialRoute=remember {if(state.error?.key=="mobile.connect.error_session_expired") "connect" else "home"}
|
||||
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
package com.voicestudio.mobile
|
||||
|
||||
import android.app.Application
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.test.*
|
||||
import androidx.compose.ui.test.junit4.createComposeRule
|
||||
import androidx.test.core.app.ApplicationProvider
|
||||
import com.voicestudio.mobile.data.AutomaticDiagnosticState
|
||||
import com.voicestudio.mobile.designsystem.VoiceStudioTheme
|
||||
import com.voicestudio.mobile.features.LocalL10n
|
||||
import com.voicestudio.mobile.l10n.L10n
|
||||
import com.voicestudio.mobile.network.DiagnosticStatus
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk=[34])
|
||||
class DiagnosticConsentFeedbackTest {
|
||||
@get:Rule val compose=createComposeRule()
|
||||
private fun failedChoiceStillOffersRetry(saving:Boolean=false,failed:Boolean=true) {
|
||||
val app=ApplicationProvider.getApplicationContext<Application>();val l=L10n.load(app,"en")
|
||||
var retried=0
|
||||
compose.setContent {
|
||||
CompositionLocalProvider(LocalL10n provides l) {VoiceStudioTheme {
|
||||
val snackbars=remember {SnackbarHostState()}
|
||||
Scaffold(snackbarHost={SnackbarHost(snackbars)}) {padding->
|
||||
DiagnosticSaveFailureNotice(AutomaticDiagnosticState(ready=true,status=DiagnosticStatus(enabled=false,prompted=true,consentSaveFailed=failed),saving=saving,saveFailed=failed),snackbars) {retried++}
|
||||
}
|
||||
}}
|
||||
}
|
||||
compose.waitForIdle()
|
||||
if(failed && !saving) {
|
||||
compose.onNodeWithText(l.t("diagnostics.save_failed")).assertIsDisplayed()
|
||||
compose.onNodeWithText(l.t("common.retry")).performClick()
|
||||
compose.runOnIdle {assertEquals(1,retried)}
|
||||
}else {
|
||||
compose.onNodeWithText(l.t("diagnostics.save_failed")).assertDoesNotExist()
|
||||
compose.runOnIdle {assertEquals(0,retried)}
|
||||
}
|
||||
}
|
||||
@Test fun failedKeepOffStillShowsRetryAfterThePermissionPromptIsClosed()=failedChoiceStillOffersRetry()
|
||||
@Test fun successfulKeepOffDoesNotAskPermissionAgain()=failedChoiceStillOffersRetry(failed=false)
|
||||
@Test fun pendingSaveDoesNotOfferAnOverlappingRetry()=failedChoiceStillOffersRetry(saving=true)
|
||||
}
|
||||
+15
-2
@@ -136,6 +136,7 @@ object AutomaticDiagnostics {
|
||||
private val choices = AtomicLong()
|
||||
@Volatile private var requestedConsent: Boolean? = null
|
||||
@Volatile private var declinedThisRun = false
|
||||
@Volatile private var hardKillCleanupJob:kotlinx.coroutines.Job?=null
|
||||
val observationRevision: Long get() = choices.get()
|
||||
|
||||
@Synchronized fun initialize(app: Application, version: String) {
|
||||
@@ -152,18 +153,20 @@ object AutomaticDiagnostics {
|
||||
if(Build.VERSION.SDK_INT >= 30) runCatching {app.getSystemService(ActivityManager::class.java).setProcessStateSummary(null)}
|
||||
mutable.value = AutomaticDiagnosticState(ready = true,
|
||||
status = DiagnosticStatus(available = false, consentSaveFailed = !saved), saveFailed = !saved)
|
||||
if(!saved)scheduleHardKillCleanup(app,choices.get())
|
||||
return@launch
|
||||
}
|
||||
val owner = AutomaticDiagnosticInitialization(scope, create = {
|
||||
fun asset(name: String) = app.assets.open(name).bufferedReader(Charsets.UTF_8).use { it.readText() }
|
||||
val config = Json.parseToJsonElement(asset("diagnostics-destination.json")).jsonObject
|
||||
val appConfig = DiagnosticAppConfiguration.resolve(runCatching { asset("supermetry-app.generated.json") }.getOrNull(), System.getenv(), config.getValue("host").jsonPrimitive.content)
|
||||
val destination = DiagnosticDestination(System.getenv("SUPERMETRY_SITE_ID") ?: config.getValue("site").jsonPrimitive.content,
|
||||
System.getenv("SUPERMETRY_HOST") ?: config.getValue("host").jsonPrimitive.content,
|
||||
System.getenv("SUPERMETRY_APP_URL") ?: config.getValue("appUrl").jsonPrimitive.content)
|
||||
System.getenv("SUPERMETRY_APP_URL") ?: config.getValue("appUrl").jsonPrimitive.content, app = appConfig)
|
||||
DiagnosticReports(File(app.noBackupFilesDir, "diagnostics"),
|
||||
DiagnosticPolicy(asset("diagnostics.json")), destination, version,
|
||||
arch = when (Build.SUPPORTED_ABIS.firstOrNull()) { "arm64-v8a" -> "arm64"; "x86_64" -> "x64"; else -> "unknown" })
|
||||
}, retain = { reporter = it }, onLoaded = { reports ->
|
||||
}, retain = { reporter = it;hardKillCleanupJob?.cancel();hardKillCleanupJob=null }, onLoaded = { reports ->
|
||||
recoverExits(app, reports)
|
||||
publishProcessConsent(app, reports)
|
||||
if(reports.status.consentSaveFailed) requestedConsent = false
|
||||
@@ -184,11 +187,13 @@ object AutomaticDiagnostics {
|
||||
initialization?.cancel()
|
||||
val reports = reporter
|
||||
if(reports == null) {
|
||||
if(!enabled) {hardKillCleanupJob?.cancel();hardKillCleanupJob=null}
|
||||
if(!enabled) application?.let {app -> scope.launch {
|
||||
if (choice != choices.get()) return@launch
|
||||
mutable.update {it.copy(saving = true, status = it.status.copy(enabled = false, optedIn = false, prompted = true))}
|
||||
val saved = DiagnosticReports.revokeStoredConsent(File(app.noBackupFilesDir, "diagnostics"))
|
||||
if (choice == choices.get()) mutable.update {it.copy(saving = false, saveFailed = !saved, status = it.status.copy(consentSaveFailed = !saved))}
|
||||
if(!saved)scheduleHardKillCleanup(app,choice)
|
||||
}}
|
||||
return
|
||||
}
|
||||
@@ -213,6 +218,14 @@ object AutomaticDiagnostics {
|
||||
if (owner != null && (owner.failed || reporter == null)) owner.retry()
|
||||
else requestedConsent?.let(::setConsent)
|
||||
}
|
||||
@Synchronized private fun scheduleHardKillCleanup(app:Application,choice:Long) {
|
||||
hardKillCleanupJob?.cancel()
|
||||
hardKillCleanupJob=scope.launch {
|
||||
DiagnosticReports.retryStoredRevocation(File(app.noBackupFilesDir,"diagnostics")) {saved->
|
||||
if(choice==choices.get())mutable.update {it.copy(saveFailed=!saved,status=it.status.copy(consentSaveFailed=!saved))}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Retention permits OFF during IO, but a partially loaded grant cannot
|
||||
// authorize intake or a new task's observation before load succeeds.
|
||||
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
package com.voicestudio.mobile.network
|
||||
|
||||
import kotlinx.serialization.json.*
|
||||
|
||||
/** Build configuration only; no credential is ever placed in a stored report. */
|
||||
class DiagnosticAppConfiguration(appID: String, ingestKey: String, val host: String, val sessionPings: Boolean = false) {
|
||||
val appID=appID.trim()
|
||||
internal val ingestKey=ingestKey.trim()
|
||||
init {
|
||||
require(Regex("[a-z0-9]{6,32}").matches(this.appID))
|
||||
require(Regex("smk_[a-z2-7]{39}").matches(this.ingestKey))
|
||||
DiagnosticDestination(this.appID, host, "https://voicestudio.sh")
|
||||
}
|
||||
companion object {
|
||||
fun resolve(generated: String?, environment: Map<String,String>, fallbackHost: String): DiagnosticAppConfiguration? {
|
||||
val raw = runCatching { Json.parseToJsonElement(generated ?: "{}").jsonObject }.getOrDefault(JsonObject(emptyMap()))
|
||||
fun selected(env: String, field: String) = environment[env] ?: (raw[field] as? JsonPrimitive)?.takeIf { it.isString }?.content
|
||||
val host = selected("SUPERMETRY_APP_HOST", "host") ?: fallbackHost
|
||||
val validHost = runCatching { DiagnosticDestination("native01",host,"https://voicestudio.sh") }.isSuccess
|
||||
return runCatching { DiagnosticAppConfiguration(selected("SUPERMETRY_APP_ID","app_id") ?: "", selected("SUPERMETRY_INGEST_KEY","ingest_key") ?: "", if(validHost) host else fallbackHost,
|
||||
(raw["diagnostics"] as? JsonObject)?.get("sessionPings") == JsonPrimitive(true)) }.getOrNull()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
data class DiagnosticTransportReply(val status: Int, val body: ByteArray = byteArrayOf())
|
||||
data class DiagnosticDeliveryResult(val id:String,val status:Int,val reason:String,val warningTag:String?=null)
|
||||
private val diagnosticAppTagOrder=listOf("category","source","stage","error_code","engine_id","uptime_bucket","elapsed_bucket","memory_bucket","disk_bucket","schema_version")
|
||||
|
||||
/** ONE mapping from the existing closed projection; no exception/content enters here. */
|
||||
internal fun diagnosticAppEvent(props: JsonObject, id: String, timestamp: Long, installID: String, sessionID: String? = null, session: Boolean = false): JsonObject = buildJsonObject {
|
||||
fun string(key: String) = (props[key] as? JsonPrimitive)?.takeIf { it.isString }?.content
|
||||
val category = string("category") ?: "other"
|
||||
val crash = category in setOf("app_crash","backend_crash","renderer_crash")
|
||||
val kind = when { crash -> "crash"; category in setOf("install_failed","install_stalled","incompatibility") -> category
|
||||
category in setOf("generation_failed","model_load_failed","engine_failed","download_failed","operation_failed") -> "operation_failed"; else -> "error" }
|
||||
put("id",id);put("ts",timestamp);put("install_id",installID);put("runtime","kotlin");put("kind",if(session) "session" else kind)
|
||||
val platform = when(val p=string("platform")) { "darwin","mac","osx"->"macos";"win32","win"->"windows";"windows","macos","linux","ios","android","web"->p;else->"other" }
|
||||
val arch = when(string("arch")) {"x64","amd64","x86_64"->"x64";"arm64","aarch64"->"arm64";"ia32","x86"->"x86";"arm","armv7l"->"arm";else->"other"}
|
||||
put("platform",platform);put("arch",arch)
|
||||
sessionID?.let {put("session_id",it)}
|
||||
fun copyString(source: String, target: String, cap: Int) { string(source)?.takeIf {it.isNotEmpty() && it.toByteArray(Charsets.UTF_8).size<=cap}?.let {put(target,it)} }
|
||||
copyString("app_version","release",64)
|
||||
if(!session) {
|
||||
put("level",if(crash) "fatal" else "error");put("handled",!crash)
|
||||
copyString("build_commit","build",64);copyString("device_family","device_class",32);copyString("reason","exit_reason",32);copyString("error_type","error_type",64);copyString("signal","signal",32)
|
||||
for(key in listOf("exit_code","frames","fingerprint","occurrences")) props[key]?.let {put(key,it)}
|
||||
put("tags",buildJsonObject {
|
||||
for(key in diagnosticAppTagOrder) {
|
||||
val value=props[key] as? JsonPrimitive ?: continue
|
||||
if(value.content.isNotEmpty() && (!value.isString || value.content.toByteArray(Charsets.UTF_8).size<=200))put(key,value)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
internal fun diagnosticAppBody(site: String, events: List<JsonObject>) = buildJsonObject {put("site",site);put("events",JsonArray(events))}.toString().toByteArray(Charsets.UTF_8)
|
||||
|
||||
/** Never infer accepted indices from a malformed or ambiguous acknowledgement. */
|
||||
internal fun diagnosticAppCompleted(reply: DiagnosticTransportReply, count: Int): Set<Int> {
|
||||
return diagnosticAppAcknowledgement(reply,count)?.completed.orEmpty()
|
||||
}
|
||||
internal data class DiagnosticAppAcknowledgement(val completed:Set<Int>,val reasons:Map<Int,String>,val warnings:List<Pair<Int,String>> = emptyList())
|
||||
internal fun diagnosticAppAcknowledgement(reply: DiagnosticTransportReply, count: Int):DiagnosticAppAcknowledgement? {
|
||||
if(reply.status==400)return DiagnosticAppAcknowledgement((0 until count).toSet(),(0 until count).associateWith {"invalid"})
|
||||
if(reply.status!=202)return null
|
||||
return runCatching {
|
||||
val raw=Json.parseToJsonElement(reply.body.toString(Charsets.UTF_8)).jsonObject
|
||||
val accepted=(raw["accepted"] as? JsonPrimitive)?.takeIf {!it.isString}?.intOrNull ?: return null
|
||||
require(accepted in 0..count)
|
||||
val drops=raw.getValue("dropped").jsonArray
|
||||
val indices=mutableSetOf<Int>();val terminal=mutableSetOf<Int>();val reasons=mutableMapOf<Int,String>()
|
||||
for(drop in drops) {
|
||||
val entry=drop.jsonObject
|
||||
val index=(entry["index"] as? JsonPrimitive)?.takeIf {!it.isString}?.intOrNull ?: return null
|
||||
val reason=(entry["reason"] as? JsonPrimitive)?.takeIf {it.isString}?.content
|
||||
require(index in 0 until count && indices.add(index) && reason in setOf("too_old","invalid","duplicate","rate_limited"))
|
||||
if(reason!="rate_limited")terminal.add(index)
|
||||
reasons[index]=requireNotNull(reason)
|
||||
}
|
||||
require(accepted+indices.size==count)
|
||||
for(index in (0 until count).toSet()-indices)reasons[index]="accepted"
|
||||
val warnings=(raw["warnings"] as? JsonArray).orEmpty().take(20).mapNotNull {warning->
|
||||
val entry=warning as? JsonObject ?: return@mapNotNull null
|
||||
val index=(entry["index"] as? JsonPrimitive)?.takeIf {!it.isString}?.intOrNull ?: return@mapNotNull null
|
||||
val tag=(entry["tag"] as? JsonPrimitive)?.takeIf {it.isString}?.content
|
||||
if(index in 0 until count && entry["reason"]==JsonPrimitive("tag_not_allowed") && tag in diagnosticAppTagOrder)index to requireNotNull(tag) else null
|
||||
}
|
||||
DiagnosticAppAcknowledgement((0 until count).toSet()-indices+terminal,reasons,warnings)
|
||||
}.getOrNull()
|
||||
}
|
||||
+151
-34
@@ -75,23 +75,30 @@ data class DiagnosticStatus(val enabled: Boolean = false, val optedIn: Boolean =
|
||||
val available: Boolean = true, val pendingCount: Int = 0, val droppedCount: Int = 0, val consentSaveFailed: Boolean = false)
|
||||
data class DiagnosticRecoveryContext(val epoch: String, val enabledAtMs: Long, val appVersion: String)
|
||||
|
||||
data class DiagnosticDestination(val site: String, val host: String, val appUrl: String) {
|
||||
data class DiagnosticDestination(val site: String, val host: String, val appUrl: String, val app: DiagnosticAppConfiguration? = null) {
|
||||
internal val endpoint: HttpUrl
|
||||
internal val origin: String
|
||||
internal val eventUrl: String
|
||||
init {
|
||||
require(Regex("[a-z0-9]{6,32}").matches(site))
|
||||
val server = diagnosticDestinationURL(host); val app = diagnosticDestinationURL(appUrl)
|
||||
for (url in listOf(server, app)) {
|
||||
require(url.username.isEmpty() && url.password.isEmpty() && url.query == null && url.fragment == null)
|
||||
// Literal loopback exceptions need no DNS and cannot expose metadata
|
||||
// to a LAN/public collector over an unencrypted connection.
|
||||
require(url.isHttps || url.host in setOf("localhost", "127.0.0.1", "::1"))
|
||||
if(app!=null) {
|
||||
// The app envelope uses app.appID. These legacy inputs are unused
|
||||
// and cannot invalidate the independently validated app transport.
|
||||
endpoint=diagnosticDestinationURL(app.host).newBuilder().encodedPath("/api/public/v1/app-events").build()
|
||||
origin="";eventUrl=""
|
||||
}else {
|
||||
require(Regex("[a-z0-9]{6,32}").matches(site))
|
||||
val server = diagnosticDestinationURL(host); val appUrlValue = diagnosticDestinationURL(appUrl)
|
||||
for (url in listOf(server, appUrlValue)) {
|
||||
require(url.username.isEmpty() && url.password.isEmpty() && url.query == null && url.fragment == null)
|
||||
// Literal loopback exceptions need no DNS and cannot expose metadata
|
||||
// to a LAN/public collector over an unencrypted connection.
|
||||
require(url.isHttps || url.host in setOf("localhost", "127.0.0.1", "::1"))
|
||||
}
|
||||
require(server.encodedPath == "/")
|
||||
endpoint = server.newBuilder().encodedPath("/api/public/v1/events").build()
|
||||
origin = "${appUrlValue.scheme}://${appUrlValue.host.let { if (':' in it) "[$it]" else it }}" + if (appUrlValue.port == if (appUrlValue.isHttps) 443 else 80) "" else ":${appUrlValue.port}"
|
||||
eventUrl = appUrlValue.toString().trimEnd('/') + "/diagnostics"
|
||||
}
|
||||
require(server.encodedPath == "/")
|
||||
endpoint = server.newBuilder().encodedPath("/api/public/v1/events").build()
|
||||
origin = "${app.scheme}://${app.host.let { if (':' in it) "[$it]" else it }}" + if (app.port == if (app.isHttps) 443 else 80) "" else ":${app.port}"
|
||||
eventUrl = app.toString().trimEnd('/') + "/diagnostics"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -167,6 +174,7 @@ object SystemDiagnosticClock : DiagnosticClock {
|
||||
}
|
||||
interface DiagnosticTransport {
|
||||
suspend fun send(destination: DiagnosticDestination, body: ByteArray, allowed: () -> Boolean): Int
|
||||
suspend fun sendApp(destination: DiagnosticDestination, body: ByteArray, userAgent: String, allowed: () -> Boolean): DiagnosticTransportReply = DiagnosticTransportReply(send(destination,body,allowed))
|
||||
fun cancelAll()
|
||||
}
|
||||
/** Dedicated client: paired-host headers, cookies, authentication and redirects never participate. */
|
||||
@@ -178,9 +186,12 @@ class OkHttpDiagnosticTransport : DiagnosticTransport {
|
||||
.callTimeout(2, TimeUnit.SECONDS).build()
|
||||
private val lock = Any()
|
||||
private val calls = mutableSetOf<Call>()
|
||||
override suspend fun send(destination: DiagnosticDestination, body: ByteArray, allowed: () -> Boolean): Int = suspendCancellableCoroutine { continuation ->
|
||||
val request = Request.Builder().url(destination.endpoint).header("Origin", destination.origin)
|
||||
.post(body.toRequestBody("application/json".toMediaType())).build()
|
||||
override suspend fun send(destination: DiagnosticDestination, body: ByteArray, allowed: () -> Boolean): Int = request(destination,body,null,allowed).status
|
||||
override suspend fun sendApp(destination: DiagnosticDestination, body: ByteArray, userAgent: String, allowed: () -> Boolean): DiagnosticTransportReply = request(destination,body,userAgent,allowed)
|
||||
private suspend fun request(destination: DiagnosticDestination, body: ByteArray, userAgent: String?, allowed: () -> Boolean): DiagnosticTransportReply = suspendCancellableCoroutine { continuation ->
|
||||
val builder = Request.Builder().url(destination.endpoint).post(body.toRequestBody("application/json".toMediaType()))
|
||||
destination.app?.let { builder.header("X-Supermetry-Key",it.ingestKey);userAgent?.let {agent->builder.header("User-Agent",agent)} } ?: builder.header("Origin",destination.origin)
|
||||
val request = builder.build()
|
||||
val call = client.newCall(request)
|
||||
continuation.invokeOnCancellation { call.cancel() }
|
||||
synchronized(lock) {
|
||||
@@ -192,10 +203,14 @@ class OkHttpDiagnosticTransport : DiagnosticTransport {
|
||||
if (continuation.isActive) continuation.resumeWithException(e)
|
||||
}
|
||||
override fun onResponse(call: Call, response: Response) {
|
||||
response.use {
|
||||
synchronized(lock) { calls.remove(call) }
|
||||
if (continuation.isActive) continuation.resume(response.code)
|
||||
}
|
||||
try {
|
||||
response.use {
|
||||
synchronized(lock) { calls.remove(call) }
|
||||
val source=response.body?.source()
|
||||
val bytes=if(source!=null && !source.request(16385))source.readByteArray() else byteArrayOf()
|
||||
if (continuation.isActive) continuation.resume(DiagnosticTransportReply(response.code,bytes))
|
||||
}
|
||||
} catch(error: IOException) { if(continuation.isActive)continuation.resumeWithException(error) }
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -215,6 +230,7 @@ class DiagnosticReports(
|
||||
private val storage: DiagnosticStorage = FileDiagnosticStorage(directory),
|
||||
dispatcher: CoroutineDispatcher = Dispatchers.IO,
|
||||
private val disabled: () -> Boolean = { diagnosticKillSwitch(System.getenv("OMNIVOICE_DIAGNOSTICS_DISABLED")) || diagnosticKillSwitch(System.getenv("OMNIVOICE_ANALYTICS_DISABLED")) },
|
||||
private val onDeliveryResult: (DiagnosticDeliveryResult) -> Unit = {},
|
||||
) {
|
||||
private data class Consent(val enabled: Boolean, val epoch: String, val profile: String, val enabledAt: Long?)
|
||||
private data class Revocation(val consent:Consent?,val failed:Boolean,val saveFailed:Boolean)
|
||||
@@ -222,6 +238,15 @@ class DiagnosticReports(
|
||||
/** Bootstrap cleanup, independent of resources/config. Invalidate live reporters first. */
|
||||
suspend fun revokeStoredConsent(directory: File, storage: DiagnosticStorage = FileDiagnosticStorage(directory)): Boolean =
|
||||
withContext(Dispatchers.IO) { !revokeGrant(storage).failed }
|
||||
/** The app owns/cancels this bounded wake when resources cannot create a reporter. */
|
||||
suspend fun retryStoredRevocation(directory:File,storage:DiagnosticStorage=FileDiagnosticStorage(directory),clock:DiagnosticClock=SystemDiagnosticClock,onAttempt:suspend(Boolean)->Unit) {
|
||||
while(currentCoroutineContext().isActive) {
|
||||
clock.sleep(60000);currentCoroutineContext().ensureActive()
|
||||
val saved=revokeStoredConsent(directory,storage)
|
||||
currentCoroutineContext().ensureActive();onAttempt(saved)
|
||||
if(saved)return
|
||||
}
|
||||
}
|
||||
private fun revokeGrant(storage: DiagnosticStorage, hint: Boolean? = null, explicit: Boolean = false): Revocation {
|
||||
val hadGrant=hint==true || try { storage.read("consent.json",4096)!=null }catch(_:Exception){ hint!=false }
|
||||
var failed=false
|
||||
@@ -260,6 +285,14 @@ class DiagnosticReports(
|
||||
private var revocationPending = false
|
||||
private var revocationRetryAt: Long? = null
|
||||
private val retryAt = mutableMapOf<String,Long>()
|
||||
private var appPaused=false
|
||||
private val sessionID=UUID.randomUUID().toString().replace("-","")
|
||||
private var sessionStarted=false
|
||||
private var sessionInvalidated=false
|
||||
private var sessionEpoch:String?=null
|
||||
private var sessionEvent:Pair<String,Long>?=null
|
||||
private var sessionRetryAt:Long?=null
|
||||
private val currentRunIDs=mutableSetOf<String>()
|
||||
val status: DiagnosticStatus get() = synchronized(stateLock) {
|
||||
val killed=disabled()
|
||||
state.copy(enabled = state.enabled && !killed, optedIn = state.optedIn && !killed, available = !killed)
|
||||
@@ -348,7 +381,21 @@ class DiagnosticReports(
|
||||
private fun cancelRetryLocked() {
|
||||
retryJob?.cancel();retryJob=null;retryWakeAt=null
|
||||
}
|
||||
private fun revoked():Boolean = try { storage.read("revoked.json",4096)!=null }catch(_:Exception){ true }
|
||||
private fun revoked():Boolean = try { storage.read("revoked.json",4096)!=null }catch(_:DiagnosticStorageLimitExceeded){true}
|
||||
private fun deferConsentRead(generation:Long) {
|
||||
synchronized(stateLock) {
|
||||
if(sequence!=generation || closed)return
|
||||
loaded=false;state=state.copy(enabled=false,optedIn=false)
|
||||
}
|
||||
transport.cancelAll();consentReadRetryAt=clock.nowMs()+60000;scheduleRetry(null,generation)
|
||||
}
|
||||
/** Unknown marker IO suspends permission; only a present marker revokes. */
|
||||
private fun deliveryAllowed(epoch:String,generation:Long):Boolean {
|
||||
if(!allowed(epoch,generation))return false
|
||||
val present=try {revoked()}catch(_:Exception){deferConsentRead(generation);return false}
|
||||
if(present) {val changed=invalidateGrant();persistRevocation(changed,consent!=null,explicit=true);return false}
|
||||
return allowed(epoch,generation)
|
||||
}
|
||||
private fun retryAllowed(epoch:String?,generation:Long):Boolean = synchronized(stateLock) {
|
||||
!closed && sequence==generation && (revocationPending || consentReadRetryAt!=null || epoch!=null &&
|
||||
(allowed(epoch,generation) || outboxReadRetryEpoch==epoch && consent?.epoch==epoch && !disabled()))
|
||||
@@ -362,6 +409,7 @@ class DiagnosticReports(
|
||||
}
|
||||
/** Worker-owned durable OFF, with one bounded wake even while collection is disabled. */
|
||||
private fun persistRevocation(generation:Long,hadGrant:Boolean,explicit:Boolean):Boolean {
|
||||
sessionInvalidated=true;sessionEvent=null;sessionEpoch=null;sessionRetryAt=null;currentRunIDs.clear()
|
||||
records.clear();retryAt.clear();storageRetryAt=null;consentReadRetryAt=null;outboxReadRetryEpoch=null
|
||||
val result=revokeGrant(storage,hadGrant,explicit)
|
||||
synchronized(stateLock) {
|
||||
@@ -380,7 +428,7 @@ class DiagnosticReports(
|
||||
// Called under worker: retryAt and records belong to that worker.
|
||||
// Storage publication blocks all delivery, including already-due
|
||||
// network retries. An old network deadline must not cause a busy loop.
|
||||
val next=if(revocationPending)revocationRetryAt else consentReadRetryAt ?: storageRetryAt ?: retryAt.values.minOrNull()
|
||||
val next=if(revocationPending)revocationRetryAt else consentReadRetryAt ?: storageRetryAt ?: if(appPaused)null else (retryAt.values+listOfNotNull(sessionRetryAt)).minOrNull()
|
||||
synchronized(stateLock) {
|
||||
if(next==null || !retryAllowed(epoch,generation)) { cancelRetryLocked();return }
|
||||
if(retryJob?.isActive==true && retryWakeAt==next)return
|
||||
@@ -424,8 +472,9 @@ class DiagnosticReports(
|
||||
return withContext(scope.coroutineContext) {
|
||||
worker.withLock {
|
||||
if (closed) return@withLock status
|
||||
val blocked=revoked()
|
||||
if(loaded && !disabled() && !blocked && !revocationPending)return@withLock status
|
||||
val marker=runCatching {revoked()}
|
||||
val blocked=marker.getOrNull()==true
|
||||
if(loaded && !disabled() && !blocked && !revocationPending && marker.isSuccess)return@withLock status
|
||||
val generation = synchronized(stateLock) { sequence }
|
||||
val pendingReadAt=consentReadRetryAt ?: storageRetryAt?.takeIf {outboxReadRetryEpoch!=null}
|
||||
if(!forceRead && (pendingReadAt ?: 0)>clock.nowMs() && !disabled() && !blocked && !revocationPending) {
|
||||
@@ -433,7 +482,7 @@ class DiagnosticReports(
|
||||
throw IOException("Diagnostic consent read is pending retry")
|
||||
}
|
||||
var hadGrant=synchronized(stateLock) { consent!=null }
|
||||
var unread:Exception?=null
|
||||
var unread:Exception?=marker.exceptionOrNull() as? Exception
|
||||
val saved = try { storage.read("consent.json",4096).let { hadGrant=hadGrant || it!=null;parseConsent(it) } } catch (error: Exception) {
|
||||
if(error is CancellationException)throw error
|
||||
hadGrant=true
|
||||
@@ -506,7 +555,7 @@ class DiagnosticReports(
|
||||
}
|
||||
suspend fun setConsent(enabled: Boolean): DiagnosticStatus {
|
||||
if (enabled && disabled()) { setConsent(false);throw IllegalStateException("Diagnostic reports are disabled") }
|
||||
if (enabled && status.enabled && !revoked()) return status
|
||||
if (enabled && status.enabled && runCatching {!revoked()}.getOrDefault(false)) return status
|
||||
val generation=invalidateGrant()
|
||||
return withContext(scope.coroutineContext) {
|
||||
worker.withLock {
|
||||
@@ -524,6 +573,7 @@ class DiagnosticReports(
|
||||
if(failed)throw IOException("Could not save diagnostic consent")
|
||||
return@withLock status
|
||||
}
|
||||
if(sessionStarted) {sessionInvalidated=true;sessionEvent=null;sessionEpoch=null;currentRunIDs.clear()}
|
||||
val fresh=Consent(true,id(),"install_${id()}",clock.nowMs())
|
||||
records.clear();retryAt.clear();storageRetryAt=null;consentReadRetryAt=null;outboxReadRetryEpoch=null
|
||||
try {
|
||||
@@ -626,7 +676,10 @@ class DiagnosticReports(
|
||||
records[index] = JsonObject(old + ("props" to JsonObject(fields + ("occurrences" to JsonPrimitive(count)))))
|
||||
} else if (records.size < policy.limit("queue_count", 64)) {
|
||||
val record = buildJsonObject { put("version", 1); put("id", item.id ?: id()); put("timestamp_ms", item.timestamp); put("epoch", epoch); put("props", item.props) }
|
||||
if (JsonArray(records + record).toString().toByteArray().size <= policy.limit("queue_bytes", 524288)) records.add(record)
|
||||
if (JsonArray(records + record).toString().toByteArray().size <= policy.limit("queue_bytes", 524288)) {
|
||||
records.add(record)
|
||||
if(item.id==null && destination.app?.sessionPings==true && !sessionInvalidated)currentRunIDs.add(record.getValue("id").jsonPrimitive.content)
|
||||
}
|
||||
else synchronized(stateLock) { state = state.copy(droppedCount = state.droppedCount + 1) }
|
||||
} else synchronized(stateLock) { state = state.copy(droppedCount = state.droppedCount + 1) }
|
||||
}
|
||||
@@ -640,9 +693,11 @@ class DiagnosticReports(
|
||||
else scheduleRetry(null,generation)
|
||||
return@withLock
|
||||
}
|
||||
if(disabled() || revoked()) {
|
||||
val killed=disabled()
|
||||
val present=if(killed)false else try{revoked()}catch(_:Exception){deferConsentRead(synchronized(stateLock){sequence});return@withLock}
|
||||
if(killed || present) {
|
||||
val generation=invalidateGrant()
|
||||
persistRevocation(generation,consent!=null,explicit=revoked())
|
||||
persistRevocation(generation,consent!=null,explicit=present)
|
||||
return@withLock
|
||||
}
|
||||
val snapshot = synchronized(stateLock) { consent?.let { it to sequence } } ?: return@withLock
|
||||
@@ -657,10 +712,12 @@ class DiagnosticReports(
|
||||
}
|
||||
if(!persistOrRetry(current.epoch,generation))return@withLock
|
||||
retryAt.keys.retainAll(records.map { it["id"]!!.jsonPrimitive.content }.toSet())
|
||||
currentRunIDs.retainAll(records.map {it.getValue("id").jsonPrimitive.content}.toSet())
|
||||
if(destination.app!=null) {flushApp(current,generation);scheduleRetry(current.epoch,generation);return@withLock}
|
||||
for (record in records.toList()) {
|
||||
val identity=record["id"]!!.jsonPrimitive.content
|
||||
if ((retryAt[identity] ?: 0)>clock.nowMs()) continue
|
||||
if (!allowed(current.epoch, generation)) break
|
||||
if (!deliveryAllowed(current.epoch, generation)) break
|
||||
val body = buildJsonObject {
|
||||
put("v", 1); put("id", record["id"]!!); put("ts", record["timestamp_ms"]!!); put("site", destination.site)
|
||||
put("name", "diagnostic_report"); put("url", destination.eventUrl); put("profile_id", current.profile); put("props", record["props"]!!)
|
||||
@@ -673,10 +730,8 @@ class DiagnosticReports(
|
||||
var terminal = false
|
||||
repeat(policy.limit("max_attempts", 3)) { attempt ->
|
||||
if (terminal || !allowed(current.epoch, generation)) return@repeat
|
||||
if(revoked()) {
|
||||
val changed=invalidateGrant();persistRevocation(changed,consent!=null,explicit=true)
|
||||
return@withLock
|
||||
}
|
||||
if(sanitizeRecord(record,current.epoch)==null) {terminal=true;return@repeat}
|
||||
if(!deliveryAllowed(current.epoch,generation))return@withLock
|
||||
val code = try { transport.send(destination, body) { allowed(current.epoch, generation) } } catch (_: Exception) { null }
|
||||
terminal = code != null && code in 200..499 && code != 429
|
||||
if (!terminal && attempt < policy.limit("max_attempts", 3) - 1) {
|
||||
@@ -695,12 +750,74 @@ class DiagnosticReports(
|
||||
scheduleRetry(current.epoch,generation)
|
||||
}
|
||||
}
|
||||
private suspend fun flushApp(current: Consent, generation: Long) {
|
||||
val app=destination.app ?: return
|
||||
if(appPaused)return
|
||||
if(app.sessionPings && !sessionStarted && !sessionInvalidated) {
|
||||
sessionStarted=true;sessionEpoch=current.epoch;sessionEvent=id() to clock.nowMs()
|
||||
}
|
||||
data class Item(val id:String,val stamp:Long,val event:JsonObject,val session:Boolean=false)
|
||||
val candidates=ArrayDeque<Item>()
|
||||
sessionEvent?.takeIf {sessionEpoch==current.epoch && (sessionRetryAt ?: 0)<=clock.nowMs()}?.let {(identity,stamp)->
|
||||
val props=buildJsonObject {put("app_version",appVersion);put("platform","android");put("arch",arch)}
|
||||
candidates.add(Item(identity,stamp,diagnosticAppEvent(props,identity,stamp,current.profile,sessionID,true),true))
|
||||
}
|
||||
for(record in records) {
|
||||
val identity=record.getValue("id").jsonPrimitive.content
|
||||
if((retryAt[identity] ?: 0)>clock.nowMs())continue
|
||||
val stamp=record.getValue("timestamp_ms").jsonPrimitive.long
|
||||
val correlation=if(sessionEpoch==current.epoch && !sessionInvalidated && identity in currentRunIDs)sessionID else null
|
||||
candidates.add(Item(identity,stamp,diagnosticAppEvent(record.getValue("props").jsonObject,identity,stamp,current.profile,correlation)))
|
||||
}
|
||||
while(candidates.isNotEmpty() && deliveryAllowed(current.epoch,generation) && !appPaused) {
|
||||
val batch=mutableListOf<Item>()
|
||||
while(candidates.isNotEmpty() && batch.size<20) {
|
||||
val next=candidates.first()
|
||||
if(diagnosticAppBody(app.appID,(batch+next).map {it.event}).size>16384) {
|
||||
if(batch.isEmpty()) {candidates.removeFirst();records.removeAll {it["id"]?.jsonPrimitive?.content==next.id};currentRunIDs.remove(next.id);synchronized(stateLock){state=state.copy(droppedCount=state.droppedCount+1)};if(!persistOrRetry(current.epoch,generation))return}
|
||||
break
|
||||
}
|
||||
batch.add(candidates.removeFirst())
|
||||
}
|
||||
if(batch.isEmpty())continue
|
||||
for(attempt in 0 until policy.limit("max_attempts",3)) {
|
||||
if(!allowed(current.epoch,generation))return
|
||||
if(!deliveryAllowed(current.epoch,generation))return
|
||||
val expired=batch.filter {it.stamp<clock.nowMs()-policy.limit("ttl_ms",604800000)}.map {it.id}.toSet()
|
||||
if(expired.isNotEmpty()) {
|
||||
records.removeAll {it["id"]?.jsonPrimitive?.content in expired};currentRunIDs.removeAll(expired)
|
||||
if(batch.any {it.session && it.id in expired}) {sessionEvent=null;sessionRetryAt=null}
|
||||
batch.removeAll {it.id in expired};if(!persistOrRetry(current.epoch,generation))return
|
||||
}
|
||||
if(batch.isEmpty())break
|
||||
val reply=try {transport.sendApp(destination,diagnosticAppBody(app.appID,batch.map {it.event}),"VoiceStudio/$appVersion (android; $arch)") {allowed(current.epoch,generation)}}catch(error:Exception){if(error is CancellationException)throw error;DiagnosticTransportReply(0)}
|
||||
if(!allowed(current.epoch,generation))return
|
||||
if(reply.status==401) {appPaused=true;synchronized(stateLock){cancelRetryLocked()};batch.forEach {onDeliveryResult(DiagnosticDeliveryResult(it.id,401,"unauthorized"))};return}
|
||||
val acknowledgement=diagnosticAppAcknowledgement(reply,batch.size)
|
||||
acknowledgement?.reasons?.forEach {(index,reason)->onDeliveryResult(DiagnosticDeliveryResult(batch[index].id,reply.status,reason))}
|
||||
acknowledgement?.warnings?.forEach {(index,tag)->onDeliveryResult(DiagnosticDeliveryResult(batch[index].id,reply.status,"tag_not_allowed",tag))}
|
||||
val completed=acknowledgement?.completed.orEmpty()
|
||||
val finished=batch.filterIndexed {index,_->index in completed}
|
||||
val ids=finished.map {it.id}.toSet()
|
||||
records.removeAll {it["id"]?.jsonPrimitive?.content in ids};currentRunIDs.removeAll(ids);ids.forEach {retryAt.remove(it)}
|
||||
if(finished.any {it.session}) {sessionEvent=null;sessionRetryAt=null}
|
||||
batch.removeAll {it.id in ids}
|
||||
if(ids.isNotEmpty() && !persistOrRetry(current.epoch,generation))return
|
||||
if(batch.isEmpty() || reply.status==202 || reply.status==400)break
|
||||
if(attempt+1<policy.limit("max_attempts",3)) {
|
||||
var remaining=500L shl attempt
|
||||
while(remaining>0 && allowed(current.epoch,generation)) {clock.sleep(minOf(remaining,25));remaining-=25}
|
||||
}
|
||||
}
|
||||
batch.forEach {if(it.session)sessionRetryAt=clock.nowMs()+60000 else retryAt[it.id]=clock.nowMs()+60000}
|
||||
}
|
||||
}
|
||||
suspend fun close() {
|
||||
synchronized(stateLock) { closed = true; sequence++; state = state.copy(enabled = false, optedIn = false);cancelRetryLocked() }
|
||||
transport.cancelAll()
|
||||
try {
|
||||
withContext(Dispatchers.IO) { worker.withLock {
|
||||
val blocked=revoked()
|
||||
val blocked=if(revocationPending || disabled())false else revoked()
|
||||
if(revocationPending || disabled() || blocked) {
|
||||
// Do this before persisting any old queue or cancelling the
|
||||
// worker's scope, even when its retry deadline is later.
|
||||
|
||||
+134
@@ -0,0 +1,134 @@
|
||||
package com.voicestudio.mobile.network
|
||||
|
||||
import java.io.File
|
||||
import kotlinx.coroutines.*
|
||||
import kotlinx.coroutines.test.*
|
||||
import kotlinx.serialization.json.*
|
||||
import okhttp3.mockwebserver.MockResponse
|
||||
import okhttp3.mockwebserver.MockWebServer
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
@OptIn(ExperimentalCoroutinesApi::class)
|
||||
class DiagnosticAppIntakeTest {
|
||||
private val root=generateSequence(File(System.getProperty("user.dir"))) {it.parentFile}.first {File(it,"config/diagnostics.json").isFile}
|
||||
private val policy=DiagnosticPolicy(File(root,"config/diagnostics.json").readText(Charsets.UTF_8))
|
||||
private class Store:DiagnosticStorage {
|
||||
val files=mutableMapOf<String,ByteArray>()
|
||||
override fun read(name:String,maxBytes:Int)=files[name]?.clone()?.also {require(it.size<=maxBytes)}
|
||||
override fun write(name:String,bytes:ByteArray) {files[name]=bytes.clone()}
|
||||
override fun remove(name:String) {files.remove(name)}
|
||||
}
|
||||
private class Clock(private val scheduler:TestCoroutineScheduler):DiagnosticClock {
|
||||
override fun nowMs()=1_794_640_000_000L+scheduler.currentTime
|
||||
override suspend fun sleep(ms:Long)=delay(ms)
|
||||
}
|
||||
private class Transport:DiagnosticTransport {
|
||||
val bodies=mutableListOf<JsonObject>();val legacy=mutableListOf<String>();val replies=ArrayDeque<DiagnosticTransportReply>()
|
||||
var held:CompletableDeferred<Unit>?=null;var cancelled=0
|
||||
override suspend fun send(destination:DiagnosticDestination,body:ByteArray,allowed:()->Boolean):Int {legacy.add(body.toString(Charsets.UTF_8));return 202}
|
||||
override suspend fun sendApp(destination:DiagnosticDestination,body:ByteArray,userAgent:String,allowed:()->Boolean):DiagnosticTransportReply {
|
||||
check(allowed());val parsed=Json.parseToJsonElement(body.toString(Charsets.UTF_8)).jsonObject;bodies.add(parsed)
|
||||
held?.await();check(allowed())
|
||||
return replies.removeFirstOrNull() ?: DiagnosticTransportReply(202,"{\"accepted\":${parsed.getValue("events").jsonArray.size},\"dropped\":[]}".toByteArray())
|
||||
}
|
||||
override fun cancelAll() {cancelled++;held?.cancel()}
|
||||
}
|
||||
private fun destination(pings:Boolean=false)=DiagnosticDestination("legacy01","https://legacy.example","https://voicestudio.sh",DiagnosticAppConfiguration("native01","smk_"+"a".repeat(39),"https://intake.example",pings))
|
||||
private fun reports(store:Store,transport:Transport,scheduler:TestCoroutineScheduler,pings:Boolean=false,app:Boolean=true,results:MutableList<DiagnosticDeliveryResult> = mutableListOf())=DiagnosticReports(File("/unused"),policy,if(app)destination(pings) else DiagnosticDestination("legacy01","https://legacy.example","https://voicestudio.sh"),"0.5.9-beta.3",arch="arm64",transport=transport,clock=Clock(scheduler),storage=store,dispatcher=StandardTestDispatcher(scheduler),disabled={false},onDeliveryResult={results.add(it)})
|
||||
@Test fun commonGoldenMappingAndRawTagOrder() {
|
||||
val fixture=Json.parseToJsonElement(File(root,"tests/fixtures/diagnostic-app-events.json").readText(Charsets.UTF_8)).jsonObject
|
||||
for(case in fixture.getValue("cases").jsonArray) {
|
||||
val row=case.jsonObject;val actual=diagnosticAppEvent(row.getValue("props").jsonObject,"id",10,"profile")
|
||||
assertEquals(row.getValue("name").jsonPrimitive.content,row.getValue("expected"),JsonObject(actual-filterKeys))
|
||||
val expectedKeys=row.getValue("expected").jsonObject["tags"]?.jsonObject?.keys?.toList().orEmpty()
|
||||
assertEquals(expectedKeys,actual["tags"]?.jsonObject?.keys?.toList().orEmpty())
|
||||
val body=diagnosticAppBody("native01",listOf(actual)).toString(Charsets.UTF_8)
|
||||
var index=body.indexOf("\"tags\"")
|
||||
expectedKeys.forEach {key->val next=body.indexOf("\"$key\":",index+1);assertTrue("tag $key order",next>index);index=next}
|
||||
}
|
||||
}
|
||||
private val filterKeys=setOf("id","ts","runtime","install_id")
|
||||
@Test fun invalidSelectedCredentialsDoNotUseGeneratedFallbackAndInvalidHostUsesAnalytics() {
|
||||
val generated="""{"app_id":"native01","ingest_key":"${"smk_"+"a".repeat(39)}","host":"https://generated.example"}"""
|
||||
assertNull(DiagnosticAppConfiguration.resolve(generated,mapOf("SUPERMETRY_APP_ID" to "invalid!"),"https://fallback.example"))
|
||||
val config=requireNotNull(DiagnosticAppConfiguration.resolve(generated,mapOf("SUPERMETRY_APP_HOST" to "http://public.example"),"https://fallback.example"))
|
||||
assertEquals("https://fallback.example",config.host);assertFalse(config.sessionPings)
|
||||
}
|
||||
private fun validAppConfigurationIsIndependentOfLegacyOverrides(invalid:String) {
|
||||
val site=if(invalid in listOf("site","all")) "" else "legacy01"
|
||||
val host=if(invalid in listOf("host","all")) "http://public.example" else "https://legacy.example"
|
||||
val appURL=if(invalid in listOf("app_url","all")) "not-a-url" else "https://voicestudio.sh"
|
||||
assertTrue("Legacy-only validation must remain strict",runCatching {DiagnosticDestination(site,host,appURL)}.isFailure)
|
||||
val app=DiagnosticAppConfiguration("native01","smk_"+"a".repeat(39),"https://intake.example")
|
||||
val destination=DiagnosticDestination(site,host,appURL,app)
|
||||
assertEquals("https://intake.example/api/public/v1/app-events",destination.endpoint.toString())
|
||||
assertEquals("native01",destination.app?.appID)
|
||||
}
|
||||
@Test fun validAppIgnoresInvalidLegacySite()=validAppConfigurationIsIndependentOfLegacyOverrides("site")
|
||||
@Test fun validAppIgnoresInvalidLegacyHost()=validAppConfigurationIsIndependentOfLegacyOverrides("host")
|
||||
@Test fun validAppIgnoresInvalidLegacyAppURL()=validAppConfigurationIsIndependentOfLegacyOverrides("app_url")
|
||||
@Test fun validAppIgnoresAllInvalidLegacyFields()=validAppConfigurationIsIndependentOfLegacyOverrides("all")
|
||||
@Test fun mixed202AndAmbiguousAndBooleanAcknowledgements() {
|
||||
fun completed(text:String)=diagnosticAppCompleted(DiagnosticTransportReply(202,text.toByteArray()),4)
|
||||
assertEquals(setOf(0,1,2),completed("""{"accepted":1,"dropped":[{"index":1,"reason":"invalid"},{"index":2,"reason":"duplicate"},{"index":3,"reason":"rate_limited"}]}"""))
|
||||
assertTrue(completed("""{"accepted":1,"dropped":[]}""").isEmpty())
|
||||
assertTrue(completed("""{"accepted":true,"dropped":[]}""").isEmpty())
|
||||
assertTrue(completed("""{"accepted":3,"dropped":[{"index":true,"reason":"invalid"}]}""").isEmpty())
|
||||
assertEquals(setOf(0,1,2,3),diagnosticAppCompleted(DiagnosticTransportReply(400),4))
|
||||
}
|
||||
@Test fun actualWorkerBatchesBoundedAndRecordsNoCredentialsOrSessionByDefault()=runTest {
|
||||
val store=Store();val transport=Transport();val reports=reports(store,transport,testScheduler)
|
||||
reports.setConsent(true)
|
||||
repeat(45) {i->assertTrue(reports.capture(DiagnosticInput("engine_failed",frames=listOf(DiagnosticFrame("backend/main.py",i+1))))) }
|
||||
reports.flush()
|
||||
assertEquals(45,transport.bodies.sumOf {it.getValue("events").jsonArray.size})
|
||||
transport.bodies.forEach {assertTrue(it.getValue("events").jsonArray.size<=20);assertTrue(it.toString().toByteArray().size<=16384)}
|
||||
assertTrue(transport.bodies.flatMap {it.getValue("events").jsonArray}.none {it.jsonObject["kind"]==JsonPrimitive("session") || "session_id" in it.jsonObject})
|
||||
assertEquals(0,reports.status.pendingCount);assertFalse(store.files.values.any {it.toString(Charsets.UTF_8).contains("smk_")})
|
||||
reports.close()
|
||||
}
|
||||
@Test fun unauthorizedPausesEntireRunAndOffClearsQueue()=runTest {
|
||||
val store=Store();val transport=Transport();transport.replies.add(DiagnosticTransportReply(401));val results=mutableListOf<DiagnosticDeliveryResult>();val reports=reports(store,transport,testScheduler,results=results)
|
||||
reports.setConsent(true);reports.capture(DiagnosticInput("engine_failed"));reports.flush()
|
||||
assertEquals(1,transport.bodies.size);assertEquals(1,reports.status.pendingCount);assertEquals("unauthorized",results.single().reason)
|
||||
advanceTimeBy(60001);runCurrent();reports.capture(DiagnosticInput("download_failed"));reports.flush();assertEquals(1,transport.bodies.size)
|
||||
reports.setConsent(false);assertEquals(0,reports.status.pendingCount);assertFalse(store.files.containsKey("outbox.json"))
|
||||
reports.setConsent(true);reports.capture(DiagnosticInput("model_load_failed"));reports.flush();assertEquals(1,transport.bodies.size)
|
||||
reports.close()
|
||||
}
|
||||
@Test fun retryKeepsIDsAndMixedDropWarningRemainsLocal()=runTest {
|
||||
val store=Store();val transport=Transport();val results=mutableListOf<DiagnosticDeliveryResult>()
|
||||
transport.replies.add(DiagnosticTransportReply(429));transport.replies.add(DiagnosticTransportReply(503))
|
||||
transport.replies.add(DiagnosticTransportReply(202,"""{"accepted":1,"dropped":[{"index":1,"reason":"rate_limited"},{"index":2,"reason":"too_old"}],"warnings":[{"index":0,"reason":"tag_not_allowed","tag":"stage"}]}""".toByteArray()))
|
||||
val reports=reports(store,transport,testScheduler,results=results);reports.setConsent(true)
|
||||
listOf("engine_failed","download_failed","model_load_failed").forEach {reports.capture(DiagnosticInput(it))}
|
||||
reports.flush()
|
||||
val ids=transport.bodies.map {it.getValue("events").jsonArray.map {it.jsonObject.getValue("id")}}
|
||||
assertEquals(3,ids.size);assertEquals(ids[0],ids[1]);assertEquals(ids[1],ids[2]);assertEquals(1,reports.status.pendingCount)
|
||||
assertTrue(results.any {it.reason=="tag_not_allowed" && it.warningTag=="stage"});assertTrue(results.any {it.reason=="too_old"})
|
||||
advanceTimeBy(60001);runCurrent();reports.flush();assertEquals(0,reports.status.pendingCount)
|
||||
reports.close()
|
||||
}
|
||||
@Test fun optionalSessionIsOncePerRunAndWithdrawalEndsCorrelation()=runTest {
|
||||
val store=Store();val transport=Transport();val reports=reports(store,transport,testScheduler,pings=true)
|
||||
reports.setConsent(true);reports.capture(DiagnosticInput("engine_failed"));reports.flush()
|
||||
val events=transport.bodies.flatMap {it.getValue("events").jsonArray}.map {it.jsonObject}
|
||||
assertEquals(1,events.count {it["kind"]==JsonPrimitive("session")});assertEquals(1,events.map {it.getValue("session_id")}.toSet().size)
|
||||
assertFalse(store.files.values.any {it.toString(Charsets.UTF_8).contains("session_id")})
|
||||
reports.setConsent(false);reports.setConsent(true);reports.capture(DiagnosticInput("model_load_failed"));reports.flush()
|
||||
assertTrue(transport.bodies.last().getValue("events").jsonArray.all {"session_id" !in it.jsonObject && it.jsonObject["kind"]!=JsonPrimitive("session")})
|
||||
reports.close()
|
||||
}
|
||||
@Test fun actualTransportUsesAppEndpointKeyAgentAndNoOrigin()=runTest {
|
||||
val server=MockWebServer();server.start()
|
||||
val transport=OkHttpDiagnosticTransport()
|
||||
try {
|
||||
server.enqueue(MockResponse().setResponseCode(202).setBody("""{"accepted":1,"dropped":[]}"""))
|
||||
val config=DiagnosticAppConfiguration("native01","smk_"+"a".repeat(39),server.url("/").toString())
|
||||
val reply=transport.sendApp(DiagnosticDestination("legacy01","https://legacy.example","https://voicestudio.sh",config),"{}".toByteArray(),"VoiceStudio/0.5.9-beta.3 (android; arm64)") {true}
|
||||
assertEquals(202,reply.status);val request=server.takeRequest()
|
||||
assertEquals("/api/public/v1/app-events",request.path);assertEquals(config.ingestKey,request.getHeader("X-Supermetry-Key"));assertNull(request.getHeader("Origin"));assertEquals("VoiceStudio/0.5.9-beta.3 (android; arm64)",request.getHeader("User-Agent"))
|
||||
}finally {transport.cancelAll();server.shutdown()}
|
||||
}
|
||||
}
|
||||
+44
-1
@@ -238,6 +238,45 @@ class DiagnosticReportsTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun unreadRevocationPreservesGrantAndOutboxUntilItsBoundedReread()=runTest {
|
||||
val store=Store();val dispatcher=StandardTestDispatcher(testScheduler);val clock=ScheduledClock(testScheduler)
|
||||
val first=makeReporter(store,Transport(),clock,dispatcher)
|
||||
first.setConsent(true);first.capture(event());runCurrent();first.close()
|
||||
val saved=store.files.getValue("outbox.json").clone();val grant=store.files.getValue("consent.json").clone()
|
||||
val original=store.json("outbox.json").jsonArray.single().jsonObject
|
||||
store.unreadableRevocation=true
|
||||
val transport=Transport().apply {code=201};val next=makeReporter(store,transport,clock,dispatcher)
|
||||
try {
|
||||
try {next.load()}catch(_:IOException){}
|
||||
assertFalse(next.status.enabled);assertFalse(next.capture(event()))
|
||||
assertArrayEquals("An unknown marker is not withdrawal",saved,store.files["outbox.json"])
|
||||
assertArrayEquals(grant,store.files["consent.json"]);assertFalse(store.files.containsKey("revoked.json"));assertTrue(transport.bodies.isEmpty())
|
||||
store.unreadableRevocation=false;advanceTimeBy(59999);runCurrent();assertTrue(transport.bodies.isEmpty())
|
||||
advanceTimeBy(1);runCurrent();assertEquals(1,transport.bodies.size)
|
||||
assertEquals(original["id"],transport.bodies.single()["id"]);assertArrayEquals(grant,store.files["consent.json"]);assertTrue(next.status.enabled)
|
||||
}finally{store.unreadableRevocation=false;next.close()}
|
||||
}
|
||||
@Test fun bootstrapHardKillCleanupRetriesWithoutReporterAndHonorsCancellation()=runTest {
|
||||
for(cancel in listOf(false,true)) {
|
||||
val store=Store();val dispatcher=StandardTestDispatcher(testScheduler);val clock=ScheduledClock(testScheduler)
|
||||
val first=makeReporter(store,Transport(),clock,dispatcher)
|
||||
first.setConsent(true);first.close()
|
||||
store.blockedWrites.addAll(listOf("consent.json","revoked.json"));store.blockedRemoves.add("consent.json")
|
||||
assertFalse(DiagnosticReports.revokeStoredConsent(File("unused"),store))
|
||||
val attempts=store.revocationWriteAttempts
|
||||
val results=mutableListOf<Boolean>()
|
||||
val retry=launch {DiagnosticReports.retryStoredRevocation(File("unused"),store,clock) {results.add(it)}}
|
||||
runCurrent();advanceTimeBy(59999);runCurrent();assertEquals(attempts,store.revocationWriteAttempts)
|
||||
store.blockedWrites.clear();store.blockedRemoves.clear()
|
||||
if(cancel)retry.cancel()
|
||||
advanceTimeBy(1);runCurrent();retry.join()
|
||||
if(cancel) {assertTrue(results.isEmpty());assertEquals(attempts,store.revocationWriteAttempts)}
|
||||
else {
|
||||
assertEquals(listOf(true),results);assertTrue(store.files.containsKey("revoked.json"))
|
||||
val next=makeReporter(store,Transport(),clock,dispatcher);next.load();assertFalse(next.status.enabled);assertFalse(next.capture(event()));next.close()
|
||||
}
|
||||
}
|
||||
}
|
||||
@Test fun unreadConsentPreservesReportsAndSchedulesSameGrantRecovery()=runTest {
|
||||
val store=Store();val dispatcher=StandardTestDispatcher(testScheduler);val clock=ScheduledClock(testScheduler)
|
||||
val first=makeReporter(store,Transport(),clock,dispatcher)
|
||||
@@ -645,7 +684,11 @@ class DiagnosticReportsTest {
|
||||
val first=makeReporter(store,Transport(),clock,dispatcher);first.setConsent(true);first.close()
|
||||
store.files["revoked.json"]="{corrupt".toByteArray();store.unreadableRevocation=unreadable
|
||||
val transport=Transport().also{it.code=201};val reporter=makeReporter(store,transport,clock,dispatcher)
|
||||
try{reporter.load();assertFalse(reporter.status.enabled);assertFalse(reporter.capture(event()));runCurrent();assertTrue(transport.bodies.isEmpty())}
|
||||
try{
|
||||
if(unreadable) {try{reporter.load();fail("Unread permission must remain a retryable IO failure")}catch(_:IOException){}}
|
||||
else reporter.load()
|
||||
assertFalse(reporter.status.enabled);assertFalse(reporter.capture(event()));runCurrent();assertTrue(transport.bodies.isEmpty())
|
||||
}
|
||||
finally{store.unreadableRevocation=false;reporter.close()}
|
||||
}
|
||||
}
|
||||
|
||||
+24
-2
@@ -317,8 +317,30 @@ All tabs work without pairing once on-device models are installed (see M2); the
|
||||
offline/paired functionality. The application owns consent and delivery, not
|
||||
a screen or ViewModel; OS-owned download jobs can report terminal failures.
|
||||
Failures are projected immediately to `config/diagnostics.json`'s closed
|
||||
technical metadata and sent as `diagnostic_report` to the public Supermetry
|
||||
destination bundled from `config/analytics.json`. HTTPS is required except
|
||||
technical metadata. With valid build/runtime `SUPERMETRY_APP_ID` and
|
||||
`SUPERMETRY_INGEST_KEY` configuration, the native owners map that same closed
|
||||
projection to `/api/public/v1/app-events` (batches of at most 20 events and
|
||||
16 KiB). Generated `supermetry-app.generated.json` is optional; runtime values
|
||||
override individual fields, and an invalid selected credential disables app
|
||||
intake. `SUPERMETRY_APP_HOST` selects its HTTPS base; a missing or invalid host
|
||||
falls back to the analytics host. Otherwise the existing `diagnostic_report`
|
||||
`/api/public/v1/events` request is unchanged. App-intake credentials remain
|
||||
transport configuration and never enter stored reports or event metadata.
|
||||
The mapper emits fixed kinds/levels, normalized platform/architecture,
|
||||
release/build and allowlisted tags in canonical order; it copies no arbitrary
|
||||
properties. A valid 202 response completes accepted and terminal-drop indices,
|
||||
retains rate-limited indices, and never clears unspecified/ambiguous records.
|
||||
400 drops the batch, 401 pauses delivery for the run without deleting its
|
||||
queue, and network/429/5xx retries keep IDs and original times. Fixed local
|
||||
delivery outcomes and tag warnings are not sent back as diagnostics.
|
||||
Optional generated `diagnostics.sessionPings` defaults to false. If explicitly
|
||||
enabled, diagnostic consent permits one session ping per application run;
|
||||
only failures created in that same run/grant may share its session ID.
|
||||
Correlation is bounded in memory, never added to the closed stored schema,
|
||||
and never applied to restored failures. Withdrawal ends that run's session
|
||||
correlation; a later grant in the same process creates neither another ping
|
||||
nor a new link to earlier failures. Product analytics is unchanged.
|
||||
HTTPS is required except
|
||||
literal localhost/127.0.0.1/::1 HTTP test collectors. No audio, text, filenames,
|
||||
URLs, user/account names, credentials, logs, exception messages, raw stacks or
|
||||
manual content-report bodies are included. Only known app source locations
|
||||
|
||||
@@ -16,6 +16,7 @@ import VoiceStudioKit
|
||||
@ObservationIgnored private var reporter: DiagnosticReports?
|
||||
@ObservationIgnored private var subscriber: AppDiagnosticSubscriber?
|
||||
@ObservationIgnored private var statusTask: Task<Void, Never>?
|
||||
@ObservationIgnored private var hardKillCleanupTask: Task<Void, Never>?
|
||||
@ObservationIgnored private var started = false
|
||||
@ObservationIgnored private let disabled: Bool
|
||||
@ObservationIgnored private let injectedFixture: Bool
|
||||
@@ -26,7 +27,7 @@ import VoiceStudioKit
|
||||
self.disabled = disabled; self.reporter = reporter; self.injectedFixture = reporter != nil
|
||||
if disabled { ready = true; prompted = true }
|
||||
}
|
||||
deinit { statusTask?.cancel() }
|
||||
deinit { statusTask?.cancel(); hardKillCleanupTask?.cancel() }
|
||||
private var environmentKilled: Bool { !injectedFixture && Self.environmentDisabled() }
|
||||
var needsChoice: Bool { ready && available && !prompted }
|
||||
func load() async {
|
||||
@@ -63,6 +64,7 @@ import VoiceStudioKit
|
||||
else { await setConsent(lastChoice) }
|
||||
}
|
||||
private func revokeForHardKill() async {
|
||||
hardKillCleanupTask?.cancel(); hardKillCleanupTask = nil
|
||||
saving = true; defer { saving = false }
|
||||
enabled = false; available = false; prompted = true; ready = true
|
||||
lastChoice = false; observationRevision += 1; updateSubscription()
|
||||
@@ -71,8 +73,16 @@ import VoiceStudioKit
|
||||
if let directory = Self.ownedDirectory() {
|
||||
let success = await DiagnosticReports.revokeStoredConsent(directory: directory)
|
||||
errorKey = success ? nil : "diagnostics.save_failed"
|
||||
if !success {
|
||||
hardKillCleanupTask = Task { [weak self] in
|
||||
await DiagnosticReports.retryStoredRevocation(directory: directory) { [weak self] success in
|
||||
await self?.hardKillCleanupFinished(success)
|
||||
}
|
||||
}
|
||||
}
|
||||
} else { errorKey = "diagnostics.save_failed" }
|
||||
}
|
||||
private func hardKillCleanupFinished(_ success: Bool) { errorKey = success ? nil : "diagnostics.save_failed" }
|
||||
func flush() async { guard let reporter, !disabled else { return }; await reporter.flush(); refresh(); updateSubscription() }
|
||||
private func observeStatus(_ reporter: DiagnosticReports) {
|
||||
guard statusTask == nil else { return }
|
||||
@@ -177,7 +187,8 @@ import VoiceStudioKit
|
||||
let configuredSite = getenv("SUPERMETRY_SITE_ID").map { String(cString: $0) } ?? site
|
||||
let configuredHost = getenv("SUPERMETRY_HOST").map { String(cString: $0) } ?? host
|
||||
let configuredApp = getenv("SUPERMETRY_APP_URL").map { String(cString: $0) } ?? appURL
|
||||
let reporter = try DiagnosticReports(directory: directory, policy: DiagnosticPolicy(data: policyData), destination: DiagnosticDestination(site: configuredSite, host: configuredHost, appUrl: configuredApp), appVersion: version, arch: arch)
|
||||
let appConfig = DiagnosticAppConfiguration.resolve(generated: bundle.url(forResource: "supermetry-app.generated", withExtension: "json", subdirectory: "Catalogs").flatMap { try? Data(contentsOf: $0) }, environment: ProcessInfo.processInfo.environment, fallbackHost: host)
|
||||
let reporter = try DiagnosticReports(directory: directory, policy: DiagnosticPolicy(data: policyData), destination: DiagnosticDestination(site: configuredSite, host: configuredHost, appUrl: configuredApp, app: appConfig), appVersion: version, arch: arch)
|
||||
return (reporter, stallMs)
|
||||
} catch { return nil } // Corrupt/missing policy is unavailable, never implicit consent.
|
||||
}
|
||||
|
||||
+127
@@ -0,0 +1,127 @@
|
||||
import Foundation
|
||||
import CoreFoundation
|
||||
|
||||
/// Build configuration only. Credentials are never part of a stored report.
|
||||
public struct DiagnosticAppConfiguration: Sendable {
|
||||
public let appID: String
|
||||
let ingestKey: String
|
||||
public let host: String
|
||||
public let sessionPings: Bool
|
||||
public init(appID: String, ingestKey: String, host: String, sessionPings: Bool = false) throws {
|
||||
let appID = appID.trimmingCharacters(in: .whitespacesAndNewlines), ingestKey = ingestKey.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
guard diagnosticMatches(appID, "[a-z0-9]{6,32}"), diagnosticMatches(ingestKey, "smk_[a-z2-7]{39}") else { throw DiagnosticFailure.invalidDestination }
|
||||
_ = try DiagnosticDestination(site: appID, host: host, appUrl: "https://voicestudio.sh")
|
||||
self.appID = appID; self.ingestKey = ingestKey; self.host = host; self.sessionPings = sessionPings
|
||||
}
|
||||
public static func resolve(generated: Data?, environment: [String: String], fallbackHost: String) -> Self? {
|
||||
let raw = generated.flatMap { try? JSONSerialization.jsonObject(with: $0) as? [String: Any] } ?? [:]
|
||||
let appID = environment["SUPERMETRY_APP_ID"] ?? raw["app_id"] as? String ?? ""
|
||||
let key = environment["SUPERMETRY_INGEST_KEY"] ?? raw["ingest_key"] as? String ?? ""
|
||||
let selectedHost = environment["SUPERMETRY_APP_HOST"] ?? raw["host"] as? String ?? fallbackHost
|
||||
let validHost = (try? DiagnosticDestination(site: "native01", host: selectedHost, appUrl: "https://voicestudio.sh")) != nil
|
||||
let sessionFlag = (raw["diagnostics"] as? [String: Any])?["sessionPings"] as? NSNumber
|
||||
let sessionPings = sessionFlag.map { CFGetTypeID($0) == CFBooleanGetTypeID() && $0.boolValue } ?? false
|
||||
return try? Self(appID: appID, ingestKey: key, host: validHost ? selectedHost : fallbackHost,
|
||||
sessionPings: sessionPings)
|
||||
}
|
||||
}
|
||||
|
||||
public struct DiagnosticTransportReply: Sendable {
|
||||
public let status: Int
|
||||
public let body: Data
|
||||
public init(status: Int, body: Data = Data()) { self.status = status; self.body = body }
|
||||
}
|
||||
public struct DiagnosticDeliveryResult: Sendable {
|
||||
public let id: String
|
||||
public let status: Int
|
||||
public let reason: String
|
||||
public let warningTag: String?
|
||||
}
|
||||
private let diagnosticAppTagOrder = ["category", "source", "stage", "error_code", "engine_id", "uptime_bucket", "elapsed_bucket", "memory_bucket", "disk_bucket", "schema_version"]
|
||||
|
||||
/// This projection accepts already-sanitized closed properties, never an Error.
|
||||
func diagnosticAppEvent(_ props: [String: DiagnosticValue], id: String, timestamp: Int64,
|
||||
installID: String, sessionID: String? = nil, session: Bool = false) throws -> Data {
|
||||
func scalar(_ value: DiagnosticValue) -> Any {
|
||||
switch value { case .string(let s): return s; case .integer(let n): return n }
|
||||
}
|
||||
func bounded(_ key: String, _ cap: Int) -> String? { props[key]?.string.flatMap { $0.isEmpty || $0.utf8.count > cap ? nil : $0 } }
|
||||
let category = props["category"]?.string ?? "other"
|
||||
let crash = ["app_crash", "backend_crash", "renderer_crash"].contains(category)
|
||||
let operations = ["generation_failed", "model_load_failed", "engine_failed", "download_failed", "operation_failed"]
|
||||
let kind = crash ? "crash" : (["install_failed", "install_stalled", "incompatibility"].contains(category) ? category : (operations.contains(category) ? "operation_failed" : "error"))
|
||||
let platforms = ["darwin": "macos", "mac": "macos", "osx": "macos", "win32": "windows", "win": "windows"]
|
||||
let arches = ["x64": "x64", "amd64": "x64", "x86_64": "x64", "arm64": "arm64", "aarch64": "arm64", "ia32": "x86", "x86": "x86", "arm": "arm", "armv7l": "arm"]
|
||||
let platform = props["platform"]?.string ?? "other"
|
||||
var event: [String: Any] = ["id": id, "ts": timestamp, "install_id": installID, "runtime": "swift",
|
||||
"kind": session ? "session" : kind,
|
||||
"platform": platforms[platform] ?? (["windows", "macos", "linux", "ios", "android", "web"].contains(platform) ? platform : "other"),
|
||||
"arch": arches[props["arch"]?.string ?? ""] ?? "other"]
|
||||
if let sessionID { event["session_id"] = sessionID }
|
||||
if let release = bounded("app_version", 64) { event["release"] = release }
|
||||
if !session {
|
||||
event["level"] = crash ? "fatal" : "error"; event["handled"] = !crash
|
||||
for (source, target, cap) in [("build_commit", "build", 64), ("device_family", "device_class", 32), ("reason", "exit_reason", 32), ("error_type", "error_type", 64)] {
|
||||
if let value = bounded(source, cap) { event[target] = value }
|
||||
}
|
||||
for key in ["exit_code", "frames", "fingerprint", "occurrences"] { if let value = props[key] { event[key] = scalar(value) } }
|
||||
if let signal = bounded("signal", 32) { event["signal"] = signal }
|
||||
}
|
||||
var data = try JSONSerialization.data(withJSONObject: event, options: [.sortedKeys, .withoutEscapingSlashes])
|
||||
if !session {
|
||||
// Dictionaries/JSONEncoder do not guarantee this insertion order. Build
|
||||
// only the closed scalar tag object in the owner's canonical order.
|
||||
data.removeLast(); data.append(Data(",\"tags\":{".utf8))
|
||||
var separator = ""
|
||||
for key in diagnosticAppTagOrder {
|
||||
guard let value = props[key], value.string != "", (value.string?.utf8.count ?? 0) <= 200 else { continue }
|
||||
data.append(Data("\(separator)\"\(key)\":".utf8))
|
||||
data.append(try JSONSerialization.data(withJSONObject: scalar(value), options: [.fragmentsAllowed, .withoutEscapingSlashes]))
|
||||
separator = ","
|
||||
}
|
||||
data.append(Data("}}".utf8))
|
||||
}
|
||||
return data
|
||||
}
|
||||
|
||||
func diagnosticAppBody(site: String, events: [Data]) throws -> Data {
|
||||
var body = Data("{\"site\":".utf8)
|
||||
body.append(try JSONSerialization.data(withJSONObject: site, options: [.fragmentsAllowed]))
|
||||
body.append(Data(",\"events\":[".utf8))
|
||||
for (index, event) in events.enumerated() { if index > 0 { body.append(44) }; body.append(event) }
|
||||
body.append(Data("]}".utf8)); return body
|
||||
}
|
||||
|
||||
/// Unspecified/ambiguous acknowledgements never delete a record.
|
||||
func diagnosticAppCompleted(_ reply: DiagnosticTransportReply, count: Int) -> Set<Int> {
|
||||
diagnosticAppAcknowledgement(reply, count: count)?.completed ?? []
|
||||
}
|
||||
struct DiagnosticAppAcknowledgement {
|
||||
let completed: Set<Int>
|
||||
let reasons: [Int: String]
|
||||
let warnings: [(index: Int, tag: String)]
|
||||
}
|
||||
func diagnosticAppAcknowledgement(_ reply: DiagnosticTransportReply, count: Int) -> DiagnosticAppAcknowledgement? {
|
||||
if reply.status == 400 { return DiagnosticAppAcknowledgement(completed: Set(0..<count), reasons: Dictionary(uniqueKeysWithValues: (0..<count).map { ($0, "invalid") }), warnings: []) }
|
||||
func integer(_ raw: Any?) -> Int? {
|
||||
guard let number = raw as? NSNumber, CFGetTypeID(number) != CFBooleanGetTypeID(), number.doubleValue == Double(number.intValue) else { return nil }
|
||||
return number.intValue
|
||||
}
|
||||
guard reply.status == 202, let raw = try? JSONSerialization.jsonObject(with: reply.body) as? [String: Any],
|
||||
let accepted = integer(raw["accepted"]), accepted >= 0, accepted <= count,
|
||||
let dropped = raw["dropped"] as? [[String: Any]], dropped.count <= count else { return nil }
|
||||
var indices = Set<Int>(), terminal = Set<Int>(), reasons: [Int: String] = [:]
|
||||
for drop in dropped {
|
||||
guard let index = integer(drop["index"]), (0..<count).contains(index), indices.insert(index).inserted,
|
||||
let reason = drop["reason"] as? String, ["too_old", "invalid", "duplicate", "rate_limited"].contains(reason) else { return nil }
|
||||
reasons[index] = reason
|
||||
if reason != "rate_limited" { terminal.insert(index) }
|
||||
}
|
||||
guard accepted + indices.count == count else { return nil }
|
||||
for index in Set(0..<count).subtracting(indices) { reasons[index] = "accepted" }
|
||||
let warnings = (raw["warnings"] as? [[String: Any]] ?? []).prefix(20).compactMap { warning -> (index: Int, tag: String)? in
|
||||
guard let index = integer(warning["index"]), (0..<count).contains(index), warning["reason"] as? String == "tag_not_allowed", let tag = warning["tag"] as? String, diagnosticAppTagOrder.contains(tag) else { return nil }
|
||||
return (index, tag)
|
||||
}
|
||||
return DiagnosticAppAcknowledgement(completed: Set(0..<count).subtracting(indices).union(terminal), reasons: reasons, warnings: warnings)
|
||||
}
|
||||
+142
-14
@@ -12,9 +12,9 @@ private struct DiagnosticRevocation {
|
||||
let failed: Bool
|
||||
let prompted: Bool
|
||||
}
|
||||
private func diagnosticRevocationPresent(_ storage: any DiagnosticStorage) -> Bool {
|
||||
private func diagnosticRevocationPresent(_ storage: any DiagnosticStorage) throws -> Bool {
|
||||
do { return try storage.read("revoked.json", maxBytes: 4096) != nil }
|
||||
catch { return true }
|
||||
catch DiagnosticFailure.corruptStore { return true }
|
||||
}
|
||||
// Runs only on the owned worker or detached bootstrap task, never capture.
|
||||
private func diagnosticRevokeGrant(_ storage: any DiagnosticStorage, hadGrant hint: Bool? = nil, recordChoice: Bool = false) -> DiagnosticRevocation {
|
||||
@@ -25,7 +25,7 @@ private func diagnosticRevokeGrant(_ storage: any DiagnosticStorage, hadGrant hi
|
||||
catch { hadGrant = true }
|
||||
}
|
||||
var failed = false
|
||||
let prompted = hadGrant || recordChoice || diagnosticRevocationPresent(storage)
|
||||
let prompted = hadGrant || recordChoice || ((try? diagnosticRevocationPresent(storage)) ?? true)
|
||||
if prompted {
|
||||
// This independent anonymous file still revokes a locked old grant.
|
||||
do { try storage.write("revoked.json", data: Data("{\"version\":1}".utf8)) } catch { failed = true }
|
||||
@@ -52,6 +52,7 @@ private struct DiagnosticPending: Sendable {
|
||||
let id: String?
|
||||
let timestamp: Int64
|
||||
}
|
||||
enum DiagnosticWorkerObservation: Sendable { case flushJoined }
|
||||
/// This lock never encloses disk, network, actor waits or exception inspection.
|
||||
private final class DiagnosticGate: @unchecked Sendable {
|
||||
let lock = NSLock()
|
||||
@@ -122,11 +123,16 @@ public final class DiagnosticReports: @unchecked Sendable {
|
||||
private let transport: any DiagnosticTransport
|
||||
private let projector: DiagnosticProjector
|
||||
private let clock: any DiagnosticClock
|
||||
public init(directory: URL, policy: DiagnosticPolicy, destination: DiagnosticDestination, appVersion: String, buildCommit: String? = nil, arch: String = "unknown", transport: any DiagnosticTransport = URLSessionDiagnosticTransport(), clock: any DiagnosticClock = SystemDiagnosticClock(), storage: (any DiagnosticStorage)? = nil, disabled: (@Sendable () -> Bool)? = nil) {
|
||||
public convenience init(directory: URL, policy: DiagnosticPolicy, destination: DiagnosticDestination, appVersion: String, buildCommit: String? = nil, arch: String = "unknown", transport: any DiagnosticTransport = URLSessionDiagnosticTransport(), clock: any DiagnosticClock = SystemDiagnosticClock(), storage: (any DiagnosticStorage)? = nil, disabled: (@Sendable () -> Bool)? = nil, onDeliveryResult: @escaping @Sendable (DiagnosticDeliveryResult) -> Void = { _ in }) {
|
||||
self.init(directory: directory, policy: policy, destination: destination, appVersion: appVersion, buildCommit: buildCommit, arch: arch, transport: transport, clock: clock, storage: storage, disabled: disabled, onDeliveryResult: onDeliveryResult, observation: nil)
|
||||
}
|
||||
// Internal lifecycle observations make actor boundaries inspectable without
|
||||
// changing public reporting controls, payloads or adding IO to capture.
|
||||
init(directory: URL, policy: DiagnosticPolicy, destination: DiagnosticDestination, appVersion: String, buildCommit: String? = nil, arch: String = "unknown", transport: any DiagnosticTransport = URLSessionDiagnosticTransport(), clock: any DiagnosticClock = SystemDiagnosticClock(), storage: (any DiagnosticStorage)? = nil, disabled: (@Sendable () -> Bool)? = nil, onDeliveryResult: @escaping @Sendable (DiagnosticDeliveryResult) -> Void = { _ in }, observation: (@Sendable (DiagnosticWorkerObservation) -> Void)?) {
|
||||
self.transport = transport; self.clock = clock
|
||||
let gate = DiagnosticGate(disabled: disabled ?? { diagnosticKillSwitch(getenv("OMNIVOICE_DIAGNOSTICS_DISABLED").map { String(cString: $0) }) || diagnosticKillSwitch(getenv("OMNIVOICE_ANALYTICS_DISABLED").map { String(cString: $0) }) }); self.gate = gate
|
||||
let projector = DiagnosticProjector(policy: policy, appVersion: appVersion, buildCommit: buildCommit, arch: arch); self.projector = projector
|
||||
worker = DiagnosticWorker(gate: gate, projector: projector, destination: destination, transport: transport, clock: clock, storage: storage ?? FileDiagnosticStorage(directory: directory))
|
||||
worker = DiagnosticWorker(gate: gate, projector: projector, destination: destination, transport: transport, clock: clock, storage: storage ?? FileDiagnosticStorage(directory: directory), onDeliveryResult: onDeliveryResult, observation: observation)
|
||||
}
|
||||
/// Bootstrap hard-kill cleanup does not require valid destination/policy
|
||||
/// resources. Live reporters must invalidate their gate before this helper.
|
||||
@@ -134,6 +140,20 @@ public final class DiagnosticReports: @unchecked Sendable {
|
||||
let owned = storage ?? FileDiagnosticStorage(directory: directory)
|
||||
return await Task.detached(priority: .utility) { !diagnosticRevokeGrant(owned).failed }.value
|
||||
}
|
||||
/// A failed bootstrap withdrawal still owns cleanup when resource parsing
|
||||
/// cannot create a reporter. The app owns/cancels this task; no networking.
|
||||
public static func retryStoredRevocation(directory: URL, storage: (any DiagnosticStorage)? = nil,
|
||||
clock: any DiagnosticClock = SystemDiagnosticClock(),
|
||||
onAttempt: @escaping @Sendable (Bool) async -> Void) async {
|
||||
while !Task.isCancelled {
|
||||
do { try await clock.sleep(milliseconds: 60000) } catch { return }
|
||||
guard !Task.isCancelled else { return }
|
||||
let success = await revokeStoredConsent(directory: directory, storage: storage)
|
||||
guard !Task.isCancelled else { return }
|
||||
await onAttempt(success)
|
||||
if success { return }
|
||||
}
|
||||
}
|
||||
public var status: DiagnosticStatus { gate.status() }
|
||||
/// Coalesced local consent/readiness signal. Read current status rather than
|
||||
/// retaining a queued permission snapshot across a newer OFF or grant.
|
||||
@@ -221,6 +241,8 @@ private actor DiagnosticWorker {
|
||||
let transport: any DiagnosticTransport
|
||||
let clock: any DiagnosticClock
|
||||
let storage: any DiagnosticStorage
|
||||
let onDeliveryResult: @Sendable (DiagnosticDeliveryResult) -> Void
|
||||
let observation: (@Sendable (DiagnosticWorkerObservation) -> Void)?
|
||||
var records: [DiagnosticRecord] = []
|
||||
var sending = false
|
||||
var retryAt: [String: Int64] = [:]
|
||||
@@ -232,15 +254,26 @@ private actor DiagnosticWorker {
|
||||
var consentReadRetryAt: Int64?
|
||||
var revocationWake: (id: UUID, generation: UInt64, deadline: Int64, task: Task<Void, Never>)?
|
||||
var waiters: [CheckedContinuation<Void, Never>] = []
|
||||
init(gate: DiagnosticGate, projector: DiagnosticProjector, destination: DiagnosticDestination, transport: any DiagnosticTransport, clock: any DiagnosticClock, storage: any DiagnosticStorage) {
|
||||
var appPaused = false
|
||||
let sessionID = diagnosticID()
|
||||
var sessionStarted = false
|
||||
var sessionInvalidated = false
|
||||
var sessionEpoch: String?
|
||||
var sessionEvent: (id: String, stamp: Int64)?
|
||||
var sessionRetryAt: Int64?
|
||||
var currentRunIDs = Set<String>()
|
||||
init(gate: DiagnosticGate, projector: DiagnosticProjector, destination: DiagnosticDestination, transport: any DiagnosticTransport, clock: any DiagnosticClock, storage: any DiagnosticStorage, onDeliveryResult: @escaping @Sendable (DiagnosticDeliveryResult) -> Void, observation: (@Sendable (DiagnosticWorkerObservation) -> Void)?) {
|
||||
self.gate = gate; self.projector = projector; self.destination = destination; self.transport = transport; self.clock = clock; self.storage = storage
|
||||
self.onDeliveryResult = onDeliveryResult
|
||||
self.observation = observation
|
||||
}
|
||||
func load() {
|
||||
defer { gate.publishStatusChange() }
|
||||
let state = gate.lock.withLock { (gate.closed, gate.loaded) }
|
||||
guard !state.0 else { return }
|
||||
let revoked = diagnosticRevocationPresent(storage)
|
||||
guard !state.1 || gate.disabled() || revoked else { return }
|
||||
let marker = try? diagnosticRevocationPresent(storage)
|
||||
let revoked = marker == true
|
||||
guard !state.1 || gate.disabled() || revoked || marker == nil else { return }
|
||||
if let deadline = consentReadRetryAt, deadline > clock.nowMs(), !gate.disabled(), !revoked { return }
|
||||
cancelRetryWake()
|
||||
cancelRevocationWake()
|
||||
@@ -249,7 +282,7 @@ private actor DiagnosticWorker {
|
||||
let generation = gate.lock.withLock { gate.generation }
|
||||
var hadGrant = gate.lock.withLock { gate.consent != nil }
|
||||
var consent: DiagnosticConsent?
|
||||
var unread = false
|
||||
var unread = marker == nil
|
||||
do {
|
||||
if let data = try storage.read("consent.json", maxBytes: 4096) {
|
||||
hadGrant = true
|
||||
@@ -306,6 +339,7 @@ private actor DiagnosticWorker {
|
||||
}
|
||||
func setConsent(_ enabled: Bool, generation: UInt64) throws {
|
||||
guard gate.lock.withLock({ !gate.closed && gate.generation == generation }) else { return }
|
||||
if !enabled || sessionStarted { sessionInvalidated = true; sessionEvent = nil; sessionEpoch = nil; currentRunIDs.removeAll() }
|
||||
cancelRetryWake()
|
||||
cancelRevocationWake()
|
||||
revocationPending = false
|
||||
@@ -335,6 +369,7 @@ private actor DiagnosticWorker {
|
||||
@discardableResult private func performRevocation(generation: UInt64, recordChoice: Bool, hadGrant: Bool? = nil) -> Bool {
|
||||
guard gate.controlCurrent(generation) else { return false }
|
||||
consentReadRetryAt = nil
|
||||
sessionInvalidated = true; sessionEvent = nil; sessionEpoch = nil; currentRunIDs.removeAll()
|
||||
cancelRetryWake(); storageRetryAt = nil; outboxLoaded = true
|
||||
records.removeAll(); retryAt.removeAll()
|
||||
gate.lock.withLock { gate.pending.removeAll() }
|
||||
@@ -380,7 +415,15 @@ private actor DiagnosticWorker {
|
||||
}
|
||||
private func deliveryAllowed(_ consent: DiagnosticConsent, generation: UInt64) -> Bool {
|
||||
guard gate.allowed(consent.epoch, generation) else { return false }
|
||||
if diagnosticRevocationPresent(storage) {
|
||||
let revoked: Bool
|
||||
do { revoked = try diagnosticRevocationPresent(storage) }
|
||||
catch {
|
||||
gate.lock.withLock { if gate.generation == generation { gate.loaded = false; gate.state.enabled = false; gate.state.optedIn = false } }
|
||||
transport.cancelAll(); consentReadRetryAt = clock.nowMs() + 60000
|
||||
scheduleRevocationWake(generation: generation); gate.publishStatusChange()
|
||||
return false
|
||||
}
|
||||
if revoked {
|
||||
if let next = gate.revokeIfCurrent(consent.epoch, generation) {
|
||||
transport.cancelAll()
|
||||
_ = performRevocation(generation: next, recordChoice: true, hadGrant: true)
|
||||
@@ -430,12 +473,18 @@ private actor DiagnosticWorker {
|
||||
continue
|
||||
}
|
||||
var candidate = records
|
||||
var currentIdentity: String?
|
||||
if pending.id == nil, let index = records.firstIndex(where: { $0.props["fingerprint"] == pending.props["fingerprint"] && abs(pending.timestamp - $0.timestamp_ms) <= Int64(projector.policy.limit("dedupe_ms", 60000)) }) {
|
||||
candidate[index].props["occurrences"] = .integer(min((candidate[index].props["occurrences"]?.integer ?? 1) + 1, 1_000_000))
|
||||
} else if records.count < projector.policy.limit("queue_count", 64) {
|
||||
candidate.append(DiagnosticRecord(version: 1, id: pending.id ?? diagnosticID(), timestamp_ms: pending.timestamp, epoch: epoch, props: pending.props))
|
||||
let identity = pending.id ?? diagnosticID()
|
||||
candidate.append(DiagnosticRecord(version: 1, id: identity, timestamp_ms: pending.timestamp, epoch: epoch, props: pending.props))
|
||||
if pending.id == nil { currentIdentity = identity }
|
||||
} else { gate.drop(); continue }
|
||||
if try diagnosticEncode(candidate).count <= projector.policy.limit("queue_bytes", 524288) { records = candidate } else { gate.drop() }
|
||||
if try diagnosticEncode(candidate).count <= projector.policy.limit("queue_bytes", 524288) {
|
||||
records = candidate
|
||||
if let identity = currentIdentity, destination.app?.sessionPings == true, !sessionInvalidated { currentRunIDs.insert(identity) }
|
||||
} else { gate.drop() }
|
||||
}
|
||||
gate.count(records.count)
|
||||
}
|
||||
@@ -445,7 +494,10 @@ private actor DiagnosticWorker {
|
||||
}
|
||||
private func scheduleRetryWake(epoch: String, generation: UInt64) {
|
||||
guard gate.allowed(epoch, generation) else { return }
|
||||
guard let deadline = storageRetryAt ?? records.compactMap({ retryAt[$0.id] }).min() else { cancelRetryWake(); return }
|
||||
// A 401 pauses the network for this run, not publication of newly
|
||||
// accepted reports after a transient storage failure.
|
||||
let deliveryDeadline = appPaused ? nil : (records.compactMap({ retryAt[$0.id] }) + [sessionRetryAt].compactMap { $0 }).min()
|
||||
guard let deadline = storageRetryAt ?? deliveryDeadline else { cancelRetryWake(); return }
|
||||
if let wake = retryWake, wake.epoch == epoch, wake.generation == generation, wake.deadline == deadline { return }
|
||||
cancelRetryWake()
|
||||
let id = UUID(), clock = self.clock, gate = self.gate
|
||||
@@ -469,7 +521,7 @@ private actor DiagnosticWorker {
|
||||
guard let (consent, generation) = expected ?? gate.snapshot(), gate.allowed(consent.epoch, generation) else { return }
|
||||
if sending {
|
||||
let pendingAtJoin = gate.lock.withLock { gate.pending.contains { $0.epoch == consent.epoch } }
|
||||
await withCheckedContinuation { waiters.append($0) }
|
||||
await withCheckedContinuation { waiters.append($0); observation?(.flushJoined) }
|
||||
// Joining a burst must also service intake accepted before this
|
||||
// call. One follow-up covers that snapshot without chasing later
|
||||
// captures, bypassing storage cooldown or borrowing another grant.
|
||||
@@ -499,6 +551,8 @@ private actor DiagnosticWorker {
|
||||
storageRetryAt = nil
|
||||
let remainingIDs = Set(records.map(\.id))
|
||||
retryAt = retryAt.filter { remainingIDs.contains($0.key) }
|
||||
currentRunIDs.formIntersection(remainingIDs)
|
||||
if destination.app != nil { try await flushApp(consent, generation: generation); return }
|
||||
for record in records {
|
||||
if (retryAt[record.id] ?? 0) > clock.nowMs() { continue }
|
||||
guard deliveryAllowed(consent, generation: generation) else { break }
|
||||
@@ -508,6 +562,7 @@ private actor DiagnosticWorker {
|
||||
var terminal = false
|
||||
for attempt in 0..<projector.policy.limit("max_attempts", 3) {
|
||||
guard deliveryAllowed(consent, generation: generation) else { break }
|
||||
guard sanitized(record, epoch: consent.epoch) != nil else { terminal = true; break }
|
||||
do {
|
||||
let status = try await transport.send(destination: destination, body: body, allowed: { [gate] in gate.allowed(consent.epoch, generation) })
|
||||
terminal = (200...499).contains(status) && status != 429
|
||||
@@ -529,6 +584,79 @@ private actor DiagnosticWorker {
|
||||
if gate.allowed(consent.epoch, generation) { deferStorageRetry() }
|
||||
}
|
||||
}
|
||||
private func flushApp(_ consent: DiagnosticConsent, generation: UInt64) async throws {
|
||||
guard let app = destination.app, !appPaused else { return }
|
||||
if app.sessionPings, !sessionStarted, !sessionInvalidated {
|
||||
sessionStarted = true; sessionEpoch = consent.epoch
|
||||
sessionEvent = (diagnosticID(), clock.nowMs())
|
||||
}
|
||||
struct Item { let id: String; let stamp: Int64; let event: Data; let session: Bool }
|
||||
var candidates: [Item] = []
|
||||
if let ping = sessionEvent, sessionEpoch == consent.epoch, (sessionRetryAt ?? 0) <= clock.nowMs() {
|
||||
let props: [String: DiagnosticValue] = ["app_version": .string(projector.appVersion), "platform": .string("ios"), "arch": .string(projector.arch)]
|
||||
candidates.append(Item(id: ping.id, stamp: ping.stamp, event: try diagnosticAppEvent(props, id: ping.id, timestamp: ping.stamp, installID: consent.profile_id, sessionID: sessionID, session: true), session: true))
|
||||
}
|
||||
for record in records where (retryAt[record.id] ?? 0) <= clock.nowMs() {
|
||||
let correlation = sessionEpoch == consent.epoch && !sessionInvalidated && currentRunIDs.contains(record.id) ? sessionID : nil
|
||||
candidates.append(Item(id: record.id, stamp: record.timestamp_ms, event: try diagnosticAppEvent(projector.sanitize(record.props), id: record.id, timestamp: record.timestamp_ms, installID: consent.profile_id, sessionID: correlation), session: false))
|
||||
}
|
||||
while !candidates.isEmpty, deliveryAllowed(consent, generation: generation), !appPaused {
|
||||
var batch: [Item] = []
|
||||
while let next = candidates.first, batch.count < 20 {
|
||||
let proposed = try diagnosticAppBody(site: app.appID, events: (batch + [next]).map(\.event))
|
||||
if proposed.count > 16384 {
|
||||
if batch.isEmpty { candidates.removeFirst(); records.removeAll { $0.id == next.id }; currentRunIDs.remove(next.id); gate.drop(); try persist() }
|
||||
break
|
||||
}
|
||||
batch.append(candidates.removeFirst())
|
||||
}
|
||||
if batch.isEmpty { continue }
|
||||
for attempt in 0..<projector.policy.limit("max_attempts", 3) {
|
||||
guard deliveryAllowed(consent, generation: generation), !appPaused else { return }
|
||||
let expired = batch.filter { $0.stamp < clock.nowMs() - Int64(projector.policy.limit("ttl_ms", 604800000)) }
|
||||
if !expired.isEmpty {
|
||||
let ids = Set(expired.map(\.id)); records.removeAll { ids.contains($0.id) }; currentRunIDs.subtract(ids)
|
||||
if expired.contains(where: \.session) { sessionEvent = nil; sessionRetryAt = nil }
|
||||
batch.removeAll { ids.contains($0.id) }; try persist()
|
||||
}
|
||||
if batch.isEmpty { break }
|
||||
let body = try diagnosticAppBody(site: app.appID, events: batch.map(\.event))
|
||||
let userAgent = "VoiceStudio/\(projector.appVersion) (ios; \(projector.arch))"
|
||||
let reply = (try? await transport.sendApp(destination: destination, body: body, userAgent: userAgent, allowed: { [gate] in gate.allowed(consent.epoch, generation) })) ?? DiagnosticTransportReply(status: 0)
|
||||
guard gate.allowed(consent.epoch, generation) else { return }
|
||||
if reply.status == 401 {
|
||||
appPaused = true; cancelRetryWake()
|
||||
for item in batch { onDeliveryResult(DiagnosticDeliveryResult(id: item.id, status: 401, reason: "unauthorized", warningTag: nil)) }
|
||||
return
|
||||
}
|
||||
let acknowledgement = diagnosticAppAcknowledgement(reply, count: batch.count)
|
||||
for (index, reason) in acknowledgement?.reasons ?? [:] { onDeliveryResult(DiagnosticDeliveryResult(id: batch[index].id, status: reply.status, reason: reason, warningTag: nil)) }
|
||||
for warning in acknowledgement?.warnings ?? [] { onDeliveryResult(DiagnosticDeliveryResult(id: batch[warning.index].id, status: reply.status, reason: "tag_not_allowed", warningTag: warning.tag)) }
|
||||
let completed = acknowledgement?.completed ?? []
|
||||
let finished = batch.enumerated().filter { completed.contains($0.offset) }.map(\.element)
|
||||
let ids = Set(finished.map(\.id))
|
||||
records.removeAll { ids.contains($0.id) }; currentRunIDs.subtract(ids)
|
||||
for id in ids { retryAt.removeValue(forKey: id) }
|
||||
if finished.contains(where: \.session) { sessionEvent = nil; sessionRetryAt = nil }
|
||||
batch.removeAll { ids.contains($0.id) }
|
||||
if !ids.isEmpty { try persist() }
|
||||
if batch.isEmpty { break }
|
||||
// A well-formed partial acknowledgement may retain rate-limited
|
||||
// records; do not hammer that same response in the current burst.
|
||||
if reply.status == 202 || reply.status == 400 { break }
|
||||
if attempt + 1 < projector.policy.limit("max_attempts", 3) {
|
||||
var remaining = 500 << attempt
|
||||
while remaining > 0, gate.allowed(consent.epoch, generation) {
|
||||
try await clock.sleep(milliseconds: min(remaining, 25)); remaining -= 25
|
||||
}
|
||||
}
|
||||
}
|
||||
for retained in batch {
|
||||
if retained.session { sessionRetryAt = clock.nowMs() + 60000 }
|
||||
else { retryAt[retained.id] = clock.nowMs() + 60000 }
|
||||
}
|
||||
}
|
||||
}
|
||||
func close() {
|
||||
cancelRetryWake()
|
||||
cancelRevocationWake()
|
||||
|
||||
+19
-3
@@ -80,8 +80,14 @@ public struct FileDiagnosticStorage: DiagnosticStorage {
|
||||
}
|
||||
public protocol DiagnosticTransport: Sendable {
|
||||
func send(destination: DiagnosticDestination, body: Data, allowed: @escaping @Sendable () -> Bool) async throws -> Int
|
||||
func sendApp(destination: DiagnosticDestination, body: Data, userAgent: String, allowed: @escaping @Sendable () -> Bool) async throws -> DiagnosticTransportReply
|
||||
func cancelAll()
|
||||
}
|
||||
public extension DiagnosticTransport {
|
||||
func sendApp(destination: DiagnosticDestination, body: Data, userAgent: String, allowed: @escaping @Sendable () -> Bool) async throws -> DiagnosticTransportReply {
|
||||
DiagnosticTransportReply(status: try await send(destination: destination, body: body, allowed: allowed))
|
||||
}
|
||||
}
|
||||
private final class DiagnosticSessionDelegate: NSObject, URLSessionTaskDelegate, Sendable {
|
||||
func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping @Sendable (URLRequest?) -> Void) { completionHandler(nil) }
|
||||
}
|
||||
@@ -97,15 +103,25 @@ public final class URLSessionDiagnosticTransport: DiagnosticTransport, @unchecke
|
||||
session = URLSession(configuration: configuration, delegate: DiagnosticSessionDelegate(), delegateQueue: nil)
|
||||
}
|
||||
public func send(destination: DiagnosticDestination, body: Data, allowed: @escaping @Sendable () -> Bool) async throws -> Int {
|
||||
try await request(destination: destination, body: body, userAgent: nil, allowed: allowed).status
|
||||
}
|
||||
public func sendApp(destination: DiagnosticDestination, body: Data, userAgent: String, allowed: @escaping @Sendable () -> Bool) async throws -> DiagnosticTransportReply {
|
||||
try await request(destination: destination, body: body, userAgent: userAgent, allowed: allowed)
|
||||
}
|
||||
private func request(destination: DiagnosticDestination, body: Data, userAgent: String?, allowed: @escaping @Sendable () -> Bool) async throws -> DiagnosticTransportReply {
|
||||
var request = URLRequest(url: destination.endpoint); request.httpMethod = "POST"; request.httpBody = body
|
||||
request.setValue("application/json", forHTTPHeaderField: "Content-Type"); request.setValue(destination.origin, forHTTPHeaderField: "Origin")
|
||||
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
|
||||
if let app = destination.app {
|
||||
request.setValue(app.ingestKey, forHTTPHeaderField: "X-Supermetry-Key")
|
||||
request.setValue(userAgent, forHTTPHeaderField: "User-Agent")
|
||||
} else { request.setValue(destination.origin, forHTTPHeaderField: "Origin") }
|
||||
let identifier = UUID()
|
||||
return try await withTaskCancellationHandler {
|
||||
try await withCheckedThrowingContinuation { continuation in
|
||||
let task = session.dataTask(with: request) { [weak self] _, response, error in
|
||||
let task = session.dataTask(with: request) { [weak self] data, response, error in
|
||||
_ = self?.lock.withLock { self?.tasks.removeValue(forKey: identifier) }
|
||||
if let error { continuation.resume(throwing: error) }
|
||||
else { continuation.resume(returning: (response as? HTTPURLResponse)?.statusCode ?? 0) }
|
||||
else { continuation.resume(returning: DiagnosticTransportReply(status: (response as? HTTPURLResponse)?.statusCode ?? 0, body: (data?.count ?? 0) <= 16384 ? (data ?? Data()) : Data())) }
|
||||
}
|
||||
lock.withLock {
|
||||
guard allowed(), !Task.isCancelled else { continuation.resume(throwing: DiagnosticFailure.cancelled); return }
|
||||
|
||||
@@ -84,7 +84,19 @@ public struct DiagnosticDestination: Sendable {
|
||||
public let endpoint: URL
|
||||
public let origin: String
|
||||
public let eventURL: String
|
||||
public init(site: String, host: String, appUrl: String) throws {
|
||||
public let app: DiagnosticAppConfiguration?
|
||||
public init(site: String, host: String, appUrl: String, app: DiagnosticAppConfiguration? = nil) throws {
|
||||
self.app = app
|
||||
if let app {
|
||||
// App configuration has its own validated identity/destination;
|
||||
// unused legacy runtime overrides cannot disable this transport.
|
||||
guard var endpoint = URLComponents(string: app.host) else { throw DiagnosticFailure.invalidDestination }
|
||||
endpoint.path = "/api/public/v1/app-events"
|
||||
guard let url = endpoint.url else { throw DiagnosticFailure.invalidDestination }
|
||||
self.site = app.appID; self.endpoint = url
|
||||
self.origin = ""; self.eventURL = ""
|
||||
return
|
||||
}
|
||||
guard diagnosticMatches(site, "[a-z0-9]{6,32}"), let server = URLComponents(string: host), let app = URLComponents(string: appUrl) else { throw DiagnosticFailure.invalidDestination }
|
||||
for item in [server, app] {
|
||||
// HTTP is only for literal loopback fixtures. Inspect the encoded
|
||||
|
||||
+1
-1
@@ -218,7 +218,7 @@ func companionFailureRequiresNewServerEventAndTheSameObservedGrant(_ scenario: S
|
||||
}
|
||||
#endif
|
||||
|
||||
#if canImport(UIKit)
|
||||
#if VS_DIAGNOSTICS_APP_TESTS && canImport(UIKit)
|
||||
/// Holds an existing ModelStore actor operation, so the real native worker must
|
||||
/// await invalidateVerification/release after its body has already failed.
|
||||
private final class PhoneDiagnosticCleanupGate: @unchecked Sendable {
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
import Foundation
|
||||
import Testing
|
||||
@testable import VoiceStudioKit
|
||||
|
||||
private let intakeRoot = URL(fileURLWithPath: #filePath).deletingLastPathComponent().appendingPathComponent("../../../../..").standardizedFileURL
|
||||
private final class AppIntakeStore: DiagnosticStorage, @unchecked Sendable {
|
||||
let lock = NSLock(); var files: [String: Data] = [:]
|
||||
func read(_ name: String, maxBytes: Int) throws -> Data? { try lock.withLock { guard let data = files[name] else { return nil }; guard data.count <= maxBytes else { throw DiagnosticFailure.corruptStore }; return data } }
|
||||
func write(_ name: String, data: Data) { lock.withLock { files[name] = data } }
|
||||
func remove(_ name: String) { _ = lock.withLock { files.removeValue(forKey: name) } }
|
||||
}
|
||||
private final class AppIntakeTransport: DiagnosticTransport, @unchecked Sendable {
|
||||
let lock = NSLock(); var requests: [Data] = []; var replies: [DiagnosticTransportReply] = []; var legacy: [Data] = []
|
||||
func cancelAll() {}
|
||||
func send(destination: DiagnosticDestination, body: Data, allowed: @escaping @Sendable () -> Bool) async throws -> Int { lock.withLock { legacy.append(body) }; return 202 }
|
||||
func sendApp(destination: DiagnosticDestination, body: Data, userAgent: String, allowed: @escaping @Sendable () -> Bool) async throws -> DiagnosticTransportReply {
|
||||
guard allowed() else { throw DiagnosticFailure.cancelled }
|
||||
return lock.withLock {
|
||||
requests.append(body)
|
||||
if !replies.isEmpty { return replies.removeFirst() }
|
||||
let count = ((try? JSONSerialization.jsonObject(with: body) as? [String: Any])?["events"] as? [Any])?.count ?? 0
|
||||
return DiagnosticTransportReply(status: 202, body: Data("{\"accepted\":\(count),\"dropped\":[]}".utf8))
|
||||
}
|
||||
}
|
||||
func bodies() -> [Data] { lock.withLock { requests } }
|
||||
func setReplies(_ value: [DiagnosticTransportReply]) { lock.withLock { replies = value } }
|
||||
}
|
||||
private final class AppIntakeClock: DiagnosticClock, @unchecked Sendable {
|
||||
private let lock = NSLock(); private var value: Int64 = 1_794_640_000_000
|
||||
func nowMs() -> Int64 { lock.withLock { value } }
|
||||
func advance(_ ms: Int64) { lock.withLock { value += ms } }
|
||||
func sleep(milliseconds: Int) async throws {
|
||||
if milliseconds > 25 { try await Task.sleep(for: .seconds(3600)) }
|
||||
else { advance(Int64(milliseconds)); await Task.yield() }
|
||||
}
|
||||
}
|
||||
private final class AppIntakeResults: @unchecked Sendable {
|
||||
private let lock = NSLock(); private var values: [DiagnosticDeliveryResult] = []
|
||||
func append(_ result: DiagnosticDeliveryResult) { lock.withLock { values.append(result) } }
|
||||
func snapshot() -> [DiagnosticDeliveryResult] { lock.withLock { values } }
|
||||
}
|
||||
|
||||
struct DiagnosticAppIntakeTests {
|
||||
private func destination(pings: Bool = false) throws -> DiagnosticDestination {
|
||||
try DiagnosticDestination(site: "legacy01", host: "https://legacy.example", appUrl: "https://voicestudio.sh", app: DiagnosticAppConfiguration(appID: "native01", ingestKey: "smk_" + String(repeating: "a", count: 39), host: "https://intake.example", sessionPings: pings))
|
||||
}
|
||||
private func reporter(_ store: AppIntakeStore, _ transport: AppIntakeTransport, pings: Bool = false, clock: any DiagnosticClock = SystemDiagnosticClock(), results: AppIntakeResults = AppIntakeResults()) throws -> DiagnosticReports {
|
||||
try DiagnosticReports(directory: URL(fileURLWithPath: "/unused"), policy: DiagnosticPolicy(data: Data(contentsOf: intakeRoot.appendingPathComponent("config/diagnostics.json"))), destination: destination(pings: pings), appVersion: "0.5.9-beta.3", arch: "arm64", transport: transport, clock: clock, storage: store, disabled: { false }, onDeliveryResult: { results.append($0) })
|
||||
}
|
||||
@Test func commonGoldenMapping() throws {
|
||||
let raw = try #require(JSONSerialization.jsonObject(with: Data(contentsOf: intakeRoot.appendingPathComponent("tests/fixtures/diagnostic-app-events.json"))) as? [String: Any])
|
||||
for item in try #require(raw["cases"] as? [[String: Any]]) {
|
||||
let props = try JSONDecoder().decode([String: DiagnosticValue].self, from: JSONSerialization.data(withJSONObject: item["props"]!))
|
||||
let data = try diagnosticAppEvent(props, id: "id", timestamp: 10, installID: "profile")
|
||||
var actual = try #require(JSONSerialization.jsonObject(with: data) as? [String: Any])
|
||||
for key in ["id", "ts", "install_id", "runtime"] { actual.removeValue(forKey: key) }
|
||||
let expected = try #require(item["expected"] as? [String: Any])
|
||||
#expect(NSDictionary(dictionary: actual).isEqual(to: expected), Comment(rawValue: item["name"] as? String ?? "case"))
|
||||
let wire = String(decoding: try diagnosticAppBody(site: "native01", events: [data]), as: UTF8.self)
|
||||
let order = ["category", "source", "stage", "error_code", "engine_id", "uptime_bucket", "elapsed_bucket", "memory_bucket", "disk_bucket", "schema_version"]
|
||||
var tail = wire[try #require(wire.range(of: "\"tags\":")).upperBound...]
|
||||
for key in order where (expected["tags"] as? [String: Any])?[key] != nil {
|
||||
let range = try #require(tail.range(of: "\"\(key)\":")); tail = tail[range.upperBound...]
|
||||
}
|
||||
}
|
||||
}
|
||||
@Test func configurationOverridesAreIndependentAndInvalidSelectedValuesDoNotFallBackToGeneratedCredentials() throws {
|
||||
let generated = try JSONSerialization.data(withJSONObject: ["app_id": "native01", "ingest_key": "smk_" + String(repeating: "a", count: 39), "host": "https://generated.example"])
|
||||
#expect(DiagnosticAppConfiguration.resolve(generated: generated, environment: ["SUPERMETRY_APP_ID": "invalid!"], fallbackHost: "https://fallback.example") == nil)
|
||||
let value = try #require(DiagnosticAppConfiguration.resolve(generated: generated, environment: ["SUPERMETRY_APP_HOST": "http://public.example"], fallbackHost: "https://fallback.example"))
|
||||
#expect(value.host == "https://fallback.example"); #expect(!value.sessionPings)
|
||||
}
|
||||
@Test(arguments: ["1", "0", "\"true\"", "true", "false", "null"]) func sessionPingsRequireLiteralJSONTrue(_ flag: String) throws {
|
||||
let key = "smk_" + String(repeating: "a", count: 39)
|
||||
let generated = Data("{\"app_id\":\"native01\",\"ingest_key\":\"\(key)\",\"diagnostics\":{\"sessionPings\":\(flag)}}".utf8)
|
||||
let config = try #require(DiagnosticAppConfiguration.resolve(generated: generated, environment: [:], fallbackHost: "https://fallback.example"))
|
||||
#expect(config.sessionPings == (flag == "true"))
|
||||
}
|
||||
@Test(arguments: ["site", "host", "app_url", "all"]) func validAppConfigurationIsIndependentOfLegacyOverrides(_ invalid: String) throws {
|
||||
let site = invalid == "site" || invalid == "all" ? "" : "legacy01"
|
||||
let host = invalid == "host" || invalid == "all" ? "http://public.example" : "https://legacy.example"
|
||||
let appURL = invalid == "app_url" || invalid == "all" ? "not-a-url" : "https://voicestudio.sh"
|
||||
#expect(throws: DiagnosticFailure.self) { try DiagnosticDestination(site: site, host: host, appUrl: appURL) }
|
||||
let app = try DiagnosticAppConfiguration(appID: "native01", ingestKey: "smk_" + String(repeating: "a", count: 39), host: "https://intake.example")
|
||||
do {
|
||||
let destination = try DiagnosticDestination(site: site, host: host, appUrl: appURL, app: app)
|
||||
#expect(destination.endpoint.absoluteString == "https://intake.example/api/public/v1/app-events")
|
||||
#expect(destination.app?.appID == "native01")
|
||||
} catch { Issue.record("Valid app-intake configuration was rejected by an unused legacy override") }
|
||||
}
|
||||
@Test func mixedAndMalformedAcknowledgements() {
|
||||
func completed(_ text: String) -> Set<Int> { diagnosticAppCompleted(DiagnosticTransportReply(status: 202, body: Data(text.utf8)), count: 4) }
|
||||
#expect(completed("{\"accepted\":1,\"dropped\":[{\"index\":1,\"reason\":\"invalid\"},{\"index\":2,\"reason\":\"duplicate\"},{\"index\":3,\"reason\":\"rate_limited\"}]}") == [0,1,2])
|
||||
#expect(completed("{\"accepted\":1,\"dropped\":[]}").isEmpty)
|
||||
#expect(completed("{\"accepted\":true,\"dropped\":[]}").isEmpty)
|
||||
#expect(completed("{\"accepted\":3,\"dropped\":[{\"index\":true,\"reason\":\"invalid\"}]}").isEmpty)
|
||||
#expect(completed("{\"accepted\":3,\"dropped\":[{\"index\":4,\"reason\":\"invalid\"}]}").isEmpty)
|
||||
#expect(diagnosticAppCompleted(DiagnosticTransportReply(status: 400), count: 4) == [0,1,2,3])
|
||||
}
|
||||
@Test func unauthorizedPausesTheWholeRunAndWithdrawalPurges() async throws {
|
||||
let store = AppIntakeStore(), transport = AppIntakeTransport()
|
||||
transport.setReplies([DiagnosticTransportReply(status: 401)])
|
||||
let reports = try reporter(store, transport)
|
||||
_ = try await reports.setConsent(true)
|
||||
#expect(reports.capture(DiagnosticInput(category: "engine_failed")))
|
||||
await reports.flush(); #expect(transport.bodies().count == 1); #expect(reports.status.pendingCount == 1)
|
||||
#expect(reports.capture(DiagnosticInput(category: "download_failed")))
|
||||
await reports.flush(); #expect(transport.bodies().count == 1)
|
||||
_ = try await reports.setConsent(false); #expect(reports.status.pendingCount == 0)
|
||||
_ = try await reports.setConsent(true)
|
||||
#expect(reports.capture(DiagnosticInput(category: "model_load_failed")))
|
||||
await reports.flush(); #expect(transport.bodies().count == 1)
|
||||
await reports.close()
|
||||
}
|
||||
@Test func realWorkerSplitsCountAndBytesWithoutLosingRecords() async throws {
|
||||
let store = AppIntakeStore(), transport = AppIntakeTransport(), reports = try reporter(store, transport)
|
||||
_ = try await reports.setConsent(true)
|
||||
for index in 0..<45 {
|
||||
#expect(reports.capture(DiagnosticInput(category: "engine_failed", frames: (0..<24).map { DiagnosticFrame(path: "backend/main.py", line: 24 * index + $0 + 1) })))
|
||||
}
|
||||
await reports.flush()
|
||||
var count = 0
|
||||
for data in transport.bodies() {
|
||||
#expect(data.count <= 16384)
|
||||
let body = try #require(JSONSerialization.jsonObject(with: data) as? [String: Any])
|
||||
let events = try #require(body["events"] as? [[String: Any]])
|
||||
#expect((1...20).contains(events.count)); count += events.count
|
||||
#expect(events.allSatisfy { $0["session_id"] == nil && $0["runtime"] as? String == "swift" })
|
||||
}
|
||||
#expect(count == 45); #expect(reports.status.pendingCount == 0)
|
||||
await reports.close()
|
||||
}
|
||||
@Test func retriesKeepIDsAndMixedRepliesExposeOnlyLocalClosedResults() async throws {
|
||||
let store = AppIntakeStore(), transport = AppIntakeTransport(), results = AppIntakeResults(), clock = AppIntakeClock()
|
||||
let reports = try reporter(store, transport, clock: clock, results: results)
|
||||
_ = try await reports.setConsent(true)
|
||||
// Populate intake while publication is unavailable, then release all
|
||||
// three as one real worker batch rather than racing auto-flush captures.
|
||||
let savedConsent = try store.read("consent.json", maxBytes: 4096)
|
||||
let consent = try #require(savedConsent)
|
||||
let saved = try #require(JSONSerialization.jsonObject(with: consent) as? [String: Any])
|
||||
let epoch = try #require(saved["epoch"] as? String)
|
||||
let projector = DiagnosticProjector(policy: try DiagnosticPolicy(data: Data(contentsOf: intakeRoot.appendingPathComponent("config/diagnostics.json"))), appVersion: "0.5.9-beta.3", buildCommit: nil, arch: "arm64")
|
||||
let records = try ["engine_failed", "download_failed", "model_load_failed"].enumerated().map { index, category -> [String: Any] in
|
||||
let data = try diagnosticEncode(projector.props(DiagnosticInput(category: category), version: "0.5.9-beta.3", commit: nil))
|
||||
return ["version": 1, "id": String(repeating: String(index + 1), count: 32), "timestamp_ms": clock.nowMs(), "epoch": epoch, "props": try JSONSerialization.jsonObject(with: data)]
|
||||
}
|
||||
await reports.close()
|
||||
store.write("outbox.json", data: try JSONSerialization.data(withJSONObject: records))
|
||||
transport.setReplies([DiagnosticTransportReply(status: 429), DiagnosticTransportReply(status: 503), DiagnosticTransportReply(status: 202, body: Data("{\"accepted\":1,\"dropped\":[{\"index\":1,\"reason\":\"rate_limited\"},{\"index\":2,\"reason\":\"too_old\"}],\"warnings\":[{\"index\":0,\"reason\":\"tag_not_allowed\",\"tag\":\"stage\"}]}".utf8))])
|
||||
let retrying = try reporter(store, transport, clock: clock, results: results)
|
||||
await retrying.load(); await retrying.flush()
|
||||
let bodies = try transport.bodies().map { data -> [[String: Any]] in
|
||||
let body = try #require(JSONSerialization.jsonObject(with: data) as? [String: Any]); return try #require(body["events"] as? [[String: Any]])
|
||||
}
|
||||
#expect(bodies.count == 3)
|
||||
#expect(bodies.map { $0.compactMap { $0["id"] as? String } }.allSatisfy { $0 == bodies.first?.compactMap { $0["id"] as? String } })
|
||||
#expect(retrying.status.pendingCount == 1)
|
||||
#expect(results.snapshot().contains { $0.reason == "too_old" })
|
||||
#expect(results.snapshot().contains { $0.reason == "tag_not_allowed" && $0.warningTag == "stage" })
|
||||
clock.advance(60000); await retrying.flush(); #expect(retrying.status.pendingCount == 0)
|
||||
await retrying.close()
|
||||
}
|
||||
@Test func restoredOldFailuresAreNotRelabelledWithCurrentSession() async throws {
|
||||
let store = AppIntakeStore(), transport = AppIntakeTransport()
|
||||
transport.setReplies([DiagnosticTransportReply(status: 401)])
|
||||
let first = try reporter(store, transport)
|
||||
_ = try await first.setConsent(true); first.capture(DiagnosticInput(category: "engine_failed")); await first.flush(); await first.close()
|
||||
let prior = transport.bodies().count, restarted = try reporter(store, transport, pings: true)
|
||||
await restarted.load(); await restarted.flush()
|
||||
let events = try transport.bodies().dropFirst(prior).flatMap { data -> [[String: Any]] in
|
||||
let body = try #require(JSONSerialization.jsonObject(with: data) as? [String: Any]); return try #require(body["events"] as? [[String: Any]])
|
||||
}
|
||||
#expect(events.filter { $0["kind"] as? String == "session" }.count == 1)
|
||||
let failures = events.filter { $0["kind"] as? String != "session" }
|
||||
#expect(failures.count == 1); #expect(failures.allSatisfy { $0["session_id"] == nil })
|
||||
await restarted.close()
|
||||
}
|
||||
@Test func sessionOffByDefaultAndSingleRunCorrelationNeverEntersStorage() async throws {
|
||||
for pings in [false, true] {
|
||||
let store = AppIntakeStore(), transport = AppIntakeTransport(), reports = try reporter(store, transport, pings: pings)
|
||||
_ = try await reports.setConsent(true)
|
||||
#expect(reports.capture(DiagnosticInput(category: "engine_failed")))
|
||||
await reports.flush()
|
||||
let events = try transport.bodies().flatMap { data -> [[String: Any]] in
|
||||
let body = try #require(JSONSerialization.jsonObject(with: data) as? [String: Any]); return try #require(body["events"] as? [[String: Any]])
|
||||
}
|
||||
#expect(events.filter { $0["kind"] as? String == "session" }.count == (pings ? 1 : 0))
|
||||
#expect(events.filter { $0["kind"] as? String != "session" }.allSatisfy { ($0["session_id"] != nil) == pings })
|
||||
let persisted = try store.read("outbox.json", maxBytes: 524288)
|
||||
#expect(persisted == nil || !String(decoding: persisted!, as: UTF8.self).contains("session_id"))
|
||||
_ = try await reports.setConsent(false); _ = try await reports.setConsent(true)
|
||||
#expect(reports.capture(DiagnosticInput(category: "model_load_failed")))
|
||||
await reports.flush()
|
||||
let lastData = try #require(transport.bodies().last)
|
||||
let last = try #require(JSONSerialization.jsonObject(with: lastData) as? [String: Any])
|
||||
#expect((last["events"] as? [[String: Any]])?.allSatisfy { $0["session_id"] == nil && $0["kind"] as? String != "session" } == true)
|
||||
await reports.close()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,7 @@ private final class DiagnosticTestStore: DiagnosticStorage, @unchecked Sendable
|
||||
private var failConsentChanges = false
|
||||
private var failRevocationRemoval = false
|
||||
private var failRevocationRead = false
|
||||
private var outboxCommitted: (@Sendable () -> Void)?
|
||||
var blockOutbox = false
|
||||
let entered = DispatchSemaphore(value: 0)
|
||||
let release = DispatchSemaphore(value: 0)
|
||||
@@ -41,7 +42,8 @@ private final class DiagnosticTestStore: DiagnosticStorage, @unchecked Sendable
|
||||
return blockOutbox && name == "outbox.json"
|
||||
}
|
||||
if blocked { entered.signal(); _ = release.wait(timeout: .now() + 5) }
|
||||
lock.withLock { files[name] = data }
|
||||
let committed = lock.withLock { files[name] = data; return name == "outbox.json" ? outboxCommitted : nil }
|
||||
committed?()
|
||||
}
|
||||
func remove(_ name: String) throws {
|
||||
try lock.withLock {
|
||||
@@ -59,6 +61,7 @@ private final class DiagnosticTestStore: DiagnosticStorage, @unchecked Sendable
|
||||
func failingConsentChanges(_ value: Bool) { lock.withLock { failConsentChanges = value } }
|
||||
func failingRevocationRemoval(_ value: Bool) { lock.withLock { failRevocationRemoval = value } }
|
||||
func failingRevocationReads(_ value: Bool) { lock.withLock { failRevocationRead = value } }
|
||||
func observeOutboxCommit(_ observer: @escaping @Sendable () -> Void) { lock.withLock { outboxCommitted = observer } }
|
||||
func has(_ name: String) -> Bool { lock.withLock { files[name] != nil } }
|
||||
func data(_ name: String) -> Data? { lock.withLock { files[name] } }
|
||||
}
|
||||
@@ -125,8 +128,8 @@ private final class DiagnosticTestKill: @unchecked Sendable {
|
||||
var value: Bool { lock.withLock { killed } }
|
||||
func set(_ value: Bool) { lock.withLock { killed=value } }
|
||||
}
|
||||
private func diagnosticTestReporter(_ store: any DiagnosticStorage, _ transport: any DiagnosticTransport, _ clock: DiagnosticTestClock = DiagnosticTestClock(), appVersion: String = "0.5.9-beta.2", buildCommit: String = String(repeating: "a", count: 40), disabled: @escaping @Sendable () -> Bool = { false }) throws -> DiagnosticReports {
|
||||
try DiagnosticReports(directory: URL(fileURLWithPath: "/unused-test-diagnostics"), policy: diagnosticTestPolicy(), destination: DiagnosticDestination(site: "localtest123", host: "http://127.0.0.1:1", appUrl: "https://app.test.invalid"), appVersion: appVersion, buildCommit: buildCommit, transport: transport, clock: clock, storage: store, disabled: disabled)
|
||||
private func diagnosticTestReporter(_ store: any DiagnosticStorage, _ transport: any DiagnosticTransport, _ clock: DiagnosticTestClock = DiagnosticTestClock(), appVersion: String = "0.5.9-beta.2", buildCommit: String = String(repeating: "a", count: 40), disabled: @escaping @Sendable () -> Bool = { false }, observation: (@Sendable (DiagnosticWorkerObservation) -> Void)? = nil) throws -> DiagnosticReports {
|
||||
try DiagnosticReports(directory: URL(fileURLWithPath: "/unused-test-diagnostics"), policy: diagnosticTestPolicy(), destination: DiagnosticDestination(site: "localtest123", host: "http://127.0.0.1:1", appUrl: "https://app.test.invalid"), appVersion: appVersion, buildCommit: buildCommit, transport: transport, clock: clock, storage: store, disabled: disabled, observation: observation)
|
||||
}
|
||||
private func diagnosticObject(_ data: Data) throws -> [String: Any] { try #require(JSONSerialization.jsonObject(with: data) as? [String: Any]) }
|
||||
private func diagnosticRecords(_ store: DiagnosticTestStore) throws -> [[String: Any]] {
|
||||
@@ -135,6 +138,34 @@ private func diagnosticRecords(_ store: DiagnosticTestStore) throws -> [[String:
|
||||
}
|
||||
private func diagnosticEvent() -> DiagnosticInput { DiagnosticInput(category: "generation_failed", stage: "generation", errorType: "TypeError") }
|
||||
|
||||
private final class DiagnosticExpiryTransport: DiagnosticTransport, @unchecked Sendable {
|
||||
private let clock: DiagnosticTestClock
|
||||
private let lock = NSLock(); private var calls = 0
|
||||
init(_ clock: DiagnosticTestClock) { self.clock = clock }
|
||||
var count: Int { lock.withLock { calls } }
|
||||
func send(destination: DiagnosticDestination, body: Data, allowed: @escaping @Sendable () -> Bool) async throws -> Int {
|
||||
let first = lock.withLock { calls += 1; return calls == 1 }
|
||||
if first { clock.advance(604800001) }
|
||||
return 503
|
||||
}
|
||||
func cancelAll() {}
|
||||
}
|
||||
|
||||
extension DiagnosticReportsTests {
|
||||
@Test func expiryIsRecheckedForRetriesAndLaterRecordsInOneBurst() async throws {
|
||||
let store = DiagnosticTestStore(), clock = DiagnosticTestClock()
|
||||
_ = try await diagnosticSeedSavedOutbox(store)
|
||||
let original = try #require(diagnosticRecords(store).first)
|
||||
var second = original; second["id"] = String(repeating: "b", count: 32)
|
||||
store.set("outbox.json", try JSONSerialization.data(withJSONObject: [original, second]))
|
||||
let transport = DiagnosticExpiryTransport(clock), reports = try diagnosticTestReporter(store, transport, clock)
|
||||
await reports.load(); await reports.flush()
|
||||
#expect(transport.count == 1)
|
||||
#expect(reports.status.pendingCount == 0); #expect(!store.has("outbox.json"))
|
||||
await reports.close()
|
||||
}
|
||||
}
|
||||
|
||||
private func diagnosticBlockedIntake(recovered: Bool) async throws -> (DiagnosticTestStore, DiagnosticTestTransport, DiagnosticTestClock, DiagnosticReports, Int64) {
|
||||
let store = DiagnosticTestStore(), transport = DiagnosticTestTransport(), clock = DiagnosticTestClock()
|
||||
transport.set(code: 201)
|
||||
@@ -307,21 +338,23 @@ private final class DiagnosticFileCommitProbe: DiagnosticFileSynchronizing, @unc
|
||||
#expect(!next.capture(diagnosticEvent())); store.failing(false); await next.close()
|
||||
}
|
||||
#if os(macOS)
|
||||
@Test func realLocalHTTPUsesPublicEndpointAndDoesNotFollowRedirect() async throws {
|
||||
@Test(arguments: [false, true]) func realLocalHTTPUsesPublicEndpointAndDoesNotFollowRedirect(_ appIntake: Bool) async throws {
|
||||
let directory = FileManager.default.temporaryDirectory.appendingPathComponent("diagnostic-http-" + UUID().uuidString)
|
||||
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
|
||||
defer { try? FileManager.default.removeItem(at: directory) }
|
||||
let output = directory.appendingPathComponent("requests.json")
|
||||
let script = """
|
||||
import http.server,json,sys
|
||||
import http.server,json,sys,socket
|
||||
socket.getfqdn=lambda host:host
|
||||
requests=[]
|
||||
class Handler(http.server.BaseHTTPRequestHandler):
|
||||
def do_POST(self):
|
||||
requests.append({'path':self.path,'headers':dict(self.headers),'body':self.rfile.read(int(self.headers['Content-Length'])).decode()})
|
||||
with open(sys.argv[1],'w',encoding='utf-8') as f:json.dump(requests,f)
|
||||
self.send_response(201 if len(requests)==1 else 302)
|
||||
self.send_response((202 if self.path.endswith('/app-events') else 201) if len(requests)==1 else 302)
|
||||
if len(requests)>1:self.send_header('Location','http://127.0.0.1:'+str(self.server.server_port)+'/private')
|
||||
self.end_headers()
|
||||
self.wfile.write(b'{"accepted":1,"dropped":[]}')
|
||||
def log_message(self,*args):pass
|
||||
server=http.server.HTTPServer(('127.0.0.1',0),Handler)
|
||||
print(server.server_port,flush=True)
|
||||
@@ -329,14 +362,24 @@ server.serve_forever()
|
||||
"""
|
||||
let process = try TestProcess(["python3", "-c", script, output.path]); defer { process.stop() }
|
||||
let port = try process.port(within: 5)
|
||||
let destination = try DiagnosticDestination(site: "localtest123", host: "http://127.0.0.1:\(port)", appUrl: "https://app.test.invalid")
|
||||
let app = appIntake ? try DiagnosticAppConfiguration(appID: "native01", ingestKey: "smk_" + String(repeating: "a", count: 39), host: "http://127.0.0.1:\(port)") : nil
|
||||
let destination = try DiagnosticDestination(site: "localtest123", host: "http://127.0.0.1:\(port)", appUrl: "https://app.test.invalid", app: app)
|
||||
let transport = URLSessionDiagnosticTransport()
|
||||
#expect(try await transport.send(destination: destination, body: Data("{\"v\":1}".utf8), allowed: { true }) == 201)
|
||||
#expect(try await transport.send(destination: destination, body: Data("{}".utf8), allowed: { true }) == 302)
|
||||
if appIntake {
|
||||
let reply = try await transport.sendApp(destination: destination, body: Data("{\"site\":\"native01\",\"events\":[{}]}".utf8), userAgent: "VoiceStudio/0.5.9-beta.3 (ios; arm64)", allowed: { true })
|
||||
#expect(reply.status == 202); #expect(diagnosticAppCompleted(reply, count: 1) == [0])
|
||||
#expect(try await transport.sendApp(destination: destination, body: Data("{}".utf8), userAgent: "VoiceStudio/0.5.9-beta.3 (ios; arm64)", allowed: { true }).status == 302)
|
||||
} else {
|
||||
#expect(try await transport.send(destination: destination, body: Data("{\"v\":1}".utf8), allowed: { true }) == 201)
|
||||
#expect(try await transport.send(destination: destination, body: Data("{}".utf8), allowed: { true }) == 302)
|
||||
}
|
||||
let requests = try #require(JSONSerialization.jsonObject(with: Data(contentsOf: output)) as? [[String: Any]])
|
||||
#expect(requests.count == 2); #expect(requests.first?["path"] as? String == "/api/public/v1/events")
|
||||
#expect(requests.count == 2); #expect(requests.first?["path"] as? String == (appIntake ? "/api/public/v1/app-events" : "/api/public/v1/events"))
|
||||
let headers = try #require(requests.first?["headers"] as? [String: String])
|
||||
#expect(headers["Origin"] == "https://app.test.invalid"); #expect(headers["Authorization"] == nil); #expect(headers["Cookie"] == nil); #expect(headers["Referer"] == nil)
|
||||
#expect(headers["Origin"] == (appIntake ? nil : "https://app.test.invalid")); #expect(headers["Authorization"] == nil); #expect(headers["Cookie"] == nil); #expect(headers["Referer"] == nil)
|
||||
#expect(headers["X-Supermetry-Key"] == app?.ingestKey)
|
||||
if appIntake { #expect(headers["User-Agent"] == "VoiceStudio/0.5.9-beta.3 (ios; arm64)") }
|
||||
else { #expect(requests.first?["body"] as? String == "{\"v\":1}") }
|
||||
transport.cancelAll()
|
||||
}
|
||||
#endif
|
||||
@@ -774,6 +817,44 @@ extension DiagnosticReportsTests {
|
||||
}
|
||||
}
|
||||
}
|
||||
private final class DiagnosticPausedTransport: DiagnosticTransport, @unchecked Sendable {
|
||||
private let lock = NSLock(); private var sent = 0
|
||||
var count: Int { lock.withLock { sent } }
|
||||
func send(destination: DiagnosticDestination, body: Data, allowed: @escaping @Sendable () -> Bool) async throws -> Int { throw DiagnosticFailure.invalidDestination }
|
||||
func sendApp(destination: DiagnosticDestination, body: Data, userAgent: String, allowed: @escaping @Sendable () -> Bool) async throws -> DiagnosticTransportReply {
|
||||
guard allowed() else { throw DiagnosticFailure.cancelled }
|
||||
lock.withLock { sent += 1 }
|
||||
return DiagnosticTransportReply(status: 401)
|
||||
}
|
||||
func cancelAll() {}
|
||||
}
|
||||
extension DiagnosticReportsTests {
|
||||
@Test func unauthorizedPausesNetworkButAutomaticallyRetriesDurablePublication() async throws {
|
||||
let store = DiagnosticTestStore(), transport = DiagnosticPausedTransport(), clock = DiagnosticRetryClock()
|
||||
let app = try DiagnosticAppConfiguration(appID: "native01", ingestKey: "smk_" + String(repeating: "a", count: 39), host: "https://intake.example")
|
||||
let reports = try DiagnosticReports(directory: URL(fileURLWithPath: "/unused"), policy: diagnosticTestPolicy(), destination: DiagnosticDestination(site: "legacy01", host: "https://legacy.example", appUrl: "https://app.test.invalid", app: app), appVersion: "0.5.9-beta.3", transport: transport, clock: clock, storage: store, disabled: { false })
|
||||
try await reports.setConsent(true)
|
||||
#expect(reports.capture(diagnosticEvent())); await reports.flush()
|
||||
#expect(transport.count == 1); #expect(try diagnosticRecords(store).count == 1)
|
||||
store.failingOutboxWrites(true)
|
||||
#expect(reports.capture(DiagnosticInput(category: "install_failed"))); await reports.flush()
|
||||
#expect(reports.status.pendingCount == 2); #expect(try diagnosticRecords(store).count == 1)
|
||||
// Observe the actual storage commit, not a manual flush/load/close that
|
||||
// could accidentally repair missing autonomous retry scheduling.
|
||||
let committed = DispatchSemaphore(value: 0)
|
||||
store.observeOutboxCommit { committed.signal() }
|
||||
let attempts = store.outboxWriteAttempts
|
||||
#expect(await clock.waitForSchedule())
|
||||
store.failingOutboxWrites(false); clock.advance(59999)
|
||||
#expect(store.outboxWriteAttempts == attempts)
|
||||
clock.advance(1)
|
||||
#expect(await diagnosticWaitForEvent(committed))
|
||||
#expect(try diagnosticRecords(store).count == 2)
|
||||
#expect(transport.count == 1)
|
||||
#expect(reports.status.pendingCount == 2)
|
||||
await reports.close()
|
||||
}
|
||||
}
|
||||
private func diagnosticRetryReporter(_ store: DiagnosticTestStore, _ transport: any DiagnosticTransport, _ clock: DiagnosticRetryClock, disabled: @escaping @Sendable () -> Bool = { false }) throws -> DiagnosticReports {
|
||||
try DiagnosticReports(directory: URL(fileURLWithPath: "/unused-test-diagnostics"), policy: diagnosticTestPolicy(), destination: DiagnosticDestination(site: "localtest123", host: "http://127.0.0.1:1", appUrl: "https://app.test.invalid"), appVersion: "0.5.9-beta.2", transport: transport, clock: clock, storage: store, disabled: disabled)
|
||||
}
|
||||
@@ -901,17 +982,15 @@ extension DiagnosticReportsTests {
|
||||
@Test func joiningFlushServicesIntakeAcceptedDuringTheHeldFirstSend() async throws {
|
||||
let store = DiagnosticTestStore(), transport = DiagnosticTestTransport()
|
||||
transport.set(code: 201); transport.setHolding(true)
|
||||
let reports = try diagnosticTestReporter(store, transport)
|
||||
let joined = DispatchSemaphore(value: 0)
|
||||
let reports = try diagnosticTestReporter(store, transport, observation: { _ in joined.signal() })
|
||||
try await reports.setConsent(true)
|
||||
let epoch = try #require(reports.recoveryContext?.epoch)
|
||||
#expect(reports.capture(diagnosticEvent(), expectedEpoch: epoch))
|
||||
try #require(await transport.waitForEntry())
|
||||
#expect(reports.capture(DiagnosticInput(category: "install_failed"), expectedEpoch: epoch))
|
||||
let joining = Task { await reports.flush(); return transport.bodies().count }
|
||||
// Admit the queued caller, then use the worker's existing actor load
|
||||
// entry as a scheduling barrier while the first transport is held.
|
||||
await Task.yield()
|
||||
await reports.load()
|
||||
try #require(await diagnosticWaitForEvent(joined))
|
||||
transport.finishHolding()
|
||||
let deliveredAtReturn = await joining.value
|
||||
#expect(deliveredAtReturn == 2)
|
||||
@@ -920,13 +999,14 @@ extension DiagnosticReportsTests {
|
||||
@Test func joiningFlushHonorsStorageCooldownWithoutWaitingForAnotherCapture() async throws {
|
||||
let store = DiagnosticTestStore(), transport = DiagnosticTestTransport(), clock = DiagnosticTestClock()
|
||||
transport.set(code: 201); transport.setHolding(true)
|
||||
let reports = try diagnosticTestReporter(store, transport, clock)
|
||||
let joined = DispatchSemaphore(value: 0)
|
||||
let reports = try diagnosticTestReporter(store, transport, clock, observation: { _ in joined.signal() })
|
||||
try await reports.setConsent(true)
|
||||
reports.capture(diagnosticEvent()); try #require(await transport.waitForEntry())
|
||||
store.failingOutboxWrites(true)
|
||||
reports.capture(DiagnosticInput(category: "install_failed"))
|
||||
let joining = Task { await reports.flush() }
|
||||
await Task.yield(); await reports.load()
|
||||
try #require(await diagnosticWaitForEvent(joined))
|
||||
let attempts = store.outboxWriteAttempts
|
||||
transport.finishHolding(); await joining.value
|
||||
#expect(transport.bodies().count == 1)
|
||||
@@ -940,14 +1020,15 @@ extension DiagnosticReportsTests {
|
||||
@Test(arguments: ["off", "reenable", "close"]) func joiningFlushCannotOutliveItsObservedGrant(_ change: String) async throws {
|
||||
let store = DiagnosticTestStore(), transport = DiagnosticTestTransport()
|
||||
transport.set(code: 201); transport.setHolding(true); transport.setIgnoringCancellation(true)
|
||||
let reports = try diagnosticTestReporter(store, transport)
|
||||
let joined = DispatchSemaphore(value: 0)
|
||||
let reports = try diagnosticTestReporter(store, transport, observation: { _ in joined.signal() })
|
||||
try await reports.setConsent(true)
|
||||
let epoch = try #require(reports.recoveryContext?.epoch)
|
||||
reports.capture(diagnosticEvent(), expectedEpoch: epoch); try #require(await transport.waitForEntry())
|
||||
reports.capture(DiagnosticInput(category: "install_failed"), expectedEpoch: epoch)
|
||||
let completed = DispatchSemaphore(value: 0)
|
||||
let joining = Task { await reports.flush(); completed.signal() }
|
||||
await Task.yield(); await reports.load()
|
||||
try #require(await diagnosticWaitForEvent(joined))
|
||||
if change == "close" { await reports.close() }
|
||||
else {
|
||||
try await reports.setConsent(false)
|
||||
@@ -971,13 +1052,14 @@ extension DiagnosticReportsTests {
|
||||
@Test func joiningFlushDoesNotWaitForIntakeAcceptedAfterItsFollowUpBegan() async throws {
|
||||
let store = DiagnosticTestStore(), transport = DiagnosticTestTransport()
|
||||
transport.set(code: 201); transport.setHolding(true)
|
||||
let reports = try diagnosticTestReporter(store, transport)
|
||||
let joined = DispatchSemaphore(value: 0)
|
||||
let reports = try diagnosticTestReporter(store, transport, observation: { _ in joined.signal() })
|
||||
try await reports.setConsent(true)
|
||||
reports.capture(diagnosticEvent()); try #require(await transport.waitForEntry())
|
||||
reports.capture(DiagnosticInput(category: "install_failed"))
|
||||
let completed = DispatchSemaphore(value: 0)
|
||||
let joining = Task { await reports.flush(); completed.signal() }
|
||||
await Task.yield(); await reports.load()
|
||||
try #require(await diagnosticWaitForEvent(joined))
|
||||
transport.finishHolding(keepHolding: true)
|
||||
try #require(await transport.waitForEntry())
|
||||
reports.capture(DiagnosticInput(category: "backend_crash"))
|
||||
@@ -1182,6 +1264,45 @@ extension DiagnosticReportsTests {
|
||||
|
||||
|
||||
extension DiagnosticReportsTests {
|
||||
@Test(arguments: [false, true]) func bootstrapHardKillCleanupRetriesWithoutAReporterAndHonorsCancellation(_ cancel: Bool) async throws {
|
||||
let store = DiagnosticTestStore(), clock = DiagnosticRetryClock()
|
||||
_ = try await diagnosticSeedSavedOutbox(store)
|
||||
store.failing(true); store.failingConsentChanges(true)
|
||||
#expect(await DiagnosticReports.revokeStoredConsent(directory: URL(fileURLWithPath: "/unused"), storage: store) == false)
|
||||
let reads = store.consentReadAttempts
|
||||
let retry = Task { await DiagnosticReports.retryStoredRevocation(directory: URL(fileURLWithPath: "/unused"), storage: store, clock: clock, onAttempt: { _ in }) }
|
||||
try #require(await clock.waitForSchedule())
|
||||
store.failing(false); store.failingConsentChanges(false)
|
||||
clock.advance(59999); #expect(store.consentReadAttempts == reads)
|
||||
if cancel { retry.cancel() }
|
||||
clock.advance(1); await retry.value
|
||||
if cancel { #expect(store.consentReadAttempts == reads) }
|
||||
else {
|
||||
#expect(store.has("revoked.json"))
|
||||
let reloaded = try diagnosticTestReporter(store, DiagnosticTestTransport()); await reloaded.load()
|
||||
#expect(!reloaded.status.enabled); #expect(!reloaded.capture(diagnosticEvent())); await reloaded.close()
|
||||
}
|
||||
}
|
||||
@Test func unreadRevocationMarkerPreservesGrantAndOutboxUntilReadRecovers() async throws {
|
||||
let store = DiagnosticTestStore(), clock = DiagnosticRetryClock()
|
||||
let saved = try await diagnosticSeedSavedOutbox(store)
|
||||
let grant = try #require(store.data("consent.json"))
|
||||
let original = try #require(diagnosticRecords(store).first)
|
||||
store.failingRevocationReads(true)
|
||||
let transport = DiagnosticCommittedTransport(store), reports = try diagnosticRetryReporter(store, transport, clock)
|
||||
await reports.load(); await reports.flush()
|
||||
#expect(!reports.status.enabled); #expect(!reports.capture(diagnosticEvent()))
|
||||
#expect(store.data("outbox.json") == saved); #expect(store.data("consent.json") == grant)
|
||||
#expect(!store.has("revoked.json")); #expect(transport.bodies().isEmpty)
|
||||
try #require(await clock.waitForSchedule())
|
||||
store.failingRevocationReads(false); clock.advance(60000)
|
||||
try #require(await transport.waitForEntry()); await reports.flush()
|
||||
let deliveredData = try #require(transport.bodies().first)
|
||||
let delivered = try diagnosticObject(deliveredData)
|
||||
#expect(delivered["id"] as? String == original["id"] as? String)
|
||||
#expect(store.data("consent.json") == grant); #expect(reports.status.enabled)
|
||||
await reports.close()
|
||||
}
|
||||
@Test(arguments: [5, 13]) func unreadConsentPreservesReportsAndSchedulesSameGrantRecovery(_ code: Int) async throws {
|
||||
let store = DiagnosticTestStore(), clock = DiagnosticRetryClock()
|
||||
let saved = try await diagnosticSeedSavedOutbox(store)
|
||||
|
||||
@@ -249,7 +249,7 @@ final class PhoneScreenshotTour: XCTestCase {
|
||||
}
|
||||
@MainActor func testPhoneFirstScreens() {
|
||||
let app = XCUIApplication(); app.launchArguments = ["--ui-smoke","-AppleLanguages","(en)"]
|
||||
app.launch(); XCTAssertTrue(app.buttons["consent.no"].waitForExistence(timeout: uiReadyTimeout)); XCTAssertTrue(app.staticTexts["Usage analytics are not sent from this phone; your choice is stored locally. Automatic diagnostic reports have a separate opt-in."].exists); capture("Consent",app); app.declineConsent(); capture("Home",app); app.openSpeak()
|
||||
app.launch(); XCTAssertTrue(app.buttons["consent.no"].waitForExistence(timeout: uiReadyTimeout)); XCTAssertTrue(app.staticTexts.matching(NSPredicate(format: "label == %@", "Usage analytics are not sent from this phone; your choice is stored locally. Automatic diagnostic reports have a separate opt-in.")).firstMatch.exists); capture("Consent",app); app.declineConsent(); capture("Home",app); app.openSpeak()
|
||||
XCTAssertTrue(app.textViews["speak.text"].waitForExistence(timeout: uiReadyTimeout)); capture("Speak-phone",app)
|
||||
app.tabButton("Voices").tapReady(); capture("Voices-phone",app)
|
||||
app.buttons["voices.create"].tapReady(); XCTAssertTrue(app.textFields["voices.clone.name"].waitForExistence(timeout: uiReadyTimeout)); capture("Clone-phone",app); app.buttons["Cancel"].tapReady()
|
||||
|
||||
@@ -172,7 +172,7 @@ final class SmokeTests: XCTestCase {
|
||||
XCTAssertEqual(no.label, "No thanks")
|
||||
XCTAssertEqual(yes.frame.width, no.frame.width, accuracy: 1)
|
||||
XCTAssertFalse(app.buttons["consent.dismiss"].exists)
|
||||
XCTAssertTrue(app.staticTexts["Usage analytics are not sent from this phone; your choice is stored locally. Automatic diagnostic reports have a separate opt-in."].exists)
|
||||
XCTAssertTrue(app.staticTexts.matching(NSPredicate(format: "label == %@", "Usage analytics are not sent from this phone; your choice is stored locally. Automatic diagnostic reports have a separate opt-in.")).firstMatch.exists)
|
||||
// First opt in, then prove passive dismissal replaces a prior Yes with No.
|
||||
yes.tap()
|
||||
XCTAssertTrue(app.tabBars.buttons["Settings"].waitForExistence(timeout: uiReadyTimeout))
|
||||
|
||||
Reference in new issue
Block a user