From 882eb0d3dc8063ea5f94937d318ddaf7ca6d84be Mon Sep 17 00:00:00 2001 From: "Md. Asaduzzaman Nur" Date: Thu, 13 Aug 2026 11:52:15 +0600 Subject: [PATCH 1/7] docs: design for the Remote Config inspector (#6) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Issue #6 asks to see which Remote Config values are active on a device and where each one came from. The hard question in practice is not what a value is but why it is that value — a key showing an in-app default because the fetch was throttled looks identical to one the console actually published, and that difference is the whole debugging story. Scoped read-only, and structured as a vendor-neutral core plus a reflection-based Firebase adapter so Firebase stays off the classpath of consumers that do not use it, matching the existing push triad. Co-Authored-By: Claude Opus 5 --- ...26-08-13-remote-config-inspector-design.md | 335 ++++++++++++++++++ 1 file changed, 335 insertions(+) create mode 100644 docs/superpowers/specs/2026-08-13-remote-config-inspector-design.md diff --git a/docs/superpowers/specs/2026-08-13-remote-config-inspector-design.md b/docs/superpowers/specs/2026-08-13-remote-config-inspector-design.md new file mode 100644 index 0000000..90bebe0 --- /dev/null +++ b/docs/superpowers/specs/2026-08-13-remote-config-inspector-design.md @@ -0,0 +1,335 @@ +# Remote Config Inspector + +Date: 2026-08-13 +Status: Approved design +Issue: [#6 — Add Remote Config Inspector to DevConsole](https://github.com/devconsole-android/DevConsole/issues/6) + +## Summary + +Add a read-only Remote Config inspector to DevConsole: every fetched Remote Config key, its current +value, and the source that value came from (remote server, in-app default, SDK static fallback, or a +local override), alongside fetch metadata (last fetch time, last fetch status, minimum fetch +interval). + +The feature ships as a vendor-neutral core module plus a Firebase adapter that carries no +compile-time Firebase dependency, following the existing `push` / `push-firebase` / +`push-firebase-noop` triad exactly. Both DevConsole surfaces render it: the browser dashboard gets a +new rail view, and the Compose inspector gets a section on its Control screen. + +## Problem + +There is no way to see Remote Config state from DevConsole today — grep finds zero references to +Remote Config anywhere in the repository. A developer or QA engineer verifying a feature flag on a +device has to fall back to logcat or a purpose-built debug screen in the host app. + +The specific question that is hard to answer without this is not "what is the value" but **"why is it +that value"** — whether a key is showing the remote value the console published, or has silently +fallen back to an in-app default because the fetch failed or was throttled. That distinction is the +difference between "the rollout works" and "the rollout never reached this device." + +## Goals + +- List every Remote Config key currently active on the device with its value and source attribution. +- Surface fetch metadata: last fetch time, last fetch status, minimum fetch interval. +- Work without adding a Firebase dependency to consumers who do not use Firebase. +- Support non-Firebase Remote Config providers through a host-implementable interface. +- Render on both the browser dashboard and the on-device Compose inspector. +- Never throw into the host application, and never leak secrets held in config values. + +## Non-goals + +- **No setting of overrides from DevConsole.** The `OVERRIDE` source is displayed when a host has + applied one, but DevConsole does not create overrides in this change. Deferred deliberately; see + "Deferred: override editing". +- No triggering of `fetch()` / `activate()` from DevConsole. The inspector observes; it does not + drive the Remote Config lifecycle. +- No timeline events or historical fetch records. This is a current-state view, not an event stream. +- No `ui-views` work. That module is a thin launcher panel and renders no flag or state data today. + +## Approach + +Three new modules, mirroring the existing push triad: + +| Module | Namespace | Contents | +| --- | --- | --- | +| `:sdk:remote-config` | `io.devconsole.remoteconfig` | Vendor-neutral model + registry. No Android or Firebase dependencies. | +| `:sdk:remote-config-firebase` | `io.devconsole.remoteconfig.firebase` | Reflection adapter + `RemoteConfigFirebaseCaptureMarker`. | +| `:sdk:remote-config-firebase-noop` | `io.devconsole.remoteconfig.firebase.noop` | Protected-build twin returning an empty, clearly-labelled snapshot. | + +Rejected alternatives: + +- **Firebase-only single module.** Fewer modules, but breaks the repo's core+adapter convention and + locks the feature to one vendor; adding a second provider later would be a breaking restructure. +- **Document `StateProvider` instead of shipping code.** Zero SDK code, but `StateValue` has no + concept of value *source* or fetch metadata — precisely what the issue asks for — so every host + would hand-roll Firebase reflection and still get no source attribution. + +## Data model (`:sdk:remote-config`) + +```kotlin +enum class RemoteConfigSource(val wireName: String) { + REMOTE("remote"), // fetched and activated from the server + DEFAULT("default"), // in-app defaults (setDefaultsAsync) + STATIC("static"), // set nowhere; the SDK's static fallback + OVERRIDE("override"), // a host applied a local override + UNKNOWN("unknown"), // the provider could not attribute it +} + +data class RemoteConfigEntry( + val key: String, + val value: String, + val source: RemoteConfigSource, + val redacted: Boolean = false, + val truncated: Boolean = false, +) + +enum class RemoteConfigFetchStatus { SUCCESS, NO_FETCH_YET, FAILURE, THROTTLED, UNKNOWN } + +data class RemoteConfigFetchInfo( + val lastFetchEpochMs: Long?, + val status: RemoteConfigFetchStatus, + val minimumFetchIntervalSeconds: Long?, +) + +data class RemoteConfigSnapshot( + val providerId: String, + val entries: List, + val fetchInfo: RemoteConfigFetchInfo, + val unavailableReason: String? = null, +) + +interface RemoteConfigProvider { + val id: String + + fun snapshot(): RemoteConfigSnapshot +} +``` + +`RemoteConfigRegistry` mirrors `StateRegistry`: `register(provider)` rejecting blank and duplicate +ids, plus `providerIds()`, `snapshot(id)`, and `snapshots()`. + +Decisions embedded in the model: + +- **`value` is a `String`.** Remote Config is string-typed at the source; `asLong()` / `asBoolean()` + are interpretations applied by the reader. Recording a guessed type would invent information the + server never sent. The dashboard may still pretty-print a value that parses as JSON. +- **Values are truncated at 8 KB** with `truncated = true`, following the repo's existing + body-preview convention. A single pathological config value must not bloat every snapshot response. + Truncation is enforced by `RemoteConfigRegistry` when it normalizes a provider's snapshot, not by + each adapter, so a host-written provider inherits the cap for free rather than having to remember + it. `MAX_VALUE_LENGTH` is a public constant on the registry's companion. +- **`OVERRIDE` exists but nothing emits it yet.** It is what the issue asks us to *display*, and + Firebase has no such concept — it arises only where a host layers one on. Reserving the enum case + now means the deferred override feature is not a wire-format break later. +- **`unavailableReason` instead of exceptions.** Per CONTRIBUTING, capture code must never throw into + the host. `RemoteConfigRegistry` wraps every `provider.snapshot()` in `runCatching` and converts a + failure into an empty snapshot carrying the reason, so a broken provider degrades to a visible + "unavailable" row rather than taking down the inspector. Such a snapshot carries + `fetchInfo = RemoteConfigFetchInfo(lastFetchEpochMs = null, status = UNKNOWN, + minimumFetchIntervalSeconds = null)` — a failed provider must not report a confident fetch status. + The reason string is the throwable's message, or its class name when the message is null. +- **Pull, not push.** Snapshots are evaluated on demand when a surface asks, exactly like + `StateProvider`. "Which values are currently active" is a state question, not an event stream. + +## Firebase adapter (`:sdk:remote-config-firebase`) + +```kotlin +class FirebaseRemoteConfigAdapter @JvmOverloads constructor( + private val remoteConfig: Any, // com.google.firebase.remoteconfig.FirebaseRemoteConfig + override val id: String = "firebase", +) : RemoteConfigProvider +``` + +Reflection only — no compile-time Firebase dependency — identical in construction to +`FirebaseRemoteMessageAdapter`, including its private `Any.call(name)` helper that returns `null` +rather than throwing when a method is absent. + +Reads `getAll()` → `Map`, then per value `asString()` and +`getSource()`; and `getInfo()` → `getFetchTimeMillis()`, `getLastFetchStatus()`, and +`getConfigSettings().getMinimumFetchIntervalInSeconds()`. + +Constant values, verified against `firebase-android-sdk` source rather than assumed: + +```java +VALUE_SOURCE_STATIC = 0; VALUE_SOURCE_DEFAULT = 1; VALUE_SOURCE_REMOTE = 2; +LAST_FETCH_STATUS_SUCCESS = -1; NO_FETCH_YET = 0; FAILURE = 1; THROTTLED = 2; +``` + +Two traps this mapping must handle explicitly, both verified above: + +1. **`LAST_FETCH_STATUS_SUCCESS` is `-1`, not `0`.** An "unknown status" fallback keyed on negative + numbers would silently mislabel every successful fetch. +2. **`getFetchTimeMillis()` returns `-1` when no fetch has happened.** Normalized to + `lastFetchEpochMs = null`, never rendered as a 1969 timestamp. + +The adapter resolves these constants reflectively from the Firebase class when it is present and +falls back to the literals above, so a future renumbering cannot silently mis-badge every row. Any +unrecognized integer maps to `UNKNOWN` rather than guessing. + +The noop twin returns `RemoteConfigSnapshot(providerId = id, entries = emptyList(), …, +unavailableReason = "disabled-build")` and does not reflect on the supplied object at all, matching +the noop push adapter's contract. + +## Host wiring + +`DevConsoleConfig` gains `remoteConfigProviders` as an **additive field outside the primary +constructor** (`withRemoteConfigProviders()`, `Builder.addRemoteConfigProvider()`) — the rule that +file already states for preserving the 1.x JVM ABI. + +```kotlin +DevConsole.initialize( + application, + DevConsoleConfig(/* … */) + .withRemoteConfigProviders(listOf(FirebaseRemoteConfigAdapter(Firebase.remoteConfig))), +) +``` + +Late registration via `DevConsole.registerRemoteConfigProvider()` mirrors `registerStateProvider`. +This is safe here precisely because reads are pull-based — unlike feature flags, whose init-only +restriction exists to avoid a race between a late registration and a snapshot the dashboard has +already read. + +**Capture gating uses the existing `CaptureCategory.STATE`** rather than a new category. STATE +already means "state providers + feature flags"; Remote Config is the same shape of data. A new enum +constant would widen the wire format and force every host to revisit their `captureCategories` set +for no real benefit. The STATE KDoc and docs are updated to read "state providers, feature flags, and +remote config". + +## Redaction + +Remote Config values routinely hold API keys, endpoints, and third-party tokens, so they are treated +as a capture boundary like any other. + +Redaction is applied **once, in `:sdk:full`**, by wrapping the registry before it is handed to either +consumer. Both the Ktor routes and `FullInspectorDataSource` therefore receive already-redacted +entries, and neither the JSON serializer nor the Compose renderer needs to know redaction exists — +the arrangement CONTRIBUTING prescribes. This matters because the Compose inspector reads in-process +through `InspectorDataSource` and never crosses the HTTP boundary, so redaction applied only in +`server-ktor` would leave the on-device surface unprotected. + +Matching is by **key name** through `RedactionEngine.redactFields()`. `RedactionPolicy`'s default +`sensitiveFieldNames` already carries `api-key`, `apikey`, `access_token`, `refresh_token` and +similar — exactly the shape of a leaky Remote Config key. A redacted entry has its `value` replaced +by `RedactionPolicy.replacement` (`` by default) **and** sets `redacted = true`, so both +surfaces can badge it as withheld rather than letting a reader mistake the replacement string for the +literally configured value. The key itself is never redacted — knowing *which* key is withheld is the +whole point of the view, and the key name is what the host wrote in the Remote Config console. + +## REST API + +A single endpoint, `GET /api/v1/remote-config`, returning every provider's snapshot inline: + +```json +{"data":[{ + "id":"firebase", + "fetch":{"lastFetchEpochMs":1755043200000,"status":"success","minimumFetchIntervalSeconds":3600}, + "unavailableReason":null, + "entries":[ + {"key":"checkout_v2","value":"true","source":"remote","redacted":false,"truncated":false} + ] +}]} +``` + +Wire names deliberately differ from the Kotlin field names in two places, and the serializer must map +them: `RemoteConfigSnapshot.providerId` → `"id"`, and `RemoteConfigSnapshot.fetchInfo` → `"fetch"`. +`RemoteConfigSource.wireName` and a lowercase form of `RemoteConfigFetchStatus` supply the enum +strings. These wire names are the stable contract; the Kotlin names may not be changed to match. + +Unlike `/api/v1/state`, this does not split into a list-ids call plus a per-id snapshot call. That +two-step exists because state providers can be numerous and individually expensive to evaluate; +Remote Config providers are effectively always one, and the whole snapshot is small. + +Authentication matches `GET /api/v1/flags` (authenticated session required), and the response when +`CaptureCategory.STATE` is disabled matches whatever that route already returns, rather than +inventing a second convention for the same category. + +## Surfaces + +### Browser dashboard + +- New `viewRemoteConfig` rail button in `index.html`, grouped with "State & flags". +- A view section with a provider header (last fetch, status, minimum interval) and a table of + Key / Value / Source, with a source badge per row. +- `dashboard.js` fetches `/api/v1/remote-config` and wires into the existing view-switch and refresh + machinery. `dashboard.css` gains `.badge-remote` / `.badge-default` / `.badge-static` / + `.badge-override` on top of the existing badge classes. +- A client-side key filter input, since real Remote Config sets get large. + +### Compose inspector + +- UI-shaped mirror types `InspectorRemoteConfigUi` and `InspectorRemoteConfigProviderUi` in + `InspectorDataSource.kt`, carrying no `:sdk:remote-config` dependency — the precedent set by + `InspectorBodyKind` mirroring `network.BodyPreview`. +- `InspectorSnapshot` gains `remoteConfig: List = emptyList()`. The + default keeps every existing fake and adapter compiling unchanged. +- Rendered on the **Control** screen, where feature flags already live, as a `CollapsibleSection`: + header shows provider id, last fetch, and status; rows show key, value, and source badge. Key + filtering reuses `InspectorDetailSearchField`. +- `FullInspectorDataSource` populates it from the redacted registry, honoring the STATE gate. + +### Empty and error states + +Four distinct states, none of which may render as a blank page: + +1. No provider registered → "No Remote Config provider registered", linking to the docs. +2. `CaptureCategory.STATE` disabled → the same shape the flags surface already uses. +3. Provider threw → `unavailableReason` surfaced as a warning row. +4. Zero keys / never fetched → "No values" plus an explicit "last fetch: never". This is the + `NO_FETCH_YET` case and the single most common real-world confusion, so it is called out rather + than shown as an empty table. + +## Gradle plugin registration + +A new protected adapter module must be registered in **four** places, or the release-variant +protection silently does not apply to it: + +1. `FULL_RUNTIME_COORDINATE` regex (`DevConsoleVariantPolicyPlugin.kt`) — add + `devconsole-remote-config-firebase`. +2. `FORBIDDEN_SIGNATURES` — add `DEVCONSOLE_ENABLED_REMOTE_CONFIG_FIREBASE_V1`. +3. `protectedDependencyPaths` convention — add `:sdk:remote-config-firebase`. +4. `NoopRuntimeExcludesFullModulesTest` — add the module and its noop twin. + +`:sdk:remote-config` itself is **not** protected, exactly as `:sdk:push` is not: it is an inert data +model with no capture behavior. + +## Testing + +- **`:sdk:remote-config`** — registry rejects blank/duplicate ids; unknown id returns null; a provider + that throws yields `unavailableReason` rather than propagating; truncation boundary. +- **`:sdk:remote-config-firebase`** — adapter driven by fake Firebase-shaped Kotlin objects with + matching method names, the technique `FirebaseRemoteMessageAdapterTest` already uses, so no + Firebase dependency enters the test classpath. Covers all three sources, all four fetch statuses + including `SUCCESS = -1`, `fetchTimeMillis = -1` → `null`, absent methods → `UNKNOWN`, and a + malformed object that would throw. +- **`:sdk:remote-config-firebase-noop`** — returns the disabled-build snapshot and does not reflect, + mirroring `FirebaseRemoteMessageAdapterNoopTest`. +- **`:sdk:full`** — redaction applied on both the HTTP and in-process paths; STATE gating added to + `CaptureCategoryGatingTest`; `FullInspectorDataSource` mapping. +- **`:sdk:server-ktor`** — route JSON shape, auth required, category-gated response. +- **`gradle-plugin`** — the extended `NoopRuntimeExcludesFullModulesTest`. + +## Documentation and CI + +- New `docs/REMOTE_CONFIG.md`; linked from `docs/README.md`. +- Row added to `docs/PROTOCOL_REFERENCE.md`; cross-reference from `docs/STATE_AND_FLAGS.md`. +- README feature list and `CHANGELOG.md`. +- `./gradlew apiDump` for the three new modules, which carry `api/*.api` baselines. +- New Kotlin files carry the `@author` / `@since 13/08/26` header the repo requires. +- `settings.gradle.kts` include lines; each module applies `devconsole.android.library`, + `devconsole.quality`, and `devconsole.publishing`. + +Verification commands: `./gradlew build`, `./gradlew testDebugUnitTest`, +`./gradlew ktlintCheck detekt`, `./gradlew apiCheck`, `./gradlew -p gradle-plugin test`, and — because +this touches a protected-variant boundary — the three sample `assembleDebug` / `assembleRelease` / +`verifyDevConsoleProtectedArtifacts` runs. + +## Deferred: override editing + +The natural follow-up is a session-scoped override layer letting QA force a value without publishing +to the Remote Config console. It is deliberately out of scope here because it needs machinery this +change does not: hosts must read values back through DevConsole for an override to affect behavior +(the `featureFlagValue` problem), plus an `EditingCapabilities` gate, command-audit records, timeline +events, and session-integrity reporting. + +The `OVERRIDE` enum case and the `RemoteConfigProvider` interface are shaped so that work lands +additively rather than as a breaking change. From 4679e9200a45cb3a0bfbae941611ba67c186735e Mon Sep 17 00:00:00 2001 From: "Md. Asaduzzaman Nur" Date: Thu, 13 Aug 2026 12:48:22 +0600 Subject: [PATCH 2/7] feat: Remote Config inspector (#6) Seeing a flag's value was never the hard part. The hard part is knowing whether it reads that way because you published it, or because the last fetch was throttled and the app quietly fell back to an in-app default. Those two look identical from inside the app, and the difference is "the rollout works" versus "the rollout never reached this device". So the source attribution, not the value, is the feature. Structured as a vendor-neutral core plus a reflection-based Firebase adapter, mirroring the push triad, so Firebase stays off the classpath of consumers that never touch it and a host on another vendor can implement RemoteConfigProvider instead. Gated by the existing STATE capture category rather than a new one: it is the same kind of data as state providers and feature flags, and a new category would have widened the wire format for nothing. Two details worth calling out, both of which bite silently: Firebase's LAST_FETCH_STATUS_SUCCESS is -1, not 0, and getFetchTimeMillis returns -1 before the first fetch. Verified against the SDK source rather than assumed; a "negative means unknown" mapping would have mislabelled every successful fetch, and a raw timestamp would have dated a never-fetched provider to 1969. Redaction runs at one boundary in :sdk:full, not at the HTTP route. The Compose inspector reads the registry in-process and never crosses that route, so redacting there would have protected the browser and left the device showing raw secrets. Matching is separator-insensitive because RedactionPolicy's defaults are an HTTP-header list compared by exact name, while Remote Config keys are snake_case and camelCase -- api_key would otherwise have sailed past the policy's api-key entry in full. Read-only by design; the OVERRIDE source is reserved so the deferred override-editing work lands additively rather than as a wire break. Design: docs/superpowers/specs/2026-08-13-remote-config-inspector-design.md Co-Authored-By: Claude Opus 5 --- CHANGELOG.md | 30 +++ README.md | 1 + docs/PROTOCOL_REFERENCE.md | 9 + docs/README.md | 1 + docs/REMOTE_CONFIG.md | 131 ++++++++++ docs/STATE_AND_FLAGS.md | 6 + .../gradle/DevConsoleVariantPolicyPlugin.kt | 5 +- .../NoopRuntimeExcludesFullModulesTest.kt | 2 + sdk/api/api/api.api | 4 + sdk/api/build.gradle.kts | 1 + .../io/devconsole/api/DevConsoleConfig.kt | 20 +- .../api/DevConsoleFacadeProvider.kt | 14 + .../api/RemoteConfigConfigurationTest.kt | 67 +++++ .../main/kotlin/io/devconsole/DevConsole.kt | 9 + sdk/full/api/full.api | 1 + .../io/devconsole/FullInspectorDataSource.kt | 40 +++ .../io/devconsole/PlatformFacadeProvider.kt | 23 ++ .../io/devconsole/RedactingRemoteConfig.kt | 61 +++++ .../devconsole/RemoteConfigInspectorTest.kt | 218 ++++++++++++++++ sdk/noop/api/noop.api | 1 + .../io/devconsole/PlatformFacadeProvider.kt | 3 + .../api/remote-config-firebase-noop.api | 8 + .../build.gradle.kts | 11 + .../firebase/FirebaseRemoteConfigAdapter.kt | 31 +++ .../FirebaseRemoteConfigAdapterNoopTest.kt | 62 +++++ .../api/remote-config-firebase.api | 15 ++ sdk/remote-config-firebase/build.gradle.kts | 12 + sdk/remote-config-firebase/consumer-rules.pro | 1 + .../RemoteConfigFirebaseCaptureMarker.kt | 9 + .../firebase/FirebaseRemoteConfigAdapter.kt | 110 ++++++++ .../FirebaseRemoteConfigAdapterTest.kt | 208 +++++++++++++++ sdk/remote-config/api/remote-config.api | 107 ++++++++ sdk/remote-config/build.gradle.kts | 5 + .../devconsole/remoteconfig/RemoteConfig.kt | 107 ++++++++ .../remoteconfig/RemoteConfigRegistry.kt | 72 +++++ .../remoteconfig/RemoteConfigRegistryTest.kt | 181 +++++++++++++ sdk/server-ktor/api/server-ktor.api | 6 +- sdk/server-ktor/build.gradle.kts | 1 + .../server/ktor/DevConsoleKtorModule.kt | 50 ++++ .../resources/devconsole-web/dashboard.js | 82 +++++- .../main/resources/devconsole-web/index.html | 15 ++ .../server/ktor/RemoteConfigRoutesTest.kt | 246 ++++++++++++++++++ sdk/ui-compose/api/ui-compose.api | 107 +++++--- .../ui/compose/InspectorControlScreen.kt | 109 ++++++++ .../ui/compose/InspectorDataSource.kt | 31 +++ .../devconsole/ui/compose/InspectorState.kt | 2 + .../ui/compose/InspectorViewModel.kt | 1 + settings.gradle.kts | 3 + 48 files changed, 2204 insertions(+), 35 deletions(-) create mode 100644 docs/REMOTE_CONFIG.md create mode 100644 sdk/api/src/test/kotlin/io/devconsole/api/RemoteConfigConfigurationTest.kt create mode 100644 sdk/full/src/main/kotlin/io/devconsole/RedactingRemoteConfig.kt create mode 100644 sdk/full/src/test/kotlin/io/devconsole/RemoteConfigInspectorTest.kt create mode 100644 sdk/remote-config-firebase-noop/api/remote-config-firebase-noop.api create mode 100644 sdk/remote-config-firebase-noop/build.gradle.kts create mode 100644 sdk/remote-config-firebase-noop/src/main/kotlin/io/devconsole/remoteconfig/firebase/FirebaseRemoteConfigAdapter.kt create mode 100644 sdk/remote-config-firebase-noop/src/test/kotlin/io/devconsole/remoteconfig/firebase/FirebaseRemoteConfigAdapterNoopTest.kt create mode 100644 sdk/remote-config-firebase/api/remote-config-firebase.api create mode 100644 sdk/remote-config-firebase/build.gradle.kts create mode 100644 sdk/remote-config-firebase/consumer-rules.pro create mode 100644 sdk/remote-config-firebase/src/main/kotlin/io/devconsole/internal/enabled/RemoteConfigFirebaseCaptureMarker.kt create mode 100644 sdk/remote-config-firebase/src/main/kotlin/io/devconsole/remoteconfig/firebase/FirebaseRemoteConfigAdapter.kt create mode 100644 sdk/remote-config-firebase/src/test/kotlin/io/devconsole/remoteconfig/firebase/FirebaseRemoteConfigAdapterTest.kt create mode 100644 sdk/remote-config/api/remote-config.api create mode 100644 sdk/remote-config/build.gradle.kts create mode 100644 sdk/remote-config/src/main/kotlin/io/devconsole/remoteconfig/RemoteConfig.kt create mode 100644 sdk/remote-config/src/main/kotlin/io/devconsole/remoteconfig/RemoteConfigRegistry.kt create mode 100644 sdk/remote-config/src/test/kotlin/io/devconsole/remoteconfig/RemoteConfigRegistryTest.kt create mode 100644 sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/RemoteConfigRoutesTest.kt diff --git a/CHANGELOG.md b/CHANGELOG.md index 0349546..5963118 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,6 +20,36 @@ joined this list.) ## Unreleased +### Added + +- **Remote Config inspector** ([#6](https://github.com/devconsole-android/DevConsole/issues/6)). + Read-only view of the Remote Config values active on the device, with the attribution that makes + them diagnosable: whether each value came from the server, an in-app default, the SDK's static + fallback, or a local override — plus last fetch time, last fetch status, and minimum fetch + interval. A key serving a default because the fetch was throttled is otherwise indistinguishable + from one you actually published. + + Three new modules following the existing push triad: `devconsole-remote-config` (vendor-neutral + model and registry), `devconsole-remote-config-firebase` (reads `FirebaseRemoteConfig` by + reflection, so Firebase stays off the classpath of consumers that do not use it), and + `devconsole-remote-config-firebase-noop` (the protected-build twin, which reports + `disabled-build` rather than pretending config is simply empty). Neither adapter is re-exported by + the `devconsole` umbrella. + + Surfaces on both the browser dashboard (a Remote Config page under Data) and the Compose + inspector's Control screen, and over `GET /api/v1/remote-config`. Gated by the existing + `CaptureCategory.STATE`, alongside state providers and feature flags. Register a provider with + `DevConsoleConfig.withRemoteConfigProviders(...)` or, for a lazily-built client, + `DevConsole.registerRemoteConfigProvider(...)`. Read-only by design: DevConsole does not set + overrides and never triggers `fetch()`/`activate()`. See + [docs/REMOTE_CONFIG.md](docs/REMOTE_CONFIG.md). + + Values are redacted by key name at a single boundary shared by both surfaces — the on-device + inspector reads in-process and never crosses the HTTP boundary, so redacting at the route alone + would have left it exposed. Matching is separator-insensitive here, unlike the raw + `RedactionPolicy`, whose defaults are an HTTP-header list compared by exact name: `api_key` and + `apiKey` now match the policy's `api-key` instead of being displayed in full. + ## 1.1.1 — 2026-08-12 A build-and-distribution patch: no SDK code changed, and the public API is byte-for-byte the diff --git a/README.md b/README.md index ac72de3..8059a99 100644 --- a/README.md +++ b/README.md @@ -437,6 +437,7 @@ Full index: [docs/README.md](docs/README.md). Highlights: [Push](docs/PUSH.md) - [Data inspectors and exports](docs/DATA_INSPECTORS_AND_EXPORTS.md) · [Evidence and bug reports](docs/EVIDENCE_AND_BUG_REPORTS.md) +- [State and feature flags](docs/STATE_AND_FLAGS.md) · [Remote Config](docs/REMOTE_CONFIG.md) - [Crash and ANR capture](docs/CRASH_AND_ANR.md) · [Background keep-alive](docs/BACKGROUND_KEEPALIVE.md) - [FAQ / troubleshooting](docs/FAQ_TROUBLESHOOTING.md) diff --git a/docs/PROTOCOL_REFERENCE.md b/docs/PROTOCOL_REFERENCE.md index ed63770..507cc07 100644 --- a/docs/PROTOCOL_REFERENCE.md +++ b/docs/PROTOCOL_REFERENCE.md @@ -210,6 +210,15 @@ accepted since surrounding quotes are trimmed). `FeatureFlagType` has two member allowed values the declared option set) — see [STATE_AND_FLAGS.md](STATE_AND_FLAGS.md#flags-with-named-options-environment-switching) for the named-options use case (environment/account-tier switching). +### Remote Config + +`GET /api/v1/remote-config` (auth). Read-only; there is no write route. Returns one object per +registered provider: `id`, `fetch` (`lastFetchEpochMs` — **null**, never a sentinel, when no fetch +has completed — plus `status` and `minimumFetchIntervalSeconds`), `unavailableReason`, and `entries` +(`key`, `value`, `source`, `redacted`, `truncated`). `source` is one of `remote`, `default`, +`static`, `override`, `unknown`. Gated by the `state` capture category, the same one that covers +state providers and feature flags. See [REMOTE_CONFIG.md](REMOTE_CONFIG.md). + ### Composer `POST /api/v1/composer/execute` (auth — one-off request; `method` restricted to diff --git a/docs/README.md b/docs/README.md index c7fc3b0..94c7a7d 100644 --- a/docs/README.md +++ b/docs/README.md @@ -28,6 +28,7 @@ read one page here, make it the threat model, especially before you put the dash - [Composer and mocks](COMPOSER_AND_MOCKS.md) - [Push](PUSH.md) - [State and feature flags](STATE_AND_FLAGS.md) +- [Remote Config](REMOTE_CONFIG.md) - [Crash and ANR capture](CRASH_AND_ANR.md) — all-thread dumps, breadcrumbs, `CrashPolicy`, and the Crashes surface on both web and Android - [Data inspectors, exports, and the More screen](DATA_INSPECTORS_AND_EXPORTS.md) — preferences, diff --git a/docs/REMOTE_CONFIG.md b/docs/REMOTE_CONFIG.md new file mode 100644 index 0000000..c8cbb3c --- /dev/null +++ b/docs/REMOTE_CONFIG.md @@ -0,0 +1,131 @@ +# Remote Config + +A read-only view of the Remote Config values active on the device: every key, its current value, and +— the part that actually matters — **where that value came from**. + +Knowing a flag reads `false` is rarely the hard part. The hard part is knowing whether it reads +`false` because that is what you published, or because the last fetch was throttled and the app fell +back to an in-app default. Those two situations look identical from inside the app and are the +difference between "the rollout works" and "the rollout never reached this device". + +## Registering a provider + +```kotlin +DevConsole.initialize( + application, + DevConsoleConfig(/* … */) + .withRemoteConfigProviders(listOf(FirebaseRemoteConfigAdapter(Firebase.remoteConfig))), +) +``` + +`FirebaseRemoteConfigAdapter` takes the `FirebaseRemoteConfig` instance as `Any` and reads it by +reflection, so DevConsole has **no compile-time Firebase dependency** — Firebase stays off the +classpath of consumers that do not use this adapter, exactly like `FirebaseRemoteMessageAdapter` for +Cloud Messaging. Add the adapter coordinate yourself; it is deliberately not re-exported by the +`devconsole` umbrella. + +```kotlin +debugImplementation("io.github.devconsole-android:devconsole-remote-config-firebase:") +releaseImplementation("io.github.devconsole-android:devconsole-remote-config-firebase-noop:") +``` + +A provider constructed later — through DI, or after a first fetch completes — can register itself: + +```kotlin +DevConsole.registerRemoteConfigProvider(FirebaseRemoteConfigAdapter(Firebase.remoteConfig)) +``` + +Late registration is supported here (unlike feature flags) because snapshots are pulled on demand +rather than captured at startup, so there is no race with a dashboard that already read an earlier +list. It returns `false` when the runtime is disabled or `CaptureCategory.STATE` is off. + +## Value sources + +| Source | Meaning | +| --- | --- | +| `remote` | Fetched from the server and activated. | +| `default` | An in-app default (`setDefaultsAsync`); no server value is active for this key. | +| `static` | Set nowhere — the SDK's static fallback for an unknown key. | +| `override` | A local override is masking whatever the provider resolved. | +| `unknown` | The provider could not attribute the value. Never guessed at. | + +Alongside the values, each provider reports its last fetch time, last fetch status (`success`, +`no_fetch_yet`, `failure`, `throttled`, `unknown`), and configured minimum fetch interval. A provider +that has never fetched reports a **null** timestamp and is rendered as "never" — never as an epoch +date. + +## Another Remote Config vendor + +The model is vendor-neutral. Implement `RemoteConfigProvider` for any other service: + +```kotlin +class ConfigCatProvider(private val client: ConfigCatClient) : RemoteConfigProvider { + override val id = "configcat" + + override fun snapshot() = RemoteConfigSnapshot( + providerId = id, + entries = client.allValues().map { (key, value) -> + RemoteConfigEntry(key, value.toString(), RemoteConfigSource.REMOTE) + }, + fetchInfo = RemoteConfigFetchInfo( + lastFetchEpochMs = client.lastRefreshMillis(), + status = RemoteConfigFetchStatus.SUCCESS, + minimumFetchIntervalSeconds = null, + ), + ) +} +``` + +`RemoteConfigRegistry` normalizes whatever you return: it caps values at 8 KB (setting +`truncated`), forces the registered id onto the snapshot, and — because a debugging tool must never +crash the app it exists to observe — converts a provider that throws into an `unavailableReason` +rather than propagating the exception. + +## Redaction + +Values are redacted by key name at a single boundary in `:sdk:full`, so the browser dashboard and the +on-device inspector both receive already-redacted entries. The key itself is never redacted: knowing +*which* value was withheld is the point of the view. + +Matching is separator-insensitive, which the raw `RedactionPolicy` is not. Its +`sensitiveFieldNames` defaults are an HTTP-header list (`api-key`, `apikey`) compared by exact name, +while Remote Config keys are written snake_case and camelCase — so `api_key` and `apiKey` are matched +against the policy's `api-key` here, instead of being displayed in full. Values are also run through +the engine's text patterns, so a bearer token pasted into an otherwise innocuous key is still caught. + +This remains allowlist-based: a key holding a secret under a name nobody thought to list is still +shown. Add your own names through `RedactionPolicy.sensitiveFieldNames`. + +## Dashboard and inspector + +The browser dashboard's **Remote Config** page (under Data, next to State & flags) lists each +provider with its fetch line and a Key / Value / Source table, filterable by key and by source. The +Compose inspector shows the same data as a section on its **Control** screen, beside feature flags. + +Both distinguish four states explicitly rather than rendering a blank table: no provider registered, +capture category disabled, provider unavailable, and "fetched nothing / never fetched". + +## Scope + +This inspector is **read-only**. DevConsole does not set overrides and does not trigger `fetch()` or +`activate()` — it observes the Remote Config lifecycle rather than driving it. The `override` source +is displayed when a host has applied one of its own. + +## REST + +`GET /api/v1/remote-config` (auth required, gated by `CaptureCategory.STATE`) returns every +provider's snapshot: + +```json +{"data":[{ + "id":"firebase", + "fetch":{"lastFetchEpochMs":1755043200000,"status":"success","minimumFetchIntervalSeconds":3600}, + "unavailableReason":null, + "entries":[ + {"key":"checkout_v2","value":"true","source":"remote","redacted":false,"truncated":false} + ] +}]} +``` + +See [PROTOCOL_REFERENCE.md](PROTOCOL_REFERENCE.md) and +[STATE_AND_FLAGS.md](STATE_AND_FLAGS.md) for the neighbouring surfaces. diff --git a/docs/STATE_AND_FLAGS.md b/docs/STATE_AND_FLAGS.md index af1f08c..e402b01 100644 --- a/docs/STATE_AND_FLAGS.md +++ b/docs/STATE_AND_FLAGS.md @@ -64,6 +64,12 @@ The State & Flags page shows a provider tree with sensitivity badges, and a flag source/default/current/override columns plus a "reset all session overrides" command. Every flag change produces both a command-audit record and a timeline event with the before/after values. +## Remote Config + +Values fetched from a Remote Config service are inspected separately, with source attribution +(remote / default / static / override) and fetch metadata — see [REMOTE_CONFIG.md](REMOTE_CONFIG.md). +It shares the `CaptureCategory.STATE` gate with everything on this page. + ## Flags with named options (environment switching) A flag is not limited to on/off. `FeatureFlag.ofOptions` declares a set of named values, which is diff --git a/gradle-plugin/src/main/kotlin/io/devconsole/gradle/DevConsoleVariantPolicyPlugin.kt b/gradle-plugin/src/main/kotlin/io/devconsole/gradle/DevConsoleVariantPolicyPlugin.kt index 688336f..0bfca6c 100644 --- a/gradle-plugin/src/main/kotlin/io/devconsole/gradle/DevConsoleVariantPolicyPlugin.kt +++ b/gradle-plugin/src/main/kotlin/io/devconsole/gradle/DevConsoleVariantPolicyPlugin.kt @@ -153,7 +153,8 @@ abstract class VerifyDevConsoleProtectedArtifactsTask : DefaultTask() { Regex( "^io\\.github\\.devconsole-android:" + "(?:devconsole|devconsole-network-okhttp|devconsole-mocks-okhttp|" + - "devconsole-socket-okhttp|devconsole-socket-paho|devconsole-push-firebase):.+", + "devconsole-socket-okhttp|devconsole-socket-paho|devconsole-push-firebase|" + + "devconsole-remote-config-firebase):.+", ) } } @@ -388,6 +389,7 @@ abstract class VerifyDevConsolePackagedArtifactTask : DefaultTask() { "DEVCONSOLE_ENABLED_MOCKS_OKHTTP_V1", "DEVCONSOLE_ENABLED_SOCKET_OKHTTP_V1", "DEVCONSOLE_ENABLED_PUSH_FIREBASE_V1", + "DEVCONSOLE_ENABLED_REMOTE_CONFIG_FIREBASE_V1", "Lio/devconsole/server/ktor/KtorLocalServerEngine;", "io.devconsole.DevConsoleInitializer", ".devconsoleinitializer", @@ -431,6 +433,7 @@ class DevConsoleVariantPolicyPlugin : Plugin { ":sdk:socket-okhttp", ":sdk:socket-paho", ":sdk:push-firebase", + ":sdk:remote-config-firebase", ), ) // PROTECTED by default: a release-signed staging/beta/preprod build type (anything not in diff --git a/gradle-plugin/src/test/kotlin/io/devconsole/gradle/NoopRuntimeExcludesFullModulesTest.kt b/gradle-plugin/src/test/kotlin/io/devconsole/gradle/NoopRuntimeExcludesFullModulesTest.kt index 92c467a..6c968f2 100644 --- a/gradle-plugin/src/test/kotlin/io/devconsole/gradle/NoopRuntimeExcludesFullModulesTest.kt +++ b/gradle-plugin/src/test/kotlin/io/devconsole/gradle/NoopRuntimeExcludesFullModulesTest.kt @@ -36,6 +36,7 @@ class NoopRuntimeExcludesFullModulesTest { "sdk/socket-okhttp-noop", "sdk/socket-paho-noop", "sdk/push-firebase-noop", + "sdk/remote-config-firebase-noop", ) /** @@ -59,6 +60,7 @@ class NoopRuntimeExcludesFullModulesTest { ":sdk:mocks-okhttp", ":sdk:socket-okhttp", ":sdk:socket-paho", + ":sdk:remote-config-firebase", ) @Test diff --git a/sdk/api/api/api.api b/sdk/api/api/api.api index a0b44a8..9ecff6e 100644 --- a/sdk/api/api/api.api +++ b/sdk/api/api/api.api @@ -256,6 +256,7 @@ public final class io/devconsole/api/DevConsoleConfig { public final fun getFeatureFlags ()Ljava/util/List; public final fun getOpenTriggers ()Lio/devconsole/api/OpenTriggers; public final fun getRedactionPolicy ()Lio/devconsole/security/RedactionPolicy; + public final fun getRemoteConfigProviders ()Ljava/util/List; public final fun getRetentionPolicy ()Lio/devconsole/api/RetentionPolicy; public final fun getScreenshotPolicy ()Lio/devconsole/api/ScreenshotPolicy; public final fun getSessionPolicy ()Lio/devconsole/api/SessionPolicy; @@ -274,6 +275,7 @@ public final class io/devconsole/api/DevConsoleConfig { public final fun withCrashPolicy (Lio/devconsole/api/CrashPolicy;)Lio/devconsole/api/DevConsoleConfig; public final fun withEditingCapabilities (Lio/devconsole/api/EditingCapabilities;)Lio/devconsole/api/DevConsoleConfig; public final fun withOpenTriggers (Lio/devconsole/api/OpenTriggers;)Lio/devconsole/api/DevConsoleConfig; + public final fun withRemoteConfigProviders (Ljava/util/List;)Lio/devconsole/api/DevConsoleConfig; public final fun withRetentionPolicy (Lio/devconsole/api/RetentionPolicy;)Lio/devconsole/api/DevConsoleConfig; public final fun withScreenshotPolicy (Lio/devconsole/api/ScreenshotPolicy;)Lio/devconsole/api/DevConsoleConfig; public final fun withSessionPolicy (Lio/devconsole/api/SessionPolicy;)Lio/devconsole/api/DevConsoleConfig; @@ -284,6 +286,7 @@ public final class io/devconsole/api/DevConsoleConfig$Builder { public fun ()V public final fun addCaptureCategory (Lio/devconsole/api/CaptureCategory;)Lio/devconsole/api/DevConsoleConfig$Builder; public final fun addFeatureFlag (Lio/devconsole/state/FeatureFlag;)Lio/devconsole/api/DevConsoleConfig$Builder; + public final fun addRemoteConfigProvider (Lio/devconsole/remoteconfig/RemoteConfigProvider;)Lio/devconsole/api/DevConsoleConfig$Builder; public final fun addStateProvider (Lio/devconsole/state/StateProvider;)Lio/devconsole/api/DevConsoleConfig$Builder; public final fun browserConfig (Lio/devconsole/api/BrowserConfig;)Lio/devconsole/api/DevConsoleConfig$Builder; public final fun build ()Lio/devconsole/api/DevConsoleConfig; @@ -320,6 +323,7 @@ public abstract interface class io/devconsole/api/DevConsoleFacadeProvider { public abstract fun networkRecorder ()Lio/devconsole/network/NetworkTransactionRecorder; public abstract fun openInspector (Landroid/content/Context;)Lio/devconsole/api/InspectorOpenResult; public abstract fun recordPush (Lio/devconsole/push/PushInput;)Lio/devconsole/push/PushEvent; + public abstract fun registerRemoteConfigProvider (Lio/devconsole/remoteconfig/RemoteConfigProvider;)Z public abstract fun registerStateProvider (Lio/devconsole/state/StateProvider;)Z public abstract fun socketRecorder ()Lio/devconsole/socket/SocketRecorder; public abstract fun startBrowser (Lio/devconsole/api/StartRequest;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; diff --git a/sdk/api/build.gradle.kts b/sdk/api/build.gradle.kts index ea1bd21..599ce9d 100644 --- a/sdk/api/build.gradle.kts +++ b/sdk/api/build.gradle.kts @@ -11,6 +11,7 @@ dependencies { api(project(":sdk:socket")) api(project(":sdk:push")) api(project(":sdk:state")) + api(project(":sdk:remote-config")) api(project(":sdk:security")) api(project(":sdk:mocks")) api(project(":sdk:logs")) diff --git a/sdk/api/src/main/kotlin/io/devconsole/api/DevConsoleConfig.kt b/sdk/api/src/main/kotlin/io/devconsole/api/DevConsoleConfig.kt index b17f144..61e31f6 100644 --- a/sdk/api/src/main/kotlin/io/devconsole/api/DevConsoleConfig.kt +++ b/sdk/api/src/main/kotlin/io/devconsole/api/DevConsoleConfig.kt @@ -1,5 +1,6 @@ package io.devconsole.api +import io.devconsole.remoteconfig.RemoteConfigProvider import io.devconsole.security.RedactionEngine import io.devconsole.security.RedactionPolicy import io.devconsole.state.FeatureFlag @@ -70,6 +71,14 @@ data class DevConsoleConfig( var openTriggers: OpenTriggers = OpenTriggers() private set + /** + * Remote Config sources the inspector reads. Like [stateProviders] these are pull-based, so a + * provider constructed after `initialize` can still be added through + * [io.devconsole.DevConsole.registerRemoteConfigProvider]. Gated by [CaptureCategory.STATE]. + */ + var remoteConfigProviders: List = emptyList() + private set + fun withStoragePolicy(value: StoragePolicy): DevConsoleConfig = duplicate().also { it.storagePolicy = value @@ -112,6 +121,9 @@ data class DevConsoleConfig( fun withOpenTriggers(value: OpenTriggers): DevConsoleConfig = duplicate().also { it.openTriggers = value } + fun withRemoteConfigProviders(value: List): DevConsoleConfig = + duplicate().also { it.remoteConfigProviders = value.toList() } + fun capturesCategory(category: CaptureCategory): Boolean = category in captureCategories /** @@ -160,7 +172,8 @@ data class DevConsoleConfig( crashPolicy == other.crashPolicy && screenshotPolicy == other.screenshotPolicy && captureCategories == other.captureCategories && - openTriggers == other.openTriggers + openTriggers == other.openTriggers && + remoteConfigProviders == other.remoteConfigProviders private fun duplicate(): DevConsoleConfig = copy().also { @@ -173,6 +186,7 @@ data class DevConsoleConfig( it.screenshotPolicy = screenshotPolicy it.captureCategories = captureCategories it.openTriggers = openTriggers + it.remoteConfigProviders = remoteConfigProviders } /** Mutable builder for Java callers and for incremental construction. */ @@ -194,6 +208,7 @@ data class DevConsoleConfig( private var screenshotPolicy = ScreenshotPolicy() private var captureCategories: Set = CaptureCategory.all() private var openTriggers = OpenTriggers() + private val remoteConfigProviders = mutableListOf() fun eventBufferCapacity(value: Int) = apply { eventBufferCapacity = value } @@ -229,6 +244,8 @@ data class DevConsoleConfig( fun openTriggers(value: OpenTriggers) = apply { openTriggers = value } + fun addRemoteConfigProvider(value: RemoteConfigProvider) = apply { remoteConfigProviders += value } + fun build(): DevConsoleConfig { val configured = DevConsoleConfig( @@ -247,6 +264,7 @@ data class DevConsoleConfig( .withScreenshotPolicy(screenshotPolicy) .withCaptureCategories(captureCategories) .withOpenTriggers(openTriggers) + .withRemoteConfigProviders(remoteConfigProviders) return retentionPolicy?.let(configured::withRetentionPolicy) ?: configured } } diff --git a/sdk/api/src/main/kotlin/io/devconsole/api/DevConsoleFacadeProvider.kt b/sdk/api/src/main/kotlin/io/devconsole/api/DevConsoleFacadeProvider.kt index a3fe94d..89426b1 100644 --- a/sdk/api/src/main/kotlin/io/devconsole/api/DevConsoleFacadeProvider.kt +++ b/sdk/api/src/main/kotlin/io/devconsole/api/DevConsoleFacadeProvider.kt @@ -8,6 +8,7 @@ import io.devconsole.mocks.MockEngine import io.devconsole.network.NetworkTransactionRecorder import io.devconsole.push.PushEvent import io.devconsole.push.PushInput +import io.devconsole.remoteconfig.RemoteConfigProvider import io.devconsole.socket.SocketRecorder import io.devconsole.state.StateProvider import kotlinx.coroutines.flow.StateFlow @@ -43,6 +44,19 @@ interface DevConsoleFacadeProvider { */ fun registerStateProvider(provider: StateProvider): Boolean + /** + * Registers a Remote Config source after [initialize]. Safe to call late -- unlike feature + * flags, providers here are read on demand rather than snapshotted at startup, so there is no + * race with a dashboard that already read an earlier list. Returns false if the runtime is + * disabled or [CaptureCategory.STATE] is off. + * + * Abstract, not defaulted, like every other member here: the compiler refusing to build a + * facade that misses a member is what guarantees full/no-op parity (see + * `NoopFacadeProviderContractTest`). A default would let the no-op facade silently inherit + * "registered nothing" for a capture-gated method instead of stating it deliberately. + */ + fun registerRemoteConfigProvider(provider: RemoteConfigProvider): Boolean + /** * The endpoint of the running server, or null when it is not running. [DevConsoleState.Running] * carries no payload, so without this a host that loses its [StartResult.Started] -- to an diff --git a/sdk/api/src/test/kotlin/io/devconsole/api/RemoteConfigConfigurationTest.kt b/sdk/api/src/test/kotlin/io/devconsole/api/RemoteConfigConfigurationTest.kt new file mode 100644 index 0000000..cde2109 --- /dev/null +++ b/sdk/api/src/test/kotlin/io/devconsole/api/RemoteConfigConfigurationTest.kt @@ -0,0 +1,67 @@ +/** + * @author Md. Asaduzzaman Nur + * @since 13/08/26 + */ +package io.devconsole.api + +import io.devconsole.remoteconfig.RemoteConfigFetchInfo +import io.devconsole.remoteconfig.RemoteConfigProvider +import io.devconsole.remoteconfig.RemoteConfigSnapshot +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class RemoteConfigConfigurationTest { + private fun provider(id: String): RemoteConfigProvider = + object : RemoteConfigProvider { + override val id: String = id + + override fun snapshot(): RemoteConfigSnapshot = + RemoteConfigSnapshot(id, emptyList(), RemoteConfigFetchInfo.unknown()) + } + + @Test + fun `defaults to no remote config providers`() { + assertTrue(DevConsoleConfig().remoteConfigProviders.isEmpty()) + } + + @Test + fun `carries providers supplied through the additive setter`() { + val config = DevConsoleConfig().withRemoteConfigProviders(listOf(provider("firebase"))) + + assertEquals(listOf("firebase"), config.remoteConfigProviders.map { it.id }) + } + + @Test + fun `the java builder accumulates providers`() { + val config = + DevConsoleConfig + .builder() + .addRemoteConfigProvider(provider("firebase")) + .addRemoteConfigProvider(provider("configcat")) + .build() + + assertEquals(listOf("firebase", "configcat"), config.remoteConfigProviders.map { it.id }) + } + + /** The additive fields survive every other `with…` copy, or a config silently loses providers. */ + @Test + fun `providers survive an unrelated policy copy`() { + val config = + DevConsoleConfig() + .withRemoteConfigProviders(listOf(provider("firebase"))) + .withCaptureCategories(CaptureCategory.all()) + .withCrashPolicy(CrashPolicy()) + + assertEquals(listOf("firebase"), config.remoteConfigProviders.map { it.id }) + } + + @Test + fun `runtime equivalence distinguishes differing providers`() { + val base = DevConsoleConfig().withRemoteConfigProviders(listOf(provider("firebase"))) + + assertFalse(base.runtimeEquivalentTo(DevConsoleConfig())) + assertTrue(base.runtimeEquivalentTo(base.withRemoteConfigProviders(base.remoteConfigProviders))) + } +} diff --git a/sdk/facade-shared/src/main/kotlin/io/devconsole/DevConsole.kt b/sdk/facade-shared/src/main/kotlin/io/devconsole/DevConsole.kt index fe46e32..84beae7 100644 --- a/sdk/facade-shared/src/main/kotlin/io/devconsole/DevConsole.kt +++ b/sdk/facade-shared/src/main/kotlin/io/devconsole/DevConsole.kt @@ -18,6 +18,7 @@ import io.devconsole.mocks.MockEngine import io.devconsole.network.NetworkTransactionRecorder import io.devconsole.push.PushEvent import io.devconsole.push.PushInput +import io.devconsole.remoteconfig.RemoteConfigProvider import io.devconsole.socket.SocketRecorder import io.devconsole.state.StateProvider import kotlinx.coroutines.CoroutineScope @@ -187,6 +188,14 @@ object DevConsole { @JvmStatic fun registerStateProvider(provider: StateProvider): Boolean = this.provider.registerStateProvider(provider) + /** + * Registers a Remote Config source after [initialize], for a client built lazily through DI. + * Returns false when the runtime is disabled or the STATE capture category is off. + */ + @JvmStatic + fun registerRemoteConfigProvider(provider: RemoteConfigProvider): Boolean = + this.provider.registerRemoteConfigProvider(provider) + /** Address of the running server, or null when it is not running. Survives activity recreation. */ @JvmStatic fun endpoint(): BrowserEndpoint? = provider.endpoint() diff --git a/sdk/full/api/full.api b/sdk/full/api/full.api index c39e91f..7440361 100644 --- a/sdk/full/api/full.api +++ b/sdk/full/api/full.api @@ -14,6 +14,7 @@ public final class io/devconsole/DevConsole { public static final fun networkRecorder ()Lio/devconsole/network/NetworkTransactionRecorder; public static final fun open (Landroid/content/Context;)Lio/devconsole/api/InspectorOpenResult; public static final fun recordPush (Lio/devconsole/push/PushInput;)Lio/devconsole/push/PushEvent; + public static final fun registerRemoteConfigProvider (Lio/devconsole/remoteconfig/RemoteConfigProvider;)Z public static final fun registerStateProvider (Lio/devconsole/state/StateProvider;)Z public static final fun socketRecorder ()Lio/devconsole/socket/SocketRecorder; public static final fun startBrowser (Lio/devconsole/api/StartRequest;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; diff --git a/sdk/full/src/main/kotlin/io/devconsole/FullInspectorDataSource.kt b/sdk/full/src/main/kotlin/io/devconsole/FullInspectorDataSource.kt index f90f9e2..2904534 100644 --- a/sdk/full/src/main/kotlin/io/devconsole/FullInspectorDataSource.kt +++ b/sdk/full/src/main/kotlin/io/devconsole/FullInspectorDataSource.kt @@ -33,6 +33,9 @@ import io.devconsole.network.NetworkTransactionQuery import io.devconsole.push.InMemoryPushStore import io.devconsole.push.PushEvent import io.devconsole.push.PushStore +import io.devconsole.remoteconfig.RemoteConfigRegistry +import io.devconsole.security.RedactionEngine +import io.devconsole.security.RedactionPolicy import io.devconsole.server.api.DatabaseExecResult import io.devconsole.server.api.DatabaseInspector import io.devconsole.server.api.DatabaseListingData @@ -85,6 +88,8 @@ import io.devconsole.ui.compose.InspectorPreferenceEntryUi import io.devconsole.ui.compose.InspectorPreferenceFileUi import io.devconsole.ui.compose.InspectorPushUi import io.devconsole.ui.compose.InspectorQueryResultUi +import io.devconsole.ui.compose.InspectorRemoteConfigEntryUi +import io.devconsole.ui.compose.InspectorRemoteConfigUi import io.devconsole.ui.compose.InspectorRetentionUi import io.devconsole.ui.compose.InspectorSessionUi import io.devconsole.ui.compose.InspectorSnapshot @@ -120,6 +125,11 @@ internal class FullInspectorDataSource( private val timelineSupplier: () -> Timeline? = { null }, private val featureFlagsSupplier: () -> FeatureFlagProvider? = { null }, private val stateRegistry: StateRegistry? = null, + /** + * Remote Config sources, read on demand. Null on a build where no host provider was registered, + * which reads as "no remote config" rather than as an error. + */ + private val remoteConfigRegistry: RemoteConfigRegistry? = null, private val preferencesInspector: PreferencesInspector? = null, private val fileInspector: FileInspector? = null, private val databaseInspector: DatabaseInspector? = null, @@ -342,6 +352,7 @@ internal class FullInspectorDataSource( crashes = if (CaptureCategory.CRASHES in categories) readCrashes() else emptyList(), featureFlags = if (stateOn) readFeatureFlags() else emptyList(), stateProviders = if (stateOn) readStateProviders() else emptyList(), + remoteConfig = if (stateOn) readRemoteConfig(config) else emptyList(), preferenceFiles = if (inspectionOn) preferencesInspector?.files().orEmpty().map { it.toUi() } else emptyList(), fileRoots = if (inspectionOn) fileInspector?.roots().orEmpty() else emptyList(), @@ -410,6 +421,35 @@ internal class FullInspectorDataSource( return provider.flags().map { flag -> flag.toUi(provider.value(flag.key), overrides.containsKey(flag.key)) } } + /** + * Redacts here rather than trusting the caller: this is the in-process path the Compose + * inspector reads, and it never passes through the server's redaction boundary. + */ + private fun readRemoteConfig(config: DevConsoleConfig?): List { + val registry = remoteConfigRegistry ?: return emptyList() + val policy = config?.redactionPolicy ?: RedactionPolicy.default() + val redacting = RedactingRemoteConfig(RedactionEngine(policy), policy) + return registry.snapshots().map { snapshot -> + InspectorRemoteConfigUi( + id = snapshot.providerId, + entries = + redacting.apply(snapshot.entries).map { entry -> + InspectorRemoteConfigEntryUi( + key = entry.key, + value = entry.value, + source = entry.source.wireName, + redacted = entry.redacted, + truncated = entry.truncated, + ) + }, + lastFetchEpochMs = snapshot.fetchInfo.lastFetchEpochMs, + status = snapshot.fetchInfo.status.wireName, + minimumFetchIntervalSeconds = snapshot.fetchInfo.minimumFetchIntervalSeconds, + unavailableReason = snapshot.unavailableReason, + ) + } + } + private fun readStateProviders(): List { val registry = stateRegistry ?: return emptyList() return registry.providerIds().mapNotNull { id -> diff --git a/sdk/full/src/main/kotlin/io/devconsole/PlatformFacadeProvider.kt b/sdk/full/src/main/kotlin/io/devconsole/PlatformFacadeProvider.kt index 8bf606b..6fd7e8f 100644 --- a/sdk/full/src/main/kotlin/io/devconsole/PlatformFacadeProvider.kt +++ b/sdk/full/src/main/kotlin/io/devconsole/PlatformFacadeProvider.kt @@ -44,6 +44,9 @@ import io.devconsole.push.PushRecorder import io.devconsole.push.PushSimulationCallback import io.devconsole.push.PushSimulator import io.devconsole.push.PushStore +import io.devconsole.remoteconfig.RemoteConfigProvider +import io.devconsole.remoteconfig.RemoteConfigRegistry +import io.devconsole.remoteconfig.RemoteConfigSnapshot import io.devconsole.security.RedactionEngine import io.devconsole.security.RedactionPolicy import io.devconsole.server.api.BrowserPrincipal @@ -171,6 +174,7 @@ internal class PlatformFacadeProvider : DevConsoleFacadeProvider { private val inMemoryPushStore = InMemoryPushStore() private val pushStore = TeeingPushStore(inMemoryPushStore, captureBridge, liveCaptureLock) private val stateRegistry = StateRegistry() + private val remoteConfigRegistry = RemoteConfigRegistry() private val mockEngineInstance = MockEngine(emptyList()).withOutcomeSink(::recordMockOutcome) /** Handed back by [mockEngine] instead of [mockEngineInstance] while MOCKS is off. Never mutated. */ @@ -694,6 +698,9 @@ internal class PlatformFacadeProvider : DevConsoleFacadeProvider { redaction.updatePolicy(config.redactionPolicy) if (config.capturesCategory(CaptureCategory.STATE)) { config.stateProviders.forEach(stateRegistry::register) + // A duplicate id from a host that both configured and late-registered a provider must + // not take down initialize(); the registration is simply ignored. + config.remoteConfigProviders.forEach { provider -> safely { remoteConfigRegistry.register(provider) } } } featureFlags = SessionFeatureFlags(config.featureFlags) buildOrReconfigureServerEngine( @@ -738,6 +745,7 @@ internal class PlatformFacadeProvider : DevConsoleFacadeProvider { timelineSupplier = { cachedTimeline }, featureFlagsSupplier = { if (::featureFlags.isInitialized) featureFlags else null }, stateRegistry = stateRegistry, + remoteConfigRegistry = remoteConfigRegistry, preferencesInspector = gatedPreferencesInspector, fileInspector = gatedFileInspector, databaseInspector = gatedDatabaseInspector, @@ -905,6 +913,10 @@ internal class PlatformFacadeProvider : DevConsoleFacadeProvider { socketStore = socketStore, pushStore = pushStore, stateRegistry = stateRegistry, + // Redacted here, not in the route: the Compose inspector reads the same registry + // in-process and never crosses the HTTP boundary, so this is the shared boundary both + // surfaces go through. + remoteConfigSnapshots = { redactedRemoteConfigSnapshots(config) }, featureFlags = featureFlags, featureFlagsEditable = featureFlagsEditable, mockEngine = mockEngineInstance, @@ -1111,6 +1123,17 @@ internal class PlatformFacadeProvider : DevConsoleFacadeProvider { override fun registerStateProvider(provider: StateProvider): Boolean = categoryEnabled(CaptureCategory.STATE) && safely { stateRegistry.register(provider) } + @Synchronized + override fun registerRemoteConfigProvider(provider: RemoteConfigProvider): Boolean = + categoryEnabled(CaptureCategory.STATE) && safely { remoteConfigRegistry.register(provider) } + + /** Empty when the STATE category is off, so the dashboard route cannot outflank the host's gate. */ + private fun redactedRemoteConfigSnapshots(config: DevConsoleConfig): List { + if (!config.capturesCategory(CaptureCategory.STATE)) return emptyList() + val redacting = RedactingRemoteConfig(redaction, config.redactionPolicy) + return remoteConfigRegistry.snapshots().map { it.copy(entries = redacting.apply(it.entries)) } + } + /** Late registration must never throw into the host; a rejected duplicate just returns false. */ private inline fun safely(block: () -> Unit): Boolean = runCatching(block).isSuccess diff --git a/sdk/full/src/main/kotlin/io/devconsole/RedactingRemoteConfig.kt b/sdk/full/src/main/kotlin/io/devconsole/RedactingRemoteConfig.kt new file mode 100644 index 0000000..43bf28d --- /dev/null +++ b/sdk/full/src/main/kotlin/io/devconsole/RedactingRemoteConfig.kt @@ -0,0 +1,61 @@ +/** + * @author Md. Asaduzzaman Nur + * @since 13/08/26 + */ +package io.devconsole + +import io.devconsole.remoteconfig.RemoteConfigEntry +import io.devconsole.security.RedactionEngine +import io.devconsole.security.RedactionPolicy + +/** + * The one redaction boundary for Remote Config values. + * + * It sits in `:sdk:full` rather than in `:sdk:server-ktor` on purpose: the Compose inspector reads + * the registry in-process through [FullInspectorDataSource] and never crosses the HTTP boundary, so + * redacting at the route would protect the browser and leave the on-device surface showing raw + * secrets. Applying it here means the JSON serializer and the Compose renderer both receive + * already-redacted entries and neither needs to know redaction exists. + */ +internal class RedactingRemoteConfig( + private val redaction: RedactionEngine, + policy: RedactionPolicy = RedactionPolicy.default(), +) { + private val sensitiveNames: Set = policy.sensitiveFieldNames.mapTo(mutableSetOf(), String::lowercase) + + private val collapsedNames: Set = sensitiveNames.mapTo(mutableSetOf()) { it.collapseSeparators() } + + private val replacement: String = policy.replacement + + fun apply(entries: List): List = entries.map(::redact) + + /** + * The key is deliberately never redacted: knowing *which* value was withheld is the point of the + * view, and the key name is what the host typed into the Remote Config console, not a secret. + */ + private fun redact(entry: RemoteConfigEntry): RemoteConfigEntry = + if (isSensitive(entry.key)) { + entry.copy(value = replacement, redacted = true) + } else { + // Still run the value through the engine: a non-sensitive key can hold a bearer token, + // and the engine's text patterns are what catch that. + val scrubbed = redaction.redactText(entry.value) + if (scrubbed == entry.value) entry else entry.copy(value = scrubbed, redacted = true) + } + + /** + * Matches separator-insensitively, which the raw policy does not. + * [RedactionPolicy.sensitiveFieldNames] is an HTTP-header list (`api-key`, `apikey`) compared by + * exact lowercased name, but Remote Config keys are written snake_case or camelCase. Without + * this, `api_key` -- the likeliest name for a secret accidentally shipped through Remote Config + * -- would not match the policy's `api-key` and would be displayed in full. + */ + private fun isSensitive(key: String): Boolean { + val lowered = key.lowercase() + return lowered in sensitiveNames || lowered.collapseSeparators() in collapsedNames + } + + private companion object { + fun String.collapseSeparators(): String = replace("-", "").replace("_", "") + } +} diff --git a/sdk/full/src/test/kotlin/io/devconsole/RemoteConfigInspectorTest.kt b/sdk/full/src/test/kotlin/io/devconsole/RemoteConfigInspectorTest.kt new file mode 100644 index 0000000..686b6f2 --- /dev/null +++ b/sdk/full/src/test/kotlin/io/devconsole/RemoteConfigInspectorTest.kt @@ -0,0 +1,218 @@ +/** + * @author Md. Asaduzzaman Nur + * @since 13/08/26 + */ +package io.devconsole + +import io.devconsole.api.CaptureCategory +import io.devconsole.api.DevConsoleConfig +import io.devconsole.mocks.MockEngine +import io.devconsole.network.InMemoryNetworkTransactionStore +import io.devconsole.network.NetworkCursorCodec +import io.devconsole.remoteconfig.RemoteConfigEntry +import io.devconsole.remoteconfig.RemoteConfigFetchInfo +import io.devconsole.remoteconfig.RemoteConfigFetchStatus +import io.devconsole.remoteconfig.RemoteConfigProvider +import io.devconsole.remoteconfig.RemoteConfigRegistry +import io.devconsole.remoteconfig.RemoteConfigSnapshot +import io.devconsole.remoteconfig.RemoteConfigSource +import io.devconsole.security.RedactionEngine +import io.devconsole.security.RedactionPolicy +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class RemoteConfigInspectorTest { + private fun registryWith(vararg entries: RemoteConfigEntry): RemoteConfigRegistry = + RemoteConfigRegistry().apply { + register( + object : RemoteConfigProvider { + override val id: String = "firebase" + + override fun snapshot(): RemoteConfigSnapshot = + RemoteConfigSnapshot( + providerId = "firebase", + entries = entries.toList(), + fetchInfo = + RemoteConfigFetchInfo( + lastFetchEpochMs = 1_755_043_200_000L, + status = RemoteConfigFetchStatus.SUCCESS, + minimumFetchIntervalSeconds = 3600L, + ), + ) + }, + ) + } + + private fun entry( + key: String, + value: String, + ) = RemoteConfigEntry(key = key, value = value, source = RemoteConfigSource.REMOTE) + + private fun source( + config: DevConsoleConfig, + registry: RemoteConfigRegistry, + ) = FullInspectorDataSource( + InMemoryNetworkTransactionStore(NetworkCursorCodec("network-cursor-key-1234567890".encodeToByteArray())), + MockEngine(emptyList()), + configSupplier = { config }, + remoteConfigRegistry = registry, + ) + + private fun enabledConfig() = DevConsoleConfig().withCaptureCategories(CaptureCategory.all()) + + @Test + fun `exposes remote config entries with their source`() { + val snapshot = source(enabledConfig(), registryWith(entry("checkout_v2", "true"))).snapshot() + + val provider = snapshot.remoteConfig.single() + assertEquals("firebase", provider.id) + assertEquals("checkout_v2", provider.entries.single().key) + assertEquals("true", provider.entries.single().value) + assertEquals(RemoteConfigSource.REMOTE.wireName, provider.entries.single().source) + } + + @Test + fun `carries fetch metadata onto the ui model`() { + val provider = source(enabledConfig(), registryWith(entry("k", "v"))).snapshot().remoteConfig.single() + + assertEquals(1_755_043_200_000L, provider.lastFetchEpochMs) + assertEquals(RemoteConfigFetchStatus.SUCCESS.wireName, provider.status) + assertEquals(3600L, provider.minimumFetchIntervalSeconds) + assertNull(provider.unavailableReason) + } + + @Test + fun `disabling the state category empties remote config`() { + val config = DevConsoleConfig().withCaptureCategories(CaptureCategory.all() - CaptureCategory.STATE) + + val snapshot = source(config, registryWith(entry("checkout_v2", "true"))).snapshot() + + assertTrue(snapshot.remoteConfig.isEmpty()) + } + + /** + * The Compose surface reads in-process and never crosses the HTTP boundary, so redaction applied + * only in the server would leave this path exposed. + */ + @Test + fun `redacts a sensitive key on the in-process compose path`() { + val snapshot = source(enabledConfig(), registryWith(entry("api_key", "super-secret"))).snapshot() + + val redacted = + snapshot.remoteConfig + .single() + .entries + .single() + assertEquals(RedactionPolicy.default().replacement, redacted.value) + assertTrue(redacted.redacted) + } + + @Test + fun `keeps the key readable so you can see which value was withheld`() { + val snapshot = source(enabledConfig(), registryWith(entry("api_key", "super-secret"))).snapshot() + + assertEquals( + "api_key", + snapshot.remoteConfig + .single() + .entries + .single() + .key, + ) + } + + @Test + fun `leaves an ordinary value untouched`() { + val snapshot = source(enabledConfig(), registryWith(entry("checkout_v2", "true"))).snapshot() + + val plain = + snapshot.remoteConfig + .single() + .entries + .single() + assertEquals("true", plain.value) + assertFalse(plain.redacted) + } + + @Test + fun `surfaces an unavailable provider rather than dropping it`() { + val registry = + RemoteConfigRegistry().apply { + register( + object : RemoteConfigProvider { + override val id: String = "firebase" + + override fun snapshot(): RemoteConfigSnapshot = error("firebase exploded") + }, + ) + } + + val provider = source(enabledConfig(), registry).snapshot().remoteConfig.single() + + assertEquals("firebase exploded", provider.unavailableReason) + assertTrue(provider.entries.isEmpty()) + } + + @Test + fun `a null registry yields no remote config rather than failing`() { + val plain = + FullInspectorDataSource( + InMemoryNetworkTransactionStore( + NetworkCursorCodec("network-cursor-key-1234567890".encodeToByteArray()), + ), + MockEngine(emptyList()), + configSupplier = { enabledConfig() }, + ) + + assertTrue(plain.snapshot().remoteConfig.isEmpty()) + } + + @Test + fun `redaction is applied by the shared boundary both surfaces read`() { + val entries = + redactingBoundary().apply( + listOf(entry("access_token", "raw"), entry("checkout_v2", "true")), + ) + + assertEquals(RedactionPolicy.default().replacement, entries.first().value) + assertTrue(entries.first().redacted) + assertEquals("true", entries.last().value) + assertFalse(entries.last().redacted) + } + + /** + * The stock policy is an HTTP-header list matched by exact name, but Remote Config keys are + * written snake_case and camelCase -- so `api_key` must still match the policy's `api-key`. + */ + @Test + fun `matches sensitive names across separator styles`() { + val entries = + redactingBoundary().apply( + listOf(entry("api_key", "raw"), entry("apiKey", "raw"), entry("API-KEY", "raw")), + ) + + assertTrue(entries.all { it.redacted }) + assertTrue(entries.all { it.value == RedactionPolicy.default().replacement }) + } + + @Test + fun `a bearer token inside an ordinary value is still scrubbed`() { + val entries = redactingBoundary().apply(listOf(entry("welcome_banner", "Bearer abc123def"))) + + assertTrue(entries.single().redacted) + assertFalse(entries.single().value.contains("abc123def")) + } + + @Test + fun `a separator-free ordinary key is not over-redacted`() { + val entries = redactingBoundary().apply(listOf(entry("checkout_v2", "true"), entry("monkey", "yes"))) + + assertTrue(entries.none { it.redacted }) + } + + private fun redactingBoundary() = + RedactingRemoteConfig(RedactionEngine(RedactionPolicy.default()), RedactionPolicy.default()) +} diff --git a/sdk/noop/api/noop.api b/sdk/noop/api/noop.api index b3fa416..0fa96f0 100644 --- a/sdk/noop/api/noop.api +++ b/sdk/noop/api/noop.api @@ -14,6 +14,7 @@ public final class io/devconsole/DevConsole { public static final fun networkRecorder ()Lio/devconsole/network/NetworkTransactionRecorder; public static final fun open (Landroid/content/Context;)Lio/devconsole/api/InspectorOpenResult; public static final fun recordPush (Lio/devconsole/push/PushInput;)Lio/devconsole/push/PushEvent; + public static final fun registerRemoteConfigProvider (Lio/devconsole/remoteconfig/RemoteConfigProvider;)Z public static final fun registerStateProvider (Lio/devconsole/state/StateProvider;)Z public static final fun socketRecorder ()Lio/devconsole/socket/SocketRecorder; public static final fun startBrowser (Lio/devconsole/api/StartRequest;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; diff --git a/sdk/noop/src/main/kotlin/io/devconsole/PlatformFacadeProvider.kt b/sdk/noop/src/main/kotlin/io/devconsole/PlatformFacadeProvider.kt index dddfb69..523fa18 100644 --- a/sdk/noop/src/main/kotlin/io/devconsole/PlatformFacadeProvider.kt +++ b/sdk/noop/src/main/kotlin/io/devconsole/PlatformFacadeProvider.kt @@ -25,6 +25,7 @@ import io.devconsole.push.InMemoryPushStore import io.devconsole.push.PushEvent import io.devconsole.push.PushInput import io.devconsole.push.PushRecorder +import io.devconsole.remoteconfig.RemoteConfigProvider import io.devconsole.security.RedactionEngine import io.devconsole.security.RedactionPolicy import io.devconsole.socket.InMemorySocketStore @@ -89,6 +90,8 @@ internal class PlatformFacadeProvider : DevConsoleFacadeProvider { override fun registerStateProvider(provider: StateProvider): Boolean = false + override fun registerRemoteConfigProvider(provider: RemoteConfigProvider): Boolean = false + override fun endpoint(): BrowserEndpoint? = null override fun accessInfo(): AccessInfo? = null diff --git a/sdk/remote-config-firebase-noop/api/remote-config-firebase-noop.api b/sdk/remote-config-firebase-noop/api/remote-config-firebase-noop.api new file mode 100644 index 0000000..270f7c1 --- /dev/null +++ b/sdk/remote-config-firebase-noop/api/remote-config-firebase-noop.api @@ -0,0 +1,8 @@ +public final class io/devconsole/remoteconfig/firebase/FirebaseRemoteConfigAdapter : io/devconsole/remoteconfig/RemoteConfigProvider { + public fun (Ljava/lang/Object;)V + public fun (Ljava/lang/Object;Ljava/lang/String;)V + public synthetic fun (Ljava/lang/Object;Ljava/lang/String;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public fun getId ()Ljava/lang/String; + public fun snapshot ()Lio/devconsole/remoteconfig/RemoteConfigSnapshot; +} + diff --git a/sdk/remote-config-firebase-noop/build.gradle.kts b/sdk/remote-config-firebase-noop/build.gradle.kts new file mode 100644 index 0000000..d6ec1b8 --- /dev/null +++ b/sdk/remote-config-firebase-noop/build.gradle.kts @@ -0,0 +1,11 @@ +plugins { + id("devconsole.android.library") + id("devconsole.quality") + id("devconsole.publishing") +} + +android { namespace = "io.devconsole.remoteconfig.firebase.noop" } + +dependencies { + api(project(":sdk:remote-config")) +} diff --git a/sdk/remote-config-firebase-noop/src/main/kotlin/io/devconsole/remoteconfig/firebase/FirebaseRemoteConfigAdapter.kt b/sdk/remote-config-firebase-noop/src/main/kotlin/io/devconsole/remoteconfig/firebase/FirebaseRemoteConfigAdapter.kt new file mode 100644 index 0000000..b275288 --- /dev/null +++ b/sdk/remote-config-firebase-noop/src/main/kotlin/io/devconsole/remoteconfig/firebase/FirebaseRemoteConfigAdapter.kt @@ -0,0 +1,31 @@ +/** + * @author Md. Asaduzzaman Nur + * @since 13/08/26 + */ +package io.devconsole.remoteconfig.firebase + +import io.devconsole.remoteconfig.RemoteConfigFetchInfo +import io.devconsole.remoteconfig.RemoteConfigProvider +import io.devconsole.remoteconfig.RemoteConfigSnapshot + +/** + * Protected-build adapter: does not reflect on or read the supplied Firebase instance. + * + * It reports `disabled-build` rather than an empty config, because "this build cannot show you + * Remote Config" and "this app has no Remote Config values" are different answers, and silently + * returning the second would be a misleading debugging tool. + */ +class FirebaseRemoteConfigAdapter + @JvmOverloads + constructor( + @Suppress("UNUSED_PARAMETER") remoteConfig: Any, + override val id: String = "firebase", + ) : RemoteConfigProvider { + override fun snapshot(): RemoteConfigSnapshot = + RemoteConfigSnapshot( + providerId = id, + entries = emptyList(), + fetchInfo = RemoteConfigFetchInfo.unknown(), + unavailableReason = "disabled-build", + ) + } diff --git a/sdk/remote-config-firebase-noop/src/test/kotlin/io/devconsole/remoteconfig/firebase/FirebaseRemoteConfigAdapterNoopTest.kt b/sdk/remote-config-firebase-noop/src/test/kotlin/io/devconsole/remoteconfig/firebase/FirebaseRemoteConfigAdapterNoopTest.kt new file mode 100644 index 0000000..836b410 --- /dev/null +++ b/sdk/remote-config-firebase-noop/src/test/kotlin/io/devconsole/remoteconfig/firebase/FirebaseRemoteConfigAdapterNoopTest.kt @@ -0,0 +1,62 @@ +/** + * @author Md. Asaduzzaman Nur + * @since 13/08/26 + */ +package io.devconsole.remoteconfig.firebase + +import io.devconsole.remoteconfig.RemoteConfigFetchStatus +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class FirebaseRemoteConfigAdapterNoopTest { + private class SpyRemoteConfig { + var touched: Boolean = false + + fun getAll(): Map { + touched = true + return emptyMap() + } + + fun getInfo(): Any { + touched = true + return Any() + } + } + + @Test + fun `reports no entries in a protected build`() { + assertTrue(FirebaseRemoteConfigAdapter(SpyRemoteConfig()).snapshot().entries.isEmpty()) + } + + @Test + fun `labels itself a disabled build rather than pretending config is simply empty`() { + assertEquals("disabled-build", FirebaseRemoteConfigAdapter(SpyRemoteConfig()).snapshot().unavailableReason) + } + + @Test + fun `never reflects on the supplied firebase instance`() { + val spy = SpyRemoteConfig() + + FirebaseRemoteConfigAdapter(spy).snapshot() + + assertFalse(spy.touched) + } + + @Test + fun `reports no fetch metadata`() { + val fetch = FirebaseRemoteConfigAdapter(SpyRemoteConfig()).snapshot().fetchInfo + + assertEquals(RemoteConfigFetchStatus.UNKNOWN, fetch.status) + assertNull(fetch.lastFetchEpochMs) + assertNull(fetch.minimumFetchIntervalSeconds) + } + + @Test + fun `keeps the same id contract as the enabled adapter`() { + assertEquals("firebase", FirebaseRemoteConfigAdapter(SpyRemoteConfig()).id) + assertEquals("rc-staging", FirebaseRemoteConfigAdapter(SpyRemoteConfig(), "rc-staging").id) + } +} diff --git a/sdk/remote-config-firebase/api/remote-config-firebase.api b/sdk/remote-config-firebase/api/remote-config-firebase.api new file mode 100644 index 0000000..3cd1bda --- /dev/null +++ b/sdk/remote-config-firebase/api/remote-config-firebase.api @@ -0,0 +1,15 @@ +public final class io/devconsole/remoteconfig/firebase/FirebaseRemoteConfigAdapter : io/devconsole/remoteconfig/RemoteConfigProvider { + public static final field LAST_FETCH_STATUS_FAILURE I + public static final field LAST_FETCH_STATUS_NO_FETCH_YET I + public static final field LAST_FETCH_STATUS_SUCCESS I + public static final field LAST_FETCH_STATUS_THROTTLED I + public static final field VALUE_SOURCE_DEFAULT I + public static final field VALUE_SOURCE_REMOTE I + public static final field VALUE_SOURCE_STATIC I + public fun (Ljava/lang/Object;)V + public fun (Ljava/lang/Object;Ljava/lang/String;)V + public synthetic fun (Ljava/lang/Object;Ljava/lang/String;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public fun getId ()Ljava/lang/String; + public fun snapshot ()Lio/devconsole/remoteconfig/RemoteConfigSnapshot; +} + diff --git a/sdk/remote-config-firebase/build.gradle.kts b/sdk/remote-config-firebase/build.gradle.kts new file mode 100644 index 0000000..23661f1 --- /dev/null +++ b/sdk/remote-config-firebase/build.gradle.kts @@ -0,0 +1,12 @@ +plugins { + id("devconsole.android.library") + id("devconsole.quality") + id("devconsole.publishing") +} +android { + namespace = "io.devconsole.remoteconfig.firebase" + defaultConfig { consumerProguardFiles("consumer-rules.pro") } +} +// `api`, not `implementation`: the adapter implements the public RemoteConfigProvider interface and +// hosts must name that type to hand the adapter to DevConsoleConfig. +dependencies { api(project(":sdk:remote-config")) } diff --git a/sdk/remote-config-firebase/consumer-rules.pro b/sdk/remote-config-firebase/consumer-rules.pro new file mode 100644 index 0000000..5420daa --- /dev/null +++ b/sdk/remote-config-firebase/consumer-rules.pro @@ -0,0 +1 @@ +-keep class io.devconsole.internal.enabled.RemoteConfigFirebaseCaptureMarker { *; } diff --git a/sdk/remote-config-firebase/src/main/kotlin/io/devconsole/internal/enabled/RemoteConfigFirebaseCaptureMarker.kt b/sdk/remote-config-firebase/src/main/kotlin/io/devconsole/internal/enabled/RemoteConfigFirebaseCaptureMarker.kt new file mode 100644 index 0000000..757c128 --- /dev/null +++ b/sdk/remote-config-firebase/src/main/kotlin/io/devconsole/internal/enabled/RemoteConfigFirebaseCaptureMarker.kt @@ -0,0 +1,9 @@ +/** + * @author Md. Asaduzzaman Nur + * @since 13/08/26 + */ +package io.devconsole.internal.enabled + +internal object RemoteConfigFirebaseCaptureMarker { + const val SIGNATURE = "DEVCONSOLE_ENABLED_REMOTE_CONFIG_FIREBASE_V1" +} diff --git a/sdk/remote-config-firebase/src/main/kotlin/io/devconsole/remoteconfig/firebase/FirebaseRemoteConfigAdapter.kt b/sdk/remote-config-firebase/src/main/kotlin/io/devconsole/remoteconfig/firebase/FirebaseRemoteConfigAdapter.kt new file mode 100644 index 0000000..0306ff0 --- /dev/null +++ b/sdk/remote-config-firebase/src/main/kotlin/io/devconsole/remoteconfig/firebase/FirebaseRemoteConfigAdapter.kt @@ -0,0 +1,110 @@ +/** + * @author Md. Asaduzzaman Nur + * @since 13/08/26 + */ +package io.devconsole.remoteconfig.firebase + +import io.devconsole.remoteconfig.RemoteConfigEntry +import io.devconsole.remoteconfig.RemoteConfigFetchInfo +import io.devconsole.remoteconfig.RemoteConfigFetchStatus +import io.devconsole.remoteconfig.RemoteConfigProvider +import io.devconsole.remoteconfig.RemoteConfigSnapshot +import io.devconsole.remoteconfig.RemoteConfigSource + +/** + * Optional Firebase bridge with no Firebase compile-time dependency. Consumers pass a + * `com.google.firebase.remoteconfig.FirebaseRemoteConfig`; reflection keeps Firebase absent + * everywhere else, exactly as `FirebaseRemoteMessageAdapter` does for Cloud Messaging. + */ +class FirebaseRemoteConfigAdapter + @JvmOverloads + constructor( + private val remoteConfig: Any, + override val id: String = "firebase", + ) : RemoteConfigProvider { + override fun snapshot(): RemoteConfigSnapshot = + RemoteConfigSnapshot( + providerId = id, + entries = readEntries(), + fetchInfo = readFetchInfo(), + ) + + /** + * Sorted by key: Firebase hands back an unordered map, and an inspector whose rows reshuffle + * on every refresh is unreadable when you are watching one key. + */ + private fun readEntries(): List { + val all = remoteConfig.call("getAll") as? Map<*, *> ?: return emptyList() + return all.entries + .mapNotNull { (key, value) -> + val name = key as? String ?: return@mapNotNull null + RemoteConfigEntry( + key = name, + value = value?.call("asString") as? String ?: "", + source = sourceOf(value), + ) + }.sortedBy(RemoteConfigEntry::key) + } + + private fun sourceOf(value: Any?): RemoteConfigSource = + when ((value?.call("getSource") as? Number)?.toInt()) { + constant("VALUE_SOURCE_REMOTE", VALUE_SOURCE_REMOTE) -> RemoteConfigSource.REMOTE + constant("VALUE_SOURCE_DEFAULT", VALUE_SOURCE_DEFAULT) -> RemoteConfigSource.DEFAULT + constant("VALUE_SOURCE_STATIC", VALUE_SOURCE_STATIC) -> RemoteConfigSource.STATIC + else -> RemoteConfigSource.UNKNOWN + } + + private fun readFetchInfo(): RemoteConfigFetchInfo { + val info = remoteConfig.call("getInfo") ?: return RemoteConfigFetchInfo.unknown() + return RemoteConfigFetchInfo( + lastFetchEpochMs = (info.call("getFetchTimeMillis") as? Number)?.toLong()?.takeIf { it > 0 }, + status = statusOf(info), + minimumFetchIntervalSeconds = + ( + info + .call("getConfigSettings") + ?.call("getMinimumFetchIntervalInSeconds") as? Number + )?.toLong(), + ) + } + + private fun statusOf(info: Any): RemoteConfigFetchStatus = + when ((info.call("getLastFetchStatus") as? Number)?.toInt()) { + constant("LAST_FETCH_STATUS_SUCCESS", LAST_FETCH_STATUS_SUCCESS) -> RemoteConfigFetchStatus.SUCCESS + constant("LAST_FETCH_STATUS_NO_FETCH_YET", LAST_FETCH_STATUS_NO_FETCH_YET) -> + RemoteConfigFetchStatus.NO_FETCH_YET + constant("LAST_FETCH_STATUS_FAILURE", LAST_FETCH_STATUS_FAILURE) -> RemoteConfigFetchStatus.FAILURE + constant( + "LAST_FETCH_STATUS_THROTTLED", + LAST_FETCH_STATUS_THROTTLED, + ), + -> RemoteConfigFetchStatus.THROTTLED + else -> RemoteConfigFetchStatus.UNKNOWN + } + + /** + * Prefers the constant declared on the supplied Firebase class over the literal below, so a + * future renumbering in the Firebase SDK cannot silently mis-badge every row. + */ + private fun constant( + name: String, + fallback: Int, + ): Int = runCatching { remoteConfig.javaClass.getField(name).getInt(null) }.getOrDefault(fallback) + + private fun Any.call(name: String): Any? = + runCatching { + javaClass.methods.firstOrNull { it.name == name && it.parameterCount == 0 }?.invoke(this) + }.getOrNull() + + private companion object { + // Verified against firebase-android-sdk's FirebaseRemoteConfig.java. LAST_FETCH_STATUS_SUCCESS + // is -1, not 0 -- treating "negative" as unknown would mislabel every successful fetch. + const val VALUE_SOURCE_STATIC = 0 + const val VALUE_SOURCE_DEFAULT = 1 + const val VALUE_SOURCE_REMOTE = 2 + const val LAST_FETCH_STATUS_SUCCESS = -1 + const val LAST_FETCH_STATUS_NO_FETCH_YET = 0 + const val LAST_FETCH_STATUS_FAILURE = 1 + const val LAST_FETCH_STATUS_THROTTLED = 2 + } + } diff --git a/sdk/remote-config-firebase/src/test/kotlin/io/devconsole/remoteconfig/firebase/FirebaseRemoteConfigAdapterTest.kt b/sdk/remote-config-firebase/src/test/kotlin/io/devconsole/remoteconfig/firebase/FirebaseRemoteConfigAdapterTest.kt new file mode 100644 index 0000000..a4acaea --- /dev/null +++ b/sdk/remote-config-firebase/src/test/kotlin/io/devconsole/remoteconfig/firebase/FirebaseRemoteConfigAdapterTest.kt @@ -0,0 +1,208 @@ +/** + * @author Md. Asaduzzaman Nur + * @since 13/08/26 + */ +package io.devconsole.remoteconfig.firebase + +import io.devconsole.remoteconfig.RemoteConfigFetchStatus +import io.devconsole.remoteconfig.RemoteConfigSource +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * Drives the adapter with plain Kotlin stand-ins whose method names match Firebase's, the same + * technique `FirebaseRemoteMessageAdapterTest` uses -- so the real Firebase SDK never enters this + * module's test classpath, which is the whole point of the reflection bridge. + */ +class FirebaseRemoteConfigAdapterTest { + private class FakeValue( + private val value: String, + val source: Int, + ) { + fun asString(): String = value + } + + private class FakeSettings( + val minimumFetchIntervalInSeconds: Long, + ) + + private class FakeInfo( + val fetchTimeMillis: Long, + val lastFetchStatus: Int, + val configSettings: FakeSettings = FakeSettings(3600L), + ) + + private class FakeRemoteConfig( + private val all: Map, + private val info: FakeInfo = FakeInfo(FETCH_TIME, SUCCESS), + ) { + fun getAll(): Map = all + + fun getInfo(): FakeInfo = info + } + + @Test + fun `maps firebase value sources onto the vendor-neutral enum`() { + val adapter = + FirebaseRemoteConfigAdapter( + FakeRemoteConfig( + mapOf( + "fromServer" to FakeValue("a", VALUE_SOURCE_REMOTE), + "fromDefaults" to FakeValue("b", VALUE_SOURCE_DEFAULT), + "fromNowhere" to FakeValue("c", VALUE_SOURCE_STATIC), + ), + ), + ) + + val bySource = adapter.snapshot().entries.associate { it.key to it.source } + + assertEquals(RemoteConfigSource.REMOTE, bySource["fromServer"]) + assertEquals(RemoteConfigSource.DEFAULT, bySource["fromDefaults"]) + assertEquals(RemoteConfigSource.STATIC, bySource["fromNowhere"]) + } + + @Test + fun `an unrecognised source integer reads as unknown rather than being guessed`() { + val adapter = FirebaseRemoteConfigAdapter(FakeRemoteConfig(mapOf("k" to FakeValue("v", 99)))) + + assertEquals( + RemoteConfigSource.UNKNOWN, + adapter + .snapshot() + .entries + .single() + .source, + ) + } + + @Test + fun `reads the value through asString`() { + val adapter = + FirebaseRemoteConfigAdapter(FakeRemoteConfig(mapOf("k" to FakeValue("hello", VALUE_SOURCE_REMOTE)))) + + assertEquals( + "hello", + adapter + .snapshot() + .entries + .single() + .value, + ) + } + + /** Firebase's LAST_FETCH_STATUS_SUCCESS is -1, so a "negative means unknown" guess breaks every success. */ + @Test + fun `fetch status success is the negative constant`() { + val adapter = fetchInfoAdapter(FakeInfo(FETCH_TIME, SUCCESS)) + + assertEquals(RemoteConfigFetchStatus.SUCCESS, adapter.snapshot().fetchInfo.status) + } + + @Test + fun `maps the remaining fetch statuses`() { + assertEquals( + RemoteConfigFetchStatus.NO_FETCH_YET, + fetchInfoAdapter(FakeInfo(FETCH_TIME, NO_FETCH_YET)).snapshot().fetchInfo.status, + ) + assertEquals( + RemoteConfigFetchStatus.FAILURE, + fetchInfoAdapter(FakeInfo(FETCH_TIME, FAILURE)).snapshot().fetchInfo.status, + ) + assertEquals( + RemoteConfigFetchStatus.THROTTLED, + fetchInfoAdapter(FakeInfo(FETCH_TIME, THROTTLED)).snapshot().fetchInfo.status, + ) + } + + @Test + fun `an unrecognised fetch status reads as unknown`() { + assertEquals( + RemoteConfigFetchStatus.UNKNOWN, + fetchInfoAdapter(FakeInfo(FETCH_TIME, 77)).snapshot().fetchInfo.status, + ) + } + + /** Firebase reports -1 for "no fetch yet"; rendering that raw would date the fetch to 1969. */ + @Test + fun `a negative fetch time reads as never fetched rather than an epoch sentinel`() { + val adapter = fetchInfoAdapter(FakeInfo(-1L, NO_FETCH_YET)) + + assertNull(adapter.snapshot().fetchInfo.lastFetchEpochMs) + } + + @Test + fun `a real fetch time is carried through`() { + val adapter = fetchInfoAdapter(FakeInfo(FETCH_TIME, SUCCESS)) + + assertEquals(FETCH_TIME, adapter.snapshot().fetchInfo.lastFetchEpochMs) + } + + @Test + fun `reads the minimum fetch interval from the nested config settings`() { + val adapter = fetchInfoAdapter(FakeInfo(FETCH_TIME, SUCCESS, FakeSettings(43_200L))) + + assertEquals(43_200L, adapter.snapshot().fetchInfo.minimumFetchIntervalSeconds) + } + + @Test + fun `entries are sorted by key so a refresh does not reshuffle the table`() { + val adapter = + FirebaseRemoteConfigAdapter( + FakeRemoteConfig( + mapOf( + "zeta" to FakeValue("z", VALUE_SOURCE_REMOTE), + "alpha" to FakeValue("a", VALUE_SOURCE_REMOTE), + "mid" to FakeValue("m", VALUE_SOURCE_REMOTE), + ), + ), + ) + + assertEquals(listOf("alpha", "mid", "zeta"), adapter.snapshot().entries.map { it.key }) + } + + @Test + fun `an object that is not firebase shaped yields an unavailable snapshot instead of throwing`() { + val snapshot = FirebaseRemoteConfigAdapter(Any()).snapshot() + + assertTrue(snapshot.entries.isEmpty()) + assertEquals(RemoteConfigFetchStatus.UNKNOWN, snapshot.fetchInfo.status) + assertNull(snapshot.fetchInfo.lastFetchEpochMs) + } + + @Test + fun `a remote config whose getAll throws does not propagate`() { + val exploding = + object { + fun getAll(): Map = error("firebase exploded") + + fun getInfo(): FakeInfo = FakeInfo(FETCH_TIME, SUCCESS) + } + + assertTrue(FirebaseRemoteConfigAdapter(exploding).snapshot().entries.isEmpty()) + } + + @Test + fun `defaults its provider id to firebase and honours an explicit one`() { + assertEquals("firebase", FirebaseRemoteConfigAdapter(FakeRemoteConfig(emptyMap())).id) + assertEquals("rc-staging", FirebaseRemoteConfigAdapter(FakeRemoteConfig(emptyMap()), "rc-staging").id) + assertEquals( + "rc-staging", + FirebaseRemoteConfigAdapter(FakeRemoteConfig(emptyMap()), "rc-staging").snapshot().providerId, + ) + } + + private fun fetchInfoAdapter(info: FakeInfo) = FirebaseRemoteConfigAdapter(FakeRemoteConfig(emptyMap(), info)) + + private companion object { + const val VALUE_SOURCE_STATIC = 0 + const val VALUE_SOURCE_DEFAULT = 1 + const val VALUE_SOURCE_REMOTE = 2 + const val SUCCESS = -1 + const val NO_FETCH_YET = 0 + const val FAILURE = 1 + const val THROTTLED = 2 + const val FETCH_TIME = 1_755_043_200_000L + } +} diff --git a/sdk/remote-config/api/remote-config.api b/sdk/remote-config/api/remote-config.api new file mode 100644 index 0000000..96604da --- /dev/null +++ b/sdk/remote-config/api/remote-config.api @@ -0,0 +1,107 @@ +public final class io/devconsole/remoteconfig/RemoteConfigEntry { + public fun (Ljava/lang/String;Ljava/lang/String;Lio/devconsole/remoteconfig/RemoteConfigSource;ZZ)V + public synthetic fun (Ljava/lang/String;Ljava/lang/String;Lio/devconsole/remoteconfig/RemoteConfigSource;ZZILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1 ()Ljava/lang/String; + public final fun component2 ()Ljava/lang/String; + public final fun component3 ()Lio/devconsole/remoteconfig/RemoteConfigSource; + public final fun component4 ()Z + public final fun component5 ()Z + public final fun copy (Ljava/lang/String;Ljava/lang/String;Lio/devconsole/remoteconfig/RemoteConfigSource;ZZ)Lio/devconsole/remoteconfig/RemoteConfigEntry; + public static synthetic fun copy$default (Lio/devconsole/remoteconfig/RemoteConfigEntry;Ljava/lang/String;Ljava/lang/String;Lio/devconsole/remoteconfig/RemoteConfigSource;ZZILjava/lang/Object;)Lio/devconsole/remoteconfig/RemoteConfigEntry; + public fun equals (Ljava/lang/Object;)Z + public final fun getKey ()Ljava/lang/String; + public final fun getRedacted ()Z + public final fun getSource ()Lio/devconsole/remoteconfig/RemoteConfigSource; + public final fun getTruncated ()Z + public final fun getValue ()Ljava/lang/String; + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + +public final class io/devconsole/remoteconfig/RemoteConfigFetchInfo { + public static final field Companion Lio/devconsole/remoteconfig/RemoteConfigFetchInfo$Companion; + public fun (Ljava/lang/Long;Lio/devconsole/remoteconfig/RemoteConfigFetchStatus;Ljava/lang/Long;)V + public final fun component1 ()Ljava/lang/Long; + public final fun component2 ()Lio/devconsole/remoteconfig/RemoteConfigFetchStatus; + public final fun component3 ()Ljava/lang/Long; + public final fun copy (Ljava/lang/Long;Lio/devconsole/remoteconfig/RemoteConfigFetchStatus;Ljava/lang/Long;)Lio/devconsole/remoteconfig/RemoteConfigFetchInfo; + public static synthetic fun copy$default (Lio/devconsole/remoteconfig/RemoteConfigFetchInfo;Ljava/lang/Long;Lio/devconsole/remoteconfig/RemoteConfigFetchStatus;Ljava/lang/Long;ILjava/lang/Object;)Lio/devconsole/remoteconfig/RemoteConfigFetchInfo; + public fun equals (Ljava/lang/Object;)Z + public final fun getLastFetchEpochMs ()Ljava/lang/Long; + public final fun getMinimumFetchIntervalSeconds ()Ljava/lang/Long; + public final fun getStatus ()Lio/devconsole/remoteconfig/RemoteConfigFetchStatus; + public fun hashCode ()I + public fun toString ()Ljava/lang/String; + public static final fun unknown ()Lio/devconsole/remoteconfig/RemoteConfigFetchInfo; +} + +public final class io/devconsole/remoteconfig/RemoteConfigFetchInfo$Companion { + public final fun unknown ()Lio/devconsole/remoteconfig/RemoteConfigFetchInfo; +} + +public final class io/devconsole/remoteconfig/RemoteConfigFetchStatus : java/lang/Enum { + public static final field FAILURE Lio/devconsole/remoteconfig/RemoteConfigFetchStatus; + public static final field NO_FETCH_YET Lio/devconsole/remoteconfig/RemoteConfigFetchStatus; + public static final field SUCCESS Lio/devconsole/remoteconfig/RemoteConfigFetchStatus; + public static final field THROTTLED Lio/devconsole/remoteconfig/RemoteConfigFetchStatus; + public static final field UNKNOWN Lio/devconsole/remoteconfig/RemoteConfigFetchStatus; + public static fun getEntries ()Lkotlin/enums/EnumEntries; + public final fun getWireName ()Ljava/lang/String; + public static fun valueOf (Ljava/lang/String;)Lio/devconsole/remoteconfig/RemoteConfigFetchStatus; + public static fun values ()[Lio/devconsole/remoteconfig/RemoteConfigFetchStatus; +} + +public abstract interface class io/devconsole/remoteconfig/RemoteConfigProvider { + public abstract fun getId ()Ljava/lang/String; + public abstract fun snapshot ()Lio/devconsole/remoteconfig/RemoteConfigSnapshot; +} + +public final class io/devconsole/remoteconfig/RemoteConfigRegistry { + public static final field Companion Lio/devconsole/remoteconfig/RemoteConfigRegistry$Companion; + public static final field MAX_VALUE_LENGTH I + public fun ()V + public final fun providerIds ()Ljava/util/List; + public final fun register (Lio/devconsole/remoteconfig/RemoteConfigProvider;)V + public final fun snapshot (Ljava/lang/String;)Lio/devconsole/remoteconfig/RemoteConfigSnapshot; + public final fun snapshots ()Ljava/util/List; +} + +public final class io/devconsole/remoteconfig/RemoteConfigRegistry$Companion { +} + +public final class io/devconsole/remoteconfig/RemoteConfigSnapshot { + public fun (Ljava/lang/String;Ljava/util/List;Lio/devconsole/remoteconfig/RemoteConfigFetchInfo;Ljava/lang/String;)V + public synthetic fun (Ljava/lang/String;Ljava/util/List;Lio/devconsole/remoteconfig/RemoteConfigFetchInfo;Ljava/lang/String;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1 ()Ljava/lang/String; + public final fun component2 ()Ljava/util/List; + public final fun component3 ()Lio/devconsole/remoteconfig/RemoteConfigFetchInfo; + public final fun component4 ()Ljava/lang/String; + public final fun copy (Ljava/lang/String;Ljava/util/List;Lio/devconsole/remoteconfig/RemoteConfigFetchInfo;Ljava/lang/String;)Lio/devconsole/remoteconfig/RemoteConfigSnapshot; + public static synthetic fun copy$default (Lio/devconsole/remoteconfig/RemoteConfigSnapshot;Ljava/lang/String;Ljava/util/List;Lio/devconsole/remoteconfig/RemoteConfigFetchInfo;Ljava/lang/String;ILjava/lang/Object;)Lio/devconsole/remoteconfig/RemoteConfigSnapshot; + public fun equals (Ljava/lang/Object;)Z + public final fun getEntries ()Ljava/util/List; + public final fun getFetchInfo ()Lio/devconsole/remoteconfig/RemoteConfigFetchInfo; + public final fun getProviderId ()Ljava/lang/String; + public final fun getUnavailableReason ()Ljava/lang/String; + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + +public final class io/devconsole/remoteconfig/RemoteConfigSource : java/lang/Enum { + public static final field Companion Lio/devconsole/remoteconfig/RemoteConfigSource$Companion; + public static final field DEFAULT Lio/devconsole/remoteconfig/RemoteConfigSource; + public static final field OVERRIDE Lio/devconsole/remoteconfig/RemoteConfigSource; + public static final field REMOTE Lio/devconsole/remoteconfig/RemoteConfigSource; + public static final field STATIC Lio/devconsole/remoteconfig/RemoteConfigSource; + public static final field UNKNOWN Lio/devconsole/remoteconfig/RemoteConfigSource; + public static final fun fromWireName (Ljava/lang/String;)Lio/devconsole/remoteconfig/RemoteConfigSource; + public static fun getEntries ()Lkotlin/enums/EnumEntries; + public final fun getWireName ()Ljava/lang/String; + public static fun valueOf (Ljava/lang/String;)Lio/devconsole/remoteconfig/RemoteConfigSource; + public static fun values ()[Lio/devconsole/remoteconfig/RemoteConfigSource; +} + +public final class io/devconsole/remoteconfig/RemoteConfigSource$Companion { + public final fun fromWireName (Ljava/lang/String;)Lio/devconsole/remoteconfig/RemoteConfigSource; +} + diff --git a/sdk/remote-config/build.gradle.kts b/sdk/remote-config/build.gradle.kts new file mode 100644 index 0000000..7b77444 --- /dev/null +++ b/sdk/remote-config/build.gradle.kts @@ -0,0 +1,5 @@ +plugins { + id("devconsole.kotlin.jvm") + id("devconsole.quality") + id("devconsole.publishing") +} diff --git a/sdk/remote-config/src/main/kotlin/io/devconsole/remoteconfig/RemoteConfig.kt b/sdk/remote-config/src/main/kotlin/io/devconsole/remoteconfig/RemoteConfig.kt new file mode 100644 index 0000000..a6d5a46 --- /dev/null +++ b/sdk/remote-config/src/main/kotlin/io/devconsole/remoteconfig/RemoteConfig.kt @@ -0,0 +1,107 @@ +/** + * @author Md. Asaduzzaman Nur + * @since 13/08/26 + */ +package io.devconsole.remoteconfig + +/** + * Where a Remote Config value actually came from. This -- not the value itself -- is what makes a + * config problem diagnosable: a key serving an in-app [DEFAULT] because the fetch was throttled + * looks identical to one the server published, until you can see the source. + */ +enum class RemoteConfigSource( + val wireName: String, +) { + /** Fetched from the server and activated. */ + REMOTE("remote"), + + /** An in-app default (e.g. Firebase's `setDefaultsAsync`); no server value is active. */ + DEFAULT("default"), + + /** Set nowhere -- the provider's static fallback for an unknown key. */ + STATIC("static"), + + /** A locally applied override sitting on top of whatever the provider resolved. */ + OVERRIDE("override"), + + /** The provider could not attribute the value. Never guessed at. */ + UNKNOWN("unknown"), + ; + + companion object { + @JvmStatic + fun fromWireName(value: String?): RemoteConfigSource? = + entries.firstOrNull { it.wireName.equals(value, ignoreCase = true) } + } +} + +/** + * One Remote Config key as it stands on the device right now. + * + * [value] is a `String` because Remote Config is string-typed at the source -- reading a key as a + * long or a boolean is an interpretation the *reader* applies, so storing a parsed type here would + * record information the server never sent. + */ +data class RemoteConfigEntry( + val key: String, + val value: String, + val source: RemoteConfigSource, + /** True when [value] was withheld by redaction, so a surface can badge it rather than show it. */ + val redacted: Boolean = false, + /** True when [value] was cut to [RemoteConfigRegistry.MAX_VALUE_LENGTH]. */ + val truncated: Boolean = false, +) + +/** Outcome of the provider's most recent fetch attempt. */ +enum class RemoteConfigFetchStatus( + val wireName: String, +) { + SUCCESS("success"), + NO_FETCH_YET("no_fetch_yet"), + FAILURE("failure"), + THROTTLED("throttled"), + UNKNOWN("unknown"), +} + +/** + * Fetch metadata for a provider. [lastFetchEpochMs] is null -- never a sentinel like `-1` or `0` -- + * when no fetch has happened, so a surface cannot render "never fetched" as a 1970 timestamp. + */ +data class RemoteConfigFetchInfo( + val lastFetchEpochMs: Long?, + val status: RemoteConfigFetchStatus, + val minimumFetchIntervalSeconds: Long?, +) { + companion object { + /** What a provider that failed or cannot report reads as; never a confident status. */ + @JvmStatic + fun unknown(): RemoteConfigFetchInfo = + RemoteConfigFetchInfo( + lastFetchEpochMs = null, + status = RemoteConfigFetchStatus.UNKNOWN, + minimumFetchIntervalSeconds = null, + ) + } +} + +/** + * Everything one provider can currently report. A non-null [unavailableReason] means [entries] is + * empty because the provider could not be read -- a state the surfaces show explicitly rather than + * rendering as "no config". + */ +data class RemoteConfigSnapshot( + val providerId: String, + val entries: List, + val fetchInfo: RemoteConfigFetchInfo, + val unavailableReason: String? = null, +) + +/** + * A host-facing source of Remote Config values. Implement this to inspect a provider DevConsole + * ships no adapter for; [snapshot] is called on demand, when a surface asks, and is never polled. + */ +interface RemoteConfigProvider { + val id: String + + fun snapshot(): RemoteConfigSnapshot +} diff --git a/sdk/remote-config/src/main/kotlin/io/devconsole/remoteconfig/RemoteConfigRegistry.kt b/sdk/remote-config/src/main/kotlin/io/devconsole/remoteconfig/RemoteConfigRegistry.kt new file mode 100644 index 0000000..4e6c7d2 --- /dev/null +++ b/sdk/remote-config/src/main/kotlin/io/devconsole/remoteconfig/RemoteConfigRegistry.kt @@ -0,0 +1,72 @@ +/** + * @author Md. Asaduzzaman Nur + * @since 13/08/26 + */ +package io.devconsole.remoteconfig + +/** + * Holds the host's registered [RemoteConfigProvider]s and normalizes what they return. + * + * Normalization lives here rather than in each adapter so that a host-written provider inherits the + * same value cap and the same never-throw guarantee as the adapters DevConsole ships, instead of + * having to remember them. + */ +class RemoteConfigRegistry { + private val providers = linkedMapOf() + + fun register(provider: RemoteConfigProvider) { + require(provider.id.isNotBlank()) { "Remote config provider id must not be blank" } + require(provider.id !in providers) { "Duplicate remote config provider: ${provider.id}" } + providers[provider.id] = provider + } + + fun providerIds(): List = providers.keys.toList() + + /** Null for an unknown id; a provider that throws yields an unavailable snapshot, never an exception. */ + fun snapshot(id: String): RemoteConfigSnapshot? = providers[id]?.let { read(id, it) } + + fun snapshots(): List = providers.map { (id, provider) -> read(id, provider) } + + /** + * A debugging tool that crashes the app it exists to observe is worse than no tool, so a + * provider that throws is reported as unavailable rather than propagated to the host. + */ + private fun read( + id: String, + provider: RemoteConfigProvider, + ): RemoteConfigSnapshot = + runCatching { provider.snapshot().normalized(id) } + .getOrElse { failure -> + RemoteConfigSnapshot( + providerId = id, + entries = emptyList(), + fetchInfo = RemoteConfigFetchInfo.unknown(), + unavailableReason = + failure.message?.takeIf(String::isNotBlank) + ?: failure.javaClass.simpleName, + ) + } + + /** + * Forces the registered id onto the result: the registry's own key is what every surface + * addresses a provider by, so a provider reporting a different [RemoteConfigSnapshot.providerId] + * must not produce a snapshot nothing can look up again. + */ + private fun RemoteConfigSnapshot.normalized(id: String): RemoteConfigSnapshot = + copy(providerId = id, entries = entries.map { it.capped() }) + + private fun RemoteConfigEntry.capped(): RemoteConfigEntry = + if (value.length <= MAX_VALUE_LENGTH) { + this + } else { + copy(value = value.take(MAX_VALUE_LENGTH), truncated = true) + } + + companion object { + /** + * Values longer than this are cut. One pathological config value (a base64 blob, an inlined + * JSON document) must not bloat every snapshot response on a phone-hosted server. + */ + const val MAX_VALUE_LENGTH: Int = 8 * 1024 + } +} diff --git a/sdk/remote-config/src/test/kotlin/io/devconsole/remoteconfig/RemoteConfigRegistryTest.kt b/sdk/remote-config/src/test/kotlin/io/devconsole/remoteconfig/RemoteConfigRegistryTest.kt new file mode 100644 index 0000000..22f18d6 --- /dev/null +++ b/sdk/remote-config/src/test/kotlin/io/devconsole/remoteconfig/RemoteConfigRegistryTest.kt @@ -0,0 +1,181 @@ +/** + * @author Md. Asaduzzaman Nur + * @since 13/08/26 + */ +package io.devconsole.remoteconfig + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class RemoteConfigRegistryTest { + @Test + fun `snapshot returns the registered provider's entries`() { + val registry = RemoteConfigRegistry() + registry.register(provider("firebase", entry("checkout_v2", "true", RemoteConfigSource.REMOTE))) + + val snapshot = registry.snapshot("firebase") + + assertNotNull(snapshot) + assertEquals(listOf("checkout_v2"), snapshot!!.entries.map { it.key }) + assertEquals(RemoteConfigSource.REMOTE, snapshot.entries.single().source) + } + + @Test + fun `unknown provider id reads as null rather than throwing`() { + assertNull(RemoteConfigRegistry().snapshot("absent")) + } + + @Test + fun `duplicate provider id is rejected`() { + val registry = RemoteConfigRegistry() + registry.register(provider("firebase")) + + val failure = runCatching { registry.register(provider("firebase")) }.exceptionOrNull() + + assertTrue(failure is IllegalArgumentException) + } + + @Test + fun `blank provider id is rejected`() { + val failure = runCatching { RemoteConfigRegistry().register(provider(" ")) }.exceptionOrNull() + + assertTrue(failure is IllegalArgumentException) + } + + @Test + fun `a provider that throws degrades to an unavailable snapshot instead of propagating`() { + val registry = RemoteConfigRegistry() + registry.register( + object : RemoteConfigProvider { + override val id: String = "broken" + + override fun snapshot(): RemoteConfigSnapshot = error("firebase exploded") + }, + ) + + val snapshot = registry.snapshot("broken") + + assertNotNull(snapshot) + assertEquals("firebase exploded", snapshot!!.unavailableReason) + assertTrue(snapshot.entries.isEmpty()) + } + + @Test + fun `an unavailable snapshot reports no confident fetch status`() { + val registry = RemoteConfigRegistry() + registry.register( + object : RemoteConfigProvider { + override val id: String = "broken" + + override fun snapshot(): RemoteConfigSnapshot = error("boom") + }, + ) + + val fetch = registry.snapshot("broken")!!.fetchInfo + + assertEquals(RemoteConfigFetchStatus.UNKNOWN, fetch.status) + assertNull(fetch.lastFetchEpochMs) + assertNull(fetch.minimumFetchIntervalSeconds) + } + + @Test + fun `a throwable with no message falls back to its class name`() { + val registry = RemoteConfigRegistry() + registry.register( + object : RemoteConfigProvider { + override val id: String = "broken" + + // Deliberately not error(): that always attaches a message, and a *message-less* + // throwable is precisely the case this test covers. + @Suppress("UseCheckOrError") + override fun snapshot(): RemoteConfigSnapshot = throw IllegalStateException() + }, + ) + + assertEquals("IllegalStateException", registry.snapshot("broken")!!.unavailableReason) + } + + @Test + fun `an oversized value is truncated by the registry rather than by each provider`() { + val registry = RemoteConfigRegistry() + val oversized = "x".repeat(RemoteConfigRegistry.MAX_VALUE_LENGTH + 100) + registry.register(provider("firebase", entry("blob", oversized, RemoteConfigSource.REMOTE))) + + val stored = registry.snapshot("firebase")!!.entries.single() + + assertEquals(RemoteConfigRegistry.MAX_VALUE_LENGTH, stored.value.length) + assertTrue(stored.truncated) + } + + @Test + fun `a value at the cap is not marked truncated`() { + val registry = RemoteConfigRegistry() + val exact = "x".repeat(RemoteConfigRegistry.MAX_VALUE_LENGTH) + registry.register(provider("firebase", entry("blob", exact, RemoteConfigSource.REMOTE))) + + val stored = registry.snapshot("firebase")!!.entries.single() + + assertEquals(exact, stored.value) + assertTrue(!stored.truncated) + } + + @Test + fun `snapshots returns every provider in registration order`() { + val registry = RemoteConfigRegistry() + registry.register(provider("firebase")) + registry.register(provider("configcat")) + + assertEquals(listOf("firebase", "configcat"), registry.snapshots().map { it.providerId }) + assertEquals(listOf("firebase", "configcat"), registry.providerIds()) + } + + @Test + fun `a provider reporting an id different from its registration keeps the registered id`() { + val registry = RemoteConfigRegistry() + registry.register( + object : RemoteConfigProvider { + override val id: String = "firebase" + + override fun snapshot(): RemoteConfigSnapshot = + RemoteConfigSnapshot( + providerId = "something-else", + entries = emptyList(), + fetchInfo = unknownFetch(), + ) + }, + ) + + assertEquals("firebase", registry.snapshot("firebase")!!.providerId) + } + + private fun unknownFetch() = + RemoteConfigFetchInfo( + lastFetchEpochMs = null, + status = RemoteConfigFetchStatus.UNKNOWN, + minimumFetchIntervalSeconds = null, + ) + + private fun entry( + key: String, + value: String, + source: RemoteConfigSource, + ) = RemoteConfigEntry(key = key, value = value, source = source) + + private fun provider( + id: String, + vararg entries: RemoteConfigEntry, + ): RemoteConfigProvider = + object : RemoteConfigProvider { + override val id: String = id + + override fun snapshot(): RemoteConfigSnapshot = + RemoteConfigSnapshot( + providerId = id, + entries = entries.toList(), + fetchInfo = unknownFetch(), + ) + } +} diff --git a/sdk/server-ktor/api/server-ktor.api b/sdk/server-ktor/api/server-ktor.api index 2282e23..6b53a6e 100644 --- a/sdk/server-ktor/api/server-ktor.api +++ b/sdk/server-ktor/api/server-ktor.api @@ -35,6 +35,7 @@ public final class io/devconsole/server/ktor/DevConsoleModuleConfig { public final fun getPushSimulator ()Lio/devconsole/push/PushSimulator; public final fun getPushStore ()Lio/devconsole/push/PushStore; public final fun getRedactionPolicy ()Lio/devconsole/security/RedactionPolicy; + public final fun getRemoteConfigSnapshots ()Lkotlin/jvm/functions/Function0; public final fun getRetainedCaptures ()Lio/devconsole/storage/api/RetainedCaptureQuery; public final fun getScreenshotCapture ()Lkotlin/jvm/functions/Function1; public final fun getSdkHealth ()Lkotlin/jvm/functions/Function0; @@ -75,6 +76,7 @@ public final class io/devconsole/server/ktor/DevConsoleModuleConfig { public final fun setPushSimulator (Lio/devconsole/push/PushSimulator;)V public final fun setPushStore (Lio/devconsole/push/PushStore;)V public final fun setRedactionPolicy (Lio/devconsole/security/RedactionPolicy;)V + public final fun setRemoteConfigSnapshots (Lkotlin/jvm/functions/Function0;)V public final fun setRetainedCaptures (Lio/devconsole/storage/api/RetainedCaptureQuery;)V public final fun setScreenshotCapture (Lkotlin/jvm/functions/Function1;)V public final fun setSdkHealth (Lkotlin/jvm/functions/Function0;)V @@ -103,8 +105,8 @@ public final class io/devconsole/server/ktor/EventStreamHub$Companion { public final class io/devconsole/server/ktor/KtorLocalServerEngine : io/devconsole/server/api/LocalServerEngine { public fun ()V - public fun (Lio/devconsole/server/api/SessionAuthority;Lio/devconsole/server/api/SessionCodeAuthority;Lkotlin/jvm/functions/Function0;Lkotlin/jvm/functions/Function0;Lio/devconsole/network/NetworkTransactionStore;Lio/devconsole/socket/SocketStore;Lio/devconsole/push/PushStore;Lio/devconsole/state/StateRegistry;Lio/devconsole/state/SessionFeatureFlags;ZLio/devconsole/mocks/MockEngine;ZLio/devconsole/api/CaptureRuleEngine;ZLio/devconsole/server/api/PreferencesInspector;ZLio/devconsole/server/api/DatabaseInspector;ZLio/devconsole/server/api/FileInspector;ZLio/devconsole/timeline/Timeline;ZLjava/util/Set;ZLio/devconsole/security/RedactionPolicy;Lio/devconsole/push/PushSimulator;Lio/devconsole/server/api/CommandAuditLog;Lio/devconsole/timeline/TimelineAnnotations;Lio/devconsole/composer/ComposerCollectionStore;Lio/devconsole/composer/ComposerExecutor;Lio/devconsole/storage/api/EvidenceStore;Lkotlin/jvm/functions/Function0;Lkotlin/jvm/functions/Function1;Lkotlin/jvm/functions/Function1;Lkotlin/jvm/functions/Function1;Lkotlin/jvm/functions/Function0;)V - public synthetic fun (Lio/devconsole/server/api/SessionAuthority;Lio/devconsole/server/api/SessionCodeAuthority;Lkotlin/jvm/functions/Function0;Lkotlin/jvm/functions/Function0;Lio/devconsole/network/NetworkTransactionStore;Lio/devconsole/socket/SocketStore;Lio/devconsole/push/PushStore;Lio/devconsole/state/StateRegistry;Lio/devconsole/state/SessionFeatureFlags;ZLio/devconsole/mocks/MockEngine;ZLio/devconsole/api/CaptureRuleEngine;ZLio/devconsole/server/api/PreferencesInspector;ZLio/devconsole/server/api/DatabaseInspector;ZLio/devconsole/server/api/FileInspector;ZLio/devconsole/timeline/Timeline;ZLjava/util/Set;ZLio/devconsole/security/RedactionPolicy;Lio/devconsole/push/PushSimulator;Lio/devconsole/server/api/CommandAuditLog;Lio/devconsole/timeline/TimelineAnnotations;Lio/devconsole/composer/ComposerCollectionStore;Lio/devconsole/composer/ComposerExecutor;Lio/devconsole/storage/api/EvidenceStore;Lkotlin/jvm/functions/Function0;Lkotlin/jvm/functions/Function1;Lkotlin/jvm/functions/Function1;Lkotlin/jvm/functions/Function1;Lkotlin/jvm/functions/Function0;IILkotlin/jvm/internal/DefaultConstructorMarker;)V + public fun (Lio/devconsole/server/api/SessionAuthority;Lio/devconsole/server/api/SessionCodeAuthority;Lkotlin/jvm/functions/Function0;Lkotlin/jvm/functions/Function0;Lio/devconsole/network/NetworkTransactionStore;Lio/devconsole/socket/SocketStore;Lio/devconsole/push/PushStore;Lio/devconsole/state/StateRegistry;Lkotlin/jvm/functions/Function0;Lio/devconsole/state/SessionFeatureFlags;ZLio/devconsole/mocks/MockEngine;ZLio/devconsole/api/CaptureRuleEngine;ZLio/devconsole/server/api/PreferencesInspector;ZLio/devconsole/server/api/DatabaseInspector;ZLio/devconsole/server/api/FileInspector;ZLio/devconsole/timeline/Timeline;ZLjava/util/Set;ZLio/devconsole/security/RedactionPolicy;Lio/devconsole/push/PushSimulator;Lio/devconsole/server/api/CommandAuditLog;Lio/devconsole/timeline/TimelineAnnotations;Lio/devconsole/composer/ComposerCollectionStore;Lio/devconsole/composer/ComposerExecutor;Lio/devconsole/storage/api/EvidenceStore;Lkotlin/jvm/functions/Function0;Lkotlin/jvm/functions/Function1;Lkotlin/jvm/functions/Function1;Lkotlin/jvm/functions/Function1;Lkotlin/jvm/functions/Function0;)V + public synthetic fun (Lio/devconsole/server/api/SessionAuthority;Lio/devconsole/server/api/SessionCodeAuthority;Lkotlin/jvm/functions/Function0;Lkotlin/jvm/functions/Function0;Lio/devconsole/network/NetworkTransactionStore;Lio/devconsole/socket/SocketStore;Lio/devconsole/push/PushStore;Lio/devconsole/state/StateRegistry;Lkotlin/jvm/functions/Function0;Lio/devconsole/state/SessionFeatureFlags;ZLio/devconsole/mocks/MockEngine;ZLio/devconsole/api/CaptureRuleEngine;ZLio/devconsole/server/api/PreferencesInspector;ZLio/devconsole/server/api/DatabaseInspector;ZLio/devconsole/server/api/FileInspector;ZLio/devconsole/timeline/Timeline;ZLjava/util/Set;ZLio/devconsole/security/RedactionPolicy;Lio/devconsole/push/PushSimulator;Lio/devconsole/server/api/CommandAuditLog;Lio/devconsole/timeline/TimelineAnnotations;Lio/devconsole/composer/ComposerCollectionStore;Lio/devconsole/composer/ComposerExecutor;Lio/devconsole/storage/api/EvidenceStore;Lkotlin/jvm/functions/Function0;Lkotlin/jvm/functions/Function1;Lkotlin/jvm/functions/Function1;Lkotlin/jvm/functions/Function1;Lkotlin/jvm/functions/Function0;IILkotlin/jvm/internal/DefaultConstructorMarker;)V public fun bindAddressChanged ()Z public final fun getStreamHub ()Lio/devconsole/server/ktor/EventStreamHub; public final fun reconfigure (Lio/devconsole/state/SessionFeatureFlags;ZLjava/util/Set;ZLio/devconsole/security/RedactionPolicy;ZZZZZZ)V diff --git a/sdk/server-ktor/build.gradle.kts b/sdk/server-ktor/build.gradle.kts index 50b8644..9afa7af 100644 --- a/sdk/server-ktor/build.gradle.kts +++ b/sdk/server-ktor/build.gradle.kts @@ -21,6 +21,7 @@ dependencies { implementation(project(":sdk:composer")) implementation(project(":sdk:push")) implementation(project(":sdk:state")) + implementation(project(":sdk:remote-config")) implementation(project(":sdk:export")) implementation(project(":sdk:storage-api")) implementation("io.ktor:ktor-server-core:3.0.3") diff --git a/sdk/server-ktor/src/main/kotlin/io/devconsole/server/ktor/DevConsoleKtorModule.kt b/sdk/server-ktor/src/main/kotlin/io/devconsole/server/ktor/DevConsoleKtorModule.kt index 2b77233..0bd529f 100644 --- a/sdk/server-ktor/src/main/kotlin/io/devconsole/server/ktor/DevConsoleKtorModule.kt +++ b/sdk/server-ktor/src/main/kotlin/io/devconsole/server/ktor/DevConsoleKtorModule.kt @@ -51,6 +51,8 @@ import io.devconsole.push.PushEvent import io.devconsole.push.PushInput import io.devconsole.push.PushSimulator import io.devconsole.push.PushStore +import io.devconsole.remoteconfig.RemoteConfigEntry +import io.devconsole.remoteconfig.RemoteConfigSnapshot import io.devconsole.security.RedactionEngine import io.devconsole.security.RedactionPolicy import io.devconsole.server.api.BindingMode @@ -214,6 +216,13 @@ class DevConsoleModuleConfig { var stateRegistry: StateRegistry = StateRegistry() var stateMutationsEnabled: Boolean = false + /** + * Remote Config snapshots, **already redacted** by the caller. `:sdk:full` owns that boundary + * because the Compose inspector reads the same registry in-process without passing through here, + * so redacting at this route would protect only the browser. + */ + var remoteConfigSnapshots: () -> List = { emptyList() } + /** Reads (file/entry listing) always work; [preferencesEditable] mirrors `EditingCapabilities.preferences`. */ var preferencesInspector: PreferencesInspector? = null var preferencesEditable: Boolean = false @@ -316,6 +325,7 @@ fun Application.devConsoleModule( val featureFlags = config.featureFlags val featureFlagsEditable = config.featureFlagsEditable val stateRegistry = config.stateRegistry + val remoteConfigSnapshots = config.remoteConfigSnapshots val stateMutationsEnabled = config.stateMutationsEnabled val preferencesInspector = config.preferencesInspector val preferencesEditable = config.preferencesEditable @@ -1526,6 +1536,22 @@ fun Application.devConsoleModule( } call.respondText("{\"data\":[$flags]}", contentType = io.ktor.http.ContentType.Application.Json) } + get("/api/v1/remote-config") { + if (sessionAuthority.bearerSession(call.request.headers[HttpHeaders.Authorization]) == + null + ) { + call.respondText("{\"code\":\"AUTH_REQUIRED\"}", status = HttpStatusCode.Unauthorized) + return@get + } + // Remote Config sits under the same "state" category as state providers and feature + // flags -- it is the same kind of data, so it is gated the same way. + if (!categoryEnabled("state")) { + call.respondCategoryDisabled("state") + return@get + } + val providers = remoteConfigSnapshots().joinToString(",") { it.json() } + call.respondText("{\"data\":[$providers]}", contentType = io.ktor.http.ContentType.Application.Json) + } post("/api/v1/flags/{key}") { val session = sessionAuthority.bearerSession(call.request.headers[HttpHeaders.Authorization]) val expectedOrigin = "http://${call.request.headers[HttpHeaders.Host].orEmpty()}" @@ -3415,6 +3441,8 @@ class KtorLocalServerEngine( private val socketStore: SocketStore = InMemorySocketStore(), private val pushStore: PushStore = InMemoryPushStore(), private val stateRegistry: StateRegistry = StateRegistry(), + /** Already-redacted Remote Config snapshots; see [DevConsoleModuleConfig.remoteConfigSnapshots]. */ + private val remoteConfigSnapshots: () -> List = { emptyList() }, featureFlags: SessionFeatureFlags = SessionFeatureFlags(emptyList()), featureFlagsEditable: Boolean = false, private val mockEngine: MockEngine = MockEngine(emptyList()), @@ -3595,6 +3623,7 @@ class KtorLocalServerEngine( this.socketStore = this@KtorLocalServerEngine.socketStore this.pushStore = this@KtorLocalServerEngine.pushStore this.stateRegistry = this@KtorLocalServerEngine.stateRegistry + this.remoteConfigSnapshots = this@KtorLocalServerEngine.remoteConfigSnapshots this.featureFlags = configuration.featureFlags this.featureFlagsEditable = configuration.featureFlagsEditable this.mockEngine = this@KtorLocalServerEngine.mockEngine @@ -4465,6 +4494,27 @@ private fun CaptureRule.json(): String = "\"pathPrefix\":${pathPrefix?.let { "\"${it.escapeJson()}\"" } ?: "null"}," + "\"enabled\":$enabled}" +/** + * Wire names deliberately differ from the Kotlin field names -- `providerId` serializes as `id` and + * `fetchInfo` as `fetch` -- and these names, not the Kotlin ones, are the stable contract the + * dashboard reads. Keys and values originate in the host's Remote Config console, so both are + * escaped. `lastFetchEpochMs` is emitted as literal `null` for a never-fetched provider rather than + * as a sentinel number, so the dashboard can render "never" instead of a 1970 date. + */ +private fun RemoteConfigSnapshot.json(): String { + val rows = entries.joinToString(",") { it.json() } + return "{\"id\":\"${providerId.escapeJson()}\"," + + "\"fetch\":{\"lastFetchEpochMs\":${fetchInfo.lastFetchEpochMs ?: "null"}," + + "\"status\":\"${fetchInfo.status.wireName}\"," + + "\"minimumFetchIntervalSeconds\":${fetchInfo.minimumFetchIntervalSeconds ?: "null"}}," + + "\"unavailableReason\":${unavailableReason?.let { "\"${it.escapeJson()}\"" } ?: "null"}," + + "\"entries\":[$rows]}" +} + +private fun RemoteConfigEntry.json(): String = + "{\"key\":\"${key.escapeJson()}\",\"value\":\"${value.escapeJson()}\"," + + "\"source\":\"${source.wireName}\",\"redacted\":$redacted,\"truncated\":$truncated}" + /** * Rule ids, hosts, and paths are user-supplied, so every string field is escaped. [stats] comes * from [MockEngine.stats] rather than [MockRule] itself -- hit counts live in the engine's side diff --git a/sdk/server-ktor/src/main/resources/devconsole-web/dashboard.js b/sdk/server-ktor/src/main/resources/devconsole-web/dashboard.js index c6dfb8c..337da70 100644 --- a/sdk/server-ktor/src/main/resources/devconsole-web/dashboard.js +++ b/sdk/server-ktor/src/main/resources/devconsole-web/dashboard.js @@ -1026,7 +1026,7 @@ // applyRailAdvancedGrouping) since the eight advanced-only views visually relocate into one // collapsed group rather than merely hiding in place. // ================================================================ - const RAIL_ADVANCED_IDS = ['viewSdkHealth', 'viewComposer', 'viewCaptureRules', 'viewState', 'viewPreferences', 'viewDatabase', 'viewFiles', 'viewSession']; + const RAIL_ADVANCED_IDS = ['viewSdkHealth', 'viewComposer', 'viewCaptureRules', 'viewState', 'viewRemoteConfig', 'viewPreferences', 'viewDatabase', 'viewFiles', 'viewSession']; const RAIL_ADVANCED_VIEWS = new Set(['sdkHealth', 'composer', 'captureRules', 'state', 'preferences', 'database', 'files', 'session']); // ================================================================ @@ -1042,7 +1042,9 @@ push: { ids: ['viewPush'], views: ['push'] }, logs: { ids: ['viewTimeline'], views: ['timeline'] }, crashes: { ids: ['viewCrashes'], views: ['crashes'] }, - state: { ids: ['viewState'], views: ['state'] }, + // Remote Config shares the STATE category with state providers and feature flags -- it is the + // same kind of data, and the route is gated identically. + state: { ids: ['viewState', 'viewRemoteConfig'], views: ['state', 'remoteConfig'] }, inspection: { ids: ['viewPreferences', 'viewDatabase', 'viewFiles'], views: ['preferences', 'database', 'files'] }, mocks: { ids: ['viewMocks', 'viewCaptureRules'], views: ['mocks', 'captureRules'] }, }; @@ -4386,6 +4388,74 @@ ]); } + // ================================================================ + // Remote Config + // ================================================================ + let remoteConfigProviders = []; + let remoteConfigQuery = ''; + let remoteConfigSourceFilter = 'all'; + const REMOTE_CONFIG_SOURCE_TONE = { remote: 'signal', override: 'warn', default: 'muted', static: 'muted', unknown: 'muted' }; + async function loadRemoteConfig() { + if (!token) return; + const r = await fetch('/api/v1/remote-config', { headers: auth() }); + if (!r.ok) { + remoteConfigProviders = []; + cardsGridHtml('remoteConfigCards', [{ icon: 'sliders', iconTone: 'signal', title: 'Remote Config', lede: 'Remote Config unavailable: ' + r.status }]); + return; + } + remoteConfigProviders = (await r.json()).data || []; + renderRemoteConfigCards(); + } + /** Never-fetched is spelled out; rendering epoch 0 (or a sentinel) as a date would read as a real fetch. */ + function remoteConfigFetchLine(provider) { + const fetchInfo = provider.fetch || {}; + const when = fetchInfo.lastFetchEpochMs == null ? 'never' : new Date(fetchInfo.lastFetchEpochMs).toLocaleString(); + const status = (fetchInfo.status || 'unknown').replace(/_/g, ' '); + const interval = fetchInfo.minimumFetchIntervalSeconds == null ? '' : ' · min interval ' + fetchInfo.minimumFetchIntervalSeconds + 's'; + return 'last fetch: ' + when + ' · ' + status + interval; + } + function renderRemoteConfigCards() { + const total = remoteConfigProviders.reduce((sum, p) => sum + (p.entries || []).length, 0); + $('navCountRemoteConfig').textContent = total; + $('remoteConfigBadge').textContent = remoteConfigProviders.length + ? total + ' key' + (total === 1 ? '' : 's') + ' · ' + remoteConfigProviders.length + ' provider' + (remoteConfigProviders.length === 1 ? '' : 's') + : 'no providers'; + if (!remoteConfigProviders.length) { + cardsGridHtml('remoteConfigCards', [{ + icon: 'sliders', iconTone: 'signal', title: 'Remote Config', span: 2, + lede: 'No Remote Config provider is registered for this session. Register one with DevConsoleConfig.withRemoteConfigProviders(...) — see docs/REMOTE_CONFIG.md.', + }]); + return; + } + const needle = remoteConfigQuery.trim().toLowerCase(); + cardsGridHtml('remoteConfigCards', remoteConfigProviders.map((provider) => { + const all = provider.entries || []; + const shown = all.filter((e) => (!needle || e.key.toLowerCase().includes(needle)) + && (remoteConfigSourceFilter === 'all' || e.source === remoteConfigSourceFilter)); + // Four distinct states, none of which may render as an unexplained blank table. + let lede = false; + if (provider.unavailableReason) lede = 'Remote Config unavailable: ' + provider.unavailableReason; + else if (!all.length) { + lede = (provider.fetch || {}).lastFetchEpochMs == null + ? 'No values — this provider has not completed a fetch yet.' + : 'No values returned by the last fetch.'; + } else if (!shown.length) lede = 'No key matches the current filter.'; + return { + icon: 'sliders', iconTone: provider.unavailableReason ? 'warn' : 'signal', span: 2, + title: 'Remote Config · ' + provider.id, + badge: remoteConfigFetchLine(provider), badgeTone: provider.unavailableReason ? 'warn' : 'muted', + lede, + rows: shown.map((e) => ({ + k: e.key, + v: e.redacted ? '' : e.value, + tone: e.source === 'remote' ? 'ink' : 'muted', + tag: (e.source || 'unknown').toUpperCase() + (e.truncated ? ' · TRUNCATED' : ''), + tagTone: REMOTE_CONFIG_SOURCE_TONE[e.source] || 'muted', + })), + }; + })); + } + // ================================================================ // Preferences // ================================================================ @@ -6938,6 +7008,7 @@ network: 'networkView', socket: 'socketView', state: 'stateView', + remoteConfig: 'remoteConfigView', preferences: 'preferencesView', database: 'databaseView', files: 'filesView', @@ -6960,6 +7031,7 @@ network: 'viewNetwork', socket: 'viewSockets', state: 'viewState', + remoteConfig: 'viewRemoteConfig', preferences: 'viewPreferences', database: 'viewDatabase', files: 'viewFiles', @@ -6994,6 +7066,7 @@ network: loadNetwork, socket: loadSockets, state: loadState, + remoteConfig: loadRemoteConfig, preferences: loadPreferences, database: loadDatabases, files: loadFileRoots, @@ -7200,6 +7273,7 @@ $('viewNetwork').onclick = () => show('network'); $('viewSockets').onclick = () => show('socket'); $('viewState').onclick = () => show('state'); + $('viewRemoteConfig').onclick = () => show('remoteConfig'); $('viewPush').onclick = () => show('push'); $('viewComposer').onclick = () => show('composer'); $('viewMocks').onclick = () => show('mocks'); @@ -7210,6 +7284,10 @@ $('viewSdkHealth').onclick = () => show('sdkHealth'); $('viewSession').onclick = () => show('session'); + $('remoteConfigRefresh').onclick = loadRemoteConfig; + $('remoteConfigSearch').oninput = (e) => { remoteConfigQuery = e.target.value; renderRemoteConfigCards(); }; + wireSeg($('remoteConfigSourceSeg'), (value) => { remoteConfigSourceFilter = value; renderRemoteConfigCards(); }); + $('prefFile').onchange = (e) => renderPreferenceFile(e.target.value); $('dbName').onchange = (e) => { diff --git a/sdk/server-ktor/src/main/resources/devconsole-web/index.html b/sdk/server-ktor/src/main/resources/devconsole-web/index.html index 19cae9a..b2ab665 100644 --- a/sdk/server-ktor/src/main/resources/devconsole-web/index.html +++ b/sdk/server-ktor/src/main/resources/devconsole-web/index.html @@ -116,6 +116,7 @@
Data
+ @@ -464,6 +465,20 @@
Not connected yet
Open DevConsole on the device → More → scan the QR or paste the code in Overview to inspect state and flags.
+ +
+
+

Remote Config

+

Read-only view of the Remote Config values active on this device. The source badge is the point: a key serving a default because the last fetch failed or was throttled looks identical to a published one until you can see where it came from.

+
+
+ +
Source
+ +
+
Not connected yet
Open DevConsole on the device → More → scan the QR or paste the code in Overview to inspect Remote Config.
+
+
diff --git a/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/RemoteConfigRoutesTest.kt b/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/RemoteConfigRoutesTest.kt new file mode 100644 index 0000000..e0632b3 --- /dev/null +++ b/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/RemoteConfigRoutesTest.kt @@ -0,0 +1,246 @@ +/** + * @author Md. Asaduzzaman Nur + * @since 13/08/26 + */ +package io.devconsole.server.ktor + +import io.devconsole.remoteconfig.RemoteConfigEntry +import io.devconsole.remoteconfig.RemoteConfigFetchInfo +import io.devconsole.remoteconfig.RemoteConfigFetchStatus +import io.devconsole.remoteconfig.RemoteConfigSnapshot +import io.devconsole.remoteconfig.RemoteConfigSource +import io.devconsole.server.api.BrowserSession +import io.devconsole.server.api.ServerMetadata +import io.devconsole.server.api.SessionAuthority +import io.devconsole.server.api.SessionCodeAuthority +import io.ktor.client.request.get +import io.ktor.client.request.header +import io.ktor.client.request.post +import io.ktor.client.request.setBody +import io.ktor.client.statement.bodyAsText +import io.ktor.http.ContentType +import io.ktor.http.HttpHeaders +import io.ktor.http.HttpStatusCode +import io.ktor.server.testing.ApplicationTestBuilder +import io.ktor.server.testing.testApplication +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class RemoteConfigRoutesTest { + private fun snapshot( + unavailableReason: String? = null, + entries: List = + listOf( + RemoteConfigEntry("checkout_v2", "true", RemoteConfigSource.REMOTE), + RemoteConfigEntry("banner", "hi", RemoteConfigSource.DEFAULT), + ), + ) = RemoteConfigSnapshot( + providerId = "firebase", + entries = entries, + fetchInfo = + RemoteConfigFetchInfo( + lastFetchEpochMs = 1_755_043_200_000L, + status = RemoteConfigFetchStatus.SUCCESS, + minimumFetchIntervalSeconds = 3600L, + ), + unavailableReason = unavailableReason, + ) + + @Test + fun `requires an authenticated session`() = + testApplication { + val sessions = SessionAuthority() + val sessionCodes = SessionCodeAuthority(sessions) + application { + devConsoleModule(sessions, sessionCodes) { + remoteConfigSnapshots = { listOf(snapshot()) } + } + } + + val response = client.get("/api/v1/remote-config") { header(HttpHeaders.Host, "localhost") } + + assertEquals(HttpStatusCode.Unauthorized, response.status) + assertTrue(response.bodyAsText().contains("AUTH_REQUIRED")) + } + + @Test + fun `is refused when the state category is disabled`() = + testApplication { + val sessions = SessionAuthority() + val sessionCodes = SessionCodeAuthority(sessions) + application { + devConsoleModule(sessions, sessionCodes) { + remoteConfigSnapshots = { listOf(snapshot()) } + metadata = ServerMetadata(captureCategories = listOf("network", "logs")) + } + } + val session = approvedSession(sessions, sessionCodes) + + val response = client.get("/api/v1/remote-config") { authed(session) } + + assertEquals(HttpStatusCode.Forbidden, response.status) + assertTrue(response.bodyAsText().contains("CATEGORY_DISABLED")) + } + + @Test + fun `serves entries with source and fetch metadata under the documented wire names`() = + testApplication { + val sessions = SessionAuthority() + val sessionCodes = SessionCodeAuthority(sessions) + application { + devConsoleModule(sessions, sessionCodes) { + remoteConfigSnapshots = { listOf(snapshot()) } + } + } + val session = approvedSession(sessions, sessionCodes) + + val body = client.get("/api/v1/remote-config") { authed(session) }.bodyAsText() + + assertTrue(body, body.contains("\"id\":\"firebase\"")) + assertTrue(body, body.contains("\"fetch\":{")) + assertTrue(body, body.contains("\"lastFetchEpochMs\":1755043200000")) + assertTrue(body, body.contains("\"status\":\"success\"")) + assertTrue(body, body.contains("\"minimumFetchIntervalSeconds\":3600")) + assertTrue(body, body.contains("\"key\":\"checkout_v2\"")) + assertTrue(body, body.contains("\"source\":\"remote\"")) + assertTrue(body, body.contains("\"source\":\"default\"")) + } + + @Test + fun `reports never-fetched as a null timestamp rather than a sentinel`() = + testApplication { + val sessions = SessionAuthority() + val sessionCodes = SessionCodeAuthority(sessions) + application { + devConsoleModule(sessions, sessionCodes) { + remoteConfigSnapshots = { + listOf( + RemoteConfigSnapshot( + "firebase", + emptyList(), + RemoteConfigFetchInfo(null, RemoteConfigFetchStatus.NO_FETCH_YET, null), + ), + ) + } + } + } + val session = approvedSession(sessions, sessionCodes) + + val body = client.get("/api/v1/remote-config") { authed(session) }.bodyAsText() + + assertTrue(body, body.contains("\"lastFetchEpochMs\":null")) + assertTrue(body, body.contains("\"status\":\"no_fetch_yet\"")) + assertTrue(body, body.contains("\"minimumFetchIntervalSeconds\":null")) + } + + @Test + fun `surfaces an unavailable provider`() = + testApplication { + val sessions = SessionAuthority() + val sessionCodes = SessionCodeAuthority(sessions) + application { + devConsoleModule(sessions, sessionCodes) { + remoteConfigSnapshots = + { listOf(snapshot(unavailableReason = "disabled-build", entries = emptyList())) } + } + } + val session = approvedSession(sessions, sessionCodes) + + val body = client.get("/api/v1/remote-config") { authed(session) }.bodyAsText() + + assertTrue(body, body.contains("\"unavailableReason\":\"disabled-build\"")) + } + + @Test + fun `an absent provider list serves an empty payload rather than failing`() = + testApplication { + val sessions = SessionAuthority() + val sessionCodes = SessionCodeAuthority(sessions) + application { devConsoleModule(sessions, sessionCodes) {} } + val session = approvedSession(sessions, sessionCodes) + + val response = client.get("/api/v1/remote-config") { authed(session) } + + assertEquals(HttpStatusCode.OK, response.status) + assertEquals("{\"data\":[]}", response.bodyAsText()) + } + + @Test + fun `escapes quotes in keys and values so the payload stays parseable`() = + testApplication { + val sessions = SessionAuthority() + val sessionCodes = SessionCodeAuthority(sessions) + application { + devConsoleModule(sessions, sessionCodes) { + remoteConfigSnapshots = { + listOf( + snapshot( + entries = listOf(RemoteConfigEntry("quote\"key", "va\"lue", RemoteConfigSource.REMOTE)), + ), + ) + } + } + } + val session = approvedSession(sessions, sessionCodes) + + val body = client.get("/api/v1/remote-config") { authed(session) }.bodyAsText() + + assertTrue(body, body.contains("quote\\\"key")) + assertFalse(body, body.contains("\"quote\"key\"")) + } + + @Test + fun `carries the redaction and truncation flags through to the wire`() = + testApplication { + val sessions = SessionAuthority() + val sessionCodes = SessionCodeAuthority(sessions) + application { + devConsoleModule(sessions, sessionCodes) { + remoteConfigSnapshots = { + listOf( + snapshot( + entries = + listOf( + RemoteConfigEntry( + "api_key", + "", + RemoteConfigSource.REMOTE, + redacted = true, + truncated = true, + ), + ), + ), + ) + } + } + } + val session = approvedSession(sessions, sessionCodes) + + val body = client.get("/api/v1/remote-config") { authed(session) }.bodyAsText() + + assertTrue(body, body.contains("\"redacted\":true")) + assertTrue(body, body.contains("\"truncated\":true")) + } + + private fun io.ktor.client.request.HttpRequestBuilder.authed(session: BrowserSession) { + header(HttpHeaders.Host, "localhost") + header(HttpHeaders.Authorization, "Bearer ${session.token}") + } + + private suspend fun ApplicationTestBuilder.approvedSession( + sessions: SessionAuthority, + sessionCodes: SessionCodeAuthority, + ): BrowserSession { + val code = sessionCodes.issueCode().code + val response = + client.post("/api/v1/auth/session-code/exchange") { + header(HttpHeaders.Host, "localhost") + header(HttpHeaders.ContentType, ContentType.Application.FormUrlEncoded) + setBody("code=$code") + } + val token = Regex("\"accessToken\":\"([^\"]+)\"").find(response.bodyAsText())!!.groupValues[1] + return sessions.sessionForToken(token)!! + } +} diff --git a/sdk/ui-compose/api/ui-compose.api b/sdk/ui-compose/api/ui-compose.api index 9d03b5f..30539dd 100644 --- a/sdk/ui-compose/api/ui-compose.api +++ b/sdk/ui-compose/api/ui-compose.api @@ -20,6 +20,7 @@ public final class io/devconsole/ui/compose/ComposableSingletons$DevConsolePanel public final class io/devconsole/ui/compose/ComposableSingletons$InspectorControlScreenKt { public static final field INSTANCE Lio/devconsole/ui/compose/ComposableSingletons$InspectorControlScreenKt; public fun ()V + public final fun getLambda$-1143782739$ui_compose_release ()Lkotlin/jvm/functions/Function3; public final fun getLambda$-1373757892$ui_compose_release ()Lkotlin/jvm/functions/Function3; public final fun getLambda$-153603954$ui_compose_release ()Lkotlin/jvm/functions/Function2; public final fun getLambda$-1946392255$ui_compose_release ()Lkotlin/jvm/functions/Function3; @@ -1249,6 +1250,50 @@ public final class io/devconsole/ui/compose/InspectorQueryResultUi { public fun toString ()Ljava/lang/String; } +public final class io/devconsole/ui/compose/InspectorRemoteConfigEntryUi { + public static final field $stable I + public fun (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZ)V + public synthetic fun (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1 ()Ljava/lang/String; + public final fun component2 ()Ljava/lang/String; + public final fun component3 ()Ljava/lang/String; + public final fun component4 ()Z + public final fun component5 ()Z + public final fun copy (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZ)Lio/devconsole/ui/compose/InspectorRemoteConfigEntryUi; + public static synthetic fun copy$default (Lio/devconsole/ui/compose/InspectorRemoteConfigEntryUi;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZILjava/lang/Object;)Lio/devconsole/ui/compose/InspectorRemoteConfigEntryUi; + public fun equals (Ljava/lang/Object;)Z + public final fun getKey ()Ljava/lang/String; + public final fun getRedacted ()Z + public final fun getSource ()Ljava/lang/String; + public final fun getTruncated ()Z + public final fun getValue ()Ljava/lang/String; + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + +public final class io/devconsole/ui/compose/InspectorRemoteConfigUi { + public static final field $stable I + public fun (Ljava/lang/String;Ljava/util/List;Ljava/lang/Long;Ljava/lang/String;Ljava/lang/Long;Ljava/lang/String;)V + public synthetic fun (Ljava/lang/String;Ljava/util/List;Ljava/lang/Long;Ljava/lang/String;Ljava/lang/Long;Ljava/lang/String;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1 ()Ljava/lang/String; + public final fun component2 ()Ljava/util/List; + public final fun component3 ()Ljava/lang/Long; + public final fun component4 ()Ljava/lang/String; + public final fun component5 ()Ljava/lang/Long; + public final fun component6 ()Ljava/lang/String; + public final fun copy (Ljava/lang/String;Ljava/util/List;Ljava/lang/Long;Ljava/lang/String;Ljava/lang/Long;Ljava/lang/String;)Lio/devconsole/ui/compose/InspectorRemoteConfigUi; + public static synthetic fun copy$default (Lio/devconsole/ui/compose/InspectorRemoteConfigUi;Ljava/lang/String;Ljava/util/List;Ljava/lang/Long;Ljava/lang/String;Ljava/lang/Long;Ljava/lang/String;ILjava/lang/Object;)Lio/devconsole/ui/compose/InspectorRemoteConfigUi; + public fun equals (Ljava/lang/Object;)Z + public final fun getEntries ()Ljava/util/List; + public final fun getId ()Ljava/lang/String; + public final fun getLastFetchEpochMs ()Ljava/lang/Long; + public final fun getMinimumFetchIntervalSeconds ()Ljava/lang/Long; + public final fun getStatus ()Ljava/lang/String; + public final fun getUnavailableReason ()Ljava/lang/String; + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + public final class io/devconsole/ui/compose/InspectorRetentionUi { public static final field $stable I public fun (IJJ)V @@ -1291,8 +1336,8 @@ public final class io/devconsole/ui/compose/InspectorSessionUi { public final class io/devconsole/ui/compose/InspectorSnapshot { public static final field $stable I public fun ()V - public fun (ZLjava/util/List;Lio/devconsole/ui/compose/InspectorEditingUi;ZLjava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Lio/devconsole/ui/compose/InspectorHealthUi;Lio/devconsole/ui/compose/InspectorBrowserUi;Lio/devconsole/ui/compose/InspectorRetentionUi;ZLjava/util/Set;)V - public synthetic fun (ZLjava/util/List;Lio/devconsole/ui/compose/InspectorEditingUi;ZLjava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Lio/devconsole/ui/compose/InspectorHealthUi;Lio/devconsole/ui/compose/InspectorBrowserUi;Lio/devconsole/ui/compose/InspectorRetentionUi;ZLjava/util/Set;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public fun (ZLjava/util/List;Lio/devconsole/ui/compose/InspectorEditingUi;ZLjava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Lio/devconsole/ui/compose/InspectorHealthUi;Lio/devconsole/ui/compose/InspectorBrowserUi;Lio/devconsole/ui/compose/InspectorRetentionUi;ZLjava/util/Set;)V + public synthetic fun (ZLjava/util/List;Lio/devconsole/ui/compose/InspectorEditingUi;ZLjava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Lio/devconsole/ui/compose/InspectorHealthUi;Lio/devconsole/ui/compose/InspectorBrowserUi;Lio/devconsole/ui/compose/InspectorRetentionUi;ZLjava/util/Set;ILkotlin/jvm/internal/DefaultConstructorMarker;)V public final fun component1 ()Z public final fun component10 ()Ljava/util/List; public final fun component11 ()Ljava/util/List; @@ -1301,12 +1346,13 @@ public final class io/devconsole/ui/compose/InspectorSnapshot { public final fun component14 ()Ljava/util/List; public final fun component15 ()Ljava/util/List; public final fun component16 ()Ljava/util/List; - public final fun component17 ()Lio/devconsole/ui/compose/InspectorHealthUi; - public final fun component18 ()Lio/devconsole/ui/compose/InspectorBrowserUi; - public final fun component19 ()Lio/devconsole/ui/compose/InspectorRetentionUi; + public final fun component17 ()Ljava/util/List; + public final fun component18 ()Lio/devconsole/ui/compose/InspectorHealthUi; + public final fun component19 ()Lio/devconsole/ui/compose/InspectorBrowserUi; public final fun component2 ()Ljava/util/List; - public final fun component20 ()Z - public final fun component21 ()Ljava/util/Set; + public final fun component20 ()Lio/devconsole/ui/compose/InspectorRetentionUi; + public final fun component21 ()Z + public final fun component22 ()Ljava/util/Set; public final fun component3 ()Lio/devconsole/ui/compose/InspectorEditingUi; public final fun component4 ()Z public final fun component5 ()Ljava/util/List; @@ -1314,8 +1360,8 @@ public final class io/devconsole/ui/compose/InspectorSnapshot { public final fun component7 ()Ljava/util/List; public final fun component8 ()Ljava/util/List; public final fun component9 ()Ljava/util/List; - public final fun copy (ZLjava/util/List;Lio/devconsole/ui/compose/InspectorEditingUi;ZLjava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Lio/devconsole/ui/compose/InspectorHealthUi;Lio/devconsole/ui/compose/InspectorBrowserUi;Lio/devconsole/ui/compose/InspectorRetentionUi;ZLjava/util/Set;)Lio/devconsole/ui/compose/InspectorSnapshot; - public static synthetic fun copy$default (Lio/devconsole/ui/compose/InspectorSnapshot;ZLjava/util/List;Lio/devconsole/ui/compose/InspectorEditingUi;ZLjava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Lio/devconsole/ui/compose/InspectorHealthUi;Lio/devconsole/ui/compose/InspectorBrowserUi;Lio/devconsole/ui/compose/InspectorRetentionUi;ZLjava/util/Set;ILjava/lang/Object;)Lio/devconsole/ui/compose/InspectorSnapshot; + public final fun copy (ZLjava/util/List;Lio/devconsole/ui/compose/InspectorEditingUi;ZLjava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Lio/devconsole/ui/compose/InspectorHealthUi;Lio/devconsole/ui/compose/InspectorBrowserUi;Lio/devconsole/ui/compose/InspectorRetentionUi;ZLjava/util/Set;)Lio/devconsole/ui/compose/InspectorSnapshot; + public static synthetic fun copy$default (Lio/devconsole/ui/compose/InspectorSnapshot;ZLjava/util/List;Lio/devconsole/ui/compose/InspectorEditingUi;ZLjava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Lio/devconsole/ui/compose/InspectorHealthUi;Lio/devconsole/ui/compose/InspectorBrowserUi;Lio/devconsole/ui/compose/InspectorRetentionUi;ZLjava/util/Set;ILjava/lang/Object;)Lio/devconsole/ui/compose/InspectorSnapshot; public fun equals (Ljava/lang/Object;)Z public final fun getAvailable ()Z public final fun getBrowser ()Lio/devconsole/ui/compose/InspectorBrowserUi; @@ -1333,6 +1379,7 @@ public final class io/devconsole/ui/compose/InspectorSnapshot { public final fun getMocksEnabled ()Z public final fun getPreferenceFiles ()Ljava/util/List; public final fun getPushEvents ()Ljava/util/List; + public final fun getRemoteConfig ()Ljava/util/List; public final fun getRetention ()Lio/devconsole/ui/compose/InspectorRetentionUi; public final fun getSessions ()Ljava/util/List; public final fun getSockets ()Ljava/util/List; @@ -1450,8 +1497,8 @@ public final class io/devconsole/ui/compose/InspectorSqlResultUi$Wrote : io/devc public final class io/devconsole/ui/compose/InspectorState { public static final field $stable I public fun ()V - public fun (ZZLjava/util/List;Lio/devconsole/ui/compose/InspectorEditingUi;ZLjava/util/List;Ljava/util/List;Lio/devconsole/ui/compose/InspectorCommandResult;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/Set;Ljava/util/Set;Lio/devconsole/ui/compose/ObserveTab;Ljava/util/Set;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Lio/devconsole/ui/compose/InspectorFileListingUi;Lio/devconsole/ui/compose/InspectorFilePreviewUi;Ljava/lang/String;Ljava/util/List;Lio/devconsole/ui/compose/InspectorDatabaseListingUi;Lio/devconsole/ui/compose/InspectorQueryResultUi;Lio/devconsole/ui/compose/InspectorSqlResultUi;Ljava/util/List;Ljava/lang/String;ZLio/devconsole/ui/compose/InspectorHealthUi;Lio/devconsole/ui/compose/InspectorBrowserUi;Lio/devconsole/ui/compose/InspectorRetentionUi;Lio/devconsole/api/ScreenshotResult;ZLjava/util/Set;)V - public synthetic fun (ZZLjava/util/List;Lio/devconsole/ui/compose/InspectorEditingUi;ZLjava/util/List;Ljava/util/List;Lio/devconsole/ui/compose/InspectorCommandResult;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/Set;Ljava/util/Set;Lio/devconsole/ui/compose/ObserveTab;Ljava/util/Set;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Lio/devconsole/ui/compose/InspectorFileListingUi;Lio/devconsole/ui/compose/InspectorFilePreviewUi;Ljava/lang/String;Ljava/util/List;Lio/devconsole/ui/compose/InspectorDatabaseListingUi;Lio/devconsole/ui/compose/InspectorQueryResultUi;Lio/devconsole/ui/compose/InspectorSqlResultUi;Ljava/util/List;Ljava/lang/String;ZLio/devconsole/ui/compose/InspectorHealthUi;Lio/devconsole/ui/compose/InspectorBrowserUi;Lio/devconsole/ui/compose/InspectorRetentionUi;Lio/devconsole/api/ScreenshotResult;ZLjava/util/Set;IILkotlin/jvm/internal/DefaultConstructorMarker;)V + public fun (ZZLjava/util/List;Lio/devconsole/ui/compose/InspectorEditingUi;ZLjava/util/List;Ljava/util/List;Lio/devconsole/ui/compose/InspectorCommandResult;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/Set;Ljava/util/Set;Lio/devconsole/ui/compose/ObserveTab;Ljava/util/Set;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Lio/devconsole/ui/compose/InspectorFileListingUi;Lio/devconsole/ui/compose/InspectorFilePreviewUi;Ljava/lang/String;Ljava/util/List;Lio/devconsole/ui/compose/InspectorDatabaseListingUi;Lio/devconsole/ui/compose/InspectorQueryResultUi;Lio/devconsole/ui/compose/InspectorSqlResultUi;Ljava/util/List;Ljava/lang/String;ZLio/devconsole/ui/compose/InspectorHealthUi;Lio/devconsole/ui/compose/InspectorBrowserUi;Lio/devconsole/ui/compose/InspectorRetentionUi;Lio/devconsole/api/ScreenshotResult;ZLjava/util/Set;)V + public synthetic fun (ZZLjava/util/List;Lio/devconsole/ui/compose/InspectorEditingUi;ZLjava/util/List;Ljava/util/List;Lio/devconsole/ui/compose/InspectorCommandResult;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/Set;Ljava/util/Set;Lio/devconsole/ui/compose/ObserveTab;Ljava/util/Set;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Lio/devconsole/ui/compose/InspectorFileListingUi;Lio/devconsole/ui/compose/InspectorFilePreviewUi;Ljava/lang/String;Ljava/util/List;Lio/devconsole/ui/compose/InspectorDatabaseListingUi;Lio/devconsole/ui/compose/InspectorQueryResultUi;Lio/devconsole/ui/compose/InspectorSqlResultUi;Ljava/util/List;Ljava/lang/String;ZLio/devconsole/ui/compose/InspectorHealthUi;Lio/devconsole/ui/compose/InspectorBrowserUi;Lio/devconsole/ui/compose/InspectorRetentionUi;Lio/devconsole/api/ScreenshotResult;ZLjava/util/Set;IILkotlin/jvm/internal/DefaultConstructorMarker;)V public final fun component1 ()Z public final fun component10 ()Ljava/util/List; public final fun component11 ()Ljava/util/List; @@ -1465,31 +1512,32 @@ public final class io/devconsole/ui/compose/InspectorState { public final fun component19 ()Ljava/util/List; public final fun component2 ()Z public final fun component20 ()Ljava/util/List; - public final fun component21 ()Lio/devconsole/ui/compose/InspectorFileListingUi; - public final fun component22 ()Lio/devconsole/ui/compose/InspectorFilePreviewUi; - public final fun component23 ()Ljava/lang/String; - public final fun component24 ()Ljava/util/List; - public final fun component25 ()Lio/devconsole/ui/compose/InspectorDatabaseListingUi; - public final fun component26 ()Lio/devconsole/ui/compose/InspectorQueryResultUi; - public final fun component27 ()Lio/devconsole/ui/compose/InspectorSqlResultUi; - public final fun component28 ()Ljava/util/List; - public final fun component29 ()Ljava/lang/String; + public final fun component21 ()Ljava/util/List; + public final fun component22 ()Lio/devconsole/ui/compose/InspectorFileListingUi; + public final fun component23 ()Lio/devconsole/ui/compose/InspectorFilePreviewUi; + public final fun component24 ()Ljava/lang/String; + public final fun component25 ()Ljava/util/List; + public final fun component26 ()Lio/devconsole/ui/compose/InspectorDatabaseListingUi; + public final fun component27 ()Lio/devconsole/ui/compose/InspectorQueryResultUi; + public final fun component28 ()Lio/devconsole/ui/compose/InspectorSqlResultUi; + public final fun component29 ()Ljava/util/List; public final fun component3 ()Ljava/util/List; - public final fun component30 ()Z - public final fun component31 ()Lio/devconsole/ui/compose/InspectorHealthUi; - public final fun component32 ()Lio/devconsole/ui/compose/InspectorBrowserUi; - public final fun component33 ()Lio/devconsole/ui/compose/InspectorRetentionUi; - public final fun component34 ()Lio/devconsole/api/ScreenshotResult; - public final fun component35 ()Z - public final fun component36 ()Ljava/util/Set; + public final fun component30 ()Ljava/lang/String; + public final fun component31 ()Z + public final fun component32 ()Lio/devconsole/ui/compose/InspectorHealthUi; + public final fun component33 ()Lio/devconsole/ui/compose/InspectorBrowserUi; + public final fun component34 ()Lio/devconsole/ui/compose/InspectorRetentionUi; + public final fun component35 ()Lio/devconsole/api/ScreenshotResult; + public final fun component36 ()Z + public final fun component37 ()Ljava/util/Set; public final fun component4 ()Lio/devconsole/ui/compose/InspectorEditingUi; public final fun component5 ()Z public final fun component6 ()Ljava/util/List; public final fun component7 ()Ljava/util/List; public final fun component8 ()Lio/devconsole/ui/compose/InspectorCommandResult; public final fun component9 ()Ljava/util/List; - public final fun copy (ZZLjava/util/List;Lio/devconsole/ui/compose/InspectorEditingUi;ZLjava/util/List;Ljava/util/List;Lio/devconsole/ui/compose/InspectorCommandResult;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/Set;Ljava/util/Set;Lio/devconsole/ui/compose/ObserveTab;Ljava/util/Set;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Lio/devconsole/ui/compose/InspectorFileListingUi;Lio/devconsole/ui/compose/InspectorFilePreviewUi;Ljava/lang/String;Ljava/util/List;Lio/devconsole/ui/compose/InspectorDatabaseListingUi;Lio/devconsole/ui/compose/InspectorQueryResultUi;Lio/devconsole/ui/compose/InspectorSqlResultUi;Ljava/util/List;Ljava/lang/String;ZLio/devconsole/ui/compose/InspectorHealthUi;Lio/devconsole/ui/compose/InspectorBrowserUi;Lio/devconsole/ui/compose/InspectorRetentionUi;Lio/devconsole/api/ScreenshotResult;ZLjava/util/Set;)Lio/devconsole/ui/compose/InspectorState; - public static synthetic fun copy$default (Lio/devconsole/ui/compose/InspectorState;ZZLjava/util/List;Lio/devconsole/ui/compose/InspectorEditingUi;ZLjava/util/List;Ljava/util/List;Lio/devconsole/ui/compose/InspectorCommandResult;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/Set;Ljava/util/Set;Lio/devconsole/ui/compose/ObserveTab;Ljava/util/Set;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Lio/devconsole/ui/compose/InspectorFileListingUi;Lio/devconsole/ui/compose/InspectorFilePreviewUi;Ljava/lang/String;Ljava/util/List;Lio/devconsole/ui/compose/InspectorDatabaseListingUi;Lio/devconsole/ui/compose/InspectorQueryResultUi;Lio/devconsole/ui/compose/InspectorSqlResultUi;Ljava/util/List;Ljava/lang/String;ZLio/devconsole/ui/compose/InspectorHealthUi;Lio/devconsole/ui/compose/InspectorBrowserUi;Lio/devconsole/ui/compose/InspectorRetentionUi;Lio/devconsole/api/ScreenshotResult;ZLjava/util/Set;IILjava/lang/Object;)Lio/devconsole/ui/compose/InspectorState; + public final fun copy (ZZLjava/util/List;Lio/devconsole/ui/compose/InspectorEditingUi;ZLjava/util/List;Ljava/util/List;Lio/devconsole/ui/compose/InspectorCommandResult;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/Set;Ljava/util/Set;Lio/devconsole/ui/compose/ObserveTab;Ljava/util/Set;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Lio/devconsole/ui/compose/InspectorFileListingUi;Lio/devconsole/ui/compose/InspectorFilePreviewUi;Ljava/lang/String;Ljava/util/List;Lio/devconsole/ui/compose/InspectorDatabaseListingUi;Lio/devconsole/ui/compose/InspectorQueryResultUi;Lio/devconsole/ui/compose/InspectorSqlResultUi;Ljava/util/List;Ljava/lang/String;ZLio/devconsole/ui/compose/InspectorHealthUi;Lio/devconsole/ui/compose/InspectorBrowserUi;Lio/devconsole/ui/compose/InspectorRetentionUi;Lio/devconsole/api/ScreenshotResult;ZLjava/util/Set;)Lio/devconsole/ui/compose/InspectorState; + public static synthetic fun copy$default (Lio/devconsole/ui/compose/InspectorState;ZZLjava/util/List;Lio/devconsole/ui/compose/InspectorEditingUi;ZLjava/util/List;Ljava/util/List;Lio/devconsole/ui/compose/InspectorCommandResult;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/Set;Ljava/util/Set;Lio/devconsole/ui/compose/ObserveTab;Ljava/util/Set;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Lio/devconsole/ui/compose/InspectorFileListingUi;Lio/devconsole/ui/compose/InspectorFilePreviewUi;Ljava/lang/String;Ljava/util/List;Lio/devconsole/ui/compose/InspectorDatabaseListingUi;Lio/devconsole/ui/compose/InspectorQueryResultUi;Lio/devconsole/ui/compose/InspectorSqlResultUi;Ljava/util/List;Ljava/lang/String;ZLio/devconsole/ui/compose/InspectorHealthUi;Lio/devconsole/ui/compose/InspectorBrowserUi;Lio/devconsole/ui/compose/InspectorRetentionUi;Lio/devconsole/api/ScreenshotResult;ZLjava/util/Set;IILjava/lang/Object;)Lio/devconsole/ui/compose/InspectorState; public fun equals (Ljava/lang/Object;)Z public final fun getAvailable ()Z public final fun getBrowser ()Lio/devconsole/ui/compose/InspectorBrowserUi; @@ -1517,6 +1565,7 @@ public final class io/devconsole/ui/compose/InspectorState { public final fun getPreferenceFiles ()Ljava/util/List; public final fun getPushEvents ()Ljava/util/List; public final fun getQueryResult ()Lio/devconsole/ui/compose/InspectorQueryResultUi; + public final fun getRemoteConfig ()Ljava/util/List; public final fun getRetention ()Lio/devconsole/ui/compose/InspectorRetentionUi; public final fun getSelectedSessionId ()Ljava/lang/String; public final fun getSelectedTransactionIds ()Ljava/util/Set; diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorControlScreen.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorControlScreen.kt index e14e445..a2d2a23 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorControlScreen.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorControlScreen.kt @@ -23,6 +23,7 @@ import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.AlertDialog +import androidx.compose.material3.MaterialTheme import androidx.compose.material3.SnackbarHost import androidx.compose.material3.SnackbarHostState import androidx.compose.material3.Switch @@ -222,6 +223,26 @@ internal fun ControlScreen( } item { Spacer(Modifier.height(8.dp)) } } + // Remote Config is read-only and shares the STATE category with flags. The section + // renders whenever a provider is registered -- including one that reports nothing -- + // because "fetched nothing" and "never fetched" are the answers you came here for. + if (state.captures(CaptureCategory.STATE) && state.remoteConfig.isNotEmpty()) { + state.remoteConfig.forEach { provider -> + item(key = "rc-head-${provider.id}") { RemoteConfigHeader(provider, colors) } + if (provider.unavailableReason != null) { + item(key = "rc-unavailable-${provider.id}") { + WarnNote("Remote Config unavailable: ${provider.unavailableReason}") + } + } else if (provider.entries.isEmpty()) { + item(key = "rc-empty-${provider.id}") { RemoteConfigEmptyNote(provider, colors) } + } else { + items(provider.entries, key = { "rc-${provider.id}-${it.key}" }) { entry -> + RemoteConfigRow(entry, colors) + } + } + item(key = "rc-space-${provider.id}") { Spacer(Modifier.height(8.dp)) } + } + } item { WarnNote( "Composer is intentionally absent — typing URLs on a phone is hostile, so " + @@ -503,6 +524,94 @@ private fun FlagRow( ) } +/** + * Header for one Remote Config provider. The fetch line is the reason this screen exists: a value + * serving an in-app default because the last fetch was throttled looks identical to a published one + * until you can see when the fetch happened and how it ended. + */ +@Composable +private fun RemoteConfigHeader( + provider: InspectorRemoteConfigUi, + colors: DevConsoleColors, +) { + GroupLabel("Remote Config · ${provider.id}") + Text( + text = remoteConfigFetchLine(provider), + modifier = Modifier.padding(start = 16.dp, end = 16.dp, bottom = 8.dp), + color = colors.text3, + style = MaterialTheme.typography.bodySmall, + ) +} + +/** "Never fetched" is spelled out rather than shown as an epoch date. */ +private fun remoteConfigFetchLine(provider: InspectorRemoteConfigUi): String = + buildString { + append("last fetch: ") + append( + provider.lastFetchEpochMs?.let(::formatCaptureClockTime) ?: "never", + ) + append(" · ") + append(provider.status.replace('_', ' ')) + provider.minimumFetchIntervalSeconds?.let { append(" · min interval ${it}s") } + } + +/** + * The `NO_FETCH_YET` case, which is the most commonly misread state: an empty table alone reads as + * "this app has no Remote Config", when the truth is usually that no fetch has completed yet. + */ +@Composable +private fun RemoteConfigEmptyNote( + provider: InspectorRemoteConfigUi, + colors: DevConsoleColors, +) { + Text( + text = + if (provider.lastFetchEpochMs == null) { + "No values — this provider has not completed a fetch yet." + } else { + "No values returned by the last fetch." + }, + modifier = Modifier.padding(start = 16.dp, end = 16.dp, bottom = 8.dp), + color = colors.muted, + style = MaterialTheme.typography.bodySmall, + ) +} + +@Composable +private fun RemoteConfigRow( + entry: InspectorRemoteConfigEntryUi, + colors: DevConsoleColors, +) { + // Colour carries the same meaning as the flag rows above: signal = came from the server, + // warn = a local override is masking it, muted = never reached the server at all. + val leadColor = + when (entry.source) { + "remote" -> colors.signal + "override" -> colors.warn + else -> colors.text3 + } + val leadBg = + when (entry.source) { + "remote" -> colors.signalSoft + "override" -> colors.warnSoft + else -> colors.surface3 + } + val sub = + buildString { + append(if (entry.redacted) "" else entry.value) + if (entry.truncated) append(" · truncated") + } + TonalListRow( + leadText = entry.source.take(3).uppercase(), + leadColor = leadColor, + leadContainerColor = leadBg, + title = entry.key, + subtitle = sub, + trailValue = entry.source, + trailValueColor = if (entry.source == "remote") colors.signal else colors.muted, + ) +} + /** Hand-built fixture for [ControlScreenPreview]. */ private fun controlScreenPreviewState() = InspectorState( diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDataSource.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDataSource.kt index df4f865..460594c 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDataSource.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDataSource.kt @@ -378,6 +378,32 @@ data class InspectorRetentionUi( val maxBytes: Long, ) +/** + * One Remote Config key on the Control surface. Mirrors `remoteconfig.RemoteConfigEntry` without a + * `:sdk:remote-config` dependency, the same way [InspectorBodyKind] mirrors `network.BodyPreview`. + * [source] carries the wire name (`remote`/`default`/`static`/`override`/`unknown`) rather than an + * enum, so this module never has to track the producer's type. + */ +data class InspectorRemoteConfigEntryUi( + val key: String, + val value: String, + val source: String, + val redacted: Boolean = false, + val truncated: Boolean = false, +) + +/** One Remote Config provider and its fetch state, as shown on the Control surface. */ +data class InspectorRemoteConfigUi( + val id: String, + val entries: List = emptyList(), + /** Null means never fetched -- rendered as "never", never as a 1970 timestamp. */ + val lastFetchEpochMs: Long? = null, + val status: String = "unknown", + val minimumFetchIntervalSeconds: Long? = null, + /** Non-null when the provider could not be read at all; shown instead of an empty table. */ + val unavailableReason: String? = null, +) + data class InspectorSnapshot( val available: Boolean = false, val transactions: List = emptyList(), @@ -391,6 +417,11 @@ data class InspectorSnapshot( val crashes: List = emptyList(), val featureFlags: List = emptyList(), val stateProviders: List = emptyList(), + /** + * Remote Config providers, already redacted and gated by [CaptureCategory.STATE]. Defaults to + * empty so every existing adapter and test fake keeps compiling unchanged. + */ + val remoteConfig: List = emptyList(), val preferenceFiles: List = emptyList(), val fileRoots: List = emptyList(), val databases: List = emptyList(), diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorState.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorState.kt index e38d0f5..4bd323e 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorState.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorState.kt @@ -35,6 +35,8 @@ data class InspectorState( val selectedTransactionIds: Set = emptySet(), val featureFlags: List = emptyList(), val stateProviders: List = emptyList(), + /** Remote Config providers, already redacted and STATE-gated by the data source. */ + val remoteConfig: List = emptyList(), val preferenceFiles: List = emptyList(), val fileRoots: List = emptyList(), val fileListing: InspectorFileListingUi? = null, diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorViewModel.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorViewModel.kt index 7164e4f..bfc28cc 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorViewModel.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorViewModel.kt @@ -239,6 +239,7 @@ class InspectorViewModel }, featureFlags = snapshot.featureFlags, stateProviders = snapshot.stateProviders, + remoteConfig = snapshot.remoteConfig, preferenceFiles = snapshot.preferenceFiles, fileRoots = snapshot.fileRoots, databases = snapshot.databases, diff --git a/settings.gradle.kts b/settings.gradle.kts index 6743ca8..095808e 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -47,6 +47,9 @@ include(":sdk:push") include(":sdk:push-firebase") include(":sdk:push-firebase-noop") include(":sdk:state") +include(":sdk:remote-config") +include(":sdk:remote-config-firebase") +include(":sdk:remote-config-firebase-noop") include(":sdk:ui-views") include(":sdk:ui-compose") include(":samples:foundation-app") From 9293bd5485116bbee9fd118d6c2f1fe80177637c Mon Sep 17 00:00:00 2001 From: "Md. Asaduzzaman Nur" Date: Thu, 13 Aug 2026 13:18:56 +0600 Subject: [PATCH 3/7] samples: demonstrate the Remote Config inspector in compose-app compose-app is the full showcase, so it is where the new inspector should be visible without a Firebase project standing in the way. The stand-in provider covers one key of each source -- server, in-app default, static fallback, local override -- so the source badges mean something at a glance rather than all reading "remote". api_key is written snake_case deliberately: that is how Remote Config keys are actually written, and it is exactly the shape a header-derived redaction allowlist misses, so the sample doubles as a live check that the masking works. Co-Authored-By: Claude Opus 5 --- .../devconsole/sample/compose/MainActivity.kt | 49 +++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/samples/compose-app/src/main/kotlin/io/devconsole/sample/compose/MainActivity.kt b/samples/compose-app/src/main/kotlin/io/devconsole/sample/compose/MainActivity.kt index 80e96a1..986afd0 100644 --- a/samples/compose-app/src/main/kotlin/io/devconsole/sample/compose/MainActivity.kt +++ b/samples/compose-app/src/main/kotlin/io/devconsole/sample/compose/MainActivity.kt @@ -94,6 +94,12 @@ import io.devconsole.mocks.MockRule import io.devconsole.mocks.okhttp.DevConsoleMockInterceptor import io.devconsole.network.okhttp.installDevConsole import io.devconsole.push.PushInput +import io.devconsole.remoteconfig.RemoteConfigEntry +import io.devconsole.remoteconfig.RemoteConfigFetchInfo +import io.devconsole.remoteconfig.RemoteConfigFetchStatus +import io.devconsole.remoteconfig.RemoteConfigProvider +import io.devconsole.remoteconfig.RemoteConfigSnapshot +import io.devconsole.remoteconfig.RemoteConfigSource import io.devconsole.socket.okhttp.DevConsoleOkHttpWebSocketListener import io.devconsole.socket.okhttp.DevConsoleRecordingWebSocket import io.devconsole.socket.paho.DevConsolePahoMqtt @@ -117,6 +123,47 @@ import java.util.concurrent.atomic.AtomicInteger private const val SHOW_ORDER_HISTORY_FLAG = "compose_sample.show_order_history" private const val MOCK_RULE_ID = "compose-sample-orders" + +/** + * Stands in for a real Remote Config client so the sample can demonstrate the inspector without + * requiring a Firebase project. A Firebase-backed app registers + * `FirebaseRemoteConfigAdapter(Firebase.remoteConfig)` from + * `devconsole-remote-config-firebase` instead, and reaches the identical view. + * + * The values are chosen to show each thing the inspector is for: one key served from the server, + * one that fell back to an in-app default, one the server has never heard of, one masked by a local + * override, and one whose name trips redaction — `api_key` is written snake_case on purpose, + * because that is how Remote Config keys are actually written and it is the case a header-shaped + * allowlist misses. + */ +private class SampleRemoteConfigProvider : RemoteConfigProvider { + override val id: String = "sample-remote-config" + + override fun snapshot(): RemoteConfigSnapshot = + RemoteConfigSnapshot( + providerId = id, + entries = + listOf( + RemoteConfigEntry("checkout_v2_enabled", "true", RemoteConfigSource.REMOTE), + RemoteConfigEntry("promo_banner_text", "Free delivery this week", RemoteConfigSource.REMOTE), + RemoteConfigEntry("max_cart_items", "20", RemoteConfigSource.DEFAULT), + RemoteConfigEntry("courier_eta_strategy", "", RemoteConfigSource.STATIC), + RemoteConfigEntry("api_base_url", "https://staging.example.test", RemoteConfigSource.OVERRIDE), + RemoteConfigEntry("api_key", "super-secret-value", RemoteConfigSource.REMOTE), + ), + fetchInfo = + RemoteConfigFetchInfo( + lastFetchEpochMs = System.currentTimeMillis() - FETCH_AGE_MS, + status = RemoteConfigFetchStatus.SUCCESS, + minimumFetchIntervalSeconds = 3600L, + ), + ) + + private companion object { + const val FETCH_AGE_MS = 90_000L + } +} + private val requestCount = AtomicInteger(0) /** @@ -285,6 +332,8 @@ class MainActivity : ComponentActivity() { composerAllowedHosts = setOf("jsonplaceholder.typicode.com", "example.test", "postman-echo.com"), // Lets the dashboard drive registered state mutations; state is read-only otherwise. stateMutationsEnabled = true, + ).withRemoteConfigProviders( + listOf(SampleRemoteConfigProvider()), ).withBrowserConfig( // Governs the in-app inspector's own More-screen Start button, which issues no // StartRequest of its own -- without this it would bind loopback while the sample's From 95f9cc5d496b3974af2eb35d205f570278ce6135 Mon Sep 17 00:00:00 2001 From: "Md. Asaduzzaman Nur" Date: Thu, 13 Aug 2026 13:34:57 +0600 Subject: [PATCH 4/7] docs: document Remote Config setup in the README The feature was reachable only from docs/REMOTE_CONFIG.md, which is the wrong place to learn a coordinate exists. The README now carries the setup walkthrough next to the network one, the adapter's coordinate pair in the add-on table, and a row in the capability table. The source table is the part worth having in front of you: it is the column that separates "the value you published" from "a default the app fell back to when the fetch was throttled", which is the question the inspector exists to answer. Also corrects the module count from 31 to 34 in the README, CONTRIBUTING and MAVEN_PUBLISHING, which the three new modules invalidated. The 1.1.1 changelog entry keeps its 31 -- that was accurate when it shipped. Co-Authored-By: Claude Opus 5 --- CONTRIBUTING.md | 2 +- README.md | 57 +++++++++++++++++++++++++++++++++++++++- docs/MAVEN_PUBLISHING.md | 4 +-- 3 files changed, 59 insertions(+), 4 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index eaf9c2c..9bb6417 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,6 +1,6 @@ # Contributing to DevConsole -Thanks for taking a look. This is a 31-module Android SDK plus two included Gradle builds +Thanks for taking a look. This is a 34-module Android SDK plus two included Gradle builds (`build-logic` and `gradle-plugin`), which sounds like a lot until you realise you rarely touch more than one at a time. The quickest way in is to run the same commands CI runs, listed below and in [Verify](.github/workflows/verify.yml). diff --git a/README.md b/README.md index 8059a99..ab6eaed 100644 --- a/README.md +++ b/README.md @@ -101,6 +101,7 @@ gets you nothing. | **Crash & ANR capture** | Uncaught exceptions and a main-looper watchdog with bounded all-thread dumps and breadcrumbs. Always delegates to any crash reporter you already have. | | **Push timeline** | Record FCM (or any) push messages and their lifecycle: received → displayed → opened. The Firebase adapter uses reflection — no compile-time Firebase dependency. | | **State & feature flags** | Snapshot host-registered state and override feature flags from the browser. | +| **Remote Config inspector** | Every Remote Config value active on the device, and where each one came from — server, in-app default, static fallback, or a local override — plus last fetch time and status. Read-only. The Firebase adapter uses reflection — no compile-time Firebase dependency. | | **Data inspectors** | Browse SharedPreferences, SQLite (incl. a SQL console), and app files. Read-only by default; every edit surface is opt-in. | | **Evidence tray & exports** | Flag anything, attach it to a bug report bundle or Markdown/Jira/GitHub clipboard text. Export HAR, Postman Collection, or a full session ZIP. | | **Background keep-alive** | Opt-in foreground service that keeps the server alive while your app is backgrounded. Manifest-only opt-in, zero SDK-declared permissions. | @@ -281,6 +282,59 @@ you can replay it, clone it into the composer, or flag it into a bug report:

Network inspector in the browser dashboard, showing a captured request and response side by side

+### Set up Remote Config + +Add the adapter — it is not part of the `devconsole` umbrella, so that Firebase never lands on the +classpath of an app that doesn't use it: + +```kotlin +debugImplementation("io.github.devconsole-android:devconsole-remote-config-firebase:1.1.1") +releaseImplementation("io.github.devconsole-android:devconsole-remote-config-firebase-noop:1.1.1") +``` + +Then hand DevConsole your `FirebaseRemoteConfig` instance at init: + +```kotlin +DevConsole.initialize( + application, + DevConsoleConfig(/* … */) + .withRemoteConfigProviders(listOf(FirebaseRemoteConfigAdapter(Firebase.remoteConfig))), +) +``` + +If the client is built lazily — through DI, or only once a first fetch completes — register it when +you have it. This is safe to call late, unlike feature flags, because values are read on demand +rather than snapshotted at startup: + +```kotlin +DevConsole.registerRemoteConfigProvider(FirebaseRemoteConfigAdapter(Firebase.remoteConfig)) +``` + +That's the whole setup. Values then appear on the dashboard's **Remote Config** page and in the +in-app inspector's **Control** screen, each tagged with where it came from: + +| Source | Meaning | +|---|---| +| `remote` | Fetched from the server and activated. | +| `default` | An in-app default (`setDefaultsAsync`) — no server value is active for this key. | +| `static` | Set nowhere — the SDK's static fallback for an unknown key. | +| `override` | A local override is masking whatever the provider resolved. | + +That last column is the reason this inspector exists. Knowing a flag reads `false` is rarely the +hard part; knowing whether it reads `false` because you published it, or because the last fetch was +throttled and the app quietly fell back to a default, is. Each provider also reports its last fetch +time, last fetch status, and minimum fetch interval — and a provider that has never fetched says +`never`, rather than showing an epoch date. + +Not using Firebase? Implement `RemoteConfigProvider` for any other service — the model is +vendor-neutral, and [docs/REMOTE_CONFIG.md](docs/REMOTE_CONFIG.md) has a worked example. The +inspector is read-only: DevConsole never sets overrides and never triggers `fetch()` or `activate()`. + +Values are redacted by key name before either surface sees them, matched separator-insensitively so +`api_key` and `apiKey` are caught as well as `api-key`. It is still an allowlist, so a secret under +a name nobody listed is shown in full — extend `RedactionPolicy.sensitiveFieldNames` if you keep +anything sensitive in Remote Config. + ## Artifacts Group `io.github.devconsole-android`, one version for everything. There is deliberately no BOM, and @@ -300,6 +354,7 @@ Opt-in add-ons (each `-noop` twin is the matching `releaseImplementation`): | `devconsole-network-ktor` | *(none)* | Ktor `HttpClient` capture plugin (full request + response body capture, any engine; see [Network adapters](docs/NETWORK_ADAPTERS.md)) | | `devconsole-socket-paho` | `devconsole-socket-paho-noop` | MQTT capture via Eclipse Paho | | `devconsole-push-firebase` | `devconsole-push-firebase-noop` | FCM push adapter (reflection-based) | +| `devconsole-remote-config-firebase` | `devconsole-remote-config-firebase-noop` | Firebase Remote Config adapter (reflection-based; see [Remote Config](docs/REMOTE_CONFIG.md)) | Everything else (`devconsole-core`, `devconsole-storage-room`, and the rest) arrives transitively. You never name those. Every module publishes sources, javadoc, and a signed POM. @@ -332,7 +387,7 @@ A release tag works as the bare tag, as above. Any branch works as `-SNA written as `~`, so a `feature/x` branch is `feature~x-SNAPSHOT`. JitPack support starts at **1.1.1**; earlier tags do not build there. Three things to know before you rely on it: -- **The Gradle plugin is not on JitPack.** Only the 31 library artifacts are, so the +- **The Gradle plugin is not on JitPack.** Only the 34 library artifacts are, so the `plugins { id("io.github.devconsole-android") … }` block above does not apply. Name the `debugImplementation` and `releaseImplementation` coordinates yourself. You also give up the plugin's variant-policy check, which is the thing that keeps the full SDK out of release builds. diff --git a/docs/MAVEN_PUBLISHING.md b/docs/MAVEN_PUBLISHING.md index cf7b052..b42e484 100644 --- a/docs/MAVEN_PUBLISHING.md +++ b/docs/MAVEN_PUBLISHING.md @@ -1,6 +1,6 @@ # Publishing to Maven Central -All 31 modules under `sdk/` are wired with the +All 34 modules under `sdk/` are wired with the [Vanniktech Maven Publish plugin](https://github.com/vanniktech/gradle-maven-publish-plugin) (via the `devconsole.publishing` convention), targeting the Sonatype **Central Portal** under the group `io.github.devconsole-android`. Artifact IDs follow the mapping in @@ -117,6 +117,6 @@ that registers `.asc` artifacts fails there with "artifact file does not exist". `PublishingConventionPlugin` calls `signAllPublications()` only when a key is configured — the same condition that lets a contributor run `publishToMavenLocal` without one. -Only the 31 library modules are served; `gradle-plugin` is an `includeBuild` and is not among them, +Only the 34 library modules are served; `gradle-plugin` is an `includeBuild` and is not among them, so JitPack consumers use plain coordinates rather than the plugin. Check a build at `https://jitpack.io/api/builds/com.github.devconsole-android/DevConsole`. From 0ec1e53bb2fe23056d726ee8b8d33525c465891a Mon Sep 17 00:00:00 2001 From: "Md. Asaduzzaman Nur" Date: Thu, 13 Aug 2026 16:58:32 +0600 Subject: [PATCH 5/7] feat: open a Remote Config value in full from the dashboard A Remote Config value is a string on the wire, so the table row could only ever preview it -- a JSON blob read as one elided line, which is the shape most non-trivial config actually takes. Clicking a key now opens the whole thing. Pretty JSON is the default, but only where it means something. The viewer parses first: on success it renders the existing syntax-highlighted block, and on failure it opens on Raw with the JSON segment disabled and says so. It never re-quotes a non-JSON value into a JSON string literal to make the toggle work -- the quotes would be this viewer's invention rather than something the server sent, which is the same rule the source badge follows. Values like `on` or `v2` are common enough that the fallback is the ordinary path, not an edge case. Truncated and redacted values are told apart from "just not JSON" in the notice line, so nobody debugs a parse failure that is really a length cut or a redaction. cardRowsHtml grew an optional `click` id that renders the row as a real ${block}
`; @@ -772,15 +779,20 @@ .map((s) => `${esc(s.label)}${esc(s.val)}`) .join('')}
`; } + /** `r.click`, when set, makes the row a real `` + : `
${inner}
`; + }) .join('')}`; } function cardMetricsHtml(metrics) { @@ -917,7 +929,7 @@ if (wiredCardGrids.has(containerId)) return; wiredCardGrids.add(containerId); $(containerId).addEventListener('click', (e) => { - const { onToggle, onButton, onTree, onDelete, onEdit } = cardGridHandlers[containerId]; + const { onToggle, onButton, onTree, onDelete, onEdit, onRow } = cardGridHandlers[containerId]; const ed = e.target.closest('[data-card-edit]'); if (ed && onEdit) { onEdit(ed.dataset.cardEdit); @@ -938,6 +950,11 @@ onButton(b.dataset.cardBtn); return; } + const row = e.target.closest('[data-card-row]'); + if (row && onRow) { + onRow(row.dataset.cardRow); + return; + } const n = e.target.closest('[data-tree-id]'); if (n && onTree) onTree(n.dataset.treeId); }); @@ -1347,6 +1364,8 @@ const overlay = $('codeFullscreenModal'); if (!overlay || !sourceBlock) return; $('codeFullscreenTitle').textContent = title || 'JSON body'; + // Clones the already-escaped markup rather than re-deriving it from data, so this cannot + // disagree with what the page underneath is showing. $('codeFullscreenBody').innerHTML = `
${sourceBlock.innerHTML}
`; codeFullscreenOpenerEl = document.activeElement; overlay.hidden = false; @@ -4448,6 +4467,11 @@ rows: shown.map((e) => ({ k: e.key, v: e.redacted ? '' : e.value, + // A [providerId, key] pair, not a position in `shown`: the search box and the source + // filter re-render this list constantly, and an index would point at a different key + // after either one changes. Same composite-dataset-key shape the mock diff rows use. + click: JSON.stringify([provider.id, e.key]), + clickTitle: 'Show the full value of ' + e.key, tone: e.source === 'remote' ? 'ink' : 'muted', tag: (e.source || 'unknown').toUpperCase() + (e.truncated ? ' · TRUNCATED' : ''), tagTone: REMOTE_CONFIG_SOURCE_TONE[e.source] || 'muted', @@ -4456,6 +4480,116 @@ })); } + // ================================================================ + // Remote Config value modal — a Remote Config value is a *string* on the wire (see + // RemoteConfigEntry's own doc), so the card row can only ever show a one-line preview of it. + // This is where you read the whole thing: pretty-printed when it really is JSON, verbatim when + // it is not. Deliberately never renders a non-JSON value as a quoted JSON string — the quotes + // would be this viewer's invention, not something the server sent, which is the same rule the + // source badge follows. + // ================================================================ + let remoteConfigValueTarget = null; // { providerId, key } — null while the modal is closed + let remoteConfigValueMode = 'json'; // 'json' | 'raw' + let remoteConfigValueOpenerEl = null; + function remoteConfigEntryAt(providerId, key) { + const provider = remoteConfigProviders.find((p) => p.id === providerId); + return provider ? (provider.entries || []).find((e) => e.key === key) : undefined; + } + /** Pretty JSON is offered only when the value actually parses. A redacted value has no real + * content to parse, and a truncated one is a cut string that will almost never parse — both are + * told apart from "just not JSON" so nobody debugs a parse failure that is really a length cut. */ + function remoteConfigValueView(entry) { + if (!entry) return { mode: 'raw', jsonOk: false, text: '', notice: '' }; + if (entry.redacted) { + return { mode: 'raw', jsonOk: false, text: '', notice: 'Value withheld by the redaction policy.' }; + } + const text = entry.value == null ? '' : String(entry.value); + let parsed; + try { + parsed = JSON.parse(text); + } catch { + return { + mode: 'raw', jsonOk: false, text, + notice: entry.truncated + ? 'Value was truncated on capture, so it no longer parses as JSON — showing raw text.' + : 'Not valid JSON — showing raw text.', + }; + } + return { mode: 'json', jsonOk: true, parsed, text, notice: entry.truncated ? 'Value was truncated on capture.' : '' }; + } + function renderRemoteConfigValueModal() { + if (!remoteConfigValueTarget) return; + const entry = remoteConfigEntryAt(remoteConfigValueTarget.providerId, remoteConfigValueTarget.key); + const view = remoteConfigValueView(entry); + const source = (entry && entry.source) || 'unknown'; + $('remoteConfigValueTitle').textContent = remoteConfigValueTarget.key; + const badge = $('remoteConfigValueSource'); + badge.textContent = source.toUpperCase() + (entry && entry.truncated ? ' · TRUNCATED' : ''); + badge.className = 'card-row-tag tone-text-' + (REMOTE_CONFIG_SOURCE_TONE[source] || 'muted'); + $('remoteConfigValueProvider').textContent = remoteConfigValueTarget.providerId; + const jsonBtn = $('remoteConfigValueSeg').querySelector('button[data-value="json"]'); + jsonBtn.disabled = !view.jsonOk; + jsonBtn.title = view.jsonOk ? 'Pretty-print this value as JSON' : 'This value is not valid JSON'; + $('remoteConfigValueSeg').querySelectorAll('button').forEach((b) => { + const on = b.dataset.value === remoteConfigValueMode; + b.classList.toggle('active', on); + b.setAttribute('aria-pressed', String(on)); + }); + const notice = $('remoteConfigValueNotice'); + notice.textContent = view.notice; + notice.hidden = !view.notice; + $('remoteConfigValueBody').innerHTML = remoteConfigValueMode === 'json' && view.jsonOk + ? codeLinesHtml(formatJsonLines(view.parsed, ''), true) + : `
${esc(view.text)}
`; + } + function openRemoteConfigValue(rowId) { + let providerId, key; + try { + [providerId, key] = JSON.parse(rowId); + } catch { + return; + } + const entry = remoteConfigEntryAt(providerId, key); + if (!entry) return; + remoteConfigValueTarget = { providerId, key }; + // Pretty JSON is the default, but only where it means anything: a plain string value opens on + // Raw with the JSON segment disabled rather than on an error you have to click past. + remoteConfigValueMode = remoteConfigValueView(entry).mode; + remoteConfigValueOpenerEl = document.activeElement; + renderRemoteConfigValueModal(); + $('remoteConfigValueModal').hidden = false; + document.addEventListener('keydown', remoteConfigValueKeydown); + $('remoteConfigValueClose').focus(); + } + function closeRemoteConfigValue() { + const overlay = $('remoteConfigValueModal'); + if (!overlay || overlay.hidden) return; + overlay.hidden = true; + $('remoteConfigValueBody').innerHTML = ''; + remoteConfigValueTarget = null; + document.removeEventListener('keydown', remoteConfigValueKeydown); + remoteConfigValueOpenerEl?.focus?.(); + remoteConfigValueOpenerEl = null; + } + function remoteConfigValueKeydown(e) { + const overlay = $('remoteConfigValueModal'); + if (e.key === 'Escape') { closeRemoteConfigValue(); return; } + if (e.key !== 'Tab') return; + const focusable = [...overlay.querySelectorAll('button')].filter((el) => !el.disabled && el.offsetParent !== null); + if (!focusable.length) return; + const first = focusable[0], last = focusable[focusable.length - 1]; + if (e.shiftKey && document.activeElement === first) { e.preventDefault(); last.focus(); } + else if (!e.shiftKey && document.activeElement === last) { e.preventDefault(); first.focus(); } + } + /** Copies what is on screen, not always the raw value: someone who switched to Pretty JSON to + * read it wants the indented text they are looking at. */ + function copyRemoteConfigValue() { + if (!remoteConfigValueTarget) return; + const view = remoteConfigValueView(remoteConfigEntryAt(remoteConfigValueTarget.providerId, remoteConfigValueTarget.key)); + const text = remoteConfigValueMode === 'json' && view.jsonOk ? JSON.stringify(view.parsed, null, 2) : view.text; + copyToClipboard(text, remoteConfigValueTarget.key); + } + // ================================================================ // Preferences // ================================================================ @@ -7287,6 +7421,11 @@ $('remoteConfigRefresh').onclick = loadRemoteConfig; $('remoteConfigSearch').oninput = (e) => { remoteConfigQuery = e.target.value; renderRemoteConfigCards(); }; wireSeg($('remoteConfigSourceSeg'), (value) => { remoteConfigSourceFilter = value; renderRemoteConfigCards(); }); + wireCardGrid('remoteConfigCards', { onRow: openRemoteConfigValue }); + $('remoteConfigValueClose').onclick = closeRemoteConfigValue; + $('remoteConfigValueCopy').onclick = copyRemoteConfigValue; + $('remoteConfigValueModal').addEventListener('click', (e) => { if (e.target.id === 'remoteConfigValueModal') closeRemoteConfigValue(); }); + wireSeg($('remoteConfigValueSeg'), (value) => { remoteConfigValueMode = value; renderRemoteConfigValueModal(); }); $('prefFile').onchange = (e) => renderPreferenceFile(e.target.value); diff --git a/sdk/server-ktor/src/main/resources/devconsole-web/index.html b/sdk/server-ktor/src/main/resources/devconsole-web/index.html index b2ab665..2fc72af 100644 --- a/sdk/server-ktor/src/main/resources/devconsole-web/index.html +++ b/sdk/server-ktor/src/main/resources/devconsole-web/index.html @@ -733,6 +733,26 @@ + + +
diff --git a/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/DashboardAssetsTest.kt b/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/DashboardAssetsTest.kt index cac7f17..015f7a2 100644 --- a/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/DashboardAssetsTest.kt +++ b/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/DashboardAssetsTest.kt @@ -76,6 +76,30 @@ class DashboardAssetsTest { } } + @Test + fun `remote config keys open a value viewer offering both pretty JSON and raw`() { + val dashboard = DashboardAssets.index() + val script = DashboardAssets.js() + + listOf( + "remoteConfigValueModal", + "remoteConfigValueSeg", + "remoteConfigValueBody", + "remoteConfigValueNotice", + "remoteConfigValueCopy", + "remoteConfigValueClose", + ).forEach { id -> + assertTrue("expected dashboard to contain id=\"$id\"", dashboard.contains("id=\"$id\"")) + } + // Pretty JSON is the segment that carries `active` in the static markup, so the viewer + // opens on it for every value that actually parses. + assertTrue(dashboard.contains("")) + assertTrue(dashboard.contains("data-value=\"raw\">Raw")) + // The rows have to be clickable for any of the above to be reachable. + assertTrue(script.contains("openRemoteConfigValue")) + assertTrue(script.contains("data-card-row")) + } + @Test fun `network view offers a Postman export next to the existing HAR export`() { val dashboard = DashboardAssets.index() From 15c166c273e34c8d114605f64d1d43f2045d9bc8 Mon Sep 17 00:00:00 2001 From: "Md. Asaduzzaman Nur" Date: Thu, 13 Aug 2026 16:58:53 +0600 Subject: [PATCH 6/7] feat: Remote Config moves to an Observe tab with a per-key detail Remote Config was a section on the Control screen, which is not where it belonged: it is read-only, so nothing on it was ever a control. It is now a Config tab on Observe, and tapping a key opens its value -- the same thing the dashboard's value window does, reached the same way. The tab is gated on `captures(STATE) && remoteConfig.isNotEmpty()`, the exact condition the Control section used, so which sessions can see Remote Config is unchanged; only where it lives moved. That does make it the first tab whose visibility reads data rather than its category alone, and deliberately so: InspectorTabRow is a fixed Row splitting its width equally between the tabs it is handed, and STATE is on by default, so a category-only gate would have narrowed every other tab in every app that registers no provider -- which is most of them. A provider list emptying mid-session needs no new code: the ViewModel's existing snap onto the first still-visible tab already covers it, and now has a test for it. The detail's Value section is a formattableTextBody, whose existing default is already the rule the dashboard follows -- formatted when the value parses, raw when it does not -- so the two surfaces agree without either one reimplementing it. A redacted entry gets an explicit note rather than a Raw/Formatted toggle over the literal placeholder, the same treatment a binary body gets. ObserveDetailContent gained a searchPlaceholder because the shared detail screen was offering to search "headers, payload, response" on a screen holding exactly one config value. It defaults to the old string, so only this screen changed. The sample gained a JSON-valued key: without one it demonstrated the inspector but not the reason to open a value at all. ObserveTab is public API, so the new constant is an accepted apiDump. Co-Authored-By: Claude Opus 5 --- CHANGELOG.md | 11 +- docs/REMOTE_CONFIG.md | 16 +- .../devconsole/sample/compose/MainActivity.kt | 10 ++ sdk/ui-compose/api/ui-compose.api | 11 +- .../ui/compose/InspectorControlScreen.kt | 113 +------------ .../ui/compose/InspectorDataSource.kt | 6 +- .../ui/compose/InspectorDetailSearchField.kt | 2 +- .../ui/compose/InspectorObserveDetail.kt | 11 ++ .../ui/compose/InspectorObservePreviews.kt | 34 +++- .../InspectorObserveRemoteConfigDetail.kt | 115 +++++++++++++ .../InspectorObserveRemoteConfigTab.kt | 159 ++++++++++++++++++ .../ui/compose/InspectorObserveScreen.kt | 39 +++++ .../ui/compose/InspectorRemoteConfigFormat.kt | 82 +++++++++ .../devconsole/ui/compose/InspectorState.kt | 17 +- .../InspectorCaptureCategoryGatingTest.kt | 52 +++++- .../ui/compose/InspectorViewModelTest.kt | 31 ++++ 16 files changed, 589 insertions(+), 120 deletions(-) create mode 100644 sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveRemoteConfigDetail.kt create mode 100644 sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveRemoteConfigTab.kt create mode 100644 sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorRemoteConfigFormat.kt diff --git a/CHANGELOG.md b/CHANGELOG.md index 5963118..ab992fd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -37,13 +37,22 @@ joined this list.) the `devconsole` umbrella. Surfaces on both the browser dashboard (a Remote Config page under Data) and the Compose - inspector's Control screen, and over `GET /api/v1/remote-config`. Gated by the existing + inspector's Observe screen (a **Config** tab, shown only when a provider is registered, since the + on-device tab row splits its width equally and should not spend a tab on an app with no Remote + Config), and over `GET /api/v1/remote-config`. Gated by the existing `CaptureCategory.STATE`, alongside state providers and feature flags. Register a provider with `DevConsoleConfig.withRemoteConfigProviders(...)` or, for a lazily-built client, `DevConsole.registerRemoteConfigProvider(...)`. Read-only by design: DevConsole does not set overrides and never triggers `fetch()`/`activate()`. See [docs/REMOTE_CONFIG.md](docs/REMOTE_CONFIG.md). + A config value is a string of any length, so the tables show a preview and open the full value on + demand: click a key on the dashboard, tap a row on the Config tab. Both default to pretty-printed + JSON and fall back to the raw string with a toggle between them — a value like `on` or `v2` is + never re-quoted to make it parse, since the quotes would be the viewer's invention rather than + something the server sent, and a truncated or redacted value says so rather than failing to parse + for an unexplained reason. + Values are redacted by key name at a single boundary shared by both surfaces — the on-device inspector reads in-process and never crosses the HTTP boundary, so redacting at the route alone would have left it exposed. Matching is separator-insensitive here, unlike the raw diff --git a/docs/REMOTE_CONFIG.md b/docs/REMOTE_CONFIG.md index c8cbb3c..72e3fe2 100644 --- a/docs/REMOTE_CONFIG.md +++ b/docs/REMOTE_CONFIG.md @@ -100,11 +100,25 @@ shown. Add your own names through `RedactionPolicy.sensitiveFieldNames`. The browser dashboard's **Remote Config** page (under Data, next to State & flags) lists each provider with its fetch line and a Key / Value / Source table, filterable by key and by source. The -Compose inspector shows the same data as a section on its **Control** screen, beside feature flags. +Compose inspector shows the same data on the **Config** tab of its Observe screen. That tab appears +only when at least one provider is registered — the on-device tab row splits its width equally +between tabs, so it does not spend one on an app that has no Remote Config. Both distinguish four states explicitly rather than rendering a blank table: no provider registered, capture category disabled, provider unavailable, and "fetched nothing / never fetched". +### Reading a value in full + +A Remote Config value is a string of any length, so both surfaces show only a preview in the table +and open the whole value on demand: click a key in the dashboard for a value window, or tap a row on +the Config tab for the key's detail screen. + +Both default to pretty-printed JSON and fall back to the raw string, with a toggle between the two. +The fallback is deliberate — plenty of values are plain strings like `on` or `v2`, and neither +surface will re-quote one to make it parse, because the quotes would be the viewer's invention +rather than something the server sent. A value that was truncated on capture, or withheld by +redaction, says so instead of failing to parse for an unexplained reason. + ## Scope This inspector is **read-only**. DevConsole does not set overrides and does not trigger `fetch()` or diff --git a/samples/compose-app/src/main/kotlin/io/devconsole/sample/compose/MainActivity.kt b/samples/compose-app/src/main/kotlin/io/devconsole/sample/compose/MainActivity.kt index 986afd0..fdc6997 100644 --- a/samples/compose-app/src/main/kotlin/io/devconsole/sample/compose/MainActivity.kt +++ b/samples/compose-app/src/main/kotlin/io/devconsole/sample/compose/MainActivity.kt @@ -135,6 +135,10 @@ private const val MOCK_RULE_ID = "compose-sample-orders" * override, and one whose name trips redaction — `api_key` is written snake_case on purpose, * because that is how Remote Config keys are actually written and it is the case a header-shaped * allowlist misses. + * + * `checkout_experiment` holds a JSON object because that is the value shape the row can only ever + * preview: opening it shows the pretty-printed tree, while `promo_banner_text` beside it opens as + * raw text, since a plain string is not JSON and is not dressed up as though it were. */ private class SampleRemoteConfigProvider : RemoteConfigProvider { override val id: String = "sample-remote-config" @@ -145,6 +149,7 @@ private class SampleRemoteConfigProvider : RemoteConfigProvider { entries = listOf( RemoteConfigEntry("checkout_v2_enabled", "true", RemoteConfigSource.REMOTE), + RemoteConfigEntry("checkout_experiment", CHECKOUT_EXPERIMENT_JSON, RemoteConfigSource.REMOTE), RemoteConfigEntry("promo_banner_text", "Free delivery this week", RemoteConfigSource.REMOTE), RemoteConfigEntry("max_cart_items", "20", RemoteConfigSource.DEFAULT), RemoteConfigEntry("courier_eta_strategy", "", RemoteConfigSource.STATIC), @@ -161,6 +166,11 @@ private class SampleRemoteConfigProvider : RemoteConfigProvider { private companion object { const val FETCH_AGE_MS = 90_000L + + /** One line, exactly as a Remote Config server sends it — the viewer does the indenting. */ + const val CHECKOUT_EXPERIMENT_JSON = + """{"id":"checkout-flow-2026-08","variant":"b","rollout":0.25,""" + + """"steps":["cart","address","payment"],"fallback":null}""" } } diff --git a/sdk/ui-compose/api/ui-compose.api b/sdk/ui-compose/api/ui-compose.api index 30539dd..b10cd69 100644 --- a/sdk/ui-compose/api/ui-compose.api +++ b/sdk/ui-compose/api/ui-compose.api @@ -20,7 +20,6 @@ public final class io/devconsole/ui/compose/ComposableSingletons$DevConsolePanel public final class io/devconsole/ui/compose/ComposableSingletons$InspectorControlScreenKt { public static final field INSTANCE Lio/devconsole/ui/compose/ComposableSingletons$InspectorControlScreenKt; public fun ()V - public final fun getLambda$-1143782739$ui_compose_release ()Lkotlin/jvm/functions/Function3; public final fun getLambda$-1373757892$ui_compose_release ()Lkotlin/jvm/functions/Function3; public final fun getLambda$-153603954$ui_compose_release ()Lkotlin/jvm/functions/Function2; public final fun getLambda$-1946392255$ui_compose_release ()Lkotlin/jvm/functions/Function3; @@ -134,12 +133,21 @@ public final class io/devconsole/ui/compose/ComposableSingletons$InspectorObserv public final fun getLambda$-650102098$ui_compose_release ()Lkotlin/jvm/functions/Function2; public final fun getLambda$-970086269$ui_compose_release ()Lkotlin/jvm/functions/Function2; public final fun getLambda$-998201989$ui_compose_release ()Lkotlin/jvm/functions/Function2; + public final fun getLambda$1640041240$ui_compose_release ()Lkotlin/jvm/functions/Function2; public final fun getLambda$1735444109$ui_compose_release ()Lkotlin/jvm/functions/Function2; + public final fun getLambda$31180393$ui_compose_release ()Lkotlin/jvm/functions/Function2; public final fun getLambda$506389634$ui_compose_release ()Lkotlin/jvm/functions/Function2; public final fun getLambda$59331127$ui_compose_release ()Lkotlin/jvm/functions/Function2; public final fun getLambda$924899110$ui_compose_release ()Lkotlin/jvm/functions/Function2; } +public final class io/devconsole/ui/compose/ComposableSingletons$InspectorObserveRemoteConfigTabKt { + public static final field INSTANCE Lio/devconsole/ui/compose/ComposableSingletons$InspectorObserveRemoteConfigTabKt; + public fun ()V + public final fun getLambda$-1047114689$ui_compose_release ()Lkotlin/jvm/functions/Function3; + public final fun getLambda$-1125610964$ui_compose_release ()Lkotlin/jvm/functions/Function3; +} + public final class io/devconsole/ui/compose/ComposableSingletons$InspectorObserveSignalsKt { public static final field INSTANCE Lio/devconsole/ui/compose/ComposableSingletons$InspectorObserveSignalsKt; public fun ()V @@ -1714,6 +1722,7 @@ public final class io/devconsole/ui/compose/ObserveTab : java/lang/Enum { public static final field CRASHES Lio/devconsole/ui/compose/ObserveTab; public static final field LOGS Lio/devconsole/ui/compose/ObserveTab; public static final field PUSH Lio/devconsole/ui/compose/ObserveTab; + public static final field REMOTE_CONFIG Lio/devconsole/ui/compose/ObserveTab; public static final field SOCKETS Lio/devconsole/ui/compose/ObserveTab; public static final field TRAFFIC Lio/devconsole/ui/compose/ObserveTab; public static fun getEntries ()Lkotlin/enums/EnumEntries; diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorControlScreen.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorControlScreen.kt index a2d2a23..ba6ebc1 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorControlScreen.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorControlScreen.kt @@ -23,7 +23,6 @@ import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.AlertDialog -import androidx.compose.material3.MaterialTheme import androidx.compose.material3.SnackbarHost import androidx.compose.material3.SnackbarHostState import androidx.compose.material3.Switch @@ -223,26 +222,10 @@ internal fun ControlScreen( } item { Spacer(Modifier.height(8.dp)) } } - // Remote Config is read-only and shares the STATE category with flags. The section - // renders whenever a provider is registered -- including one that reports nothing -- - // because "fetched nothing" and "never fetched" are the answers you came here for. - if (state.captures(CaptureCategory.STATE) && state.remoteConfig.isNotEmpty()) { - state.remoteConfig.forEach { provider -> - item(key = "rc-head-${provider.id}") { RemoteConfigHeader(provider, colors) } - if (provider.unavailableReason != null) { - item(key = "rc-unavailable-${provider.id}") { - WarnNote("Remote Config unavailable: ${provider.unavailableReason}") - } - } else if (provider.entries.isEmpty()) { - item(key = "rc-empty-${provider.id}") { RemoteConfigEmptyNote(provider, colors) } - } else { - items(provider.entries, key = { "rc-${provider.id}-${it.key}" }) { entry -> - RemoteConfigRow(entry, colors) - } - } - item(key = "rc-space-${provider.id}") { Spacer(Modifier.height(8.dp)) } - } - } + // Remote Config used to render here, beside flags. It moved to the Observe surface's + // Config tab (see RemoteConfigTabContent): it is read-only, so nothing on it was ever + // a control, and a value big enough to need reading in full needed a detail screen + // this list had no way to open. item { WarnNote( "Composer is intentionally absent — typing URLs on a phone is hostile, so " + @@ -524,94 +507,6 @@ private fun FlagRow( ) } -/** - * Header for one Remote Config provider. The fetch line is the reason this screen exists: a value - * serving an in-app default because the last fetch was throttled looks identical to a published one - * until you can see when the fetch happened and how it ended. - */ -@Composable -private fun RemoteConfigHeader( - provider: InspectorRemoteConfigUi, - colors: DevConsoleColors, -) { - GroupLabel("Remote Config · ${provider.id}") - Text( - text = remoteConfigFetchLine(provider), - modifier = Modifier.padding(start = 16.dp, end = 16.dp, bottom = 8.dp), - color = colors.text3, - style = MaterialTheme.typography.bodySmall, - ) -} - -/** "Never fetched" is spelled out rather than shown as an epoch date. */ -private fun remoteConfigFetchLine(provider: InspectorRemoteConfigUi): String = - buildString { - append("last fetch: ") - append( - provider.lastFetchEpochMs?.let(::formatCaptureClockTime) ?: "never", - ) - append(" · ") - append(provider.status.replace('_', ' ')) - provider.minimumFetchIntervalSeconds?.let { append(" · min interval ${it}s") } - } - -/** - * The `NO_FETCH_YET` case, which is the most commonly misread state: an empty table alone reads as - * "this app has no Remote Config", when the truth is usually that no fetch has completed yet. - */ -@Composable -private fun RemoteConfigEmptyNote( - provider: InspectorRemoteConfigUi, - colors: DevConsoleColors, -) { - Text( - text = - if (provider.lastFetchEpochMs == null) { - "No values — this provider has not completed a fetch yet." - } else { - "No values returned by the last fetch." - }, - modifier = Modifier.padding(start = 16.dp, end = 16.dp, bottom = 8.dp), - color = colors.muted, - style = MaterialTheme.typography.bodySmall, - ) -} - -@Composable -private fun RemoteConfigRow( - entry: InspectorRemoteConfigEntryUi, - colors: DevConsoleColors, -) { - // Colour carries the same meaning as the flag rows above: signal = came from the server, - // warn = a local override is masking it, muted = never reached the server at all. - val leadColor = - when (entry.source) { - "remote" -> colors.signal - "override" -> colors.warn - else -> colors.text3 - } - val leadBg = - when (entry.source) { - "remote" -> colors.signalSoft - "override" -> colors.warnSoft - else -> colors.surface3 - } - val sub = - buildString { - append(if (entry.redacted) "" else entry.value) - if (entry.truncated) append(" · truncated") - } - TonalListRow( - leadText = entry.source.take(3).uppercase(), - leadColor = leadColor, - leadContainerColor = leadBg, - title = entry.key, - subtitle = sub, - trailValue = entry.source, - trailValueColor = if (entry.source == "remote") colors.signal else colors.muted, - ) -} - /** Hand-built fixture for [ControlScreenPreview]. */ private fun controlScreenPreviewState() = InspectorState( diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDataSource.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDataSource.kt index 460594c..6808816 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDataSource.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDataSource.kt @@ -379,8 +379,8 @@ data class InspectorRetentionUi( ) /** - * One Remote Config key on the Control surface. Mirrors `remoteconfig.RemoteConfigEntry` without a - * `:sdk:remote-config` dependency, the same way [InspectorBodyKind] mirrors `network.BodyPreview`. + * One Remote Config key on the Observe surface's Config tab. Mirrors `remoteconfig.RemoteConfigEntry` + * without a `:sdk:remote-config` dependency, the same way [InspectorBodyKind] mirrors `network.BodyPreview`. * [source] carries the wire name (`remote`/`default`/`static`/`override`/`unknown`) rather than an * enum, so this module never has to track the producer's type. */ @@ -392,7 +392,7 @@ data class InspectorRemoteConfigEntryUi( val truncated: Boolean = false, ) -/** One Remote Config provider and its fetch state, as shown on the Control surface. */ +/** One Remote Config provider and its fetch state, as shown on the Observe surface's Config tab. */ data class InspectorRemoteConfigUi( val id: String, val entries: List = emptyList(), diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailSearchField.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailSearchField.kt index 21e6f2d..47f4d2f 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailSearchField.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailSearchField.kt @@ -35,7 +35,7 @@ internal fun InspectorDetailSearchField( onQueryChange: (String) -> Unit, matchLabel: String, modifier: Modifier = Modifier, - placeholder: String = "Find in headers, payload, response", + placeholder: String = DEFAULT_DETAIL_SEARCH_PLACEHOLDER, matchColor: Color = DevConsoleTheme.colors.muted, ) { Row( diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveDetail.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveDetail.kt index 6950ab5..836ec04 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveDetail.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveDetail.kt @@ -263,6 +263,7 @@ internal fun InspectorObserveDetailScreen( footerActions: List, onBack: () -> Unit, modifier: Modifier = Modifier, + searchPlaceholder: String = DEFAULT_DETAIL_SEARCH_PLACEHOLDER, ) { var query by rememberSaveable(resetKey) { mutableStateOf("") } val openState = @@ -328,6 +329,7 @@ internal fun InspectorObserveDetailScreen( onQueryChange = { query = it }, matchLabel = if (query.isBlank()) "" else "$totalHits match${if (totalHits == 1) "" else "es"}", modifier = Modifier.padding(top = 12.dp), + placeholder = searchPlaceholder, ) }, footer = { InspectorDetailFooterBar(footerActions) }, @@ -349,8 +351,17 @@ internal data class ObserveDetailContent( val sections: List, val initiallyOpenSectionKeys: Set, val footerActions: List, + /** + * Overridden only by kinds whose sections are not a captured request/response. The default names + * what a network, socket, push, log or crash detail actually holds; a Remote Config key holds + * one value, and offering to search its "headers" would be describing a screen that isn't there. + */ + val searchPlaceholder: String = DEFAULT_DETAIL_SEARCH_PLACEHOLDER, ) +/** Matches [InspectorDetailSearchField]'s own default; named here so callers can opt out of it. */ +internal const val DEFAULT_DETAIL_SEARCH_PLACEHOLDER = "Find in headers, payload, response" + /** Redacted-aware header/kv rows shared by every kind's detail sections that render a raw string map. */ internal fun headerRowsBody( headers: Map, diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObservePreviews.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObservePreviews.kt index 23a80df..f2ecee4 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObservePreviews.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObservePreviews.kt @@ -2,10 +2,13 @@ * @author Shakib * @since 04/08/26 */ -@file:Suppress("FunctionNaming", "MagicNumber", "UnusedPrivateMember") +@file:Suppress("FunctionNaming", "MagicNumber", "UnusedPrivateMember", "TooManyFunctions") package io.devconsole.ui.compose +// TooManyFunctions is suppressed above because this file is one @Preview function per Observe tab +// and per detail worth eyeballing: its function count tracks the number of tabs, not complexity. + import android.content.res.Configuration import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.runtime.Composable @@ -136,6 +139,7 @@ private val PreviewObserveState = logs = PreviewLogs, crashes = PreviewCrashes, sessions = PreviewSessions, + remoteConfig = remoteConfigPreviewProviders(), capabilities = InspectorEditingUi(requestExecution = true), ) @@ -155,6 +159,8 @@ private val PreviewObserveActions = onOpenLogDetail = {}, onCrashesSearchChange = {}, onOpenCrashDetail = {}, + onRemoteConfigSearchChange = {}, + onOpenRemoteConfigDetail = { _, _ -> }, onToggleCrashFlag = {}, onToggleCrashesHero = {}, onViewPreviousCrash = {}, @@ -238,6 +244,32 @@ private fun ObserveScreenCrashesPreview() { } } +@Preview(name = "Dark", uiMode = Configuration.UI_MODE_NIGHT_YES, showBackground = true, backgroundColor = 0xFF0B0E0D) +@Preview(name = "Light", uiMode = Configuration.UI_MODE_NIGHT_NO, showBackground = true, backgroundColor = 0xFFF3F6EE) +@Composable +private fun ObserveScreenRemoteConfigPreview() { + DevConsoleTheme(darkTheme = isSystemInDarkTheme()) { + ObserveScreen( + state = PreviewObserveState.copy(observeTab = ObserveTab.REMOTE_CONFIG), + ui = PreviewObserveUi, + actions = PreviewObserveActions, + ) + } +} + +/** The JSON case: `checkout_v2` parses, so the detail opens on the formatted tree rather than raw. */ +@Preview(uiMode = Configuration.UI_MODE_NIGHT_YES, showBackground = true, backgroundColor = 0xFF0B0E0D) +@Composable +private fun ObserveScreenRemoteConfigDetailPreview() { + DevConsoleTheme(darkTheme = isSystemInDarkTheme()) { + ObserveScreen( + state = PreviewObserveState.copy(observeTab = ObserveTab.REMOTE_CONFIG), + ui = PreviewObserveUi.copy(detailTarget = ObserveDetailTarget.RemoteConfigKey("firebase", "checkout_v2")), + actions = PreviewObserveActions, + ) + } +} + @Preview(name = "Dark", uiMode = Configuration.UI_MODE_NIGHT_YES, showBackground = true, backgroundColor = 0xFF0B0E0D) @Preview(name = "Light", uiMode = Configuration.UI_MODE_NIGHT_NO, showBackground = true, backgroundColor = 0xFFF3F6EE) @Composable diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveRemoteConfigDetail.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveRemoteConfigDetail.kt new file mode 100644 index 0000000..ba984f4 --- /dev/null +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveRemoteConfigDetail.kt @@ -0,0 +1,115 @@ +/** + * @author Md. Asaduzzaman Nur + * @since 13/08/26 + */ +package io.devconsole.ui.compose + +import java.util.Locale + +/** + * Detail for one Remote Config key, opened by tapping its row on the Config tab. + * + * The Value section is an [InspectorDetailSectionBody.Formattable], which is the whole reason this + * screen is worth opening: [formattableTextBody] pretty-prints the value into the collapsible JSON + * tree when it genuinely parses, keeps the exact original text behind the Raw toggle, and -- since + * a Remote Config value is a plain string on the wire, very often `on` or `v2` rather than JSON -- + * falls back to raw with no toggle at all when it does not. Nothing here ever re-quotes a + * non-JSON value to make it parse: the quotes would be this screen's invention rather than + * something the server sent, which is the same rule the source badge follows. + */ +internal fun remoteConfigDetailContent( + provider: InspectorRemoteConfigUi, + entry: InspectorRemoteConfigEntryUi, + colors: DevConsoleColors, + copyText: (String) -> Unit, + shareText: (String, String) -> Unit, +): ObserveDetailContent { + // A redacted entry carries no value to format, so it gets an explicit note instead of a + // Raw/Formatted toggle over the literal placeholder -- the same treatment a binary body gets. + val valueBody = + if (entry.redacted) { + InspectorDetailSectionBody.Empty("Value withheld by the redaction policy.") + } else { + formattableTextBody(entry.value, colors) + } + val detailEntries = remoteConfigDetailEntries(provider, entry, colors) + return ObserveDetailContent( + header = remoteConfigDetailHeader(provider, entry, colors, copyText, shareText), + sections = + listOf( + InspectorDetailSectionSpec( + "value", + "Value", + valueBody, + copyDescription = "Copy value", + onCopy = if (entry.redacted) null else ({ copyText(entry.value) }), + ), + InspectorDetailSectionSpec( + "details", + "Details", + InspectorDetailSectionBody.KeyValues(detailEntries), + copyDescription = "Copy details", + onCopy = { copyText(detailEntries.toCopyText()) }, + ), + ), + // The value is what you opened this for; Details is one tap away when the value is not the + // answer -- the same open/closed split every other capture detail uses for body vs general. + initiallyOpenSectionKeys = setOf("value"), + // Read-only surface: there is no override-from-device action to put here yet. + footerActions = emptyList(), + searchPlaceholder = "Find in this value", + ) +} + +private fun remoteConfigDetailHeader( + provider: InspectorRemoteConfigUi, + entry: InspectorRemoteConfigEntryUi, + colors: DevConsoleColors, + copyText: (String) -> Unit, + shareText: (String, String) -> Unit, +) = InspectorObserveDetailHeaderSpec( + kindLabel = "Remote Config", + leadText = remoteConfigLeadText(entry.source), + leadColor = remoteConfigLeadColor(entry.source, colors), + leadContainerColor = remoteConfigLeadContainerColor(entry.source, colors), + title = entry.key, + subtitle = "${provider.id} · ${remoteConfigFetchLine(provider)}", + status = entry.source.uppercase(Locale.US), + statusColor = if (entry.source == "remote") colors.signal else colors.muted, + actions = + listOf( + InspectorTopAction( + contentDescription = "Copy value", + onClick = { copyText(entry.value) }, + icon = copyIconAction(colors.muted), + ), + InspectorTopAction( + contentDescription = "Share value", + onClick = { shareText(entry.value, "Share ${entry.key}") }, + icon = shareIconAction(colors.muted), + ), + ), +) + +/** The provider's fetch state travels with the key: it is what tells a `default` apart from a bug. */ +private fun remoteConfigDetailEntries( + provider: InspectorRemoteConfigUi, + entry: InspectorRemoteConfigEntryUi, + colors: DevConsoleColors, +): List = + buildList { + add(InspectorKeyValue("key", entry.key)) + add(InspectorKeyValue("source", entry.source, if (entry.source == "remote") null else colors.muted)) + add(InspectorKeyValue("provider", provider.id)) + add(InspectorKeyValue("last fetch", provider.lastFetchEpochMs?.let(::formatCaptureClockTime) ?: "never")) + add(InspectorKeyValue("fetch status", provider.status.replace('_', ' '))) + provider.minimumFetchIntervalSeconds?.let { add(InspectorKeyValue("min fetch interval", "${it}s")) } + // Both are called out only when true: a "truncated: false" row on every key would be noise, + // while a silently cut value is the thing that wastes an afternoon. + if (entry.truncated) { + add(InspectorKeyValue("truncated", "value was cut short on capture", colors.warn)) + } + if (entry.redacted) { + add(InspectorKeyValue("redacted", "withheld by the redaction policy", colors.warn)) + } + } diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveRemoteConfigTab.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveRemoteConfigTab.kt new file mode 100644 index 0000000..7e8c058 --- /dev/null +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveRemoteConfigTab.kt @@ -0,0 +1,159 @@ +/** + * @author Md. Asaduzzaman Nur + * @since 13/08/26 + */ +@file:Suppress("FunctionNaming", "MagicNumber") +@file:OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class) + +package io.devconsole.ui.compose + +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.dp +import java.util.Locale + +/** + * Remote Config tab: every provider's currently resolved keys, read-only. + * + * The source badge on each row, and the fetch line under each provider header, are the reason this + * surface exists -- a key serving an in-app default because the last fetch was throttled looks + * identical to a published one until you can see where it came from and when the fetch happened. + * Moved here from a section on the Control screen: Remote Config is something you *observe*, + * nothing on it can be changed from the device. + * + * Unlike every other Observe tab this one has no hero. The diagnostic here is per provider, not per + * tab, so a single headline number would either restate the fetch line in the ordinary + * one-provider case or average across providers and mislead. + */ +@Composable +internal fun RemoteConfigTabContent( + state: InspectorState, + ui: ObserveUiState, + actions: ObserveActions, +) { + val colors = DevConsoleTheme.colors + if (state.remoteConfig.isEmpty()) { + ObserveTabEmptyState("No Remote Config provider is registered for this session.") + return + } + val query = ui.remoteConfigSearch.trim().lowercase(Locale.US) + LazyColumn( + modifier = Modifier.fillMaxSize(), + contentPadding = PaddingValues(start = 16.dp, end = 16.dp, top = 12.dp, bottom = EvidenceFabScrollClearance), + ) { + stickyHeader { + InspectorSearchBar( + query = ui.remoteConfigSearch, + onQueryChange = actions.onRemoteConfigSearchChange, + placeholder = "Search key or value", + ) + } + item { Spacer(Modifier.height(16.dp)) } + state.remoteConfig.forEach { provider -> + item(key = "rc-head-${provider.id}") { RemoteConfigHeader(provider, colors) } + val shown = provider.entries.filter { it.matches(query) } + when { + provider.unavailableReason != null -> + item(key = "rc-unavailable-${provider.id}") { + WarnNote("Remote Config unavailable: ${provider.unavailableReason}") + } + provider.entries.isEmpty() -> + item(key = "rc-empty-${provider.id}") { RemoteConfigEmptyNote(provider, colors) } + shown.isEmpty() -> + item(key = "rc-nomatch-${provider.id}") { RemoteConfigNoMatchNote(colors) } + else -> + items(shown, key = { "rc-${provider.id}-${it.key}" }) { entry -> + RemoteConfigRow(entry, colors) { actions.onOpenRemoteConfigDetail(provider.id, entry.key) } + } + } + item(key = "rc-space-${provider.id}") { Spacer(Modifier.height(16.dp)) } + } + } +} + +/** + * Header for one Remote Config provider. The fetch line is the reason this screen exists: a value + * serving an in-app default because the last fetch was throttled looks identical to a published one + * until you can see when the fetch happened and how it ended. + */ +@Composable +private fun RemoteConfigHeader( + provider: InspectorRemoteConfigUi, + colors: DevConsoleColors, +) { + GroupLabel("Remote Config · ${provider.id}") + Text( + text = remoteConfigFetchLine(provider), + modifier = Modifier.padding(start = 16.dp, end = 16.dp, bottom = 8.dp), + color = colors.text3, + style = MaterialTheme.typography.bodySmall, + ) +} + +/** + * The `NO_FETCH_YET` case, which is the most commonly misread state: an empty table alone reads as + * "this app has no Remote Config", when the truth is usually that no fetch has completed yet. + */ +@Composable +private fun RemoteConfigEmptyNote( + provider: InspectorRemoteConfigUi, + colors: DevConsoleColors, +) { + Text( + text = + if (provider.lastFetchEpochMs == null) { + "No values — this provider has not completed a fetch yet." + } else { + "No values returned by the last fetch." + }, + modifier = Modifier.padding(start = 16.dp, end = 16.dp, bottom = 8.dp), + color = colors.muted, + style = MaterialTheme.typography.bodySmall, + ) +} + +/** Distinct from [RemoteConfigEmptyNote]: the provider has values, the search just excluded them all. */ +@Composable +private fun RemoteConfigNoMatchNote(colors: DevConsoleColors) { + Text( + text = "No key matches the current search.", + modifier = Modifier.padding(start = 16.dp, end = 16.dp, bottom = 8.dp), + color = colors.muted, + style = MaterialTheme.typography.bodySmall, + ) +} + +@Composable +private fun RemoteConfigRow( + entry: InspectorRemoteConfigEntryUi, + colors: DevConsoleColors, + onClick: () -> Unit, +) { + // Only ever a preview -- a config value is a string of any length, and the full text is one tap + // away in the detail. `truncated` is the SDK's own capture cut, not this line's shortening, so + // it stays called out rather than being conflated with the row simply running out of room. + val sub = + buildString { + append(if (entry.redacted) "" else entry.value) + if (entry.truncated) append(" · truncated") + } + TonalListRow( + leadText = remoteConfigLeadText(entry.source), + leadColor = remoteConfigLeadColor(entry.source, colors), + leadContainerColor = remoteConfigLeadContainerColor(entry.source, colors), + title = entry.key, + subtitle = sub, + trailValue = entry.source, + trailValueColor = if (entry.source == "remote") colors.signal else colors.muted, + onClick = onClick, + ) +} diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveScreen.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveScreen.kt index 2fad82f..0fce8aa 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveScreen.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveScreen.kt @@ -72,6 +72,12 @@ internal sealed interface ObserveDetailTarget { data class Crash( val crashId: String, ) : ObserveDetailTarget + + /** `(provider, key)` rather than a position: the tab's search box re-filters the list under it. */ + data class RemoteConfigKey( + val providerId: String, + val key: String, + ) : ObserveDetailTarget } /** @@ -91,6 +97,7 @@ internal data class ObserveUiState( val pushSearch: String = "", val logsSearch: String = "", val crashesSearch: String = "", + val remoteConfigSearch: String = "", val flaggedTransactionIds: Set = emptySet(), val bookmarkedLogIds: Set = emptySet(), val flaggedCrashIds: Set = emptySet(), @@ -121,6 +128,8 @@ internal data class ObserveActions( val onOpenLogDetail: (String) -> Unit, val onCrashesSearchChange: (String) -> Unit, val onOpenCrashDetail: (String) -> Unit, + val onRemoteConfigSearchChange: (String) -> Unit, + val onOpenRemoteConfigDetail: (String, String) -> Unit, val onToggleCrashFlag: (String) -> Unit, val onToggleCrashesHero: () -> Unit, /** The previous-run-crashed banner's action: opens that session's crash on the Crashes tab. */ @@ -177,6 +186,7 @@ private class ObserveRouteState( pushSearchState: MutableState, logsSearchState: MutableState, crashesSearchState: MutableState, + remoteConfigSearchState: MutableState, trafficHeroCollapsedState: MutableState, socketsHeroCollapsedState: MutableState, pushHeroCollapsedState: MutableState, @@ -189,6 +199,7 @@ private class ObserveRouteState( var pushSearch by pushSearchState var logsSearch by logsSearchState var crashesSearch by crashesSearchState + var remoteConfigSearch by remoteConfigSearchState var bookmarkedIds by mutableStateOf(emptySet()) var detailTarget by mutableStateOf(null) var mockDraft by mockDraftState @@ -215,6 +226,7 @@ private fun rememberObserveRouteState(mockDraftState: MutableState routeState.detailTarget = ObserveDetailTarget.Log(id) }, onCrashesSearchChange = { routeState.crashesSearch = it }, onOpenCrashDetail = { id -> routeState.detailTarget = ObserveDetailTarget.Crash(id) }, + onRemoteConfigSearchChange = { routeState.remoteConfigSearch = it }, + onOpenRemoteConfigDetail = { providerId, key -> + routeState.detailTarget = ObserveDetailTarget.RemoteConfigKey(providerId, key) + }, // Flag/unflag now go through the durable EvidenceStore via the ViewModel; the resulting // toast comes from InspectorState.lastCommandResult (see ObserveRoute's own LaunchedEffect), // not a locally-composed message here. @@ -499,6 +517,7 @@ private fun ObserveTabPager( ObserveTab.PUSH -> PushTabContent(state, ui, actions) ObserveTab.LOGS -> LogsTabContent(state, ui, actions) ObserveTab.CRASHES -> CrashesTabContent(state, ui, actions) + ObserveTab.REMOTE_CONFIG -> RemoteConfigTabContent(state, ui, actions) } } } @@ -510,6 +529,9 @@ private fun ObserveTab.title(): String = ObserveTab.PUSH -> "Push" ObserveTab.LOGS -> "Logs" ObserveTab.CRASHES -> "Crashes" + // One word, like every other tab: the row divides its width equally, so "Remote Config" + // would wrap or truncate on a phone. + ObserveTab.REMOTE_CONFIG -> "Config" } /** @@ -748,6 +770,22 @@ private fun resolveObserveDetail( ) target.crashId to content } + is ObserveDetailTarget.RemoteConfigKey -> + state.remoteConfig + .firstOrNull { it.id == target.providerId } + ?.let { provider -> + provider.entries.firstOrNull { it.key == target.key }?.let { entry -> + val content = + remoteConfigDetailContent( + provider = provider, + entry = entry, + colors = colors, + copyText = actions.copyText, + shareText = actions.shareText, + ) + "${target.providerId}/${target.key}" to content + } + } } /** Dispatches [target] to the matching `*DetailContent` builder and renders [InspectorObserveDetailScreen]. */ @@ -789,6 +827,7 @@ private fun ObserveDetailFromContent( initiallyOpenSectionKeys = content.initiallyOpenSectionKeys, footerActions = content.footerActions, onBack = onBack, + searchPlaceholder = content.searchPlaceholder, ) } diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorRemoteConfigFormat.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorRemoteConfigFormat.kt new file mode 100644 index 0000000..3e0d75b --- /dev/null +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorRemoteConfigFormat.kt @@ -0,0 +1,82 @@ +/** + * @author Md. Asaduzzaman Nur + * @since 13/08/26 + */ +@file:Suppress("MagicNumber") + +package io.devconsole.ui.compose + +import java.util.Locale + +// Pure presentation logic for Remote Config, shared by the Config tab's rows and the key detail +// they open. Kept out of both composable files so a source badge or a fetch line can never read one +// way in the list and another way on the screen the list opens. + +/** + * The row's and the detail header's shared lead badge. Colour carries the same meaning as the flag + * rows on Control: signal = came from the server, warn = a local override is masking it, muted = + * never reached the server at all. Shared so a source can never read one way in the list and + * another way on the screen the list opens. + */ +internal fun remoteConfigLeadText(source: String): String = source.take(SOURCE_BADGE_CHARS).uppercase(Locale.US) + +internal fun remoteConfigLeadColor( + source: String, + colors: DevConsoleColors, +) = when (source) { + "remote" -> colors.signal + "override" -> colors.warn + else -> colors.text3 +} + +internal fun remoteConfigLeadContainerColor( + source: String, + colors: DevConsoleColors, +) = when (source) { + "remote" -> colors.signalSoft + "override" -> colors.warnSoft + else -> colors.surface3 +} + +/** `REM`/`DEF`/`OVE`/`STA`/`UNK` — the width every other lead badge in the console uses. */ +private const val SOURCE_BADGE_CHARS = 3 + +/** "Never fetched" is spelled out rather than shown as an epoch date. */ +internal fun remoteConfigFetchLine(provider: InspectorRemoteConfigUi): String = + buildString { + append("last fetch: ") + append( + provider.lastFetchEpochMs?.let(::formatCaptureClockTime) ?: "never", + ) + append(" · ") + append(provider.status.replace('_', ' ')) + provider.minimumFetchIntervalSeconds?.let { append(" · min interval ${it}s") } + } + +/** Value as well as key: finding which key holds a given variant is as common as recalling its name. */ +internal fun InspectorRemoteConfigEntryUi.matches(query: String): Boolean = + query.isEmpty() || + key.lowercase(Locale.US).contains(query) || + (!redacted && value.lowercase(Locale.US).contains(query)) + +/** Hand-built fixture shared by the Observe preview and the detail preview. */ +internal fun remoteConfigPreviewProviders(): List = + listOf( + InspectorRemoteConfigUi( + id = "firebase", + entries = + listOf( + InspectorRemoteConfigEntryUi( + key = "checkout_v2", + value = """{"enabled":true,"variant":"b","rollout":0.25}""", + source = "remote", + ), + InspectorRemoteConfigEntryUi(key = "banner_copy", value = "Free delivery today", source = "remote"), + InspectorRemoteConfigEntryUi(key = "retry_budget", value = "3", source = "default"), + InspectorRemoteConfigEntryUi(key = "api_key", value = "", source = "remote", redacted = true), + ), + lastFetchEpochMs = 1_760_000_000_000, + status = "success", + minimumFetchIntervalSeconds = 3600, + ), + ) diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorState.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorState.kt index 4bd323e..fa04948 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorState.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorState.kt @@ -7,8 +7,12 @@ package io.devconsole.ui.compose import io.devconsole.api.CaptureCategory import io.devconsole.api.ScreenshotResult -/** Sub-surfaces of the Observe workspace: live traffic plus the other captured signal sources. */ -enum class ObserveTab { TRAFFIC, SOCKETS, PUSH, LOGS, CRASHES } +/** + * Sub-surfaces of the Observe workspace: live traffic plus the other captured signal sources. + * [REMOTE_CONFIG] is last because it is the one tab that is not a stream of captures arriving over + * time -- it is the current resolved snapshot of the app's config. + */ +enum class ObserveTab { TRAFFIC, SOCKETS, PUSH, LOGS, CRASHES, REMOTE_CONFIG } /** * Presentation state for the Observe and Control surfaces. Both surfaces read the same @@ -77,6 +81,14 @@ internal fun InspectorState.captures(category: CaptureCategory): Boolean = categ * plain WebSocket and MQTT capture -- either one enabled is enough to keep the tab (its contents, * [InspectorSocketUi.protocol], already distinguish the two per-row). Order matches [ObserveTab]'s * declaration order, which is also the tab row's display order. + * + * REMOTE_CONFIG is the one tab gated on *data* rather than on its category alone, and deliberately + * so: `InspectorTabRow` is a fixed Row that splits its width equally between the tabs it is given, + * so a tab that exists whenever STATE is captured -- which is on by default -- would narrow every + * other tab in every app, including the majority that register no Remote Config provider at all. + * The condition is the one the Control screen's section already used, so which sessions can see + * Remote Config is unchanged; only where it lives moved. A provider list that empties mid-session + * is handled for free by [InspectorViewModel]'s existing snap onto the first still-visible tab. */ internal fun InspectorState.visibleObserveTabs(): List = ObserveTab.entries.filter { tab -> @@ -86,6 +98,7 @@ internal fun InspectorState.visibleObserveTabs(): List = ObserveTab.PUSH -> captures(CaptureCategory.PUSH) ObserveTab.LOGS -> captures(CaptureCategory.LOGS) ObserveTab.CRASHES -> captures(CaptureCategory.CRASHES) + ObserveTab.REMOTE_CONFIG -> captures(CaptureCategory.STATE) && remoteConfig.isNotEmpty() } } diff --git a/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorCaptureCategoryGatingTest.kt b/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorCaptureCategoryGatingTest.kt index b3c4dde..b5c01c0 100644 --- a/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorCaptureCategoryGatingTest.kt +++ b/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorCaptureCategoryGatingTest.kt @@ -32,12 +32,62 @@ class InspectorCaptureCategoryGatingTest { @Test fun `every category enabled shows every tab and every destination`() { - val state = InspectorState(captureCategories = CaptureCategory.all()) + // A registered provider as well as every category: REMOTE_CONFIG is the one tab that also + // needs data to exist, so "every category on" alone is no longer enough to show them all. + val state = + InspectorState( + captureCategories = CaptureCategory.all(), + remoteConfig = listOf(InspectorRemoteConfigUi(id = "firebase")), + ) assertEquals(ObserveTab.entries, state.visibleObserveTabs()) assertEquals(InspectorDestination.entries, state.visibleDestinations()) } + @Test + fun `the Remote Config tab needs a registered provider as well as the STATE category`() { + val provider = listOf(InspectorRemoteConfigUi(id = "firebase")) + + // STATE on but nothing registered: the tab must not exist. InspectorTabRow splits its width + // equally, so an always-present sixth tab would narrow the other five in every app that has + // no Remote Config at all -- which, with STATE on by default, is most of them. + assertTrue( + ObserveTab.REMOTE_CONFIG !in + InspectorState(captureCategories = setOf(CaptureCategory.STATE)).visibleObserveTabs(), + ) + // A provider registered but STATE off: still hidden, the same way the route is gated. + assertTrue( + ObserveTab.REMOTE_CONFIG !in + InspectorState(captureCategories = setOf(CaptureCategory.NETWORK), remoteConfig = provider) + .visibleObserveTabs(), + ) + assertEquals( + listOf(ObserveTab.REMOTE_CONFIG), + InspectorState(captureCategories = setOf(CaptureCategory.STATE), remoteConfig = provider) + .visibleObserveTabs(), + ) + } + + @Test + fun `a provider that reports nothing at all still gets the tab`() { + // "Fetched nothing" and "never fetched" are answers you came to this surface for, so a + // provider with no entries -- or one that could not be read -- must not read as "no Remote + // Config". Only *no provider registered* hides the tab. + val empty = listOf(InspectorRemoteConfigUi(id = "firebase", entries = emptyList())) + val unavailable = listOf(InspectorRemoteConfigUi(id = "firebase", unavailableReason = "no such class")) + + assertTrue( + ObserveTab.REMOTE_CONFIG in + InspectorState(captureCategories = setOf(CaptureCategory.STATE), remoteConfig = empty) + .visibleObserveTabs(), + ) + assertTrue( + ObserveTab.REMOTE_CONFIG in + InspectorState(captureCategories = setOf(CaptureCategory.STATE), remoteConfig = unavailable) + .visibleObserveTabs(), + ) + } + @Test fun `an empty category set hides every tab and every gated destination without crashing`() { val state = InspectorState(captureCategories = emptySet()) diff --git a/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorViewModelTest.kt b/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorViewModelTest.kt index adf65c7..1db030e 100644 --- a/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorViewModelTest.kt +++ b/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorViewModelTest.kt @@ -1405,6 +1405,37 @@ class InspectorViewModelTest { .isEmpty(), ) } + + /** + * The Remote Config tab is gated on data, not only on its category, so it can vanish while + * selected without any capture category changing -- e.g. the host tears its provider down. The + * existing snap has to cover that case too, or the operator is left on a tab the row no longer + * draws. + */ + @Test + fun `losing the last Remote Config provider moves observeTab off the Config tab`() = + runTest { + val dispatcher = StandardTestDispatcher(testScheduler) + val withProvider = + InspectorSnapshot( + available = true, + captureCategories = setOf(CaptureCategory.NETWORK, CaptureCategory.STATE), + remoteConfig = listOf(InspectorRemoteConfigUi(id = "firebase")), + ) + val source = RecordingInspectorDataSource(withProvider) + val viewModel = InspectorViewModel(dataSource = source, dispatcher = dispatcher) + dispatcher.scheduler.advanceUntilIdle() + viewModel.dispatch(InspectorAction.SelectObserveTab(ObserveTab.REMOTE_CONFIG)) + dispatcher.scheduler.advanceUntilIdle() + assertEquals(ObserveTab.REMOTE_CONFIG, viewModel.state.value.observeTab) + + // Same categories, no provider: the tab stops existing on the next poll. + source.snapshotToReturn = withProvider.copy(remoteConfig = emptyList()) + viewModel.dispatch(InspectorAction.Refresh) + dispatcher.scheduler.advanceUntilIdle() + + assertEquals(ObserveTab.TRAFFIC, viewModel.state.value.observeTab) + } } private fun sampleTransaction(id: String = "tx-1") = From f710f872fc995e42e2e0d3c31144f18b4b917091 Mon Sep 17 00:00:00 2001 From: "Md. Asaduzzaman Nur" Date: Fri, 14 Aug 2026 21:36:24 +0600 Subject: [PATCH 7/7] fix: address review on the Remote Config inspector Fourteen of the fifteen review items; the fifteenth is answered on its thread rather than implemented. Grouped by what they actually break. Two registry defects, both of which reach the host app: `StateRegistry` and `RemoteConfigRegistry` each held an unguarded LinkedHashMap. Late registration is a documented path and the readers are the Ktor thread and the inspector's dispatcher, so registering from a post-fetch listener while the dashboard polls threw ConcurrentModificationException out of the read path -- the one outcome the read path's own doc promises not to cause. Guarded on every access rather than swapped for a ConcurrentHashMap, which would drop the insertion order surfaces list providers in; snapshots() copies under the lock and calls into host code outside it. The added test reproduces the CME against the unguarded map. Neither registry was cleared between initializes, and both reject duplicate ids, so a stop() -> initialize(configB) carrying a replacement provider under the same id had its registration refused and every surface carried on reading the torn-down original -- silently, since safely{}'s result is discarded. Both are cleared with the rest of the per-init state. State providers were also registered bare while Remote Config was wrapped in safely{}, so a duplicate id took down initialize() on one surface and not the other; both are wrapped now. The HTTP route's snapshot supplier captured createServerEngine's config parameter, which is bound once, while reconfigure() carries no supplier of its own. After a re-initialize the route kept redacting by the first config's policy and serving under its STATE gate, while FullInspectorDataSource -- reading the live activeConfig -- had moved on. Same field, two surfaces, two answers, which is exactly what redacting at a shared boundary was meant to rule out. Reads activeConfig now. Separator-insensitive matching collapsed `-` and `_` but not `.`, so `api.key` matched neither `api-key` nor `apikey` and was shown in full. Dotted keys are ordinary here; the sample's own flags use one. The Firebase adapter reported an unreadable config -- not Firebase-shaped, or getAll blowing up under R8 -- as an empty snapshot with no unavailableReason, which both surfaces render as "has not completed a fetch yet": a confident claim about a fetch that never happened. It sets a reason now. The test named for that case only asserted on entries and fetchInfo, so it passed without the snapshot being unavailable in any way a user could see. Everything else: - Copy/Share in the key detail header emitted the redaction placeholder while the Value section's own copy was already withheld -- two copy affordances on one screen disagreeing about whether the value is copyable. Dropped when redacted. - The rail count set textContent directly instead of going through setNavCount, which is what adds the `.show` class, so the badge was `display: none` and never appeared; it also skipped the 999+ clamp. A failed load now resets the count and badge instead of leaving the last successful numbers beside a card reporting the failure. - 'remoteConfig' was missing from RAIL_ADVANCED_VIEWS while viewRemoteConfig was in RAIL_ADVANCED_IDS, so switching to Simple mode stranded the active button inside the collapsed group. - The source filter offered no `override` or `unknown`, which are real sources the matcher compares exactly -- "what is a local override masking?" was unanswerable on a config too long to scroll. - The device fetch line used HH:mm:ss with no date. Firebase's default minimum fetch interval is 12h, so `09:14:02` read the same whether the fetch was a minute or a week ago -- the one distinction that surface exists to make. The dashboard already showed the date. - The adapter re-resolved every Method on each call (getMethods allocates a fresh copy, then a linear scan, twice per entry) and re-read the Firebase constants inside `when` conditions. Cached per receiver class and per adapter. - FullInspectorDataSource built a RedactionEngine per snapshot(), recompiling every text pattern; it takes the engine PlatformFacadeProvider already keeps current instead. - README still sent people to the Control screen, and pinned coordinates at 1.1.1, which predates these modules. Not done: hoisting the duplicated `Any.call` into a module both Firebase adapters share. remote-config-firebase depends only on remote-config and push-firebase on push -> security, so it would mean either a security dependency in a config module or a new published artifact with its own ABI baseline, for three lines. The stated motivation -- remembering the caching fix in two places -- does not apply either: the caching is instance-scoped to a long-lived receiver whose methods are re-called per entry, while the push adapter gets a fresh RemoteMessage per delivery and calls each method once. Co-Authored-By: Claude Opus 5 --- CHANGELOG.md | 17 ++++ README.md | 12 ++- .../io/devconsole/FullInspectorDataSource.kt | 8 +- .../io/devconsole/PlatformFacadeProvider.kt | 35 ++++++-- .../io/devconsole/RedactingRemoteConfig.kt | 9 +- .../devconsole/RemoteConfigInspectorTest.kt | 10 ++- .../firebase/FirebaseRemoteConfigAdapter.kt | 89 ++++++++++++++----- .../FirebaseRemoteConfigAdapterTest.kt | 26 ++++++ sdk/remote-config/api/remote-config.api | 1 + .../remoteconfig/RemoteConfigRegistry.kt | 32 +++++-- .../remoteconfig/RemoteConfigRegistryTest.kt | 62 +++++++++++++ .../resources/devconsole-web/dashboard.js | 8 +- .../main/resources/devconsole-web/index.html | 2 +- .../server/ktor/DashboardAssetsTest.kt | 25 +++++- sdk/state/api/state.api | 1 + .../io/devconsole/state/StateProvider.kt | 33 +++++-- .../ui/compose/InspectorObserveFormat.kt | 16 ++++ .../InspectorObserveRemoteConfigDetail.kt | 33 ++++--- .../ui/compose/InspectorRemoteConfigFormat.kt | 2 +- 19 files changed, 356 insertions(+), 65 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ab992fd..eb5efd4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -59,6 +59,23 @@ joined this list.) `RedactionPolicy`, whose defaults are an HTTP-header list compared by exact name: `api_key` and `apiKey` now match the policy's `api-key` instead of being displayed in full. +### Fixed + +- **State providers no longer race their readers.** `StateRegistry` held a plain `LinkedHashMap` + read without a lock, so a host registering a provider late — through + `DevConsole.registerStateProvider`, which is a documented path — while the dashboard's server + thread or the in-app inspector was iterating could throw `ConcurrentModificationException` into + the app being debugged. Every access is guarded now, and the insertion order surfaces list + providers in is preserved. `RemoteConfigRegistry` had the same shape and got the same fix before + it ever shipped. + +- **Re-initializing replaces registered providers instead of silently keeping the old ones.** Both + registries reject a duplicate id, and neither was cleared between `initialize()` calls, so a + `stop()` → `initialize(...)` carrying a replacement provider under the same id had its + registration refused — leaving every surface reading through the torn-down original. Both are now + cleared as part of the same per-init reset, and a duplicate id within one config is ignored rather + than thrown out of `initialize()` (state providers previously threw; Remote Config already did not). + ## 1.1.1 — 2026-08-12 A build-and-distribution patch: no SDK code changed, and the public API is byte-for-byte the diff --git a/README.md b/README.md index ab6eaed..cacdfe3 100644 --- a/README.md +++ b/README.md @@ -288,10 +288,14 @@ Add the adapter — it is not part of the `devconsole` umbrella, so that Firebas classpath of an app that doesn't use it: ```kotlin -debugImplementation("io.github.devconsole-android:devconsole-remote-config-firebase:1.1.1") -releaseImplementation("io.github.devconsole-android:devconsole-remote-config-firebase-noop:1.1.1") +debugImplementation("io.github.devconsole-android:devconsole-remote-config-firebase:1.2.0") +releaseImplementation("io.github.devconsole-android:devconsole-remote-config-firebase-noop:1.2.0") ``` +> These two artifacts are new: `1.1.1` predates them, and `1.2.0` is the release they first ship in. +> To try them before that lands, take them off the branch through +> [JitPack](#jitpack-for-unreleased-code). + Then hand DevConsole your `FirebaseRemoteConfig` instance at init: ```kotlin @@ -310,8 +314,8 @@ rather than snapshotted at startup: DevConsole.registerRemoteConfigProvider(FirebaseRemoteConfigAdapter(Firebase.remoteConfig)) ``` -That's the whole setup. Values then appear on the dashboard's **Remote Config** page and in the -in-app inspector's **Control** screen, each tagged with where it came from: +That's the whole setup. Values then appear on the dashboard's **Remote Config** page and on the +in-app inspector's **Config** tab, each tagged with where it came from: | Source | Meaning | |---|---| diff --git a/sdk/full/src/main/kotlin/io/devconsole/FullInspectorDataSource.kt b/sdk/full/src/main/kotlin/io/devconsole/FullInspectorDataSource.kt index 2904534..5d4d889 100644 --- a/sdk/full/src/main/kotlin/io/devconsole/FullInspectorDataSource.kt +++ b/sdk/full/src/main/kotlin/io/devconsole/FullInspectorDataSource.kt @@ -130,6 +130,12 @@ internal class FullInspectorDataSource( * which reads as "no remote config" rather than as an error. */ private val remoteConfigRegistry: RemoteConfigRegistry? = null, + /** + * The host's live [RedactionEngine], supplied so [readRemoteConfig] does not rebuild one (and + * recompile every text pattern) on each snapshot. Null on a build that wires no engine, where + * one is constructed from the active policy as before. + */ + private val redactionEngine: () -> RedactionEngine? = { null }, private val preferencesInspector: PreferencesInspector? = null, private val fileInspector: FileInspector? = null, private val databaseInspector: DatabaseInspector? = null, @@ -428,7 +434,7 @@ internal class FullInspectorDataSource( private fun readRemoteConfig(config: DevConsoleConfig?): List { val registry = remoteConfigRegistry ?: return emptyList() val policy = config?.redactionPolicy ?: RedactionPolicy.default() - val redacting = RedactingRemoteConfig(RedactionEngine(policy), policy) + val redacting = RedactingRemoteConfig(redactionEngine() ?: RedactionEngine(policy), policy) return registry.snapshots().map { snapshot -> InspectorRemoteConfigUi( id = snapshot.providerId, diff --git a/sdk/full/src/main/kotlin/io/devconsole/PlatformFacadeProvider.kt b/sdk/full/src/main/kotlin/io/devconsole/PlatformFacadeProvider.kt index 6fd7e8f..4dbec8b 100644 --- a/sdk/full/src/main/kotlin/io/devconsole/PlatformFacadeProvider.kt +++ b/sdk/full/src/main/kotlin/io/devconsole/PlatformFacadeProvider.kt @@ -697,9 +697,17 @@ internal class PlatformFacadeProvider : DevConsoleFacadeProvider { // Apply the host's policy at the shared capture engine so every recorder redacts by it. redaction.updatePolicy(config.redactionPolicy) if (config.capturesCategory(CaptureCategory.STATE)) { - config.stateProviders.forEach(stateRegistry::register) - // A duplicate id from a host that both configured and late-registered a provider must - // not take down initialize(); the registration is simply ignored. + // Cleared first, not merged into: both registries reject a duplicate id, so on a + // stop() -> initialize(configB) carrying a *replacement* provider under the same id + // (a fresh FirebaseRemoteConfigAdapter over a new client, say) the registration would + // be refused and every surface would keep reading through the torn-down original -- + // silently, since safely{}'s result is discarded here. Configured providers are owned + // by the config, so the new config's set is the whole truth. + stateRegistry.clear() + remoteConfigRegistry.clear() + // A duplicate id *within one config*, or from a host that both configured and + // late-registered a provider, must not take down initialize(); it is simply ignored. + config.stateProviders.forEach { provider -> safely { stateRegistry.register(provider) } } config.remoteConfigProviders.forEach { provider -> safely { remoteConfigRegistry.register(provider) } } } featureFlags = SessionFeatureFlags(config.featureFlags) @@ -746,6 +754,11 @@ internal class PlatformFacadeProvider : DevConsoleFacadeProvider { featureFlagsSupplier = { if (::featureFlags.isInitialized) featureFlags else null }, stateRegistry = stateRegistry, remoteConfigRegistry = remoteConfigRegistry, + // The one engine PlatformFacadeProvider keeps current via updatePolicy, rather than + // a fresh one per snapshot(): constructing a RedactionEngine recompiles the whole + // textPatterns set, which is why redactionValidationError() guards it at all. This + // also keeps the in-process path on the exact engine the HTTP path redacts with. + redactionEngine = { redaction }, preferencesInspector = gatedPreferencesInspector, fileInspector = gatedFileInspector, databaseInspector = gatedDatabaseInspector, @@ -916,7 +929,12 @@ internal class PlatformFacadeProvider : DevConsoleFacadeProvider { // Redacted here, not in the route: the Compose inspector reads the same registry // in-process and never crosses the HTTP boundary, so this is the shared boundary both // surfaces go through. - remoteConfigSnapshots = { redactedRemoteConfigSnapshots(config) }, + // `activeConfig`, not this call's `config`: createServerEngine runs once, while + // reconfigure() handles every later initialize() and carries no snapshot supplier of + // its own -- so capturing the parameter would pin the route to the first config's + // redaction policy and STATE gate for the process's life, while FullInspectorDataSource + // (which reads the same live field) moved on. Same field, two surfaces, one answer. + remoteConfigSnapshots = { redactedRemoteConfigSnapshots(activeConfig) }, featureFlags = featureFlags, featureFlagsEditable = featureFlagsEditable, mockEngine = mockEngineInstance, @@ -1127,9 +1145,12 @@ internal class PlatformFacadeProvider : DevConsoleFacadeProvider { override fun registerRemoteConfigProvider(provider: RemoteConfigProvider): Boolean = categoryEnabled(CaptureCategory.STATE) && safely { remoteConfigRegistry.register(provider) } - /** Empty when the STATE category is off, so the dashboard route cannot outflank the host's gate. */ - private fun redactedRemoteConfigSnapshots(config: DevConsoleConfig): List { - if (!config.capturesCategory(CaptureCategory.STATE)) return emptyList() + /** + * Empty when the STATE category is off, so the dashboard route cannot outflank the host's gate. + * A null config means initialize() has not landed yet, which reads the same way: nothing to serve. + */ + private fun redactedRemoteConfigSnapshots(config: DevConsoleConfig?): List { + if (config == null || !config.capturesCategory(CaptureCategory.STATE)) return emptyList() val redacting = RedactingRemoteConfig(redaction, config.redactionPolicy) return remoteConfigRegistry.snapshots().map { it.copy(entries = redacting.apply(it.entries)) } } diff --git a/sdk/full/src/main/kotlin/io/devconsole/RedactingRemoteConfig.kt b/sdk/full/src/main/kotlin/io/devconsole/RedactingRemoteConfig.kt index 43bf28d..eb2da03 100644 --- a/sdk/full/src/main/kotlin/io/devconsole/RedactingRemoteConfig.kt +++ b/sdk/full/src/main/kotlin/io/devconsole/RedactingRemoteConfig.kt @@ -56,6 +56,13 @@ internal class RedactingRemoteConfig( } private companion object { - fun String.collapseSeparators(): String = replace("-", "").replace("_", "") + /** + * `.` as well as `-`/`_`: dotted keys are an ordinary Remote Config naming style (the + * sample's own flags use `compose_sample.show_order_history`), and without it `api.key` + * matches neither `api-key` nor `apikey` and is shown in full. + */ + private val SEPARATORS = Regex("[-_.]") + + fun String.collapseSeparators(): String = replace(SEPARATORS, "") } } diff --git a/sdk/full/src/test/kotlin/io/devconsole/RemoteConfigInspectorTest.kt b/sdk/full/src/test/kotlin/io/devconsole/RemoteConfigInspectorTest.kt index 686b6f2..b8d8d6f 100644 --- a/sdk/full/src/test/kotlin/io/devconsole/RemoteConfigInspectorTest.kt +++ b/sdk/full/src/test/kotlin/io/devconsole/RemoteConfigInspectorTest.kt @@ -191,7 +191,15 @@ class RemoteConfigInspectorTest { fun `matches sensitive names across separator styles`() { val entries = redactingBoundary().apply( - listOf(entry("api_key", "raw"), entry("apiKey", "raw"), entry("API-KEY", "raw")), + // `api.key` included: dotted keys are an ordinary Remote Config naming style (the + // sample's own flags use `compose_sample.show_order_history`), and collapsing only + // `-`/`_` left it matching neither `api-key` nor `apikey`, shown in full. + listOf( + entry("api_key", "raw"), + entry("apiKey", "raw"), + entry("API-KEY", "raw"), + entry("api.key", "raw"), + ), ) assertTrue(entries.all { it.redacted }) diff --git a/sdk/remote-config-firebase/src/main/kotlin/io/devconsole/remoteconfig/firebase/FirebaseRemoteConfigAdapter.kt b/sdk/remote-config-firebase/src/main/kotlin/io/devconsole/remoteconfig/firebase/FirebaseRemoteConfigAdapter.kt index 0306ff0..6c99df5 100644 --- a/sdk/remote-config-firebase/src/main/kotlin/io/devconsole/remoteconfig/firebase/FirebaseRemoteConfigAdapter.kt +++ b/sdk/remote-config-firebase/src/main/kotlin/io/devconsole/remoteconfig/firebase/FirebaseRemoteConfigAdapter.kt @@ -10,6 +10,11 @@ import io.devconsole.remoteconfig.RemoteConfigFetchStatus import io.devconsole.remoteconfig.RemoteConfigProvider import io.devconsole.remoteconfig.RemoteConfigSnapshot import io.devconsole.remoteconfig.RemoteConfigSource +import java.lang.reflect.Method + +// Deliberately not the exception's message: the throw is swallowed inside `call`. Kept a private +// top-level const rather than a companion one, which would compile to a public static field. +private const val UNREADABLE_REASON = "Firebase Remote Config could not be read reflectively" /** * Optional Firebase bridge with no Firebase compile-time dependency. Consumers pass a @@ -22,20 +27,33 @@ class FirebaseRemoteConfigAdapter private val remoteConfig: Any, override val id: String = "firebase", ) : RemoteConfigProvider { - override fun snapshot(): RemoteConfigSnapshot = - RemoteConfigSnapshot( + override fun snapshot(): RemoteConfigSnapshot { + // `getAll` returning a non-Map is how a non-Firebase object, or a getAll that blew up + // (R8, a renamed method), reaches us. Reporting that as an empty-but-fine snapshot would + // make both surfaces say "this provider has not completed a fetch yet" -- a confident + // claim about a provider we never got an answer out of, and exactly the confusion the + // no-op twin exists to avoid. An unavailableReason says we could not read it instead. + val all = + remoteConfig.call("getAll") as? Map<*, *> + ?: return RemoteConfigSnapshot( + providerId = id, + entries = emptyList(), + fetchInfo = RemoteConfigFetchInfo.unknown(), + unavailableReason = UNREADABLE_REASON, + ) + return RemoteConfigSnapshot( providerId = id, - entries = readEntries(), + entries = readEntries(all), fetchInfo = readFetchInfo(), ) + } /** * Sorted by key: Firebase hands back an unordered map, and an inspector whose rows reshuffle * on every refresh is unreadable when you are watching one key. */ - private fun readEntries(): List { - val all = remoteConfig.call("getAll") as? Map<*, *> ?: return emptyList() - return all.entries + private fun readEntries(all: Map<*, *>): List = + all.entries .mapNotNull { (key, value) -> val name = key as? String ?: return@mapNotNull null RemoteConfigEntry( @@ -44,13 +62,12 @@ class FirebaseRemoteConfigAdapter source = sourceOf(value), ) }.sortedBy(RemoteConfigEntry::key) - } private fun sourceOf(value: Any?): RemoteConfigSource = when ((value?.call("getSource") as? Number)?.toInt()) { - constant("VALUE_SOURCE_REMOTE", VALUE_SOURCE_REMOTE) -> RemoteConfigSource.REMOTE - constant("VALUE_SOURCE_DEFAULT", VALUE_SOURCE_DEFAULT) -> RemoteConfigSource.DEFAULT - constant("VALUE_SOURCE_STATIC", VALUE_SOURCE_STATIC) -> RemoteConfigSource.STATIC + sourceRemote -> RemoteConfigSource.REMOTE + sourceDefault -> RemoteConfigSource.DEFAULT + sourceStatic -> RemoteConfigSource.STATIC else -> RemoteConfigSource.UNKNOWN } @@ -70,30 +87,58 @@ class FirebaseRemoteConfigAdapter private fun statusOf(info: Any): RemoteConfigFetchStatus = when ((info.call("getLastFetchStatus") as? Number)?.toInt()) { - constant("LAST_FETCH_STATUS_SUCCESS", LAST_FETCH_STATUS_SUCCESS) -> RemoteConfigFetchStatus.SUCCESS - constant("LAST_FETCH_STATUS_NO_FETCH_YET", LAST_FETCH_STATUS_NO_FETCH_YET) -> - RemoteConfigFetchStatus.NO_FETCH_YET - constant("LAST_FETCH_STATUS_FAILURE", LAST_FETCH_STATUS_FAILURE) -> RemoteConfigFetchStatus.FAILURE - constant( - "LAST_FETCH_STATUS_THROTTLED", - LAST_FETCH_STATUS_THROTTLED, - ), - -> RemoteConfigFetchStatus.THROTTLED + statusSuccess -> RemoteConfigFetchStatus.SUCCESS + statusNoFetchYet -> RemoteConfigFetchStatus.NO_FETCH_YET + statusFailure -> RemoteConfigFetchStatus.FAILURE + statusThrottled -> RemoteConfigFetchStatus.THROTTLED else -> RemoteConfigFetchStatus.UNKNOWN } /** - * Prefers the constant declared on the supplied Firebase class over the literal below, so a - * future renumbering in the Firebase SDK cannot silently mis-badge every row. + * Resolved once per adapter rather than per `when` evaluation: these sat inside the branch + * conditions, so every entry's source and every fetch-status read re-ran a `getField` + * lookup. Still prefers the constant declared on the supplied Firebase class over the + * literal fallback, so a future renumbering in the Firebase SDK cannot silently mis-badge + * every row. */ private fun constant( name: String, fallback: Int, ): Int = runCatching { remoteConfig.javaClass.getField(name).getInt(null) }.getOrDefault(fallback) + private val sourceStatic by lazy { constant("VALUE_SOURCE_STATIC", VALUE_SOURCE_STATIC) } + private val sourceDefault by lazy { constant("VALUE_SOURCE_DEFAULT", VALUE_SOURCE_DEFAULT) } + private val sourceRemote by lazy { constant("VALUE_SOURCE_REMOTE", VALUE_SOURCE_REMOTE) } + private val statusSuccess by lazy { constant("LAST_FETCH_STATUS_SUCCESS", LAST_FETCH_STATUS_SUCCESS) } + private val statusNoFetchYet by lazy { + constant("LAST_FETCH_STATUS_NO_FETCH_YET", LAST_FETCH_STATUS_NO_FETCH_YET) + } + private val statusFailure by lazy { constant("LAST_FETCH_STATUS_FAILURE", LAST_FETCH_STATUS_FAILURE) } + private val statusThrottled by lazy { constant("LAST_FETCH_STATUS_THROTTLED", LAST_FETCH_STATUS_THROTTLED) } + + /** + * `Class.getMethods()` allocates a fresh defensive copy on every call and this then linear- + * scans it, which at a few hundred keys ran twice per entry (`asString`, `getSource`) on + * every inspector refresh and every dashboard poll. Cached per receiver *class*, not per + * receiver: the map's values are `FirebaseRemoteConfigValue` instances, one per key, all of + * the same class. A null result is cached too -- a name that is absent stays absent. + */ + private val methodCache = HashMap, String>, Method?>() + private fun Any.call(name: String): Any? = runCatching { - javaClass.methods.firstOrNull { it.name == name && it.parameterCount == 0 }?.invoke(this) + val key = javaClass to name + val method = + synchronized(methodCache) { + if (methodCache.containsKey(key)) { + methodCache[key] + } else { + javaClass.methods + .firstOrNull { it.name == name && it.parameterCount == 0 } + .also { methodCache[key] = it } + } + } + method?.invoke(this) }.getOrNull() private companion object { diff --git a/sdk/remote-config-firebase/src/test/kotlin/io/devconsole/remoteconfig/firebase/FirebaseRemoteConfigAdapterTest.kt b/sdk/remote-config-firebase/src/test/kotlin/io/devconsole/remoteconfig/firebase/FirebaseRemoteConfigAdapterTest.kt index a4acaea..5f11b26 100644 --- a/sdk/remote-config-firebase/src/test/kotlin/io/devconsole/remoteconfig/firebase/FirebaseRemoteConfigAdapterTest.kt +++ b/sdk/remote-config-firebase/src/test/kotlin/io/devconsole/remoteconfig/firebase/FirebaseRemoteConfigAdapterTest.kt @@ -7,6 +7,7 @@ package io.devconsole.remoteconfig.firebase import io.devconsole.remoteconfig.RemoteConfigFetchStatus import io.devconsole.remoteconfig.RemoteConfigSource import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotNull import org.junit.Assert.assertNull import org.junit.Assert.assertTrue import org.junit.Test @@ -169,6 +170,31 @@ class FirebaseRemoteConfigAdapterTest { assertTrue(snapshot.entries.isEmpty()) assertEquals(RemoteConfigFetchStatus.UNKNOWN, snapshot.fetchInfo.status) assertNull(snapshot.fetchInfo.lastFetchEpochMs) + // The assertion this test was named for. Without it, "unavailable" was true of nothing a + // user could see: an empty snapshot with a null reason renders on both surfaces as "this + // provider has not completed a fetch yet", which is a claim about a fetch we never made. + assertNotNull(snapshot.unavailableReason) + } + + @Test + fun `a remote config whose getAll throws is unavailable rather than silently empty`() { + val exploding = + object { + fun getAll(): Map = error("firebase exploded") + } + + val snapshot = FirebaseRemoteConfigAdapter(exploding).snapshot() + + assertTrue(snapshot.entries.isEmpty()) + assertNotNull(snapshot.unavailableReason) + } + + @Test + fun `a readable config reports no unavailable reason`() { + val snapshot = FirebaseRemoteConfigAdapter(FakeRemoteConfig(mapOf("k" to FakeValue("v", 2)))).snapshot() + + assertNull(snapshot.unavailableReason) + assertTrue(snapshot.entries.isNotEmpty()) } @Test diff --git a/sdk/remote-config/api/remote-config.api b/sdk/remote-config/api/remote-config.api index 96604da..730f608 100644 --- a/sdk/remote-config/api/remote-config.api +++ b/sdk/remote-config/api/remote-config.api @@ -60,6 +60,7 @@ public final class io/devconsole/remoteconfig/RemoteConfigRegistry { public static final field Companion Lio/devconsole/remoteconfig/RemoteConfigRegistry$Companion; public static final field MAX_VALUE_LENGTH I public fun ()V + public final fun clear ()V public final fun providerIds ()Ljava/util/List; public final fun register (Lio/devconsole/remoteconfig/RemoteConfigProvider;)V public final fun snapshot (Ljava/lang/String;)Lio/devconsole/remoteconfig/RemoteConfigSnapshot; diff --git a/sdk/remote-config/src/main/kotlin/io/devconsole/remoteconfig/RemoteConfigRegistry.kt b/sdk/remote-config/src/main/kotlin/io/devconsole/remoteconfig/RemoteConfigRegistry.kt index 4e6c7d2..b0ff6f8 100644 --- a/sdk/remote-config/src/main/kotlin/io/devconsole/remoteconfig/RemoteConfigRegistry.kt +++ b/sdk/remote-config/src/main/kotlin/io/devconsole/remoteconfig/RemoteConfigRegistry.kt @@ -12,20 +12,42 @@ package io.devconsole.remoteconfig * having to remember them. */ class RemoteConfigRegistry { + /** + * Guarded by [lock] on every access, read included. Late registration is a documented path + * (`DevConsole.registerRemoteConfigProvider`), and the readers are the Ktor thread and the + * inspector's dispatcher -- so a host registering a provider from a post-fetch listener while + * the dashboard polls would otherwise throw `ConcurrentModificationException` straight out of + * the read path, into the host app. That is the one outcome [read]'s own doc promises not to + * cause. A `ConcurrentHashMap` would drop the insertion order surfaces list providers in, so + * the readers copy under the lock and iterate outside it instead. + */ + private val lock = Any() private val providers = linkedMapOf() fun register(provider: RemoteConfigProvider) { require(provider.id.isNotBlank()) { "Remote config provider id must not be blank" } - require(provider.id !in providers) { "Duplicate remote config provider: ${provider.id}" } - providers[provider.id] = provider + synchronized(lock) { + require(provider.id !in providers) { "Duplicate remote config provider: ${provider.id}" } + providers[provider.id] = provider + } } - fun providerIds(): List = providers.keys.toList() + /** Drops every registration. Called when a session ends so a re-`initialize()` starts clean. */ + fun clear() { + synchronized(lock) { providers.clear() } + } + + fun providerIds(): List = synchronized(lock) { providers.keys.toList() } /** Null for an unknown id; a provider that throws yields an unavailable snapshot, never an exception. */ - fun snapshot(id: String): RemoteConfigSnapshot? = providers[id]?.let { read(id, it) } + fun snapshot(id: String): RemoteConfigSnapshot? = synchronized(lock) { providers[id] }?.let { read(id, it) } - fun snapshots(): List = providers.map { (id, provider) -> read(id, provider) } + /** + * The copy is taken under the lock and read outside it: [read] calls into host code, which may + * be slow or may itself register a provider, and neither should happen with the lock held. + */ + fun snapshots(): List = + synchronized(lock) { providers.toList() }.map { (id, provider) -> read(id, provider) } /** * A debugging tool that crashes the app it exists to observe is worse than no tool, so a diff --git a/sdk/remote-config/src/test/kotlin/io/devconsole/remoteconfig/RemoteConfigRegistryTest.kt b/sdk/remote-config/src/test/kotlin/io/devconsole/remoteconfig/RemoteConfigRegistryTest.kt index 22f18d6..9bb770a 100644 --- a/sdk/remote-config/src/test/kotlin/io/devconsole/remoteconfig/RemoteConfigRegistryTest.kt +++ b/sdk/remote-config/src/test/kotlin/io/devconsole/remoteconfig/RemoteConfigRegistryTest.kt @@ -9,6 +9,8 @@ import org.junit.Assert.assertNotNull import org.junit.Assert.assertNull import org.junit.Assert.assertTrue import org.junit.Test +import java.util.concurrent.CopyOnWriteArrayList +import java.util.concurrent.CountDownLatch class RemoteConfigRegistryTest { @Test @@ -158,6 +160,66 @@ class RemoteConfigRegistryTest { minimumFetchIntervalSeconds = null, ) + @Test + fun `clear drops every registration so the same id can be registered again`() { + val registry = RemoteConfigRegistry() + registry.register(provider("firebase", entry("k", "old", RemoteConfigSource.REMOTE))) + + registry.clear() + // The point of clear(): re-registering the same id must be accepted, not refused as a + // duplicate. A stop() -> initialize() carrying a replacement adapter under the same id + // would otherwise leave every surface reading through the torn-down original. + registry.register(provider("firebase", entry("k", "new", RemoteConfigSource.REMOTE))) + + assertEquals(listOf("firebase"), registry.providerIds()) + val reread = registry.snapshots().single() + assertEquals("new", reread.entries.single().value) + } + + /** + * Registering while reading is a documented path (`DevConsole.registerRemoteConfigProvider` + * from a post-fetch listener) and the readers are the Ktor thread and the inspector's + * dispatcher, so an unguarded `LinkedHashMap` would throw `ConcurrentModificationException` + * into the host app -- the one thing the read path promises never to do. + */ + @Test + fun `registering while snapshots is iterating does not throw into the reader`() { + val registry = RemoteConfigRegistry() + repeat(INITIAL_PROVIDERS) { i -> + registry.register(provider("p$i", entry("k", "v", RemoteConfigSource.REMOTE))) + } + val failures = CopyOnWriteArrayList() + val start = CountDownLatch(1) + + val writer = + Thread { + start.await() + repeat(LATE_PROVIDERS) { i -> + runCatching { registry.register(provider("late$i", entry("k", "v", RemoteConfigSource.REMOTE))) } + } + } + val reader = + Thread { + start.await() + repeat(READ_ROUNDS) { + runCatching { registry.snapshots() }.onFailure(failures::add) + } + } + writer.start() + reader.start() + start.countDown() + writer.join() + reader.join() + + assertTrue("reader saw ${failures.firstOrNull()}", failures.isEmpty()) + } + + private companion object { + const val INITIAL_PROVIDERS = 20 + const val LATE_PROVIDERS = 200 + const val READ_ROUNDS = 200 + } + private fun entry( key: String, value: String, diff --git a/sdk/server-ktor/src/main/resources/devconsole-web/dashboard.js b/sdk/server-ktor/src/main/resources/devconsole-web/dashboard.js index a800979..183ead0 100644 --- a/sdk/server-ktor/src/main/resources/devconsole-web/dashboard.js +++ b/sdk/server-ktor/src/main/resources/devconsole-web/dashboard.js @@ -1044,7 +1044,7 @@ // collapsed group rather than merely hiding in place. // ================================================================ const RAIL_ADVANCED_IDS = ['viewSdkHealth', 'viewComposer', 'viewCaptureRules', 'viewState', 'viewRemoteConfig', 'viewPreferences', 'viewDatabase', 'viewFiles', 'viewSession']; - const RAIL_ADVANCED_VIEWS = new Set(['sdkHealth', 'composer', 'captureRules', 'state', 'preferences', 'database', 'files', 'session']); + const RAIL_ADVANCED_VIEWS = new Set(['sdkHealth', 'composer', 'captureRules', 'state', 'remoteConfig', 'preferences', 'database', 'files', 'session']); // ================================================================ // Capture-category gating: which rail buttons/views a server-reported disabled category (see @@ -4418,7 +4418,11 @@ if (!token) return; const r = await fetch('/api/v1/remote-config', { headers: auth() }); if (!r.ok) { + // Counter and badge are reset here too: leaving the last successful load's numbers next to a + // card that says the fetch failed is the one reading that is worse than either alone. remoteConfigProviders = []; + setNavCount('navCountRemoteConfig', 0); + $('remoteConfigBadge').textContent = 'unavailable'; cardsGridHtml('remoteConfigCards', [{ icon: 'sliders', iconTone: 'signal', title: 'Remote Config', lede: 'Remote Config unavailable: ' + r.status }]); return; } @@ -4435,7 +4439,7 @@ } function renderRemoteConfigCards() { const total = remoteConfigProviders.reduce((sum, p) => sum + (p.entries || []).length, 0); - $('navCountRemoteConfig').textContent = total; + setNavCount('navCountRemoteConfig', total); $('remoteConfigBadge').textContent = remoteConfigProviders.length ? total + ' key' + (total === 1 ? '' : 's') + ' · ' + remoteConfigProviders.length + ' provider' + (remoteConfigProviders.length === 1 ? '' : 's') : 'no providers'; diff --git a/sdk/server-ktor/src/main/resources/devconsole-web/index.html b/sdk/server-ktor/src/main/resources/devconsole-web/index.html index 2fc72af..94ef5ab 100644 --- a/sdk/server-ktor/src/main/resources/devconsole-web/index.html +++ b/sdk/server-ktor/src/main/resources/devconsole-web/index.html @@ -473,7 +473,7 @@
-
Source
+
Source
Not connected yet
Open DevConsole on the device → More → scan the QR or paste the code in Overview to inspect Remote Config.
diff --git a/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/DashboardAssetsTest.kt b/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/DashboardAssetsTest.kt index 015f7a2..454e5b6 100644 --- a/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/DashboardAssetsTest.kt +++ b/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/DashboardAssetsTest.kt @@ -93,13 +93,36 @@ class DashboardAssetsTest { } // Pretty JSON is the segment that carries `active` in the static markup, so the viewer // opens on it for every value that actually parses. - assertTrue(dashboard.contains("")) + assertTrue( + dashboard.contains(""), + ) assertTrue(dashboard.contains("data-value=\"raw\">Raw")) // The rows have to be clickable for any of the above to be reachable. assertTrue(script.contains("openRemoteConfigValue")) assertTrue(script.contains("data-card-row")) } + @Test + fun `remote config rail count goes through setNavCount and every source is filterable`() { + val dashboard = DashboardAssets.index() + val script = DashboardAssets.js() + + // Setting .textContent directly leaves the badge at `display: none` -- only setNavCount + // adds the `.show` class, and it is also what applies the 999+ clamp. + assertTrue(script.contains("setNavCount('navCountRemoteConfig'")) + assertFalse(script.contains("\$('navCountRemoteConfig').textContent")) + // Every source in the model is reachable: the matcher is an exact `===`, so a source with + // no button cannot be isolated at all -- `override` above all, which is the whole question + // the source column exists to answer. + listOf("all", "remote", "default", "static", "override", "unknown").forEach { source -> + assertTrue("no source filter for \"$source\"", dashboard.contains("data-value=\"$source\"")) + } + // The rail button and the view id move together: the id gates the auto-expand that keeps + // the active button from being stranded inside a collapsed Advanced group. + assertTrue(script.contains("'viewRemoteConfig'")) + assertTrue(script.contains("'remoteConfig', 'preferences'")) + } + @Test fun `network view offers a Postman export next to the existing HAR export`() { val dashboard = DashboardAssets.index() diff --git a/sdk/state/api/state.api b/sdk/state/api/state.api index 9535729..0a57df1 100644 --- a/sdk/state/api/state.api +++ b/sdk/state/api/state.api @@ -115,6 +115,7 @@ public final class io/devconsole/state/StateProviderKt { public final class io/devconsole/state/StateRegistry { public fun ()V + public final fun clear ()V public final fun mutate (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Lio/devconsole/state/StateMutationResult; public final fun mutators (Ljava/lang/String;)Ljava/util/List; public final fun providerIds ()Ljava/util/List; diff --git a/sdk/state/src/main/kotlin/io/devconsole/state/StateProvider.kt b/sdk/state/src/main/kotlin/io/devconsole/state/StateProvider.kt index e9adb64..0df7d8d 100644 --- a/sdk/state/src/main/kotlin/io/devconsole/state/StateProvider.kt +++ b/sdk/state/src/main/kotlin/io/devconsole/state/StateProvider.kt @@ -82,17 +82,37 @@ fun stateProvider( } class StateRegistry { + /** + * Guarded by [lock] on every access, read included: providers may be registered late (through + * `DevConsole.registerStateProvider`) while the dashboard's Ktor thread and the in-app + * inspector's dispatcher are reading, and an unguarded `LinkedHashMap` would throw + * `ConcurrentModificationException` into whichever of them happened to be iterating. A + * `ConcurrentHashMap` would drop the insertion order surfaces list providers in. + */ + private val lock = Any() private val providers = linkedMapOf() fun register(provider: StateProvider) { require(provider.id.isNotBlank()) { "State provider id must not be blank" } - require(provider.id !in providers) { "Duplicate state provider: ${provider.id}" } - providers[provider.id] = provider + synchronized(lock) { + require(provider.id !in providers) { "Duplicate state provider: ${provider.id}" } + providers[provider.id] = provider + } + } + + /** + * Drops every registration, so a re-`initialize()` starts from the new config's providers + * instead of keeping the previous session's. Public for the same reason [mutators] is: the + * caller is `sdk:full`, a separate Gradle module. + */ + fun clear() { + synchronized(lock) { providers.clear() } } - fun snapshot(id: String): StateSnapshot? = providers[id]?.snapshot() + /** Read outside the lock: [StateProvider.snapshot] calls into host code of unknown cost. */ + fun snapshot(id: String): StateSnapshot? = synchronized(lock) { providers[id] }?.snapshot() - fun providerIds(): List = providers.keys.toList() + fun providerIds(): List = synchronized(lock) { providers.keys.toList() } /** * The mutation catalogue for a provider -- empty (not null) for an unknown id or a read-only @@ -105,11 +125,12 @@ class StateRegistry { * artifact -- so a caller who upcasts the result would otherwise get a live handle into the * provider's own mutable state instead of a snapshot of its catalogue. */ - fun mutators(id: String): List = providers[id]?.mutators?.toList().orEmpty() + fun mutators(id: String): List = synchronized(lock) { providers[id] }?.mutators?.toList().orEmpty() fun mutate( providerId: String, mutatorId: String, input: String, - ): StateMutationResult? = providers[providerId]?.mutators?.firstOrNull { it.id == mutatorId }?.execute(input) + ): StateMutationResult? = + synchronized(lock) { providers[providerId] }?.mutators?.firstOrNull { it.id == mutatorId }?.execute(input) } diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveFormat.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveFormat.kt index cac8c6f..aa69591 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveFormat.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveFormat.kt @@ -2,8 +2,13 @@ * @author Shakib * @since 04/08/26 */ +@file:Suppress("TooManyFunctions") + package io.devconsole.ui.compose +// TooManyFunctions is suppressed above because this file is one small, independent formatter per +// thing the inspector renders: its function count tracks that list, not any complexity. + import android.content.Context import android.content.Intent import androidx.compose.ui.graphics.Color @@ -62,6 +67,7 @@ internal fun pushLifecycleShortLabel(lifecycle: String): String = private const val CAPTURE_CLOCK_FORMAT = "HH:mm:ss" private const val CAPTURE_CLOCK_FORMAT_SHORT = "HH:mm" +private const val CAPTURE_DATE_TIME_FORMAT = "d MMM, HH:mm:ss" /** `HH:mm:ss` of [epochMs] in the device's default locale digits (fresh formatter per call, not shared/cached). */ internal fun formatCaptureClockTime(epochMs: Long): String = @@ -71,6 +77,16 @@ internal fun formatCaptureClockTime(epochMs: Long): String = internal fun formatCaptureClockTimeShort(epochMs: Long): String = SimpleDateFormat(CAPTURE_CLOCK_FORMAT_SHORT, Locale.US).format(Date(epochMs)) +/** + * `d MMM, HH:mm:ss` of [epochMs], for timestamps that are routinely not from today. Captures are + * session-scoped and a bare clock time reads fine for them, but a Remote Config fetch is throttled + * to a 12h minimum interval by default -- so `09:14:02` alone reads identically whether the fetch + * was a minute ago or last week, which is the distinction that surface exists to make. The + * dashboard's `toLocaleString()` already carries the date; this is the on-device counterpart. + */ +internal fun formatCaptureDateTime(epochMs: Long): String = + SimpleDateFormat(CAPTURE_DATE_TIME_FORMAT, Locale.US).format(Date(epochMs)) + private const val BYTES_PER_KB = 1024L private const val BYTES_PER_MB = BYTES_PER_KB * 1024L private const val BYTES_PER_GB = BYTES_PER_MB * 1024L diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveRemoteConfigDetail.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveRemoteConfigDetail.kt index ba984f4..2fdd000 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveRemoteConfigDetail.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveRemoteConfigDetail.kt @@ -76,19 +76,26 @@ private fun remoteConfigDetailHeader( subtitle = "${provider.id} · ${remoteConfigFetchLine(provider)}", status = entry.source.uppercase(Locale.US), statusColor = if (entry.source == "remote") colors.signal else colors.muted, + // Dropped entirely for a redacted entry, matching the Value section's own copy affordance, + // which is already withheld. Keeping them would put two copy buttons on one screen disagreeing + // about whether this value is copyable, and open a share sheet holding the placeholder. actions = - listOf( - InspectorTopAction( - contentDescription = "Copy value", - onClick = { copyText(entry.value) }, - icon = copyIconAction(colors.muted), - ), - InspectorTopAction( - contentDescription = "Share value", - onClick = { shareText(entry.value, "Share ${entry.key}") }, - icon = shareIconAction(colors.muted), - ), - ), + if (entry.redacted) { + emptyList() + } else { + listOf( + InspectorTopAction( + contentDescription = "Copy value", + onClick = { copyText(entry.value) }, + icon = copyIconAction(colors.muted), + ), + InspectorTopAction( + contentDescription = "Share value", + onClick = { shareText(entry.value, "Share ${entry.key}") }, + icon = shareIconAction(colors.muted), + ), + ) + }, ) /** The provider's fetch state travels with the key: it is what tells a `default` apart from a bug. */ @@ -101,7 +108,7 @@ private fun remoteConfigDetailEntries( add(InspectorKeyValue("key", entry.key)) add(InspectorKeyValue("source", entry.source, if (entry.source == "remote") null else colors.muted)) add(InspectorKeyValue("provider", provider.id)) - add(InspectorKeyValue("last fetch", provider.lastFetchEpochMs?.let(::formatCaptureClockTime) ?: "never")) + add(InspectorKeyValue("last fetch", provider.lastFetchEpochMs?.let(::formatCaptureDateTime) ?: "never")) add(InspectorKeyValue("fetch status", provider.status.replace('_', ' '))) provider.minimumFetchIntervalSeconds?.let { add(InspectorKeyValue("min fetch interval", "${it}s")) } // Both are called out only when true: a "truncated: false" row on every key would be noise, diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorRemoteConfigFormat.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorRemoteConfigFormat.kt index 3e0d75b..be5600c 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorRemoteConfigFormat.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorRemoteConfigFormat.kt @@ -46,7 +46,7 @@ internal fun remoteConfigFetchLine(provider: InspectorRemoteConfigUi): String = buildString { append("last fetch: ") append( - provider.lastFetchEpochMs?.let(::formatCaptureClockTime) ?: "never", + provider.lastFetchEpochMs?.let(::formatCaptureDateTime) ?: "never", ) append(" · ") append(provider.status.replace('_', ' '))