From 5ad986651d7acd104528e93a5941e738b107e075 Mon Sep 17 00:00:00 2001 From: shakibuzzaman Date: Wed, 4 Nov 2026 09:30:53 +0600 Subject: [PATCH] Harden the SDK and add power-user inspection features Stability: host-crash and OOM hardening, safer destructive actions, build-variant safety checks, durable history across runs, server restart rebinding and a stream race fix (subscribe before server.welcome). UI/UX: inspector perf, liveness and state fixes; dashboard correctness, empty states, deep links, plurals and phone layout. Features: - Mocks: sequence, map-remote and throttle actions, predicates, rule import/export, Ktor-client mocks. - Network: body search, endpoint latency stats, JWT/form/GraphQL decoders, resend/edit-resend, HAR import viewer (local only, never uploads). - Capture control: pause/resume and purge in the inspector and dashboard. - Sockets: send WebSocket frames and MQTT publishes (topic/QoS/retained). - Remote Config: durable per-key overrides with provider fallback, in-app and dashboard editors; audit records value length only, never the value. - Logs: Timber / DevConsoleLog bridge (new logs-timber module). - Crash fingerprint grouping. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DDXGgZyopa182KG5tsBz3T --- README.md | 23 +- docs/BUILD_VARIANTS_AND_PRODUCTION_SAFETY.md | 36 +- docs/GETTING_STARTED_COMPOSE.md | 32 +- docs/GETTING_STARTED_XML_KOTLIN.md | 9 +- docs/MQTT_CAPTURE.md | 8 + docs/NETWORK_ADAPTERS.md | 53 +- docs/PROTOCOL_REFERENCE.md | 35 +- docs/PUBLISHING.md | 7 +- docs/REMOTE_CONFIG.md | 51 +- docs/WEBSOCKET_INSPECTOR.md | 21 +- gradle-plugin/build.gradle.kts | 12 +- .../gradle/DevConsoleVariantPolicyPlugin.kt | 54 +- .../devconsole-plugin-version.properties | 1 + ...onsoleVariantPolicyPluginFunctionalTest.kt | 77 +- samples/compose-app/build.gradle.kts | 1 + .../sample/compose/SampleKtorClient.kt | 7 + .../devconsole/sample/compose/MainActivity.kt | 69 +- sdk/api/api/api.api | 59 + .../api/DevConsoleFacadeProvider.kt | 25 + .../kotlin/io/devconsole/api/PurgeResult.kt | 19 + .../io/devconsole/api/SessionExportResult.kt | 22 + sdk/composer/api/composer.api | 1 - .../io/devconsole/composer/ComposerRequest.kt | 55 +- .../composer/ComposerExecutorTest.kt | 20 + sdk/export/api/export.api | 17 +- .../io/devconsole/export/EventExportWriter.kt | 460 ++- .../export/EventExportWriterTest.kt | 103 + .../main/kotlin/io/devconsole/DevConsole.kt | 33 + sdk/full/api/full.api | 7 + .../ScreenshotCaptureInstrumentedTest.kt | 38 +- .../io/devconsole/AndroidDatabaseInspector.kt | 97 +- .../io/devconsole/AndroidMockRuleStore.kt | 53 + .../devconsole/AndroidPreferencesInspector.kt | 49 +- .../AndroidRemoteConfigOverrideStore.kt | 135 + .../main/kotlin/io/devconsole/CaptureGate.kt | 35 + .../io/devconsole/CapturePayloadCodec.kt | 1 + .../kotlin/io/devconsole/CaptureTimeline.kt | 6 + .../io/devconsole/ComposerCollectionJson.kt | 171 ++ .../main/kotlin/io/devconsole/CrashCapture.kt | 156 +- .../devconsole/DevConsoleForegroundService.kt | 73 +- .../io/devconsole/DevConsoleInitializer.kt | 33 +- .../devconsole/FileComposerCollectionStore.kt | 136 + .../io/devconsole/FullInspectorDataSource.kt | 518 +++- .../kotlin/io/devconsole/InspectorExporter.kt | 40 +- .../kotlin/io/devconsole/PendingCrashFile.kt | 55 + .../io/devconsole/PersistentTimeline.kt | 7 +- .../io/devconsole/PlatformFacadeProvider.kt | 281 +- .../kotlin/io/devconsole/PurgeSummaryText.kt | 34 + .../RecoveringDevConsoleDatabase.kt | 1 + .../io/devconsole/RedactingRemoteConfig.kt | 20 +- .../io/devconsole/RetainedCaptureDecoder.kt | 190 ++ .../io/devconsole/RetainedNetworkStores.kt | 88 + .../io/devconsole/RetainedSessionCaptures.kt | 102 + .../devconsole/RetainedSocketPushDecoding.kt | 142 + .../kotlin/io/devconsole/ScreenshotCapture.kt | 36 +- .../kotlin/io/devconsole/SessionMarkers.kt | 7 + .../AndroidDatabaseInspectorTest.kt | 24 + .../io/devconsole/AndroidMockRuleStoreTest.kt | 20 + .../AndroidPreferencesInspectorTest.kt | 47 + .../AndroidRemoteConfigOverrideStoreTest.kt | 98 + .../kotlin/io/devconsole/CaptureGateTest.kt | 144 + .../kotlin/io/devconsole/CrashCaptureTest.kt | 58 + .../devconsole/DevConsoleInitializerTest.kt | 18 + .../FileComposerCollectionStoreTest.kt | 197 ++ .../kotlin/io/devconsole/FullFacadeTest.kt | 17 +- .../devconsole/FullInspectorDataSourceTest.kt | 325 +++ .../io/devconsole/PersistentTimelineTest.kt | 6 +- ...latformFacadeProviderCaptureControlTest.kt | 101 + .../PlatformFacadeProviderSessionReadyTest.kt | 19 + .../io/devconsole/PurgeSummaryTextTest.kt | 50 + .../devconsole/RetainedCaptureDecoderTest.kt | 396 +++ .../devconsole/RetainedNetworkStoresTest.kt | 220 ++ .../devconsole/RetainedSessionCapturesTest.kt | 115 + .../io/devconsole/ScreenshotCaptureTest.kt | 11 +- sdk/logs-timber/api/logs-timber.api | 29 + sdk/logs-timber/build.gradle.kts | 16 + sdk/logs-timber/consumer-rules.pro | 2 + .../devconsole/logs/timber/DevConsoleLog.kt | 95 + .../logs/timber/DevConsoleTimberTree.kt | 74 + .../logs/timber/DevConsoleLogTest.kt | 86 + .../logs/timber/DevConsoleTimberTreeTest.kt | 120 + .../api/mocks-okhttp-noop.api | 5 + .../mocks/okhttp/MockFailureMarker.kt | 9 + sdk/mocks-okhttp/api/mocks-okhttp.api | 5 + .../mocks/okhttp/DevConsoleMockInterceptor.kt | 110 +- .../mocks/okhttp/MockActionTransport.kt | 158 ++ .../okhttp/DevConsoleMockInterceptorTest.kt | 211 ++ sdk/mocks/api/mocks.api | 50 + .../kotlin/io/devconsole/mocks/MockEngine.kt | 312 +- .../io/devconsole/mocks/MockEngineTest.kt | 270 ++ sdk/network-ktor/api/network-ktor.api | 10 + sdk/network-ktor/build.gradle.kts | 2 + sdk/network-ktor/consumer-rules.pro | 1 + .../enabled/NetworkKtorCaptureMarker.kt | 9 + .../ktor/DevConsoleKtorClientPlugin.kt | 13 + .../network/ktor/DevConsoleKtorMocks.kt | 169 ++ .../network/ktor/KtorMockActionExecutor.kt | 200 ++ .../network/ktor/MockResponseRewrite.kt | 110 + .../network/ktor/DevConsoleKtorMocksTest.kt | 292 ++ .../okhttp/DevConsoleOkHttpInterceptor.kt | 10 +- sdk/network/api/network.api | 48 +- .../network/EndpointLatencyStats.kt | 124 + .../io/devconsole/network/ExportSelection.kt | 32 +- .../io/devconsole/network/NetworkCapture.kt | 30 + .../io/devconsole/network/NetworkExport.kt | 10 +- .../network/NetworkTransactionStore.kt | 18 +- .../network/EndpointLatencyStatsTest.kt | 136 + .../devconsole/network/ExportSelectionTest.kt | 10 + .../InMemoryNetworkTransactionStoreTest.kt | 88 + .../devconsole/network/NetworkExportTest.kt | 16 + sdk/noop/api/noop.api | 7 + .../io/devconsole/PlatformFacadeProvider.kt | 15 + .../NoopFacadeProviderContractTest.kt | 19 + .../OkHttpAdapterFullNoopParityTest.kt | 12 +- sdk/remote-config/api/remote-config.api | 46 +- .../devconsole/remoteconfig/RemoteConfig.kt | 24 +- .../remoteconfig/RemoteConfigOverrides.kt | 192 ++ .../remoteconfig/RemoteConfigRegistry.kt | 147 +- .../remoteconfig/RemoteConfigOverridesTest.kt | 358 +++ .../io/devconsole/security/RedactionEngine.kt | 2 +- .../security/RedactionEngineTest.kt | 11 + sdk/server-ktor/api/server-ktor.api | 41 +- .../devconsole/server/ktor/CaptureControl.kt | 28 + .../server/ktor/DevConsoleKtorModule.kt | 1044 +++++-- .../devconsole/server/ktor/EventStreamHub.kt | 25 +- .../devconsole/server/ktor/MockActionForm.kt | 204 ++ .../devconsole/server/ktor/MockActionJson.kt | 78 + .../server/ktor/NetworkEndpointStatsRoutes.kt | 81 + .../devconsole/server/ktor/SocketSendForm.kt | 26 + .../resources/devconsole-web/dashboard.css | 225 +- .../resources/devconsole-web/dashboard.js | 2509 +++++++++++++++-- .../main/resources/devconsole-web/index.html | 96 +- .../server/ktor/CaptureControlRoutesTest.kt | 244 ++ .../server/ktor/DevConsoleKtorModuleTest.kt | 93 +- .../ktor/EvidenceAndScreenshotRoutesTest.kt | 32 +- .../server/ktor/KtorLocalServerEngineTest.kt | 30 + .../server/ktor/MockActionRoutesTest.kt | 239 ++ .../ktor/NetworkEndpointStatsRoutesTest.kt | 233 ++ .../ktor/RemoteConfigOverrideRoutesTest.kt | 459 +++ .../server/ktor/RemoteConfigRoutesTest.kt | 2 +- .../server/ktor/RetainedNetworkRoutesTest.kt | 252 ++ .../server/ktor/SocketSendRoutesTest.kt | 275 ++ .../DevConsoleOkHttpWebSocketListener.kt | 63 +- .../DevConsoleOkHttpWebSocketListenerTest.kt | 108 +- .../socket/paho/DevConsolePahoMqtt.kt | 40 + .../socket/paho/DevConsolePahoMqttTest.kt | 78 +- sdk/socket/api/socket.api | 80 +- .../io/devconsole/socket/SocketCapture.kt | 13 +- .../io/devconsole/socket/SocketSenders.kt | 156 + .../socket/SocketSenderRegistryTest.kt | 149 + sdk/storage-api/api/storage-api.api | 17 +- .../io/devconsole/storage/api/EventStore.kt | 11 + sdk/storage-room/api/storage-room.api | 23 +- .../6.json | 603 ++++ ...EvidenceCascadeDeletionInstrumentedTest.kt | 2 +- .../room/Migration5To6InstrumentedTest.kt | 48 + .../room/RoomEventStoreInstrumentedTest.kt | 7 +- .../storage/room/DevConsoleDatabase.java | 10 +- .../io/devconsole/storage/room/EventDao.java | 26 +- .../storage/room/EventPruneCandidate.java | 18 + .../devconsole/storage/room/SessionDao.java | 7 +- .../storage/room/SessionEntity.java | 4 +- .../storage/room/EventQuotaPruner.kt | 44 +- .../devconsole/storage/room/RoomEventStore.kt | 16 +- .../storage/room/RoomRetentionCoordinator.kt | 4 + .../storage/room/RoomSessionStore.kt | 95 +- .../storage/room/EventQuotaPrunerTest.kt | 91 +- .../RoomEventStoreRetainedEventsFilterTest.kt | 9 +- .../room/SessionRetentionPrunerTest.kt | 324 ++- sdk/timeline/api/timeline.api | 3 +- .../kotlin/io/devconsole/timeline/Timeline.kt | 207 +- .../timeline/InMemoryTimelineTest.kt | 50 + sdk/ui-compose/api/ui-compose.api | 415 ++- sdk/ui-compose/build.gradle.kts | 1 + sdk/ui-compose/consumer-rules.pro | 1 + .../enabled/UiComposeCaptureMarker.kt | 9 + .../ui/compose/DevConsoleWorkspace.kt | 107 +- .../devconsole/ui/compose/InspectorAction.kt | 57 + .../ui/compose/InspectorCodeBlock.kt | 18 +- .../ui/compose/InspectorControlScreen.kt | 442 ++- .../ui/compose/InspectorCrashGrouping.kt | 121 + .../ui/compose/InspectorDataScreen.kt | 144 +- .../ui/compose/InspectorDataSource.kt | 151 +- .../ui/compose/InspectorDatabaseSection.kt | 88 +- .../ui/compose/InspectorEmptyState.kt | 1 + .../ui/compose/InspectorFilesSection.kt | 75 +- .../ui/compose/InspectorFlagEditDialogs.kt | 157 ++ .../ui/compose/InspectorMockRuleEditor.kt | 714 ++++- .../ui/compose/InspectorMockRuleForm.kt | 156 +- .../ui/compose/InspectorMoreScreen.kt | 196 +- .../ui/compose/InspectorNavComponents.kt | 25 +- .../ui/compose/InspectorNetworkSnippets.kt | 5 +- .../ui/compose/InspectorObserveCrashesTab.kt | 141 +- .../ui/compose/InspectorObserveDetail.kt | 13 +- .../compose/InspectorObserveDetailPanels.kt | 5 +- .../ui/compose/InspectorObserveFormat.kt | 7 + .../ui/compose/InspectorObserveLogDetail.kt | 18 +- .../ui/compose/InspectorObserveNetDetail.kt | 288 +- .../InspectorObserveRemoteConfigTab.kt | 94 +- .../ui/compose/InspectorObserveScreen.kt | 649 ++++- .../ui/compose/InspectorObserveSignals.kt | 53 +- .../ui/compose/InspectorObserveTrafficTab.kt | 142 +- .../ui/compose/InspectorPastRunBanner.kt | 92 + .../ui/compose/InspectorRemoteConfigFormat.kt | 4 +- .../InspectorRemoteConfigOverrideDialog.kt | 105 + .../ui/compose/InspectorResendSheet.kt | 350 +++ .../ui/compose/InspectorSocketComposer.kt | 156 + .../devconsole/ui/compose/InspectorState.kt | 18 + .../ui/compose/InspectorStructuredDecoders.kt | 422 +++ .../devconsole/ui/compose/InspectorUrlCard.kt | 8 +- .../ui/compose/InspectorViewModel.kt | 355 ++- .../ui/compose/ObserveDetailTargetSaver.kt | 46 + .../ui/compose/InspectorCountLabelTest.kt | 19 + .../ui/compose/InspectorCrashGroupingTest.kt | 180 ++ .../compose/InspectorFlagEditDialogsTest.kt | 35 + .../ui/compose/InspectorLogDetailTest.kt | 31 + .../ui/compose/InspectorMockRuleEditorTest.kt | 13 +- .../ui/compose/InspectorMockRuleFormTest.kt | 122 +- .../compose/InspectorNetworkSnippetsTest.kt | 17 + .../InspectorRemoteConfigOverrideTest.kt | 75 + .../ui/compose/InspectorResendResultTest.kt | 39 + .../ui/compose/InspectorResendSheetTest.kt | 80 + .../ui/compose/InspectorSocketComposerTest.kt | 29 + .../InspectorStructuredDecodersTest.kt | 269 ++ .../ui/compose/InspectorTrafficFiltersTest.kt | 61 + .../ui/compose/InspectorViewModelTest.kt | 321 ++- .../compose/ObserveDetailTargetSaverTest.kt | 38 + sdk/ui-views/build.gradle.kts | 5 +- sdk/ui-views/consumer-rules.pro | 1 + .../internal/enabled/UiViewsCaptureMarker.kt | 9 + settings.gradle.kts | 1 + 231 files changed, 23176 insertions(+), 1940 deletions(-) create mode 100644 gradle-plugin/src/main/resources/devconsole-plugin-version.properties create mode 100644 sdk/api/src/main/kotlin/io/devconsole/api/PurgeResult.kt create mode 100644 sdk/api/src/main/kotlin/io/devconsole/api/SessionExportResult.kt create mode 100644 sdk/full/src/main/kotlin/io/devconsole/AndroidRemoteConfigOverrideStore.kt create mode 100644 sdk/full/src/main/kotlin/io/devconsole/CaptureGate.kt create mode 100644 sdk/full/src/main/kotlin/io/devconsole/ComposerCollectionJson.kt create mode 100644 sdk/full/src/main/kotlin/io/devconsole/FileComposerCollectionStore.kt create mode 100644 sdk/full/src/main/kotlin/io/devconsole/PendingCrashFile.kt create mode 100644 sdk/full/src/main/kotlin/io/devconsole/PurgeSummaryText.kt create mode 100644 sdk/full/src/main/kotlin/io/devconsole/RetainedCaptureDecoder.kt create mode 100644 sdk/full/src/main/kotlin/io/devconsole/RetainedNetworkStores.kt create mode 100644 sdk/full/src/main/kotlin/io/devconsole/RetainedSessionCaptures.kt create mode 100644 sdk/full/src/main/kotlin/io/devconsole/RetainedSocketPushDecoding.kt create mode 100644 sdk/full/src/test/kotlin/io/devconsole/AndroidRemoteConfigOverrideStoreTest.kt create mode 100644 sdk/full/src/test/kotlin/io/devconsole/CaptureGateTest.kt create mode 100644 sdk/full/src/test/kotlin/io/devconsole/DevConsoleInitializerTest.kt create mode 100644 sdk/full/src/test/kotlin/io/devconsole/FileComposerCollectionStoreTest.kt create mode 100644 sdk/full/src/test/kotlin/io/devconsole/PlatformFacadeProviderCaptureControlTest.kt create mode 100644 sdk/full/src/test/kotlin/io/devconsole/PlatformFacadeProviderSessionReadyTest.kt create mode 100644 sdk/full/src/test/kotlin/io/devconsole/PurgeSummaryTextTest.kt create mode 100644 sdk/full/src/test/kotlin/io/devconsole/RetainedCaptureDecoderTest.kt create mode 100644 sdk/full/src/test/kotlin/io/devconsole/RetainedNetworkStoresTest.kt create mode 100644 sdk/full/src/test/kotlin/io/devconsole/RetainedSessionCapturesTest.kt create mode 100644 sdk/logs-timber/api/logs-timber.api create mode 100644 sdk/logs-timber/build.gradle.kts create mode 100644 sdk/logs-timber/consumer-rules.pro create mode 100644 sdk/logs-timber/src/main/kotlin/io/devconsole/logs/timber/DevConsoleLog.kt create mode 100644 sdk/logs-timber/src/main/kotlin/io/devconsole/logs/timber/DevConsoleTimberTree.kt create mode 100644 sdk/logs-timber/src/test/kotlin/io/devconsole/logs/timber/DevConsoleLogTest.kt create mode 100644 sdk/logs-timber/src/test/kotlin/io/devconsole/logs/timber/DevConsoleTimberTreeTest.kt create mode 100644 sdk/mocks-okhttp-noop/src/main/kotlin/io/devconsole/mocks/okhttp/MockFailureMarker.kt create mode 100644 sdk/mocks-okhttp/src/main/kotlin/io/devconsole/mocks/okhttp/MockActionTransport.kt create mode 100644 sdk/network-ktor/consumer-rules.pro create mode 100644 sdk/network-ktor/src/main/kotlin/io/devconsole/internal/enabled/NetworkKtorCaptureMarker.kt create mode 100644 sdk/network-ktor/src/main/kotlin/io/devconsole/network/ktor/DevConsoleKtorMocks.kt create mode 100644 sdk/network-ktor/src/main/kotlin/io/devconsole/network/ktor/KtorMockActionExecutor.kt create mode 100644 sdk/network-ktor/src/main/kotlin/io/devconsole/network/ktor/MockResponseRewrite.kt create mode 100644 sdk/network-ktor/src/test/kotlin/io/devconsole/network/ktor/DevConsoleKtorMocksTest.kt create mode 100644 sdk/network/src/main/kotlin/io/devconsole/network/EndpointLatencyStats.kt create mode 100644 sdk/network/src/test/kotlin/io/devconsole/network/EndpointLatencyStatsTest.kt create mode 100644 sdk/remote-config/src/main/kotlin/io/devconsole/remoteconfig/RemoteConfigOverrides.kt create mode 100644 sdk/remote-config/src/test/kotlin/io/devconsole/remoteconfig/RemoteConfigOverridesTest.kt create mode 100644 sdk/server-ktor/src/main/kotlin/io/devconsole/server/ktor/CaptureControl.kt create mode 100644 sdk/server-ktor/src/main/kotlin/io/devconsole/server/ktor/MockActionForm.kt create mode 100644 sdk/server-ktor/src/main/kotlin/io/devconsole/server/ktor/MockActionJson.kt create mode 100644 sdk/server-ktor/src/main/kotlin/io/devconsole/server/ktor/NetworkEndpointStatsRoutes.kt create mode 100644 sdk/server-ktor/src/main/kotlin/io/devconsole/server/ktor/SocketSendForm.kt create mode 100644 sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/CaptureControlRoutesTest.kt create mode 100644 sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/MockActionRoutesTest.kt create mode 100644 sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/NetworkEndpointStatsRoutesTest.kt create mode 100644 sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/RemoteConfigOverrideRoutesTest.kt create mode 100644 sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/RetainedNetworkRoutesTest.kt create mode 100644 sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/SocketSendRoutesTest.kt create mode 100644 sdk/socket/src/main/kotlin/io/devconsole/socket/SocketSenders.kt create mode 100644 sdk/socket/src/test/kotlin/io/devconsole/socket/SocketSenderRegistryTest.kt create mode 100644 sdk/storage-room/schemas/io.devconsole.storage.room.DevConsoleDatabase/6.json create mode 100644 sdk/storage-room/src/androidTest/kotlin/io/devconsole/storage/room/Migration5To6InstrumentedTest.kt create mode 100644 sdk/storage-room/src/main/java/io/devconsole/storage/room/EventPruneCandidate.java create mode 100644 sdk/ui-compose/consumer-rules.pro create mode 100644 sdk/ui-compose/src/main/kotlin/io/devconsole/internal/enabled/UiComposeCaptureMarker.kt create mode 100644 sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorCrashGrouping.kt create mode 100644 sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorFlagEditDialogs.kt create mode 100644 sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorPastRunBanner.kt create mode 100644 sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorRemoteConfigOverrideDialog.kt create mode 100644 sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorResendSheet.kt create mode 100644 sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorSocketComposer.kt create mode 100644 sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorStructuredDecoders.kt create mode 100644 sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/ObserveDetailTargetSaver.kt create mode 100644 sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorCountLabelTest.kt create mode 100644 sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorCrashGroupingTest.kt create mode 100644 sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorFlagEditDialogsTest.kt create mode 100644 sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorLogDetailTest.kt create mode 100644 sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorRemoteConfigOverrideTest.kt create mode 100644 sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorResendResultTest.kt create mode 100644 sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorResendSheetTest.kt create mode 100644 sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorSocketComposerTest.kt create mode 100644 sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorStructuredDecodersTest.kt create mode 100644 sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorTrafficFiltersTest.kt create mode 100644 sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/ObserveDetailTargetSaverTest.kt create mode 100644 sdk/ui-views/consumer-rules.pro create mode 100644 sdk/ui-views/src/main/kotlin/io/devconsole/internal/enabled/UiViewsCaptureMarker.kt diff --git a/README.md b/README.md index 2a23f19..6c2dc99 100644 --- a/README.md +++ b/README.md @@ -440,9 +440,10 @@ Opt-in add-ons (each `-noop` twin is the matching `releaseImplementation`): | Coordinate | Release twin | Adds | |---|---|---| -| `devconsole-ui-compose` | *(none — `debugImplementation` only)* | Compose launcher-panel API (the on-device inspector itself already ships inside `devconsole`; name this coordinate only to call the panel composables) | -| `devconsole-ui-views` | *(none — `debugImplementation` only)* | `DevConsolePanelView` launcher for XML/Views hosts | -| `devconsole-network-ktor` | *(none)* | Ktor `HttpClient` capture plugin (full request + response body capture, any engine; see [Network adapters](docs/NETWORK_ADAPTERS.md)) | +| `devconsole-ui-compose` | *(none — `debugImplementation` only)* | Compose launcher-panel API; protected variants reject it unless scoped to debug | +| `devconsole-ui-views` | *(none — `debugImplementation` only)* | `DevConsolePanelView` launcher for XML/Views hosts; protected variants reject it unless scoped to debug | +| `devconsole-network-ktor` | *(none)* | Ktor `HttpClient` capture plugin (full request + response body capture, any engine; protected variants reject it; see [Network adapters](docs/NETWORK_ADAPTERS.md)) | +| `devconsole-logs-timber` | *(none)* | Timber tree + `DevConsoleLog` drop-in that forward app logs to the timeline (release-safe: forwards to the no-op recorder in protected variants) | | `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)) | @@ -452,7 +453,7 @@ You never name those. Every module publishes sources, javadoc, and a POM. ### Versions and unreleased code -All 34 library artifacts come from [JitPack](https://jitpack.io/#devconsole-android/DevConsole), +All 35 library artifacts come from [JitPack](https://jitpack.io/#devconsole-android/DevConsole), which builds a ref on demand. Releases are tagged `v1.3.1`, and JitPack resolves a bare version against the `v`-prefixed tag, which is why the coordinates above read `1.3.1` — the same spelling the Gradle plugin uses on the Portal. Any branch works as `-SNAPSHOT`, with `/` written as @@ -491,7 +492,10 @@ aapt2 dump permissions app/build/outputs/apk/release/app-release.apk The Gradle plugin enforces the same split mechanically. `verifyDevConsoleProtectedArtifacts` fails the build if the full runtime reaches a protected variant, checking declared dependencies, the -resolved runtime classpath, and the final APK/AAB bytes. See +resolved runtime classpath, and (on `assemble` / `bundle`) the final packaged +APK/AAB/AAR bytes through separate `verifyDevConsolePackagedArtifact` and +`verifyDevConsolePackagedBundle` tasks. Running the per-variant +`verifyDevConsoleProtectedArtifacts` task by itself checks dependencies only. See [Build variants and production safety](docs/BUILD_VARIANTS_AND_PRODUCTION_SAFETY.md). ## Flavored projects: verify the variant you ship @@ -508,7 +512,8 @@ verifyPartnerReleaseDevConsoleProtectedArtifacts ``` Each one is wired onto **its own** `assemble` / `bundle` and nothing else, so -`./gradlew :app:assembleProductionRelease` verifies `productionRelease` and resolves +`./gradlew :app:assembleProductionRelease` checks `productionRelease` dependencies and scans its +packaged APK, then resolves `productionRelease`'s classpath — no other flavor is touched. That matters most when your flavors carry environment-specific coordinates: @@ -528,7 +533,9 @@ on the critical path of a single-flavor release build: ```bash ./gradlew :app:assembleProductionRelease # ships production, verifies production -./gradlew :app:verifyProductionReleaseDevConsoleProtectedArtifacts # the same check on its own +./gradlew :app:verifyProductionReleaseDevConsoleProtectedArtifacts # dependency graph check only +./gradlew :app:verifyProductionReleaseDevConsolePackagedArtifact # APK/AAR byte scan +./gradlew :app:verifyProductionReleaseDevConsolePackagedBundle # AAB byte scan ./gradlew :app:verifyDevConsoleProtectedArtifacts # full sweep, all flavors, CI ``` @@ -556,6 +563,8 @@ say — lower the default and name what you protect. Understand that a variant l nobody checks: ```kotlin +import io.devconsole.gradle.DevConsoleVariantPolicy + devConsole { defaultPolicy.set(DevConsoleVariantPolicy.DISABLED) protectedVariantPatterns.set(listOf("(?i)production.*release")) diff --git a/docs/BUILD_VARIANTS_AND_PRODUCTION_SAFETY.md b/docs/BUILD_VARIANTS_AND_PRODUCTION_SAFETY.md index 39994e8..ef6e556 100644 --- a/docs/BUILD_VARIANTS_AND_PRODUCTION_SAFETY.md +++ b/docs/BUILD_VARIANTS_AND_PRODUCTION_SAFETY.md @@ -34,7 +34,7 @@ runtime in an extra internal variant: devConsole { enabledVariants.set(setOf("debug", "internal")) // gets the full runtime protectedVariantPatterns.set(listOf("(?i).*release", "prod.*")) // verified free of it - protectedDependencyPaths.set(setOf(":sdk:full")) // default; override for a differently-pathed module + protectedDependencyPaths.set(setOf(":sdk:full")) // project paths only; override for a differently-pathed checkout failBuildOnUnsafeVariant.set(true) // default; false downgrades to a warning autoWireDependencies.set(true) // default; false to declare coordinates yourself sdkVersion.set("1.3.1") // default; the JitPack version to resolve @@ -42,10 +42,16 @@ devConsole { ``` `protectedVariantPatterns` entries are matched with `Regex.matches` — a **full** match against the -whole variant name, not a substring search. The bare pattern `"release"` only matches a variant -literally named `"release"`; it silently misses a flavored variant like `"prodRelease"`. Anchor -patterns with `.*` (as `(?i).*release` above does) so they match regardless of what a flavor -prefixes onto the build type. +whole variant name, not a substring search. Use `"(?i).*release"` to match release variants +including flavored names such as `"prodRelease"`. Configuration entries that match no variant are +reported as warnings. + +`protectedDependencyPaths` defaults to the ten project modules that publish the core runtime, +capture adapters and UI launchers (`:sdk:full`, `:sdk:network-okhttp`, `:sdk:network-ktor`, +`:sdk:mocks-okhttp`, `:sdk:socket-okhttp`, `:sdk:socket-paho`, `:sdk:push-firebase`, +`:sdk:remote-config-firebase`, `:sdk:ui-compose` and `:sdk:ui-views`). Setting this property replaces +that project-path set. Published coordinates are checked separately by coordinate matching, and +packaged APK/AAB/AAR bytes are scanned for retained marker signatures. **A variant that already names a DevConsole dependency is left alone.** Auto-wiring only fills a gap, so an explicit `debugImplementation("com.github.devconsole-android.DevConsole:devconsole:...")` — or a @@ -69,17 +75,21 @@ The plugin registers: - `devConsoleVariantReport` writes `build/reports/devconsole/variants.json` listing the effective policy (`ENABLED`/`DISABLED`/`PROTECTED`) for every variant. -- `verifyDevConsoleProtectedArtifacts` — one task per protected variant — inspects that - variant's dependency graph for a direct `ProjectDependency` on any path in - `protectedDependencyPaths`, and fails the build if one is found. Each variant's +- `verifyDevConsoleProtectedArtifacts` — one task per protected variant — inspects declared + dependencies and the resolved runtime dependency graph for protected DevConsole modules, and fails + the build if one is found. It does not inspect packaged bytes. Each variant's `assemble` and `bundle` depends on its own verifier, so building a protected - artifact always runs its checks. + artifact always runs its dependency checks. +- `verifyDevConsolePackagedArtifact` scans the APK (or library AAR) bytes. Applications also + register `verifyDevConsolePackagedBundle` for AAB bytes. These tasks run on their matching + `assemble` / `bundle` lifecycle paths. - `verifyDevConsoleProtectedArtifacts` is the aggregate: it depends on every per-variant verifier, and `check` hangs off it. Run it as part of your release checklist — the three sample apps run it in CI on every push (see [`.github/workflows/verify.yml`](../.github/workflows/verify.yml)). ```bash -./gradlew :app:assembleRelease :app:verifyDevConsoleProtectedArtifacts +./gradlew :app:assembleRelease # runs dependency verification and the packaged APK scan +./gradlew :app:verifyDevConsoleProtectedArtifacts # dependency graph sweep across protected variants ``` On a flavored project, ask for the variant you are actually shipping. The aggregate verifies *every* @@ -87,8 +97,10 @@ protected variant, so on a project with `production`/`staging`/`partner` flavors builds — all three release variants: ```bash -./gradlew :app:assembleProductionRelease # verifies productionRelease only -./gradlew :app:verifyProductionReleaseDevConsoleProtectedArtifacts # the same check, on its own +./gradlew :app:assembleProductionRelease # verifies dependencies and scans the production APK +./gradlew :app:verifyProductionReleaseDevConsoleProtectedArtifacts # dependency graph only +./gradlew :app:verifyProductionReleaseDevConsolePackagedArtifact # packaged APK/AAR scan +./gradlew :app:verifyProductionReleaseDevConsolePackagedBundle # packaged AAB scan ``` ## Full/no-op parity diff --git a/docs/GETTING_STARTED_COMPOSE.md b/docs/GETTING_STARTED_COMPOSE.md index ea9be95..561730d 100644 --- a/docs/GETTING_STARTED_COMPOSE.md +++ b/docs/GETTING_STARTED_COMPOSE.md @@ -31,7 +31,7 @@ dependencies { devConsole { enabledVariants.set(setOf("debug")) - protectedVariantPatterns.set(listOf("release")) + protectedVariantPatterns.set(listOf("(?i).*release")) } ``` @@ -42,11 +42,10 @@ form is used here because it also matches the plugin's version on the Gradle Plu There is no BOM. `devconsole` (the debug runtime) and `devconsole-noop` are the only two coordinates a normal integration names; everything else is `devconsole-`. -**`devconsole-ui-compose` must be `debugImplementation`, never plain `implementation`.** It has no -release no-op counterpart and merges `DevConsoleActivity` into your manifest, so a plain -`implementation` dependency ships the whole in-app inspector — and an exported-by-merge Activity — -into your release build with no build-time warning. The Gradle plugin's variant protection does not -cover this module today; it is your responsibility to scope it to `debugImplementation` yourself. +**`devconsole-ui-compose` should be `debugImplementation`, never plain `implementation`.** It has no +release no-op counterpart and merges `DevConsoleActivity` into your manifest. The Gradle plugin now +treats it as a protected coordinate and marker: a protected variant that includes it fails with a +message directing you to use `debugImplementation`. 3. Add `INTERNET` to your own app's manifest. The full debug runtime auto-merges `ACCESS_LOCAL_NETWORK`, `NEARBY_WIFI_DEVICES`, `ACCESS_NETWORK_STATE`, and the default @@ -112,6 +111,27 @@ setContent { `adb forward tcp:8080 tcp:8080` first — 8080 is only the first port tried, so use whatever port the panel actually shows. +## Forwarding Timber / Log calls + +Add `devconsole-logs-timber` to hand your existing log calls to the Logs inspector. The module is +release-safe, so it can stay on `implementation` in every variant — in protected builds it forwards +to DevConsole's disabled recorder: + +```kotlin +implementation("com.github.devconsole-android.DevConsole:devconsole-logs-timber:1.3.1") + +// Once, after DevConsole.initialize: +Timber.plant(DevConsoleTimberTree(DevConsole.logRecorder())) +DevConsoleLog.install(DevConsole.logRecorder()) + +// Existing call sites keep working and now also land on the timeline: +Timber.i("Checkout reached the timeline") +DevConsoleLog.w("Checkout", "Payment retried") +``` + +Use `DevConsoleTimberTree(recorder, minimumPriority)` to drop lines below a given +`android.util.Log` priority. + For a full working example, [`samples/compose-app`](../samples/compose-app/src/main/kotlin/io/devconsole/sample/compose/MainActivity.kt) has one button per capability: network and WebSocket capture, mocks, push simulation, a feature flag, and a state provider. diff --git a/docs/GETTING_STARTED_XML_KOTLIN.md b/docs/GETTING_STARTED_XML_KOTLIN.md index 1ba345b..79e5877 100644 --- a/docs/GETTING_STARTED_XML_KOTLIN.md +++ b/docs/GETTING_STARTED_XML_KOTLIN.md @@ -31,7 +31,7 @@ dependencies { devConsole { enabledVariants.set(setOf("debug")) - protectedVariantPatterns.set(listOf("release")) + protectedVariantPatterns.set(listOf("(?i).*release")) } ``` @@ -42,10 +42,9 @@ form is used here because it also matches the plugin's version on the Gradle Plu There is no BOM. `devconsole` (the debug runtime) and `devconsole-noop` are the only two coordinates a normal integration names; everything else is `devconsole-`. -**`devconsole-ui-views` must be `debugImplementation`, never plain `implementation`.** It has no -release no-op counterpart, so a plain `implementation` dependency ships the launcher panel into your -release build with no build-time warning. The Gradle plugin's variant protection does not cover this -module today; it is your responsibility to scope it to `debugImplementation` yourself. +**`devconsole-ui-views` should be `debugImplementation`, never plain `implementation`.** It has no +release no-op counterpart. The Gradle plugin now treats it as a protected coordinate and marker: a +protected variant that includes it fails with a message directing you to use `debugImplementation`. 3. Add `INTERNET` to your own app's manifest. The full debug runtime auto-merges `ACCESS_LOCAL_NETWORK`, `NEARBY_WIFI_DEVICES`, `ACCESS_NETWORK_STATE`, and the default diff --git a/docs/MQTT_CAPTURE.md b/docs/MQTT_CAPTURE.md index b48904b..693f774 100644 --- a/docs/MQTT_CAPTURE.md +++ b/docs/MQTT_CAPTURE.md @@ -76,3 +76,11 @@ mirroring the "record on the delegate's own success signal" rule the OkHttp WebS See `samples/compose-app`'s "Open sample MQTT connection" action for a complete, crash-safe example against a public test broker. + +## Publishing from DevConsole + +A Paho client wrapped by `DevConsolePahoMqtt` can also publish from the dashboard or the inspector: +open one of its frames and use the composer (topic required, QoS 0–2, retained). The publish goes +through the same wrapper, so it is captured as a sent frame. While Paho is reconnecting the composer +answers "Connection is not open". See [WEBSOCKET_INSPECTOR.md](WEBSOCKET_INSPECTOR.md#sending-a-frame) +for the gate and the route. diff --git a/docs/NETWORK_ADAPTERS.md b/docs/NETWORK_ADAPTERS.md index 235883e..b407bdf 100644 --- a/docs/NETWORK_ADAPTERS.md +++ b/docs/NETWORK_ADAPTERS.md @@ -9,7 +9,7 @@ about twenty lines against the same public recorder. |---|---| | **OkHttp** | Add `DevConsoleOkHttpInterceptor` (below). | | **Retrofit** | **Nothing.** Retrofit does no networking of its own — it delegates to an `OkHttpClient`. Add the interceptor to the client Retrofit is built with and every call is captured. | -| **Ktor client** | Install `DevConsoleKtorClientPlugin` (below). Engine-independent: CIO, OkHttp, Android, and Java all work, including full response-body capture. The OkHttp engine still has an edge for timing phases and mocks — see [Ktor on the OkHttp engine](#ktor-on-the-okhttp-engine). | +| **Ktor client** | Install `DevConsoleKtorClientPlugin` (below). Engine-independent: CIO, OkHttp, Android, and Java all work, including full response-body capture. Mock rules are available too via `DevConsoleKtorMocks`. The OkHttp engine still has an edge for timing phases — see [Ktor on the OkHttp engine](#ktor-on-the-okhttp-engine). | | **Apollo / GraphQL** | Runs on OkHttp, so the interceptor captures it. Bodies are shown as-is; there is no GraphQL-aware formatting yet. | | **Cronet, HttpURLConnection, Volley, anything else** | Write a small adapter against `NetworkTransactionRecorder` — see [Custom stacks](#custom-stacks). | | **gRPC** | Not supported. `grpc-okhttp` uses OkHttp's transport primitives directly and never passes through the `Interceptor` chain, so it needs a gRPC `ClientInterceptor`. Not yet written. | @@ -18,10 +18,10 @@ Three things worth knowing: - **`sdk:server-ktor` is not Ktor client support.** It is the embedded dashboard server. Ktor client capture lives in `sdk:network-ktor`. -- **Mocking, WebSocket capture, and OkHttp's DNS/TCP/TLS/send/wait/receive timing breakdown are - OkHttp-only.** `DevConsoleMockInterceptor`, `DevConsoleOkHttpWebSocketListener`, and per-phase - timing have no equivalent for other stacks yet, so a Ktor-CIO app gets full request/response - capture but not mocks, WebSocket capture, or a timing breakdown finer than total call duration. +- **WebSocket capture and OkHttp's DNS/TCP/TLS/send/wait/receive timing breakdown are + OkHttp-only.** `DevConsoleOkHttpWebSocketListener` and per-phase timing have no equivalent for + other stacks yet, so a Ktor-CIO app gets full request/response capture and mock rules but not + WebSocket capture or a timing breakdown finer than total call duration. - **Both adapters capture response bodies now, each with its own bound.** OkHttp captures a declared-length body eagerly and an unknown-length (chunked, transparently-gzipped) one through a non-blocking tee, capped at 512 KiB — see @@ -152,23 +152,46 @@ response with no declared content type is still captured, so the body-preview UT decide from the actual bytes. What the Ktor adapter still can't provide — on any engine — is OkHttp's DNS/TCP/TLS/send/wait/receive -timing breakdown and mock rules. See [Ktor on the OkHttp engine](#ktor-on-the-okhttp-engine) below. +timing breakdown. See [Ktor on the OkHttp engine](#ktor-on-the-okhttp-engine) below. + +### Mocking Ktor requests + +`DevConsoleKtorMocks` applies the same `MockEngine` rules as the OkHttp interceptor. Install it +alongside the capture plugin and pass it the host's engine: + +```kotlin +val client = HttpClient { + install(DevConsoleKtorClientPlugin) { recorder = DevConsole.networkRecorder() } + install(DevConsoleKtorMocks) { mockEngine = DevConsole.mockEngine() } +} +``` + +It intercepts `HttpSend`, so a mocked response never reaches the network but still flows through +the receive pipeline: transactions are recorded like any other call and tagged `mocked=true` plus +`mockRuleId=`. Matching uses the same rule fields as OkHttp (method, scheme, host, path +regex, query and header predicates, and a bounded body preview), and the same actions are +supported: static and template responses, delay, connection failure, timeout, status override, body +replacement, map-remote, throttle, and sequence. A disabled engine, or no matching rule, lets the +call proceed untouched. + +One gap: a `Throttle` rule paces a static payload, but latency-only pacing is applied when it wraps +a passthrough — the response channel belongs to the engine at that point, so bytes-per-second +throttling of a real response body is not simulated. ### Ktor on the OkHttp engine -`DevConsoleKtorClientPlugin` already captures full request and response bodies on every engine, so -you no longer need the engine-level interceptor just to get bodies. What it still can't provide is -the **DNS/TCP/TLS/send/wait/receive timing breakdown** and **mock rules** — both come from OkHttp's -`EventListener`/interceptor chain, which the Ktor client pipeline has no equivalent for. If your -`HttpClient` uses the **OkHttp engine** and you need either of those, instrument the engine's -`OkHttpClient` directly instead of installing the plugin: +`DevConsoleKtorClientPlugin` already captures full request and response bodies on every engine, and +`DevConsoleKtorMocks` covers mock rules, so you no longer need the engine-level interceptor for +either. What the plugin still can't provide is the **DNS/TCP/TLS/send/wait/receive timing +breakdown** — it comes from OkHttp's `EventListener`, which the Ktor client pipeline has no +equivalent for. If your `HttpClient` uses the **OkHttp engine** and you need those timing phases, +instrument the engine's `OkHttpClient` directly instead of installing the plugin: ```kotlin val client = HttpClient(OkHttp) { engine { config { installDevConsole(DevConsole.networkRecorder()) - addInterceptor(DevConsoleMockInterceptor(DevConsole.mockEngine())) // optional } } } @@ -185,8 +208,8 @@ Two caveats: [tee described above](#chunked-and-streaming-responses) and its 512 KiB cap, not the Ktor plugin's 256 KiB one. -Reach for this only when you need timing phases or mocks. For capture alone, the plugin now covers -CIO, OkHttp, Android, and Java equally well. +Reach for this only when you need timing phases. For capture and mocks, the plugin covers CIO, +OkHttp, Android, and Java equally well. ## Custom stacks diff --git a/docs/PROTOCOL_REFERENCE.md b/docs/PROTOCOL_REFERENCE.md index 0f004b0..d6c2457 100644 --- a/docs/PROTOCOL_REFERENCE.md +++ b/docs/PROTOCOL_REFERENCE.md @@ -64,10 +64,9 @@ host>}` at start-up). Otherwise: `{"code":"ORIGIN_REJECTED"}` 403. `POST /api/v1/auth/session-code/exchange` has its own limiter (5/min), checked inline and keyed by **source IP** rather than session, since it runs before a session exists. -One rate limiter is wired into the dispatcher's `when` for -`.../websockets/connections/{id}/send` without a matching route — dead capacity in the current -build. (`POST /api/v1/exports` and `GET /api/v1/report` do have routes — checked inline rather -than through the table above — sharing one 5-per-10-minute export limiter; see §3.) +`POST /api/v1/websockets/connections/{id}/send` (socket send, below) has its own limiter in the +dispatcher. (`POST /api/v1/exports` and `GET /api/v1/report` are checked inline rather than through +the table above, sharing one 5-per-10-minute export limiter; see §3.) ## Browser access modes @@ -239,12 +238,33 @@ 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 +`GET /api/v1/remote-config` (auth). 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). +state providers and feature flags. Entries also carry `providerValue`/`providerSource` while a local +override is active, and the response carries `overridesEditable`. Local overrides are set with `PUT` +and cleared with `DELETE` on `/api/v1/remote-config/{provider}/overrides/{key}`, and all cleared +with `DELETE /api/v1/remote-config/overrides` (control headers; `featureFlags` editing +capability). See [REMOTE_CONFIG.md](REMOTE_CONFIG.md#local-overrides). + +### Socket send + +`POST /api/v1/websockets/connections/{id}/send` (control headers; `requestExecution` capability; +`socket` or `mqtt` category). Form body `text`, plus `topic`/`qos`/`retained` for MQTT. See +[WEBSOCKET_INSPECTOR.md](WEBSOCKET_INSPECTOR.md#sending-a-frame) for responses. + +### Capture pause and purge + +`GET /api/v1/capture` (auth) → `{"paused":,"available":}`. `POST /api/v1/capture/paused` +(control headers; raw `true`/`false` body) pauses or resumes writing new captures and answers +`{"paused":}`; audited as `capture.pause`/`capture.resume`. `POST /api/v1/capture/purge` +(control headers) removes this run's captured network, socket and push data plus old unpinned runs +and answers the counts: `{"networkTransactions":n,"socketConnections":n,"pushEvents":n, +"retainedRunsDeleted":n}`. Both answer `CAPTURE_CONTROL_UNAVAILABLE` (503) when the host did not +wire capture control. The dashboard puts both in the topbar's overflow menu and shows a "Capture +paused" pill while paused; the inspector has them under More → Capture. ### Composer @@ -474,9 +494,6 @@ An invalid/expired cursor on either paginated family returns the generic `{"code ## 7. Known dead paths / quirks worth remembering -- `.../websockets/connections/{id}/send` has a rate limiter wired but no matching route — reserved - capacity, not a bug to chase. (`POST /api/v1/exports` looks like the same situation at a glance - but is not: it has a real route, documented in §3, on its own 5-per-10-minute limiter.) - `GET /api/v1/plugins/audit` is the command audit log, not a leftover plugin-framework route — the name is historical (see §3, Command audit). - Bookmark/note routes report `CSRF_INVALID` instead of `AUTH_REQUIRED` for a fully unauthenticated diff --git a/docs/PUBLISHING.md b/docs/PUBLISHING.md index fb7722e..13cdf7e 100644 --- a/docs/PUBLISHING.md +++ b/docs/PUBLISHING.md @@ -41,9 +41,10 @@ Check a real JitPack build at `SDK_VERSION` in `build-logic/convention-publishing/src/main/kotlin/io/devconsole/buildlogic/PublishingConventionPlugin.kt` -and `version` in `gradle-plugin/build.gradle.kts` are kept in step. JitPack derives the consumer- -facing version from the tag or branch rather than from `SDK_VERSION`, but the two should match so -`publishToMavenLocal` output and the tag agree. +and `version` in `gradle-plugin/build.gradle.kts` are kept in step. The plugin generates its auto-wire +version resource from its own declared version, so there is no third version constant to bump. JitPack +derives the consumer-facing version from the tag or branch rather than from `SDK_VERSION`, but the +two should match so `publishToMavenLocal` output and the tag agree. ## The Gradle plugin → Gradle Plugin Portal diff --git a/docs/REMOTE_CONFIG.md b/docs/REMOTE_CONFIG.md index f20d46a..c5948d0 100644 --- a/docs/REMOTE_CONFIG.md +++ b/docs/REMOTE_CONFIG.md @@ -123,11 +123,36 @@ surface will re-quote one to make it parse, because the quotes would be the view 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. +## Local overrides + +Both surfaces can override a key locally while you debug: in the dashboard, open a key and choose +**Save override**; in the inspector, tap a row's edit action on the Config tab. The overridden row +shows the `override` source and keeps the provider's own value beside it, so clearing the override +visibly restores something. **Clear all overrides** removes every one. + +DevConsole cannot change what Firebase (or any provider) returns to your code, so the host reads the +override first: + +```kotlin +val bannerText = DevConsole.remoteConfigOverride("promo_banner_text") + ?: Firebase.remoteConfig.getString("promo_banner_text") +``` + +`remoteConfigOverride(key, providerId = null)` returns the override for that key on the given +provider, or on any provider when `providerId` is null; it is always null in release builds (the +no-op facade). Overrides persist across app restarts (SharedPreferences +`devconsole_remote_config_overrides`) and survive a session restart, because they are user intent +rather than captured state. + +Editing shares the `EditingCapabilities.featureFlags` capability with feature-flag overrides, and is +gated by `CaptureCategory.STATE` like the rest of this page. The provider's value shown next to an +override goes through the same redaction as every other value. + ## 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. +DevConsole does not trigger `fetch()` or `activate()` — it observes the Remote Config lifecycle +rather than driving it. A provider can still report the `override` source for an override of its +own; that is shown as-is and is not editable from DevConsole. ## REST @@ -140,10 +165,26 @@ provider's snapshot: "fetch":{"lastFetchEpochMs":1755043200000,"status":"success","minimumFetchIntervalSeconds":3600}, "unavailableReason":null, "entries":[ - {"key":"checkout_v2","value":"true","source":"remote","redacted":false,"truncated":false} + {"key":"checkout_v2","value":"true","source":"remote","redacted":false,"truncated":false, + "providerValue":null,"providerSource":null} ] -}]} +}],"overridesEditable":true} ``` +`providerValue`/`providerSource` are non-null only while a local override replaces the value. +`overridesEditable` is true when the host wired an override store and allows feature-flag editing. + +Override routes (bearer session + `Origin` + `X-DevConsole-CSRF`, audited without raw values): + +| Route | Body | Success | +|---|---|---| +| `PUT /api/v1/remote-config/{provider}/overrides/{key}` | form `value=` | `{"status":"updated"}` | +| `DELETE /api/v1/remote-config/{provider}/overrides/{key}` | — | `{"status":"cleared"}` | +| `DELETE /api/v1/remote-config/overrides` | — | `{"status":"cleared"}` | + +Errors: `REMOTE_CONFIG_OVERRIDES_DISABLED` (403, editing capability off), +`REMOTE_CONFIG_OVERRIDES_UNAVAILABLE` (503, no store), `REMOTE_CONFIG_PROVIDER_NOT_FOUND` (404), +`VALIDATION_FAILED` (400: missing `value`, blank or over-long key, over-long value). + See [PROTOCOL_REFERENCE.md](PROTOCOL_REFERENCE.md) and [STATE_AND_FLAGS.md](STATE_AND_FLAGS.md) for the neighbouring surfaces. diff --git a/docs/WEBSOCKET_INSPECTOR.md b/docs/WEBSOCKET_INSPECTOR.md index d155b50..de56b38 100644 --- a/docs/WEBSOCKET_INSPECTOR.md +++ b/docs/WEBSOCKET_INSPECTOR.md @@ -37,9 +37,24 @@ flag (`length > 4 KiB`), never raw bytes. The full working example is The WebSockets page splits into a connection list (URL, state, duration, sent/received counts, errors) and a message stream for the selected connection, with direction and a redacted -text/binary preview. There is no manual "send a message" control in the current dashboard build — -the spec allows one only when the host explicitly opts in, and this reference build doesn't wire -that opt-in yet. +text/binary preview. + +## Sending a frame + +Open a frame of a live connection and use the composer under it (dashboard) or on the Sockets tab +(inspector) to send a text frame over the app's own socket. The sent frame is captured like any +other. Sending is offered only for connections the adapter registered as writable — an OkHttp +WebSocket opened through `DevConsoleOkHttpWebSocketListener`/the wrapper, or a Paho client wrapped +by `DevConsolePahoMqtt` — and stops when the connection closes or fails. + +It is gated by `EditingCapabilities.requestExecution` (the capability Composer and resend share), so +a host that turns that off also turns off socket send. Frames are capped at 64 KiB. The audit log +records the size and MQTT topic, never the frame text. + +`POST /api/v1/websockets/connections/{id}/send` takes a form body `text=...` (plus `topic`, `qos`, +`retained` for MQTT) and answers `{"status":"sent"}`, or `NOT_CONNECTED` (409), `SEND_REJECTED` with a +`message` or `VALIDATION_FAILED` (400), `SOCKET_SEND_DISABLED` (403), `SEND_UNSUPPORTED` (503). +Connection objects carry `canSend` and `sendProtocol` (`websocket`, `mqtt`, or null). ## Redaction diff --git a/gradle-plugin/build.gradle.kts b/gradle-plugin/build.gradle.kts index 01b72f7..422ba5f 100644 --- a/gradle-plugin/build.gradle.kts +++ b/gradle-plugin/build.gradle.kts @@ -34,6 +34,12 @@ dependencies { testImplementation(gradleTestKit()) } +tasks.processResources { + filesMatching("**/devconsole-plugin-version.properties") { + expand("pluginVersion" to project.version.toString()) + } +} + gradlePlugin { // Required by com.gradle.plugin-publish for Plugin Portal submission; matches the repo URL used // in build-logic/convention-publishing's PublishingConventionPlugin (PROJECT_URL) for the SDK @@ -48,10 +54,8 @@ gradlePlugin { implementationClass = "io.devconsole.gradle.DevConsoleVariantPolicyPlugin" displayName = "DevConsole Variant Policy" description = - "Verifies the DevConsole in-app debugging runtime (network inspector, mock " + - "responses, capture dashboard) never reaches a protected release build variant " + - "-- checking declared dependencies, the resolved transitive runtime classpath, " + - "and the final packaged APK/AAB/AAR bytes." + "Verifies the DevConsole in-app debugging runtime never reaches protected variants " + + "through declared dependencies, the resolved runtime classpath, and packaged APK/AAB/AAR scans." tags.set(listOf("android", "debugging", "devtools", "network-inspector")) } } 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 0646401..0b9e599 100644 --- a/gradle-plugin/src/main/kotlin/io/devconsole/gradle/DevConsoleVariantPolicyPlugin.kt +++ b/gradle-plugin/src/main/kotlin/io/devconsole/gradle/DevConsoleVariantPolicyPlugin.kt @@ -167,11 +167,15 @@ abstract class VerifyDevConsoleProtectedArtifactsTask : DefaultTask() { resolvedRuntimeComponents.get().flatMap { (variant, components) -> components .filter { it in badProjectDisplayNames || it.matches(FULL_RUNTIME_COORDINATE) } - .map { "$variant -> $it (resolved)" } + .map { component -> + val guidance = if (component.contains("devconsole-ui-")) "; use debugImplementation" else "" + "$variant -> $component (resolved)$guidance" + } } val found = (declared + transitive).distinct() if (found.isEmpty()) return - val message = "Protected variants contain the full DevConsole runtime: ${found.joinToString()}" + val message = "Protected variants contain DevConsole runtime components: ${found.joinToString()}. " + + "Use debugImplementation for DevConsole UI add-ons." if (failOnUnsafeVariant.get()) error(message) else logger.warn("DevConsole: $message") } @@ -180,9 +184,9 @@ abstract class VerifyDevConsoleProtectedArtifactsTask : DefaultTask() { val FULL_RUNTIME_COORDINATE = Regex( "^(?:com\\.github\\.devconsole-android\\.DevConsole|io\\.github\\.devconsole-android):" + - "(?:devconsole|devconsole-network-okhttp|devconsole-mocks-okhttp|" + + "(?:devconsole|devconsole-network-okhttp|devconsole-network-ktor|devconsole-mocks-okhttp|" + "devconsole-socket-okhttp|devconsole-socket-paho|devconsole-push-firebase|" + - "devconsole-remote-config-firebase):.+", + "devconsole-remote-config-firebase|devconsole-ui-compose|devconsole-ui-views):.+", ) } } @@ -493,10 +497,14 @@ abstract class VerifyDevConsolePackagedArtifactTask : DefaultTask() { listOf( "DEVCONSOLE_ENABLED_FULL_V1", "DEVCONSOLE_ENABLED_NETWORK_OKHTTP_V1", + "DEVCONSOLE_ENABLED_NETWORK_KTOR_V1", "DEVCONSOLE_ENABLED_MOCKS_OKHTTP_V1", "DEVCONSOLE_ENABLED_SOCKET_OKHTTP_V1", + "DEVCONSOLE_ENABLED_SOCKET_PAHO_V1", "DEVCONSOLE_ENABLED_PUSH_FIREBASE_V1", "DEVCONSOLE_ENABLED_REMOTE_CONFIG_FIREBASE_V1", + "DEVCONSOLE_ENABLED_UI_COMPOSE_V1", + "DEVCONSOLE_ENABLED_UI_VIEWS_V1", "Lio/devconsole/server/ktor/KtorLocalServerEngine;", "io.devconsole.DevConsoleInitializer", ".devconsoleinitializer", @@ -505,11 +513,8 @@ abstract class VerifyDevConsolePackagedArtifactTask : DefaultTask() { } // JitPack serves a build under its git ref name. This repo tags `v*`, and JitPack resolves a -// requested version against the `v`-prefixed tag when no bare tag exists, so "1.3.1" reaches the -// v1.3.1 build -- and reads the same as the version this plugin carries on the Plugin Portal. -// Bump in step with SDK_VERSION in convention-publishing; the tag must exist before this resolves. -private const val DEFAULT_SDK_VERSION = "1.3.1" - +// requested version against the `v`-prefixed tag when no bare tag exists, so the plugin's own +// implementation version reaches the corresponding v-prefixed SDK build. /** Gradle property backing [DevConsoleExtension.verificationEnabled]. */ private const val VERIFICATION_ENABLED_PROPERTY = "devconsole.verification.enabled" @@ -525,6 +530,18 @@ private val DEVCONSOLE_GROUPS = setOf(DEVCONSOLE_GROUP, "io.github.devconsole-an * `devconsole-ui-views`, `devconsole-network-ktor`) is *not* the core runtime and must not suppress it. */ private val CORE_RUNTIME_COORDINATE_NAMES = setOf("devconsole", "devconsole-noop") +private val PROTECTED_RUNTIME_COORDINATE_NAMES = setOf("devconsole") + + setOf("devconsole-network-ktor", "devconsole-socket-paho", "devconsole-ui-compose", "devconsole-ui-views") + +private fun Project.pluginVersion(): String = + DevConsoleVariantPolicyPlugin::class.java.`package`.implementationVersion + ?.takeIf(String::isNotBlank) + ?: DevConsoleVariantPolicyPlugin::class.java.getResourceAsStream("/devconsole-plugin-version.properties") + ?.use { properties -> + java.util.Properties().apply { load(properties) }.getProperty("pluginVersion") + } + ?.takeIf(String::isNotBlank) + ?: error("DevConsole: could not determine plugin implementation version for sdkVersion; set devConsole.sdkVersion explicitly.") class DevConsoleVariantPolicyPlugin : Plugin { override fun apply(target: Project) = with(target) { @@ -547,12 +564,15 @@ class DevConsoleVariantPolicyPlugin : Plugin { protectedDependencyPaths.convention( setOf( ":sdk:full", + ":sdk:network-ktor", ":sdk:network-okhttp", ":sdk:mocks-okhttp", ":sdk:socket-okhttp", ":sdk:socket-paho", ":sdk:push-firebase", ":sdk:remote-config-firebase", + ":sdk:ui-compose", + ":sdk:ui-views", ), ) // PROTECTED by default: a release-signed staging/beta/preprod build type (anything not in @@ -565,7 +585,7 @@ class DevConsoleVariantPolicyPlugin : Plugin { providers.gradleProperty(VERIFICATION_ENABLED_PROPERTY).map(String::toBoolean).orElse(true), ) autoWireDependencies.convention(true) - sdkVersion.convention(DEFAULT_SDK_VERSION) + sdkVersion.convention(provider { pluginVersion() }) } registerPackagedArtifactScans(extension, packagedVerificationTasks, actualVariantBuildTypes) @@ -615,6 +635,17 @@ class DevConsoleVariantPolicyPlugin : Plugin { val policies = actualVariantBuildTypes.mapValues { (variantName, buildType) -> variantPolicy(variantName, buildType, extension) } + extension.enabledVariants.get().filter { configured -> + actualVariantBuildTypes.none { (name, buildType) -> configured == name || configured == buildType } + }.forEach { configured -> + logger.warn("DevConsole: enabledVariants entry '$configured' matched no Android variant or build type in project '$path'.") + } + extension.protectedVariantPatterns.get().forEach { pattern -> + val regex = runCatching { Regex(pattern) }.getOrNull() + if (regex == null || actualVariantBuildTypes.keys.none(regex::matches)) { + logger.warn("DevConsole: protectedVariantPatterns entry '$pattern' matched no Android variant in project '$path'.") + } + } val report = tasks.register("devConsoleVariantReport") { group = "verification" variantPolicies.putAll(policies.mapValues { it.value.name }) @@ -911,7 +942,8 @@ class DevConsoleVariantPolicyPlugin : Plugin { val path = dep.projectPathCompat() if (path in protectedPaths) "$variant -> $path" else null } - dep is org.gradle.api.artifacts.ExternalModuleDependency && dep.group in DEVCONSOLE_GROUPS && dep.name == "devconsole" -> "$variant -> ${dep.group}:${dep.name}" + dep is org.gradle.api.artifacts.ExternalModuleDependency && dep.group in DEVCONSOLE_GROUPS && + dep.name in PROTECTED_RUNTIME_COORDINATE_NAMES -> "$variant -> ${dep.group}:${dep.name}" else -> null } } diff --git a/gradle-plugin/src/main/resources/devconsole-plugin-version.properties b/gradle-plugin/src/main/resources/devconsole-plugin-version.properties new file mode 100644 index 0000000..bfb04c5 --- /dev/null +++ b/gradle-plugin/src/main/resources/devconsole-plugin-version.properties @@ -0,0 +1 @@ +pluginVersion=${pluginVersion} diff --git a/gradle-plugin/src/test/kotlin/io/devconsole/gradle/DevConsoleVariantPolicyPluginFunctionalTest.kt b/gradle-plugin/src/test/kotlin/io/devconsole/gradle/DevConsoleVariantPolicyPluginFunctionalTest.kt index 51d4bbd..f568939 100644 --- a/gradle-plugin/src/test/kotlin/io/devconsole/gradle/DevConsoleVariantPolicyPluginFunctionalTest.kt +++ b/gradle-plugin/src/test/kotlin/io/devconsole/gradle/DevConsoleVariantPolicyPluginFunctionalTest.kt @@ -193,7 +193,7 @@ class DevConsoleVariantPolicyPluginFunctionalTest { val result = runner("verifyDevConsoleProtectedArtifacts").buildAndFail() - assertTrue(result.output.contains("Protected variants contain the full DevConsole runtime")) + assertTrue(result.output.contains("Protected variants contain DevConsole runtime components")) assertTrue(result.output.contains("release -> :stub-full")) } @@ -210,7 +210,7 @@ class DevConsoleVariantPolicyPluginFunctionalTest { fun `protected variant depending on a configured full-runtime path fails verification`() { writeFixture( devConsoleBlock = """ - protectedVariantPatterns.set(listOf("release")) + protectedVariantPatterns.set(listOf("(?i).*release")) protectedDependencyPaths.set(setOf(":stub-full")) """.trimIndent(), extraBuildScript = """dependencies { add("releaseImplementation", project(":stub-full")) }""", @@ -219,10 +219,46 @@ class DevConsoleVariantPolicyPluginFunctionalTest { val result = runner("verifyDevConsoleProtectedArtifacts").buildAndFail() - assertTrue(result.output.contains("Protected variants contain the full DevConsole runtime")) + assertTrue(result.output.contains("Protected variants contain DevConsole runtime components")) assertTrue(result.output.contains("release -> :stub-full")) } + @Test + fun `protected external Ktor and UI coordinates are rejected`() { + writeFixture( + devConsoleBlock = "autoWireDependencies.set(false)", + extraBuildScript = """ + dependencies { + add("releaseImplementation", "com.github.devconsole-android.DevConsole:devconsole-network-ktor:1.3.1") + add("releaseImplementation", "com.github.devconsole-android.DevConsole:devconsole-ui-compose:1.3.1") + add("releaseImplementation", "com.github.devconsole-android.DevConsole:devconsole-ui-views:1.3.1") + } + """.trimIndent(), + ) + + val result = runner("verifyReleaseDevConsoleProtectedArtifacts").buildAndFail() + + assertTrue(result.output, result.output.contains("devconsole-network-ktor")) + assertTrue(result.output, result.output.contains("devconsole-ui-compose")) + assertTrue(result.output, result.output.contains("devconsole-ui-views")) + assertTrue(result.output, result.output.contains("Use debugImplementation for DevConsole UI add-ons")) + } + + @Test + fun `unmatched enabled names and protected patterns warn after variant discovery`() { + writeFixture( + devConsoleBlock = """ + enabledVariants.set(setOf("deubg")) + protectedVariantPatterns.set(listOf("(?i).*neverMatches")) + """.trimIndent(), + ) + + val result = runner("devConsoleVariantReport").build() + + assertTrue(result.output, result.output.contains("enabledVariants entry 'deubg' matched no Android variant")) + assertTrue(result.output, result.output.contains("protectedVariantPatterns entry '(?i).*neverMatches' matched no Android variant")) + } + @Test fun `protected variant rejects an enabled capture adapter by default`() { writeFixture( @@ -278,6 +314,35 @@ class DevConsoleVariantPolicyPluginFunctionalTest { assertTrue(result.output, result.output.contains("DEVCONSOLE_ENABLED_NETWORK_OKHTTP_V1")) } + @Test + fun `packaged scan includes Ktor Paho and UI signatures`() { + val signatures = listOf( + "DEVCONSOLE_ENABLED_NETWORK_KTOR_V1", + "DEVCONSOLE_ENABLED_SOCKET_PAHO_V1", + "DEVCONSOLE_ENABLED_UI_COMPOSE_V1", + "DEVCONSOLE_ENABLED_UI_VIEWS_V1", + ) + signatures.forEachIndexed { index, signature -> + writeFixture( + devConsoleBlock = "autoWireDependencies.set(false)", + androidPlugin = "com.android.application", + applicationIdLine = "applicationId = \"io.devconsole.fixture\"\nversionCode = 1", + ) + writeZip("build/marker$index.apk", "classes.dex" to signature.encodeToByteArray()) + val script = File(projectDir.root, "build.gradle.kts") + script.appendText("\n" + """ + tasks.register("scanMarker$index") { + variantName.set("release") + failOnUnsafeVariant.set(true) + packagedArtifacts.from(file("build/marker$index.apk")) + jsonReport.set(file("build/reports/scan$index.json")) + } + """.trimIndent()) + val result = runner("scanMarker$index").buildAndFail() + assertTrue(result.output, result.output.contains(signature)) + } + } + @Test fun `protected application rejects dashboard assets in final package`() { writeFixture( @@ -592,7 +657,7 @@ class DevConsoleVariantPolicyPluginFunctionalTest { val result = runner("verifyDevConsoleProtectedArtifacts").buildAndFail() - assertTrue(result.output.contains("Protected variants contain the full DevConsole runtime")) + assertTrue(result.output.contains("Protected variants contain DevConsole runtime components")) assertTrue(result.output.contains("staging -> :stub-full")) } @@ -934,7 +999,7 @@ class DevConsoleVariantPolicyPluginFunctionalTest { // The pre-JitPack group must keep failing a protected variant: hosts that have not migrated // their coordinates still depend on this check to keep the full runtime out of release. - assertTrue(result.output, result.output.contains("Protected variants contain the full DevConsole runtime")) + assertTrue(result.output, result.output.contains("Protected variants contain DevConsole runtime components")) // The declared-dependency entry carries no version and no "(resolved)" suffix -- asserting it // specifically keeps the transitive-regex path from satisfying this test on its own. assertTrue( @@ -959,7 +1024,7 @@ class DevConsoleVariantPolicyPluginFunctionalTest { val result = runner("verifyDevConsoleProtectedArtifacts").buildAndFail() - assertTrue(result.output, result.output.contains("Protected variants contain the full DevConsole runtime")) + assertTrue(result.output, result.output.contains("Protected variants contain DevConsole runtime components")) assertTrue( result.output, Regex("release -> com\\.github\\.devconsole-android\\.DevConsole:devconsole(,|\\s*$)", RegexOption.MULTILINE) diff --git a/samples/compose-app/build.gradle.kts b/samples/compose-app/build.gradle.kts index 51aebce..dc841d5 100644 --- a/samples/compose-app/build.gradle.kts +++ b/samples/compose-app/build.gradle.kts @@ -34,6 +34,7 @@ dependencies { // network-ktor is the one adapter with no release no-op twin, so it is debug-only and the // client that installs it lives in src/debug (src/release builds the same client without it). debugImplementation(project(":sdk:network-ktor")) + implementation(project(":sdk:logs-timber")) implementation("io.ktor:ktor-client-core:3.0.3") // CIO, not the OkHttp engine: a body captured through a pure-Kotlin engine is the proof that // the Ktor plugin captures on its own rather than riding on this sample's OkHttp adapter. diff --git a/samples/compose-app/src/debug/kotlin/io/devconsole/sample/compose/SampleKtorClient.kt b/samples/compose-app/src/debug/kotlin/io/devconsole/sample/compose/SampleKtorClient.kt index 4bbd294..cc61c59 100644 --- a/samples/compose-app/src/debug/kotlin/io/devconsole/sample/compose/SampleKtorClient.kt +++ b/samples/compose-app/src/debug/kotlin/io/devconsole/sample/compose/SampleKtorClient.kt @@ -6,6 +6,7 @@ package io.devconsole.sample.compose import io.devconsole.DevConsole import io.devconsole.network.ktor.DevConsoleKtorClientPlugin +import io.devconsole.network.ktor.DevConsoleKtorMocks import io.ktor.client.HttpClient import io.ktor.client.engine.cio.CIO @@ -22,10 +23,16 @@ import io.ktor.client.engine.cio.CIO * [CIO] is deliberate, not incidental. It is a pure-Kotlin engine with no OkHttp underneath, so a * captured response body here proves the capture came from the Ktor plugin itself rather than from * the OkHttp adapter the rest of this sample uses. + * + * [DevConsoleKtorMocks] applies the same session mock rules the OkHttp adapter does, so the sample's + * `/orders` rule answers Ktor calls too. */ internal fun buildSampleKtorClient(): HttpClient = HttpClient(CIO) { install(DevConsoleKtorClientPlugin) { recorder = DevConsole.networkRecorder() } + install(DevConsoleKtorMocks) { + mockEngine = DevConsole.mockEngine() + } } 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 ba386b1..0782cea 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 @@ -87,6 +87,9 @@ import io.devconsole.api.ShakeIntensity import io.devconsole.api.StartRequest import io.devconsole.api.StartResult import io.devconsole.api.StopReason +import io.devconsole.logs.LogLevel +import io.devconsole.logs.timber.DevConsoleLog +import io.devconsole.logs.timber.DevConsoleTimberTree import io.devconsole.mocks.MockAction import io.devconsole.mocks.MockRule import io.devconsole.network.okhttp.installDevConsole @@ -117,6 +120,7 @@ import okhttp3.RequestBody.Companion.toRequestBody import org.eclipse.paho.client.mqttv3.MqttAsyncClient import org.eclipse.paho.client.mqttv3.MqttConnectOptions import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence +import timber.log.Timber import java.io.File import java.util.concurrent.atomic.AtomicInteger @@ -139,6 +143,7 @@ private const val SAMPLE_POST_BODY = private const val SHOW_ORDER_HISTORY_FLAG = "compose_sample.show_order_history" private const val MOCK_RULE_ID = "compose-sample-orders" +private const val PROMO_BANNER_KEY = "promo_banner_text" /** * Stands in for a real Remote Config client so the sample can demonstrate the inspector without @@ -166,7 +171,7 @@ private class SampleRemoteConfigProvider : RemoteConfigProvider { 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(PROMO_BANNER_KEY, PROMO_BANNER_TEXT, 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), @@ -180,11 +185,12 @@ private class SampleRemoteConfigProvider : RemoteConfigProvider { ), ) - private companion object { - const val FETCH_AGE_MS = 90_000L + companion object { + const val PROMO_BANNER_TEXT = "Free delivery this week" + private 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 = + private const val CHECKOUT_EXPERIMENT_JSON = """{"id":"checkout-flow-2026-08","variant":"b","rollout":0.25,""" + """"steps":["cart","address","payment"],"fallback":null}""" } @@ -296,6 +302,10 @@ class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) DevConsole.initialize(application, buildConfig()) + if (Timber.forest().isEmpty()) { + Timber.plant(DevConsoleTimberTree(DevConsole.logRecorder())) + } + DevConsoleLog.install(DevConsole.logRecorder()) // Installed here AND re-installed from the Running-state observer below. Both are needed: // mock rules are SESSION-scoped and DevConsole's stop sequence calls clearSessionRules(), // so a one-shot install would silently stop mocking after any restart -- but installing @@ -356,6 +366,13 @@ class MainActivity : ComponentActivity() { defaultValue = false, description = "Shows the order-history placeholder in the sample UI", ), + // A multi-value flag: the inspector offers its allowed values as a single choice. + FeatureFlag( + key = "backend_environment", + defaultValue = "production", + allowedValues = setOf("production", "staging", "local"), + description = "Which backend the sample would talk to", + ), ), ).withRemoteConfigProviders( listOf(SampleRemoteConfigProvider()), @@ -532,6 +549,18 @@ class MainActivity : ComponentActivity() { } }, ) + CapabilityCard( + title = "Send mocked Ktor request", + subtitle = "The same /orders mock rule, applied by DevConsoleKtorMocks on the Ktor client", + onClick = { + scope.launch { lastResponse = sendKtorRequest("https://example.test/orders") } + }, + ) + CapabilityCard( + title = "Read remote config", + subtitle = "A local override set in DevConsole wins over the provider's promo_banner_text", + onClick = { lastResponse = readPromoBannerText() }, + ) CapabilityCard( title = "Send mocked request", subtitle = "Served by a session mock rule, not the network", @@ -571,6 +600,12 @@ class MainActivity : ComponentActivity() { subtitle = "Recorded on the push timeline", onClick = { lastResponse = simulatePush() }, ) + CapabilityCard( + title = "Write log lines", + subtitle = + "An INFO, a WARN and an ERROR, plus one Timber and one DevConsoleLog line, on the Logs tab", + onClick = { lastResponse = writeSampleLogs() }, + ) CapabilityCard( title = "Capture screenshot", subtitle = "Screenshots are enabled by default -- foundation-app explicitly disables capture", @@ -669,6 +704,16 @@ class MainActivity : ComponentActivity() { } } + /** + * How a host reads config with DevConsole overrides: the override first, then its provider. The + * sample provider's value stands in for `Firebase.remoteConfig.getString(...)`. + */ + private fun readPromoBannerText(): String { + val override = DevConsole.remoteConfigOverride(PROMO_BANNER_KEY) + val value = override ?: SampleRemoteConfigProvider.PROMO_BANNER_TEXT + return "promo_banner_text = \"$value\" (${if (override != null) "DevConsole override" else "provider"})" + } + /** * Issues one request through the sample's Ktor client, whose debug build installs * `DevConsoleKtorClientPlugin` (see `SampleKtorClient` in `src/debug`). @@ -761,6 +806,22 @@ class MainActivity : ComponentActivity() { ) return "Push recorded: ${event.messageId}" } + + private fun writeSampleLogs(): String { + DevConsole.logRecorder().apply { + record(LogLevel.INFO, "Checkout", "Cart opened with 3 items") + record(LogLevel.WARN, "Checkout", "Coupon SAVE10 expired, falling back to full price") + record( + LogLevel.ERROR, + "Checkout", + "Payment declined", + IllegalStateException("Card issuer returned code 05"), + ) + } + Timber.i("Checkout reached the timeline through the Timber bridge") + DevConsoleLog.w("Checkout", "Coupon check reached the timeline through the DevConsoleLog bridge") + return "5 log lines recorded" + } } /** diff --git a/sdk/api/api/api.api b/sdk/api/api/api.api index 8f28093..b14974d 100644 --- a/sdk/api/api/api.api +++ b/sdk/api/api/api.api @@ -334,16 +334,21 @@ public abstract interface class io/devconsole/api/DevConsoleFacadeProvider { public abstract fun captureScreenshot (Lkotlin/coroutines/Continuation;)Ljava/lang/Object; public abstract fun createInspectorIntent (Landroid/content/Context;)Landroid/content/Intent; public abstract fun endpoint ()Lio/devconsole/api/BrowserEndpoint; + public abstract fun exportSession (Lkotlin/coroutines/Continuation;)Ljava/lang/Object; public abstract fun featureFlagStringValue (Ljava/lang/String;)Ljava/lang/String; public abstract fun featureFlagValue (Ljava/lang/String;)Z public abstract fun initialize (Landroid/app/Application;Lio/devconsole/api/DevConsoleConfig;)Lio/devconsole/api/InitResult; + public abstract fun isCapturePaused ()Z public abstract fun logRecorder ()Lio/devconsole/logs/LogRecorder; public abstract fun mockEngine ()Lio/devconsole/mocks/MockEngine; public abstract fun networkRecorder ()Lio/devconsole/network/NetworkTransactionRecorder; public abstract fun openInspector (Landroid/content/Context;)Lio/devconsole/api/InspectorOpenResult; + public abstract fun purgeCapturedData (Lkotlin/coroutines/Continuation;)Ljava/lang/Object; 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 remoteConfigOverride (Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; + public abstract fun setCapturePaused (Z)Z public abstract fun socketRecorder ()Lio/devconsole/socket/SocketRecorder; public abstract fun startBrowser (Lio/devconsole/api/StartRequest;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; public abstract fun state ()Lkotlinx/coroutines/flow/StateFlow; @@ -675,6 +680,28 @@ public final class io/devconsole/api/OpenTriggers$Companion { public final fun disabled ()Lio/devconsole/api/OpenTriggers; } +public final class io/devconsole/api/PurgeResult { + public static final field Companion Lio/devconsole/api/PurgeResult$Companion; + public fun (IIII)V + public final fun component1 ()I + public final fun component2 ()I + public final fun component3 ()I + public final fun component4 ()I + public final fun copy (IIII)Lio/devconsole/api/PurgeResult; + public static synthetic fun copy$default (Lio/devconsole/api/PurgeResult;IIIIILjava/lang/Object;)Lio/devconsole/api/PurgeResult; + public fun equals (Ljava/lang/Object;)Z + public final fun getNetworkTransactions ()I + public final fun getPushEvents ()I + public final fun getRetainedRunsDeleted ()I + public final fun getSocketConnections ()I + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + +public final class io/devconsole/api/PurgeResult$Companion { + public final fun getNOTHING ()Lio/devconsole/api/PurgeResult; +} + public final class io/devconsole/api/RetentionPolicy { public static final field Companion Lio/devconsole/api/RetentionPolicy$Companion; public static final field DEFAULT_MAX_AGE_MS J @@ -787,6 +814,38 @@ public final class io/devconsole/api/ScreenshotResult$SecureWindow : io/devconso public fun toString ()Ljava/lang/String; } +public abstract interface class io/devconsole/api/SessionExportResult { +} + +public final class io/devconsole/api/SessionExportResult$Disabled : io/devconsole/api/SessionExportResult { + public static final field INSTANCE Lio/devconsole/api/SessionExportResult$Disabled; + public fun equals (Ljava/lang/Object;)Z + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + +public final class io/devconsole/api/SessionExportResult$Exported : io/devconsole/api/SessionExportResult { + public fun (Ljava/io/File;)V + public final fun component1 ()Ljava/io/File; + public final fun copy (Ljava/io/File;)Lio/devconsole/api/SessionExportResult$Exported; + public static synthetic fun copy$default (Lio/devconsole/api/SessionExportResult$Exported;Ljava/io/File;ILjava/lang/Object;)Lio/devconsole/api/SessionExportResult$Exported; + public fun equals (Ljava/lang/Object;)Z + public final fun getFile ()Ljava/io/File; + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + +public final class io/devconsole/api/SessionExportResult$Failed : io/devconsole/api/SessionExportResult { + public fun (Ljava/lang/String;)V + public final fun component1 ()Ljava/lang/String; + public final fun copy (Ljava/lang/String;)Lio/devconsole/api/SessionExportResult$Failed; + public static synthetic fun copy$default (Lio/devconsole/api/SessionExportResult$Failed;Ljava/lang/String;ILjava/lang/Object;)Lio/devconsole/api/SessionExportResult$Failed; + public fun equals (Ljava/lang/Object;)Z + public final fun getReason ()Ljava/lang/String; + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + public final class io/devconsole/api/SessionPolicy { public static final field Companion Lio/devconsole/api/SessionPolicy$Companion; public static final field DEFAULT_MAX_AUTHENTICATED_SESSIONS I 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 1e9b1b4..d6058eb 100644 --- a/sdk/api/src/main/kotlin/io/devconsole/api/DevConsoleFacadeProvider.kt +++ b/sdk/api/src/main/kotlin/io/devconsole/api/DevConsoleFacadeProvider.kt @@ -57,6 +57,15 @@ interface DevConsoleFacadeProvider { */ fun registerRemoteConfigProvider(provider: RemoteConfigProvider): Boolean + /** + * The local override a developer applied in DevConsole for [key], or null. Hosts read it before + * their provider: `DevConsole.remoteConfigOverride("k") ?: remoteConfig.getString("k")`. + */ + fun remoteConfigOverride( + key: String, + providerId: String?, + ): String? + /** * 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 @@ -94,4 +103,20 @@ interface DevConsoleFacadeProvider { * (a boolean flag returns `"true"`/`"false"`). Falls back to `""` for an unknown key. */ fun featureFlagStringValue(key: String): String + + /** + * Pauses or resumes live capture of network transactions, socket connections, push events, and + * log lines. Returns `false` when the runtime is disabled or not initialized, and `true` when + * the state was applied. + */ + fun setCapturePaused(paused: Boolean): Boolean + + /** Whether live capture is currently paused. */ + fun isCapturePaused(): Boolean + + /** Clears captured in-memory data and deletes finished retained runs; the live run and pinned runs are kept. */ + suspend fun purgeCapturedData(): PurgeResult + + /** Exports the current session bundle as a ZIP file. */ + suspend fun exportSession(): SessionExportResult } diff --git a/sdk/api/src/main/kotlin/io/devconsole/api/PurgeResult.kt b/sdk/api/src/main/kotlin/io/devconsole/api/PurgeResult.kt new file mode 100644 index 0000000..8f2e320 --- /dev/null +++ b/sdk/api/src/main/kotlin/io/devconsole/api/PurgeResult.kt @@ -0,0 +1,19 @@ +/** + * @author Shakib + * @since 03/11/26 + */ +package io.devconsole.api + +/** + * Counts of captured records and retained sessions removed by [io.devconsole.DevConsole.purgeCapturedData]. + */ +data class PurgeResult( + val networkTransactions: Int, + val socketConnections: Int, + val pushEvents: Int, + val retainedRunsDeleted: Int, +) { + companion object { + val NOTHING = PurgeResult(0, 0, 0, 0) + } +} diff --git a/sdk/api/src/main/kotlin/io/devconsole/api/SessionExportResult.kt b/sdk/api/src/main/kotlin/io/devconsole/api/SessionExportResult.kt new file mode 100644 index 0000000..601503d --- /dev/null +++ b/sdk/api/src/main/kotlin/io/devconsole/api/SessionExportResult.kt @@ -0,0 +1,22 @@ +/** + * @author Shakib + * @since 03/11/26 + */ +package io.devconsole.api + +import java.io.File + +/** + * Outcome of [io.devconsole.DevConsole.exportSession]. + */ +sealed interface SessionExportResult { + data class Exported( + val file: File, + ) : SessionExportResult + + data class Failed( + val reason: String, + ) : SessionExportResult + + data object Disabled : SessionExportResult +} diff --git a/sdk/composer/api/composer.api b/sdk/composer/api/composer.api index a34ebdb..4311338 100644 --- a/sdk/composer/api/composer.api +++ b/sdk/composer/api/composer.api @@ -122,7 +122,6 @@ public final class io/devconsole/composer/ComposerQueryParameter { public final class io/devconsole/composer/ComposerRequest { public static final field CONTROL_CHARACTER_LIMIT I public static final field DEFAULT_TIMEOUT_MS I - public static final field HEX_RADIX I public static final field UNICODE_ESCAPE_PADDING C public static final field UNICODE_ESCAPE_WIDTH I public fun (Ljava/lang/String;Ljava/lang/String;Ljava/util/Map;Ljava/lang/String;Ljava/util/List;Lio/devconsole/composer/ComposerBodyType;Ljava/util/Map;Ljava/util/List;Lio/devconsole/composer/ComposerBinaryBody;IZLjava/util/List;)V diff --git a/sdk/composer/src/main/kotlin/io/devconsole/composer/ComposerRequest.kt b/sdk/composer/src/main/kotlin/io/devconsole/composer/ComposerRequest.kt index ea1bb27..5bf5993 100644 --- a/sdk/composer/src/main/kotlin/io/devconsole/composer/ComposerRequest.kt +++ b/sdk/composer/src/main/kotlin/io/devconsole/composer/ComposerRequest.kt @@ -5,6 +5,14 @@ import io.devconsole.security.RedactionPolicy import java.net.URI import java.net.URLEncoder +private const val URI_REFERENCE_CHARS = "-._~:/?#[]@!$&'()*+,;=" +private const val HEX = "0123456789ABCDEF" +private const val HEX_RADIX = 16 +private const val HEX_NIBBLE_MASK = 0xF +private const val URI_ESCAPE_LENGTH = 3 +private const val HEX_SHIFT = 4 +private const val ASCII_LIMIT = 128 + enum class ComposerBodyType { NONE, TEXT, JSON, FORM_URL_ENCODED, MULTIPART, BINARY_FILE } data class ComposerQueryParameter( @@ -206,7 +214,6 @@ data class ComposerRequest( private companion object { const val DEFAULT_TIMEOUT_MS = 15_000 const val CONTROL_CHARACTER_LIMIT = 0x20 - const val HEX_RADIX = 16 const val UNICODE_ESCAPE_WIDTH = 4 const val UNICODE_ESCAPE_PADDING = '0' val DEFAULT_REDACTION: RedactionEngine by lazy { RedactionEngine(RedactionPolicy.default()) } @@ -312,10 +319,7 @@ class ComposerExecutor( response.headers.entries .firstOrNull { it.key.equals(LOCATION_HEADER, ignoreCase = true) } ?.value - if (!followRedirects || response.statusCode !in REDIRECT_STATUSES || location.isNullOrBlank()) { - return null - } - val nextUrl = URI(url).resolve(location).toString() + val nextUrl = redirectedUrl(location, response.statusCode) ?: return null val nextMethod = redirectedMethod(response.statusCode) val dropsBody = nextMethod != method val crossOrigin = URI(url).origin() != URI(nextUrl).origin() @@ -330,6 +334,14 @@ class ComposerExecutor( ) } + private fun ResolvedComposerRequest.redirectedUrl( + location: String?, + statusCode: Int, + ): String? { + if (!followRedirects || statusCode !in REDIRECT_STATUSES || location.isNullOrBlank()) return null + return runCatching { URI(url).resolve(location.encodeUriReference()).toString() }.getOrNull() + } + private fun ResolvedComposerRequest.redirectedMethod(statusCode: Int): String = when { statusCode == STATUS_SEE_OTHER && method != HEAD_METHOD -> GET_METHOD @@ -342,6 +354,39 @@ class ComposerExecutor( return "${scheme.lowercase()}://${host.lowercase()}:$effectivePort" } + /** Preserve valid escapes while percent-encoding characters URI rejects. */ + private fun String.encodeUriReference(): String { + val source = this + return buildString(source.length) { + var index = 0 + while (index < source.length) { + val character = source[index] + val hasValidEscape = source.hasValidEscapeAt(index) + if (hasValidEscape) { + append(source, index, index + URI_ESCAPE_LENGTH) + index += URI_ESCAPE_LENGTH + } else if (character.isAscii() && (character.isLetterOrDigit() || character in URI_REFERENCE_CHARS)) { + append(character) + index++ + } else { + character.toString().toByteArray(Charsets.UTF_8).forEach { byte -> + append('%') + append(HEX[(byte.toInt() ushr HEX_SHIFT) and HEX_NIBBLE_MASK]) + append(HEX[byte.toInt() and HEX_NIBBLE_MASK]) + } + index++ + } + } + } + } + + private fun String.hasValidEscapeAt(index: Int): Boolean = + getOrNull(index) == '%' && + getOrNull(index + 1)?.digitToIntOrNull(HEX_RADIX) != null && + getOrNull(index + URI_ESCAPE_LENGTH - 1)?.digitToIntOrNull(HEX_RADIX) != null + + private fun Char.isAscii(): Boolean = code < ASCII_LIMIT + private fun Map.withoutCredentials(): Map = filterKeys { name -> name.lowercase() !in CREDENTIAL_HEADERS } diff --git a/sdk/composer/src/test/kotlin/io/devconsole/composer/ComposerExecutorTest.kt b/sdk/composer/src/test/kotlin/io/devconsole/composer/ComposerExecutorTest.kt index 6382d68..7877749 100644 --- a/sdk/composer/src/test/kotlin/io/devconsole/composer/ComposerExecutorTest.kt +++ b/sdk/composer/src/test/kotlin/io/devconsole/composer/ComposerExecutorTest.kt @@ -88,6 +88,26 @@ class ComposerExecutorTest { assertNull(dispatched[1].headers["Cookie"]) } + @Test + fun `redirect Location with spaces and unicode is percent encoded and followed`() { + val dispatched = mutableListOf() + val executor = + ComposerExecutor( + ComposerTransport { request -> + dispatched += request + if (dispatched.size == 1) { + ComposerResponse(statusCode = 302, headers = mapOf("Location" to "/login?next=/a b&name=雪")) + } else { + ComposerResponse(statusCode = 200) + } + }, + ) + + executor.execute(ComposerRequest(method = "GET", url = "https://api.example.test/start")) + + assertEquals("https://api.example.test/login?next=/a%20b&name=%E9%9B%AA", dispatched[1].url) + } + @Test fun `303 redirect converts post to get and drops every body representation`() { val dispatched = mutableListOf() diff --git a/sdk/export/api/export.api b/sdk/export/api/export.api index bc777f6..8f59eca 100644 --- a/sdk/export/api/export.api +++ b/sdk/export/api/export.api @@ -1,6 +1,5 @@ public final class io/devconsole/export/EventExportWriter { public static final field ATTACHMENT_NAME_HASH_CHARS I - public static final field ZIP_ENTRY_OVERHEAD_BYTES J public fun ()V public fun (Lio/devconsole/security/RedactionEngine;)V public synthetic fun (Lio/devconsole/security/RedactionEngine;ILkotlin/jvm/internal/DefaultConstructorMarker;)V @@ -54,6 +53,21 @@ public final class io/devconsole/export/EvidenceBundleContent { public fun toString ()Ljava/lang/String; } +public final class io/devconsole/export/ExportAttachmentSource { + public fun (JLjava/lang/String;Lkotlin/jvm/functions/Function1;)V + public final fun component1 ()J + public final fun component2 ()Ljava/lang/String; + public final fun component3 ()Lkotlin/jvm/functions/Function1; + public final fun copy (JLjava/lang/String;Lkotlin/jvm/functions/Function1;)Lio/devconsole/export/ExportAttachmentSource; + public static synthetic fun copy$default (Lio/devconsole/export/ExportAttachmentSource;JLjava/lang/String;Lkotlin/jvm/functions/Function1;ILjava/lang/Object;)Lio/devconsole/export/ExportAttachmentSource; + public fun equals (Ljava/lang/Object;)Z + public final fun getByteCount ()J + public final fun getMimeType ()Ljava/lang/String; + public final fun getOpen ()Lkotlin/jvm/functions/Function1; + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + public final class io/devconsole/export/ExportRequest { public fun (Ljava/lang/String;Ljava/util/List;Ljava/io/File;J)V public synthetic fun (Ljava/lang/String;Ljava/util/List;Ljava/io/File;JILkotlin/jvm/internal/DefaultConstructorMarker;)V @@ -76,6 +90,7 @@ public final class io/devconsole/export/ExportRequest { public fun hashCode ()I public fun toString ()Ljava/lang/String; public final fun withAnnotations (Ljava/util/Map;)Lio/devconsole/export/ExportRequest; + public final fun withAttachmentSources (Ljava/util/Map;)Lio/devconsole/export/ExportRequest; public final fun withAttachments (Ljava/util/Map;)Lio/devconsole/export/ExportRequest; public final fun withEvidenceBundle (Lio/devconsole/export/EvidenceBundleContent;)Lio/devconsole/export/ExportRequest; public final fun withMetadataOnly (Z)Lio/devconsole/export/ExportRequest; diff --git a/sdk/export/src/main/kotlin/io/devconsole/export/EventExportWriter.kt b/sdk/export/src/main/kotlin/io/devconsole/export/EventExportWriter.kt index eacd3cb..f19c6db 100644 --- a/sdk/export/src/main/kotlin/io/devconsole/export/EventExportWriter.kt +++ b/sdk/export/src/main/kotlin/io/devconsole/export/EventExportWriter.kt @@ -11,12 +11,48 @@ import kotlinx.coroutines.CancellationException import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withContext +import java.io.ByteArrayInputStream import java.io.File +import java.io.InputStream +import java.nio.ByteBuffer +import java.nio.charset.CodingErrorAction import java.security.MessageDigest import java.util.zip.ZipEntry import java.util.zip.ZipOutputStream const val DEFAULT_EXPORT_LIMIT_BYTES: Long = 100L * 1024L * 1024L +private const val MAX_TEXT_SNIFF_BYTES = 4L * 1024L * 1024L +private const val STREAM_BUFFER_SIZE = 8 * 1024 +private const val SHA256_HEX_LENGTH = 64 +private const val README_BYTES = 200L +private const val JSON_PLACEHOLDER_BYTES = 72L +private const val ZIP_ENTRY_OVERHEAD_BYTES = 256L +private const val UTF16_BYTES_PER_CHAR = 2L +private const val ESTIMATED_MANIFEST_BASE_BYTES = 256L +private const val ESTIMATED_MANIFEST_ENTRY_BYTES = 220L +private const val ESTIMATED_ATTACHMENT_DIGEST_BYTES = 64L +private const val ESTIMATED_ATTACHMENT_INDEX_BASE_BYTES = 180L +private const val ESTIMATED_ATTACHMENT_INDEX_OVERHEAD_BYTES = 12L +private const val ESTIMATED_TEXT_BASE_BYTES = 512L +private const val ESTIMATED_ANNOTATION_BASE_BYTES = 128L +private const val ESTIMATED_EVENT_BASE_BYTES = 256L +private const val ESTIMATED_EVENT_OVERHEAD_BYTES = 128L +private const val ESTIMATED_EVIDENCE_SESSION_BYTES = 6L +private const val ESTIMATED_EVIDENCE_ENTRY_BYTES = 180L +private const val ESTIMATED_EVIDENCE_PATH_BYTES = 6L +private const val ESTIMATED_REDACTED_ATTACHMENT_MULTIPLIER = 4L +private const val ESTIMATED_EVIDENCE_MANIFEST_BYTES = 256L +private const val ESTIMATED_ARCHIVE_FIXED_ENTRIES = 5 +private const val ESTIMATED_ATTACHMENTLESS_ARCHIVE_ENTRIES = 4 +private const val ESTIMATED_ARCHIVE_OPTIONAL_ENTRY_COUNT = 1 +private const val MAX_UTF8_ONE_BYTE_CODE = 0x7f +private const val MAX_UTF8_TWO_BYTE_CODE = 0x7ff +private const val UTF8_TWO_BYTE_WIDTH = 2L +private const val UTF8_FOUR_BYTE_WIDTH = 4L +private const val UTF8_THREE_BYTE_WIDTH = 3L +private const val CONTROL_CHARACTER_LIMIT = 0x20 +private const val UNICODE_ESCAPE_WIDTH = 4 +private const val UTF8_SURROGATE_PAIR_INDEX_ADJUSTMENT = 1 sealed interface ExportScope { data object WholeSession : ExportScope @@ -78,6 +114,13 @@ data class EvidenceBundleAttachment( val open: suspend () -> ByteArray?, ) +/** Lazy, metadata-backed source for one standard session attachment. */ +data class ExportAttachmentSource( + val byteCount: Long, + val mimeType: String, + val open: suspend () -> InputStream?, +) + /** * Everything [EventExportWriter] needs to assemble an [ExportScope.Evidence] bundle. The caller (the * `/api/v1/evidence`-owning route) resolves flagged items, the report draft, live network transactions @@ -117,6 +160,9 @@ data class ExportRequest( var attachments: Map = emptyMap() private set + internal var attachmentSources: Map = emptyMap() + private set + /** Only consulted when [scope] is [ExportScope.Evidence]; every other scope ignores this. */ var evidenceBundle: EvidenceBundleContent? = null private set @@ -133,6 +179,9 @@ data class ExportRequest( it.attachments = attachments.mapValues { (_, bytes) -> bytes.copyOf() } } + fun withAttachmentSources(sources: Map): ExportRequest = + duplicate().also { it.attachmentSources = sources.toMap() } + fun withEvidenceBundle(bundle: EvidenceBundleContent): ExportRequest = duplicate().also { it.evidenceBundle = bundle } @@ -142,6 +191,7 @@ data class ExportRequest( it.scope = scope it.metadataOnly = metadataOnly it.attachments = attachments.mapValues { (_, bytes) -> bytes.copyOf() } + it.attachmentSources = attachmentSources.toMap() it.evidenceBundle = evidenceBundle } } @@ -190,28 +240,72 @@ class EventExportWriter( estimateEvidenceBytes(request) } else { val selected = request.events.select(request.sessionId, request.scope) - val payloads = buildStandardPayloads(request, selected) - val manifestBytes = manifest(request, selected.size, payloads).encodeToByteArray() - estimatedBytesOf(payloads, manifestBytes) + estimateStandardBytes(request, selected) } - private fun estimatedBytesOf( - payloads: List, - manifestBytes: ByteArray, + private fun estimateStandardBytes( + request: ExportRequest, + events: List, + ): Long { + val textBytes = standardTextEstimate(request, events) + val attachments = if (request.metadataOnly) emptyList() else standardAttachments(request, events) + val attachmentBytes = + attachments.sumOf { attachment -> + attachment.byteCount + } + val attachmentIndexBytes = + if (attachments.isEmpty()) { + 0L + } else { + attachments.sumOf { + (it.id.length + it.eventId.length) * UTF16_BYTES_PER_CHAR + + ESTIMATED_ATTACHMENT_INDEX_BASE_BYTES + decimalLength(it.byteCount) + } + ESTIMATED_ATTACHMENT_INDEX_OVERHEAD_BYTES + } + val manifestEntryCount = + ESTIMATED_ATTACHMENTLESS_ARCHIVE_ENTRIES + attachments.size + + if (attachments.isEmpty()) 0 else ESTIMATED_ARCHIVE_OPTIONAL_ENTRY_COUNT + val manifestBytes = + ESTIMATED_MANIFEST_BASE_BYTES + request.sessionId.length * UTF16_BYTES_PER_CHAR + + decimalLength(events.size.toLong()) + manifestEntryCount * ESTIMATED_MANIFEST_ENTRY_BYTES + + attachments.size * ESTIMATED_ATTACHMENT_DIGEST_BYTES + return textBytes + attachmentBytes + attachmentIndexBytes + manifestBytes + + estimatedZipOverhead(attachments.size) + } + + private fun estimatedZipOverhead(attachmentCount: Int): Long { + val optionalIndexCount = if (attachmentCount == 0) 0 else ESTIMATED_ARCHIVE_OPTIONAL_ENTRY_COUNT + return (ESTIMATED_ARCHIVE_FIXED_ENTRIES + attachmentCount + optionalIndexCount) * ZIP_ENTRY_OVERHEAD_BYTES + } + + private fun decimalLength(value: Long): Long = value.toString().length.toLong() + + private fun standardTextEstimate( + request: ExportRequest, + events: List, ): Long = - payloads.sumOf { it.bytes.size.toLong() } + - manifestBytes.size + - (payloads.size + 1L) * ZIP_ENTRY_OVERHEAD_BYTES + ESTIMATED_TEXT_BASE_BYTES + events.sumOf(::eventEstimate) + + events.sumOf { event -> + request.annotations[event.id]?.let { + (event.id.length + (it.note?.length ?: 0) + ESTIMATED_ANNOTATION_BASE_BYTES) * + UTF16_BYTES_PER_CHAR + } ?: 0L + } + ESTIMATED_ATTACHMENT_INDEX_OVERHEAD_BYTES + README_BYTES + + private fun eventEstimate(event: StoredEvent): Long = + ( + event.id.length + event.sessionId.length + event.pluginId.length + event.type.length + + event.summary.length + + event.tagsJson.length + (event.correlationId?.length ?: 0) + (event.payloadJson?.length ?: 0) + + (event.attachmentId?.length ?: 0) + ESTIMATED_EVENT_BASE_BYTES + ) * UTF16_BYTES_PER_CHAR + ESTIMATED_EVENT_OVERHEAD_BYTES private suspend fun writeInternal(request: ExportRequest): ExportResult { require(request.maxBytes > 0) { "maxBytes must be positive" } if (request.scope is ExportScope.Evidence) return writeEvidenceInternal(request) val selected = request.events.select(request.sessionId, request.scope) - val payloads = buildStandardPayloads(request, selected) - val manifest = manifest(request, selected.size, payloads) - val manifestBytes = manifest.encodeToByteArray() - val estimatedBytes = estimatedBytesOf(payloads, manifestBytes) + val estimatedBytes = estimateStandardBytes(request, selected) if (estimatedBytes > request.maxBytes) return ExportResult.ExceedsSizeLimit var temporary: File? = null @@ -221,9 +315,19 @@ class EventExportWriter( if (!ensureDirectoryExists(parent)) return ExportResult.Unavailable temporary = File.createTempFile(".${destination.name}.", ".tmp", parent) ZipOutputStream(temporary.outputStream().buffered()).use { zip -> + val payloads = standardTextPayloads(request, selected) + val manifestEntries = mutableListOf() + payloads.forEach { payload -> + zip.writeBytes(payload.path, payload.bytes) + manifestEntries += ManifestData(payload.path, payload.bytes.sha256(), payload.bytes.size.toLong()) + } + manifestEntries += zip.writeTimeline(selected, request) + if (!request.metadataOnly) zip.streamStandardAttachments(request, selected, manifestEntries) + val manifestBytes = manifest(request, selected.size, manifestEntries).encodeToByteArray() zip.writeBytes("manifest.json", manifestBytes) - payloads.forEach { payload -> zip.writeBytes(payload.path, payload.bytes) } } + // The pre-write estimate is metadata-only; the archive actually written is the final gate. + if (temporary.length() > request.maxBytes) return ExportResult.ExceedsSizeLimit publishAtomically(temporary, destination) temporary = null ExportResult.Success(destination, selected.size) @@ -247,12 +351,15 @@ class EventExportWriter( private fun estimateEvidenceBytes(request: ExportRequest): Long { val bundle = request.evidenceBundle ?: return 0L - val textPayloads = evidenceTextPayloads(bundle) - val textEntries = textPayloads.map { it.toAppliedManifestEntry() } + val textMetadata = evidenceTextMetadata(bundle) + val textEntries = + textMetadata.map { (path, size) -> + ManifestFileEntry(path, PLACEHOLDER_SHA256, size, RedactionApplicability.APPLIED) + } // Attachments are never opened here: the placeholder hash is a fixed-length stand-in (a real // sha256 hex digest is always PLACEHOLDER_SHA256.length characters, regardless of content) and - // sizeBytes stands in for the eventual (post-redaction) byte count. Redaction can only shrink - // an attachment's bytes (see redactedCopy), so this can only ever over-, never under-, estimate. + // sizeBytes stands in for the eventual attachment length, with a conservative multiplier for + // text redaction and UTF-8 expansion. This keeps the estimate independent of attachment content. val attachmentEntries = bundle.attachments.map { attachment -> ManifestFileEntry( @@ -263,11 +370,23 @@ class EventExportWriter( ) } val manifestBytes = - evidenceManifestJson(request.sessionId, bundle.itemCount, textEntries + attachmentEntries) - .encodeToByteArray() - val payloadBytes = textPayloads.sumOf { it.bytes.size.toLong() } + bundle.attachments.sumOf { it.sizeBytes } - val entryCount = textPayloads.size + bundle.attachments.size + 1L - return payloadBytes + manifestBytes.size + entryCount * ZIP_ENTRY_OVERHEAD_BYTES + ESTIMATED_EVIDENCE_MANIFEST_BYTES + request.sessionId.length * ESTIMATED_EVIDENCE_SESSION_BYTES + + decimalLength(bundle.itemCount.toLong()) + + (textEntries.size + attachmentEntries.size) * ESTIMATED_EVIDENCE_ENTRY_BYTES + + bundle.attachments.sumOf { + it.path.length * ESTIMATED_EVIDENCE_PATH_BYTES + decimalLength(it.sizeBytes) + } + val payloadBytes = + textMetadata.sumOf { it.second } + + bundle.attachments.sumOf { attachment -> + if (attachment.redactionApplicability == RedactionApplicability.NOT_APPLICABLE) { + attachment.sizeBytes + } else { + attachment.sizeBytes * ESTIMATED_REDACTED_ATTACHMENT_MULTIPLIER + } + } + val entryCount = textMetadata.size + bundle.attachments.size + ESTIMATED_ARCHIVE_OPTIONAL_ENTRY_COUNT.toLong() + return payloadBytes + manifestBytes + entryCount * ZIP_ENTRY_OVERHEAD_BYTES } private suspend fun writeEvidenceInternal(request: ExportRequest): ExportResult { @@ -290,6 +409,8 @@ class EventExportWriter( .encodeToByteArray() zip.writeBytes("manifest.json", manifestBytes) } + // The pre-write estimate is metadata-only; the archive actually written is the final gate. + if (temporary.length() > request.maxBytes) return ExportResult.ExceedsSizeLimit publishAtomically(temporary, destination) temporary = null ExportResult.Success(destination, bundle.itemCount) @@ -344,14 +465,46 @@ class EventExportWriter( /** report.md/report.json/network.har/postman_collection.json/session.json, redacted a second time. */ private fun evidenceTextPayloads(bundle: EvidenceBundleContent): List = + evidenceTextMetadata(bundle).map { (path, _) -> + val content = + when (path) { + "report.md" -> bundle.reportMarkdown + "report.json" -> bundle.reportJson + "network.har" -> bundle.networkHar + "postman_collection.json" -> bundle.postmanCollection + else -> bundle.sessionJson + } + redactedTextPayload(path, content) + } + + private fun evidenceTextMetadata(bundle: EvidenceBundleContent): List> = listOf( - redactedTextPayload("report.md", bundle.reportMarkdown), - redactedTextPayload("report.json", bundle.reportJson), - redactedTextPayload("network.har", bundle.networkHar), - redactedTextPayload("postman_collection.json", bundle.postmanCollection), - redactedTextPayload("session.json", bundle.sessionJson), + "report.md" to utf8ByteCount(bundle.reportMarkdown), + "report.json" to maxOf(utf8ByteCount(bundle.reportJson), JSON_PLACEHOLDER_BYTES), + "network.har" to maxOf(utf8ByteCount(bundle.networkHar), JSON_PLACEHOLDER_BYTES), + "postman_collection.json" to maxOf(utf8ByteCount(bundle.postmanCollection), JSON_PLACEHOLDER_BYTES), + "session.json" to maxOf(utf8ByteCount(bundle.sessionJson), JSON_PLACEHOLDER_BYTES), ) + private fun utf8ByteCount(value: String): Long { + var bytes = 0L + var index = 0 + while (index < value.length) { + val char = value[index] + when { + char.code <= MAX_UTF8_ONE_BYTE_CODE -> bytes++ + char.code <= MAX_UTF8_TWO_BYTE_CODE -> bytes += UTF8_TWO_BYTE_WIDTH + char.isHighSurrogate() && index + 1 < value.length && value[index + 1].isLowSurrogate() -> { + bytes += UTF8_FOUR_BYTE_WIDTH + index += UTF8_SURROGATE_PAIR_INDEX_ADJUSTMENT + } + else -> bytes += UTF8_THREE_BYTE_WIDTH + } + index++ + } + return bytes + } + private data class ManifestFileEntry( val path: String, val sha256: String, @@ -383,7 +536,7 @@ class EventExportWriter( } }]}" - private fun buildStandardPayloads( + private fun standardTextPayloads( request: ExportRequest, events: List, ): List = @@ -397,14 +550,6 @@ class EventExportWriter( "\"eventCount\":${events.size}}", ), ) - add( - PayloadFile.text( - "timeline.jsonl", - events.joinToString("\n") { event -> - event.toJsonLine(request.annotations[event.id], request.metadataOnly) - }, - ), - ) val bookmarkJson = events .mapNotNull { event -> @@ -419,9 +564,6 @@ class EventExportWriter( }.joinToString(",") add(PayloadFile.text("bookmarks.json", "{\"data\":[$bookmarkJson]}")) - if (!request.metadataOnly) { - addAll(attachmentPayloads(request, events)) - } add( PayloadFile.text( "README.txt", @@ -433,51 +575,130 @@ class EventExportWriter( ) } - /** One redacted `attachments/.bin` per event that has a non-empty attachment, plus an index. */ - private fun attachmentPayloads( + private data class StandardAttachment( + val id: String, + val eventId: String, + val mimeType: String, + val byteCount: Long, + val open: suspend () -> InputStream?, + ) + + private fun standardAttachments( request: ExportRequest, events: List, - ): List = - buildList { - val attachmentIndex = mutableListOf() - events.forEach { event -> - val attachmentId = event.attachmentId ?: return@forEach - val capturedBytes = request.attachments[attachmentId]?.copyOf() ?: return@forEach - if (capturedBytes.isEmpty()) return@forEach - val bytes = - redaction - .redactText(capturedBytes.decodeToString(), capturedBytes.size) - .encodeToByteArray() - .let { redacted -> - if (redacted.size <= capturedBytes.size) redacted else redacted.copyOf(capturedBytes.size) - } - val nameHash = attachmentId.encodeToByteArray().sha256().take(ATTACHMENT_NAME_HASH_CHARS) - val path = "attachments/$nameHash.bin" - add(PayloadFile(path, bytes)) - attachmentIndex += - "{\"eventId\":\"${escape(redaction.redactText(event.id))}\"," + - "\"attachmentId\":\"${escape(redaction.redactText(attachmentId))}\"," + - "\"path\":\"$path\",\"bytes\":${bytes.size}}" - } - if (attachmentIndex.isNotEmpty()) { - add(PayloadFile.text("attachments/index.json", "{\"data\":[${attachmentIndex.joinToString(",")}]}")) + ): List = + events + .mapNotNull { event -> + val id = event.attachmentId ?: return@mapNotNull null + val source = request.attachmentSources[id] + if (source != null) { + return@mapNotNull StandardAttachment(id, event.id, source.mimeType, source.byteCount, source.open) + } + request.attachments[id]?.let { bytes -> + // Legacy in-memory attachments carry no MIME type. Redact as text only when they + // decode as UTF-8. + val mimeType = if (bytes.isUtf8Text()) "text/plain" else "application/octet-stream" + StandardAttachment(id, event.id, mimeType, bytes.size.toLong()) { ByteArrayInputStream(bytes) } + } + }.distinctBy { it.id } + .filter { it.byteCount > 0 } + + private fun attachmentPath(id: String): String = + "attachments/${id.encodeToByteArray().sha256().take(ATTACHMENT_NAME_HASH_CHARS)}.bin" + + private suspend fun ZipOutputStream.streamStandardAttachments( + request: ExportRequest, + events: List, + manifestEntries: MutableList, + ) { + val attachmentIndex = mutableListOf() + standardAttachments(request, events).forEach { attachment -> + val path = attachmentPath(attachment.id) + val result = streamStandardAttachment(attachment, path) ?: return@forEach + val (digest, byteCount) = result + manifestEntries += ManifestData(path, digest, byteCount) + attachmentIndex += attachmentIndexEntry(attachment, path, byteCount) + } + if (attachmentIndex.isNotEmpty()) { + val index = "{\"data\":[${attachmentIndex.joinToString(",")}]}" + val indexBytes = index.encodeToByteArray() + writeBytes("attachments/index.json", indexBytes) + manifestEntries += ManifestData("attachments/index.json", indexBytes.sha256(), indexBytes.size.toLong()) + } + } + + private suspend fun ZipOutputStream.streamStandardAttachment( + attachment: StandardAttachment, + path: String, + ): Pair? { + val input = attachment.open() ?: return null + return input.use { source -> + if (isTextMime(attachment.mimeType)) { + val bytes = redactTextBytes(source.readBytes()) + writeBytes(path, bytes) + bytes.sha256() to bytes.size.toLong() + } else if (attachment.byteCount <= MAX_TEXT_SNIFF_BYTES) { + // Capture-capped bodies are small: sniff them, so text stored without a + // textual MIME type still gets its second redaction pass while binary bytes + // are copied untouched. + val raw = source.readBytes() + val bytes = if (raw.isUtf8Text()) redactTextBytes(raw) else raw + writeBytes(path, bytes) + bytes.sha256() to bytes.size.toLong() + } else { + writeStream(path, source) } } + } + + private fun attachmentIndexEntry( + attachment: StandardAttachment, + path: String, + byteCount: Long, + ): String = + "{\"eventId\":\"${escape(redaction.redactText(attachment.eventId))}\"," + + "\"attachmentId\":\"${escape( + redaction.redactText(attachment.id), + )}\",\"path\":\"$path\",\"bytes\":$byteCount}" + + private fun isTextMime(mimeType: String): Boolean { + val mime = mimeType.substringBefore(';').trim().lowercase() + return mime.startsWith("text/") || + mime.contains("json") || + mime.contains("xml") || + mime.contains("x-www-form-urlencoded") || + mime.contains("javascript") + } + + private fun ByteArray.isUtf8Text(): Boolean = + runCatching { + Charsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(this)) + }.isSuccess + + private fun redactTextBytes(raw: ByteArray): ByteArray = + redaction.redactText(raw.decodeToString(), raw.size.coerceAtLeast(1)).encodeToByteArray() + + private data class ManifestData( + val path: String, + val sha256: String, + val bytes: Long, + ) private fun manifest( request: ExportRequest, eventCount: Int, - payloads: List, + payloads: List, ): String = "{\"format\":\"devconsole-export-v2\"," + "\"sessionId\":\"${escape(redaction.redactText(request.sessionId))}\"," + "\"eventCount\":$eventCount,\"metadataOnly\":${request.metadataOnly}," + - "\"manifestSelfExcluded\":true,\"files\":[${ - payloads.joinToString(",") { payload -> - "{\"path\":\"${escape(payload.path)}\",\"sha256\":\"${payload.bytes.sha256()}\"," + - "\"bytes\":${payload.bytes.size}}" - } - }]}" + "\"manifestSelfExcluded\":true,\"files\":[${payloads.joinToString(",") { entry -> + "{\"path\":\"${escape(entry.path)}\",\"sha256\":\"${entry.sha256}\",\"bytes\":${entry.bytes}}" + }}]}" private fun List.select( sessionId: String, @@ -554,6 +775,53 @@ class EventExportWriter( closeEntry() } + private fun ZipOutputStream.writeTimeline( + events: List, + request: ExportRequest, + ): ManifestData { + val digest = MessageDigest.getInstance("SHA-256") + var total = 0L + putNextEntry(ZipEntry("timeline.jsonl")) + events.forEachIndexed { index, event -> + if (index > 0) { + write('\n'.code) + digest.update('\n'.code.toByte()) + total++ + } + val line = event.toJsonLine(request.annotations[event.id], request.metadataOnly).encodeToByteArray() + write(line) + digest.update(line) + total += line.size + } + closeEntry() + return ManifestData( + "timeline.jsonl", + digest.digest().joinToString("") { + "%02x".format(it.toInt() and BYTE_MASK) + }, + total, + ) + } + + private fun ZipOutputStream.writeStream( + name: String, + input: InputStream, + ): Pair { + val digest = MessageDigest.getInstance("SHA-256") + var total = 0L + putNextEntry(ZipEntry(name)) + val buffer = ByteArray(STREAM_BUFFER_SIZE) + while (true) { + val count = input.read(buffer) + if (count < 0) break + write(buffer, 0, count) + digest.update(buffer, 0, count) + total += count + } + closeEntry() + return digest.digest().joinToString("") { "%02x".format(it.toInt() and BYTE_MASK) } to total + } + private fun ExportScope.json(): String = when (this) { ExportScope.WholeSession -> "{\"type\":\"WHOLE_SESSION\"}" @@ -567,22 +835,40 @@ class EventExportWriter( } private fun escape(value: String): String = - value - .replace("\\", "\\\\") - .replace("\"", "\\\"") - .replace("\b", "\\b") - .replace("\u000C", "\\f") - .replace("\n", "\\n") - .replace("\r", "\\r") - .replace("\t", "\\t") - - /** [RedactionEngine.redactText]'s `maxLength` must never be 0; evidence bundle files can legitimately be empty. */ - private fun String.boundedLength(): Int = length.coerceAtLeast(1) + buildString(value.length) { + value.forEach { char -> + when (char) { + '\\' -> append("\\\\") + '"' -> append("\\\"") + '\b' -> append("\\b") + '\u000C' -> append("\\f") + '\n' -> append("\\n") + '\r' -> append("\\r") + '\t' -> append("\\t") + else -> + if (char.code < CONTROL_CHARACTER_LIMIT) { + append("\\u%0${UNICODE_ESCAPE_WIDTH}x".format(char.code)) + } else { + append(char) + } + } + } + } private fun redactedTextPayload( path: String, content: String, - ): PayloadFile = PayloadFile.text(path, redaction.redactText(content, content.boundedLength())) + ): PayloadFile { + val redacted = redaction.redactText(content, Int.MAX_VALUE) + val structured = path.endsWith(".json") || path.endsWith(".har") + val safe = + if (structured && redacted.encodeToByteArray().size > content.encodeToByteArray().size) { + "{\"_comment\":\"redacted structured body omitted to preserve valid JSON\"}" + } else { + redacted + } + return PayloadFile.text(path, safe) + } /** * Second redaction pass for a bundle attachment whose text content is already redacted (a @@ -616,8 +902,6 @@ class EventExportWriter( } private companion object { - const val ZIP_ENTRY_OVERHEAD_BYTES = 256L - // Truncated hex of the attachment id's SHA-256: enough to avoid collisions while keeping // archive entry names short and free of any characters recovered from the id itself. const val ATTACHMENT_NAME_HASH_CHARS = 32 @@ -625,7 +909,7 @@ class EventExportWriter( // A real sha256 hex digest is always 64 characters; used as a fixed-length stand-in in the // Evidence-scope size estimate so an un-opened attachment's manifest entry is sized correctly // without ever computing (or needing) its real digest. - val PLACEHOLDER_SHA256 = "0".repeat(64) + val PLACEHOLDER_SHA256 = "0".repeat(SHA256_HEX_LENGTH) fun ensureDirectoryExists(directory: File): Boolean = directory.isDirectory || directory.mkdirs() diff --git a/sdk/export/src/test/kotlin/io/devconsole/export/EventExportWriterTest.kt b/sdk/export/src/test/kotlin/io/devconsole/export/EventExportWriterTest.kt index 660553c..e22f530 100644 --- a/sdk/export/src/test/kotlin/io/devconsole/export/EventExportWriterTest.kt +++ b/sdk/export/src/test/kotlin/io/devconsole/export/EventExportWriterTest.kt @@ -109,6 +109,109 @@ class EventExportWriterTest { assertTrue(metadataOnlyEstimate < withBytes) } + @Test + fun `oversized lazy attachment is rejected before its source is read and estimate does not read it`() { + val directory = Files.createTempDirectory("devconsole-export-lazy-test").toFile() + try { + var reads = 0 + val request = + ExportRequest( + sessionId = "session-1", + destination = File(directory, "export.zip"), + events = listOf(event(summary = "large", attachmentId = "lazy")), + maxBytes = 1, + ).withAttachmentSources( + mapOf( + "lazy" to + ExportAttachmentSource(1024, "application/octet-stream") { + reads++ + error("attachment source must not be opened") + }, + ), + ) + val writer = EventExportWriter(RedactionEngine(RedactionPolicy.recommended())) + assertTrue(writer.estimateBytes(request) > 1) + assertEquals(ExportResult.ExceedsSizeLimit, writer.write(request)) + assertEquals(0, reads) + } finally { + directory.deleteRecursively() + } + } + + @Test + fun `binary attachment bytes are preserved exactly`() { + val directory = Files.createTempDirectory("devconsole-export-binary-test").toFile() + try { + val source = byteArrayOf(0, 0xFF.toByte(), 0xC3.toByte(), 0x28, 0x1B) + val destination = File(directory, "export.zip") + val request = + ExportRequest("session-1", listOf(event(summary = "binary", attachmentId = "binary")), destination) + .withAttachmentSources( + mapOf( + "binary" to + ExportAttachmentSource(source.size.toLong(), "image/png") { source.inputStream() }, + ), + ) + assertTrue(EventExportWriter().write(request) is ExportResult.Success) + ZipFile(destination).use { zip -> + val path = + zip.entries().asSequence().first { + it.name.startsWith("attachments/") && + it.name.endsWith(".bin") + } + assertTrue(source.contentEquals(zip.getInputStream(path).readBytes())) + } + } finally { + directory.deleteRecursively() + } + } + + @Test + fun `control characters are JSON escaped in timeline`() { + val directory = Files.createTempDirectory("devconsole-export-control-test").toFile() + try { + val destination = File(directory, "export.zip") + val summary = "a\u0000\u0001\u001b\b\u000c\n\r\t" + val request = ExportRequest("session-1", listOf(event(summary = summary)), destination) + assertTrue(EventExportWriter().write(request) is ExportResult.Success) + ZipFile(destination).use { zip -> + val jsonLine = zip.getInputStream(zip.getEntry("timeline.jsonl")).bufferedReader().readText() + assertTrue(jsonLine.contains("\\u0000")) + assertTrue(jsonLine.contains("\\u0001")) + assertTrue(jsonLine.contains("\\u001b")) + assertTrue(jsonLine.contains("\\b")) + assertTrue(jsonLine.none { it.code < 0x20 }) + } + } finally { + directory.deleteRecursively() + } + } + + @Test + fun `structured evidence redaction growth replaces the whole file with valid JSON`() { + val directory = Files.createTempDirectory("devconsole-evidence-structured-test").toFile() + try { + val destination = File(directory, "evidence.zip") + val request = + evidenceRequest(destination).withEvidenceBundle( + baseEvidenceBundle().copy(reportJson = "{\"password\":\"x\"}"), + ) + assertTrue( + EventExportWriter( + RedactionEngine(RedactionPolicy.recommended()), + ).write(request) is ExportResult.Success, + ) + ZipFile(destination).use { zip -> + assertEquals( + "{\"_comment\":\"redacted structured body omitted to preserve valid JSON\"}", + zip.readText("report.json"), + ) + } + } finally { + directory.deleteRecursively() + } + } + @Test fun `includes bookmarks and re-redacted notes in timeline export`() { val directory = Files.createTempDirectory("devconsole-export-annotation-test").toFile() 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 10aaeba..64fbf86 100644 --- a/sdk/facade-shared/src/main/kotlin/io/devconsole/DevConsole.kt +++ b/sdk/facade-shared/src/main/kotlin/io/devconsole/DevConsole.kt @@ -9,7 +9,9 @@ import io.devconsole.api.DevConsoleConfig import io.devconsole.api.DevConsoleState import io.devconsole.api.InitResult import io.devconsole.api.InspectorOpenResult +import io.devconsole.api.PurgeResult import io.devconsole.api.ScreenshotResult +import io.devconsole.api.SessionExportResult import io.devconsole.api.StartRequest import io.devconsole.api.StartResult import io.devconsole.api.StopReason @@ -198,6 +200,17 @@ object DevConsole { fun registerRemoteConfigProvider(provider: RemoteConfigProvider): Boolean = this.provider.registerRemoteConfigProvider(provider) + /** + * The local override a developer applied in DevConsole for [key], or null. Read it before your + * own provider: `DevConsole.remoteConfigOverride("k") ?: remoteConfig.getString("k")`. + */ + @JvmStatic + @JvmOverloads + fun remoteConfigOverride( + key: String, + providerId: String? = null, + ): String? = this.provider.remoteConfigOverride(key, providerId) + /** Address of the running server, or null when it is not running. Survives activity recreation. */ @JvmStatic fun endpoint(): BrowserEndpoint? = provider.endpoint() @@ -236,4 +249,24 @@ object DevConsole { */ @JvmStatic fun featureFlagStringValue(key: String): String = provider.featureFlagStringValue(key) + + /** + * Pauses or resumes live capture of network transactions, socket connections, push events, and + * log lines. Returns `false` when the runtime is disabled or not initialized, and `true` when + * the state was applied. + */ + @JvmStatic + fun setCapturePaused(paused: Boolean): Boolean = provider.setCapturePaused(paused) + + /** Whether live capture is currently paused. */ + @JvmStatic + fun isCapturePaused(): Boolean = provider.isCapturePaused() + + /** Clears captured in-memory data and deletes finished retained runs; the live run and pinned runs are kept. */ + @JvmStatic + suspend fun purgeCapturedData(): PurgeResult = provider.purgeCapturedData() + + /** Exports the current session bundle as a ZIP file. */ + @JvmStatic + suspend fun exportSession(): SessionExportResult = provider.exportSession() } diff --git a/sdk/full/api/full.api b/sdk/full/api/full.api index 7440361..5dce772 100644 --- a/sdk/full/api/full.api +++ b/sdk/full/api/full.api @@ -5,17 +5,24 @@ public final class io/devconsole/DevConsole { public static final fun captureScreenshotAsync (Lio/devconsole/DevConsoleCallback;)V public static final fun createIntent (Landroid/content/Context;)Landroid/content/Intent; public static final fun endpoint ()Lio/devconsole/api/BrowserEndpoint; + public static final fun exportSession (Lkotlin/coroutines/Continuation;)Ljava/lang/Object; public static final fun featureFlagStringValue (Ljava/lang/String;)Ljava/lang/String; public static final fun featureFlagValue (Ljava/lang/String;)Z public static final fun initialize (Landroid/app/Application;Lio/devconsole/api/DevConsoleConfig;)Lio/devconsole/api/InitResult; public static synthetic fun initialize$default (Landroid/app/Application;Lio/devconsole/api/DevConsoleConfig;ILjava/lang/Object;)Lio/devconsole/api/InitResult; + public static final fun isCapturePaused ()Z public static final fun logRecorder ()Lio/devconsole/logs/LogRecorder; public static final fun mockEngine ()Lio/devconsole/mocks/MockEngine; 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 purgeCapturedData (Lkotlin/coroutines/Continuation;)Ljava/lang/Object; 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 remoteConfigOverride (Ljava/lang/String;)Ljava/lang/String; + public static final fun remoteConfigOverride (Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; + public static synthetic fun remoteConfigOverride$default (Ljava/lang/String;Ljava/lang/String;ILjava/lang/Object;)Ljava/lang/String; + public static final fun setCapturePaused (Z)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; public static synthetic fun startBrowser$default (Lio/devconsole/api/StartRequest;Lkotlin/coroutines/Continuation;ILjava/lang/Object;)Ljava/lang/Object; diff --git a/sdk/full/src/androidTest/kotlin/io/devconsole/ScreenshotCaptureInstrumentedTest.kt b/sdk/full/src/androidTest/kotlin/io/devconsole/ScreenshotCaptureInstrumentedTest.kt index 4d299c8..2bedd4b 100644 --- a/sdk/full/src/androidTest/kotlin/io/devconsole/ScreenshotCaptureInstrumentedTest.kt +++ b/sdk/full/src/androidTest/kotlin/io/devconsole/ScreenshotCaptureInstrumentedTest.kt @@ -2,12 +2,9 @@ * @author Shakib * @since 06/08/26 * - * NOTE: written to compile against a real device/emulator window, but not executed in this change -- - * no emulator was available in this environment. Do not treat this file as evidence the real - * `PixelCopy` path or the `FLAG_SECURE` rejection have been run; [ScreenshotCaptureTest] (Robolectric, - * `sdk:full` unit tests) exercises the same capture code path including a real `PixelCopy.request` - * dispatch under Robolectric's shadow, but that is not a substitute for verifying against an actual - * device compositor. + * Runs against a real device compositor (verified on a Pixel 6, API 37, 03/11/26): the real + * `PixelCopy` path and the `FLAG_SECURE` rejection. [ScreenshotCaptureTest] covers the same code under + * Robolectric's shadow. */ package io.devconsole @@ -29,14 +26,7 @@ class ScreenshotCaptureInstrumentedTest { val policy = ScreenshotPolicy(enabled = true, maxLongestEdgePx = 512, maxBytes = 4L * 1024 * 1024) val capture = ScreenshotCapture() - val result = - runBlocking { - var outcome: CapturedScreenshot? = null - scenario.onActivity { activity -> - outcome = runBlocking { capture.capture(activity, policy) } - } - outcome - } + val result = runBlocking { capture.capture(scenario.currentActivity(), policy) } assertTrue("expected a real capture, got $result", result is CapturedScreenshot.Bytes) result as CapturedScreenshot.Bytes @@ -56,16 +46,20 @@ class ScreenshotCaptureInstrumentedTest { } val capture = ScreenshotCapture() - val result = - runBlocking { - var outcome: CapturedScreenshot? = null - scenario.onActivity { activity -> - outcome = runBlocking { capture.capture(activity, ScreenshotPolicy(enabled = true)) } - } - outcome - } + val result = runBlocking { capture.capture(scenario.currentActivity(), ScreenshotPolicy(enabled = true)) } assertEquals(CapturedScreenshot.SecureWindow, result) } } } + +/** + * The activity, handed back to the instrumentation thread. capture() must be awaited from here, not + * inside onActivity: PixelCopy delivers its result on the main looper, so blocking main to wait for + * it can only ever time out -- which is how this test first failed on a real device. + */ +private fun ActivityScenario.currentActivity(): ScreenshotProbeActivity { + var current: ScreenshotProbeActivity? = null + onActivity { current = it } + return checkNotNull(current) +} diff --git a/sdk/full/src/main/kotlin/io/devconsole/AndroidDatabaseInspector.kt b/sdk/full/src/main/kotlin/io/devconsole/AndroidDatabaseInspector.kt index 315fe88..2bbabb1 100644 --- a/sdk/full/src/main/kotlin/io/devconsole/AndroidDatabaseInspector.kt +++ b/sdk/full/src/main/kotlin/io/devconsole/AndroidDatabaseInspector.kt @@ -15,13 +15,25 @@ import io.devconsole.server.api.DatabaseListingData import io.devconsole.server.api.DatabaseQueryData import io.devconsole.server.api.DatabaseTableData +private const val AUXILIARY_COLUMN_STRIDE = 3 +private const val ROWID_COLUMN_OFFSET = 1 + @Suppress("TooManyFunctions") // Small private cursor/SQL helpers kept beside the four interface methods. internal class AndroidDatabaseInspector( private val context: Context, private val redaction: RedactionEngine, private val maxRows: Int = DEFAULT_MAX_ROWS, ) : DatabaseInspector { - override fun databases(): List = context.databaseList().filterNot { it.isAuxiliaryFile() }.sorted() + /** + * The host's databases only. DevConsole's own capture store (`devconsole-events.db`) is SDK + * state already shown through every other tab; listing it here put it one SQL write away from + * corruption while Room holds it open. + */ + override fun databases(): List = + context + .databaseList() + .filterNot { it.isAuxiliaryFile() || INTERNAL_DATABASE_PREFIXES.any(it::startsWith) } + .sorted() override fun tables(database: String): DatabaseListingData? = withDatabase(database, writable = false) { db -> @@ -54,10 +66,10 @@ internal class AndroidDatabaseInspector( // table (or any other reason the alias fails) falls back to the plain, rowid-less query. runCatching { db - .rawQuery("SELECT rowid AS \"$ROWID_ALIAS\", * FROM \"$quoted\" LIMIT ${maxRows + 1}", null) + .rawQuery(db.boundedTableQuery(quoted, includeRowId = true), null) .use { it.toQueryData(hasRowId = true) } }.getOrElse { - db.rawQuery("SELECT * FROM \"$quoted\" LIMIT ${maxRows + 1}", null).use { it.toQueryData() } + db.rawQuery(db.boundedTableQuery(quoted, includeRowId = false), null).use { it.toQueryData() } } } } @@ -104,6 +116,35 @@ internal class AndroidDatabaseInspector( } }.getOrDefault(0L) + private fun SQLiteDatabase.boundedTableQuery( + quotedTable: String, + includeRowId: Boolean, + ): String { + val prefix = if (includeRowId) "rowid AS \"$ROWID_ALIAS\", " else "" + val columns = + rawQuery("PRAGMA table_info(\"$quotedTable\")", null).use { cursor -> + buildList { + while (cursor.moveToNext()) add(cursor.getString(1)) + } + } + val projection = + columns.joinToString(", ") { name -> + val quotedColumn = "\"${name.replace("\"", "\"\"")}\"" + val preview = "substr($quotedColumn, 1, $MAX_CELL_TEXT_CHARS)" + "CASE WHEN typeof($quotedColumn) = 'blob' THEN NULL ELSE $preview END AS \"${name.replace( + "\"", + "\"\"", + )}\", " + + "length($quotedColumn) AS \"${lengthAlias(name)}\", " + + "typeof($quotedColumn) AS \"${typeAlias(name)}\"" + } + return "SELECT $prefix$projection FROM \"$quotedTable\" LIMIT ${maxRows + 1}" + } + + private fun lengthAlias(name: String): String = "${AUXILIARY_PREFIX}l${name.hashCode().toUInt()}" + + private fun typeAlias(name: String): String = "${AUXILIARY_PREFIX}t${name.hashCode().toUInt()}" + private fun SQLiteDatabase.changesCount(): Int = runCatching { rawQuery("SELECT changes()", null).use { cursor -> if (cursor.moveToFirst()) cursor.getInt(0) else 0 } @@ -114,7 +155,13 @@ internal class AndroidDatabaseInspector( * split off into [DatabaseQueryData.rowIds] rather than shown as an ordinary, maskable column. */ private fun android.database.Cursor.toQueryData(hasRowId: Boolean = false): DatabaseQueryData { - val columns = if (hasRowId) columnNames.drop(1) else columnNames.toList() + if (columnNames.none { it.startsWith(AUXILIARY_PREFIX) }) return toDirectQueryData(hasRowId) + val physicalColumns = columnNames.toList() + val columns = physicalColumns.filterNot { it.startsWith(AUXILIARY_PREFIX) || (hasRowId && it == ROWID_ALIAS) } + val physicalIndexes = + columns.indices.map { index -> + if (hasRowId) ROWID_COLUMN_OFFSET + index * AUXILIARY_COLUMN_STRIDE else index * AUXILIARY_COLUMN_STRIDE + } val rows = mutableListOf>() val rowIds = mutableListOf() var truncated = false @@ -126,23 +173,50 @@ internal class AndroidDatabaseInspector( if (hasRowId) rowIds.add(if (isNull(0)) null else getLong(0)) rows.add( columns.indices.map { index -> - val cursorIndex = if (hasRowId) index + 1 else index - cellText(cursorIndex, columns[index]) + val cursorIndex = physicalIndexes[index] + val lengthIndex = physicalColumns.indexOf(lengthAlias(columns[index])) + val typeIndex = physicalColumns.indexOf(typeAlias(columns[index])) + cellText(cursorIndex, columns[index], lengthIndex, cursorIndex, typeIndex) }, ) } return DatabaseQueryData(columns = columns, rows = rows, truncated = truncated, rowIds = rowIds) } + private fun android.database.Cursor.toDirectQueryData(hasRowId: Boolean): DatabaseQueryData { + val columns = if (hasRowId) columnNames.drop(1) else columnNames.toList() + val rows = mutableListOf>() + val rowIds = mutableListOf() + var truncated = false + while (moveToNext()) { + if (rows.size >= maxRows) { + truncated = true + break + } + if (hasRowId) rowIds.add(if (isNull(0)) null else getLong(0)) + rows.add(columns.indices.map { index -> cellText(index + if (hasRowId) 1 else 0, columns[index]) }) + } + return DatabaseQueryData(columns = columns, rows = rows, truncated = truncated, rowIds = rowIds) + } + + private fun android.database.Cursor.cellText( + index: Int, + column: String, + ): String = cellText(index, column, index, index) + private fun android.database.Cursor.cellText( index: Int, column: String, + lengthIndex: Int, + previewIndex: Int, + typeIndex: Int = -1, ): String { - if (isNull(index)) return "NULL" + val valueType = if (typeIndex >= 0) getString(typeIndex) else null + if (valueType == "null" || (valueType != "blob" && isNull(index))) return "NULL" val raw = - when (getType(index)) { - android.database.Cursor.FIELD_TYPE_BLOB -> "[blob ${getBlob(index).size} bytes]" - else -> getString(index).orEmpty() + when (valueType) { + "blob" -> "[blob ${getLong(lengthIndex)} bytes]" + else -> getString(previewIndex).orEmpty() } if (redaction.isEnabled() && column.looksSensitiveColumn()) return redaction.replacement() return redaction.redactFields(mapOf(column to raw)).getValue(column) @@ -199,12 +273,15 @@ internal class AndroidDatabaseInspector( private companion object { const val DEFAULT_MAX_ROWS = 200 + val INTERNAL_DATABASE_PREFIXES = listOf("devconsole-", "io.devconsole.") const val TABLE_LIST_SQL = "SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name" // Unlikely to collide with a real application column; if it ever does, the SELECT below // simply fails and query() falls back to the plain, rowid-less form. const val ROWID_ALIAS = "__devconsole_rowid__" + const val MAX_CELL_TEXT_CHARS = 4_096 + const val AUXILIARY_PREFIX = "__devconsole_cell_" const val WITH_KEYWORD = "WITH" val READ_ONLY_KEYWORDS = setOf("SELECT", "PRAGMA", "EXPLAIN") val SENSITIVE_COLUMN_FRAGMENTS = diff --git a/sdk/full/src/main/kotlin/io/devconsole/AndroidMockRuleStore.kt b/sdk/full/src/main/kotlin/io/devconsole/AndroidMockRuleStore.kt index f8c116d..b0c8a79 100644 --- a/sdk/full/src/main/kotlin/io/devconsole/AndroidMockRuleStore.kt +++ b/sdk/full/src/main/kotlin/io/devconsole/AndroidMockRuleStore.kt @@ -180,10 +180,40 @@ internal class AndroidMockRuleStore( JSONObject() .put("type", "body_replacement") .put("body", body) + is MockAction.Sequence, is MockAction.MapRemote, is MockAction.Throttle -> toCompositeJson(depth) MockAction.Passthrough -> JSONObject().put("type", "passthrough") } } + /** Actions that wrap or redirect real traffic rather than answer it; split out to keep [toJson] readable. */ + private fun MockAction.toCompositeJson(depth: Int): JSONObject = + when (this) { + is MockAction.Sequence -> + JSONObject() + .put("type", "sequence") + .put("loop", loop) + .put( + "steps", + JSONArray().apply { + steps.forEach { put(it.toJson(depth + 1)) } + }, + ) + is MockAction.MapRemote -> + JSONObject() + .put("type", "map_remote") + .putNullable("scheme", scheme) + .putNullable("host", host) + .put("port", port ?: JSONObject.NULL) + .putNullable("path", path) + is MockAction.Throttle -> + JSONObject() + .put("type", "throttle") + .put("bytesPerSecond", bytesPerSecond) + .put("latencyMs", latencyMs) + .put("next", next.toJson(depth + 1)) + else -> error("${javaClass.simpleName} is not a composite mock action") + } + private fun JSONObject.toMockAction(depth: Int = 0): MockAction { require(depth <= MAX_ACTION_DEPTH) { "Persisted mock action nesting is too deep" } return when (getString("type")) { @@ -204,6 +234,29 @@ internal class AndroidMockRuleStore( "timeout" -> MockAction.Timeout(getLong("durationMs")) "status_override" -> MockAction.StatusOverride(getInt("statusCode")) "body_replacement" -> MockAction.BodyReplacement(getString("body")) + "sequence" -> { + val stepsArray = getJSONArray("steps") + MockAction.Sequence( + steps = + List(stepsArray.length()) { index -> + stepsArray.getJSONObject(index).toMockAction(depth + 1) + }, + loop = getBoolean("loop"), + ) + } + "map_remote" -> + MockAction.MapRemote( + scheme = nullableString("scheme"), + host = nullableString("host"), + port = if (isNull("port")) null else getInt("port"), + path = nullableString("path"), + ) + "throttle" -> + MockAction.Throttle( + bytesPerSecond = getLong("bytesPerSecond"), + latencyMs = getLong("latencyMs"), + next = getJSONObject("next").toMockAction(depth + 1), + ) "passthrough" -> MockAction.Passthrough else -> error("Unknown persisted mock action") } diff --git a/sdk/full/src/main/kotlin/io/devconsole/AndroidPreferencesInspector.kt b/sdk/full/src/main/kotlin/io/devconsole/AndroidPreferencesInspector.kt index 4efc91a..6c8f14c 100644 --- a/sdk/full/src/main/kotlin/io/devconsole/AndroidPreferencesInspector.kt +++ b/sdk/full/src/main/kotlin/io/devconsole/AndroidPreferencesInspector.kt @@ -6,6 +6,7 @@ package io.devconsole import android.content.Context import io.devconsole.security.RedactionEngine +import io.devconsole.security.RedactionPolicy import io.devconsole.server.api.PreferencesEntryData import io.devconsole.server.api.PreferencesFileData import io.devconsole.server.api.PreferencesInspector @@ -62,16 +63,22 @@ internal class AndroidPreferencesInspector( .commit() }.getOrDefault(false) - /** Only files inside the app's own `shared_prefs` dir are ever listed or written. */ + /** + * Only files inside the app's own `shared_prefs` dir are ever listed or written, and never + * DevConsole's own (`io.devconsole.mock_rules`, the inspector's `devconsole.ui`): they are SDK + * state, not the host's, and a hand edit there could corrupt the stored mock rules. + */ private fun preferenceFileNames(): List { val dir = File(context.applicationInfo.dataDir, SHARED_PREFS_DIR) return dir .listFiles { candidate -> candidate.isFile && candidate.name.endsWith(XML_SUFFIX) } ?.map { it.name.removeSuffix(XML_SUFFIX) } + ?.filterNot { name -> INTERNAL_PREFERENCE_PREFIXES.any(name::startsWith) } ?.sorted() .orEmpty() } + @Suppress("CyclomaticComplexMethod") // One exhaustive mapping keeps preference display and redaction in sync. private fun toEntry( key: String, value: Any?, @@ -88,13 +95,28 @@ internal class AndroidPreferencesInspector( } val raw = if (value is Set<*>) value.joinToString(", ") else value.toString() val redactable = value is String || value is Set<*> - val display = if (redactable) redaction.redactFields(mapOf(key to raw)).getValue(key) else raw - return PreferencesEntryData(key, display, type, redacted = redactable && display != raw) + val sensitiveKey = key.isSensitivePreferenceKey() + val display = + when { + sensitiveKey && redaction.isEnabled() -> redaction.replacement() + redactable -> redaction.redactFields(mapOf(key to raw)).getValue(key) + else -> raw + } + return PreferencesEntryData(key, display, type, redacted = (redactable || sensitiveKey) && display != raw) + } + + private fun String.isSensitivePreferenceKey(): Boolean { + val lowered = lowercase() + val collapsed = lowered.replace(KEY_SEPARATORS, "") + return lowered in SENSITIVE_KEY_NAMES || + collapsed in COLLAPSED_SENSITIVE_KEY_NAMES || + SENSITIVE_KEY_FRAGMENTS.any { collapsed.contains(it) } } private companion object { const val SHARED_PREFS_DIR = "shared_prefs" const val XML_SUFFIX = ".xml" + val INTERNAL_PREFERENCE_PREFIXES = listOf("io.devconsole.", "devconsole.") const val TYPE_BOOLEAN = "BOOLEAN" const val TYPE_INT = "INT" const val TYPE_LONG = "LONG" @@ -102,5 +124,26 @@ internal class AndroidPreferencesInspector( const val TYPE_STRING = "STRING" const val TYPE_STRING_SET = "STRING_SET" const val TYPE_UNKNOWN = "UNKNOWN" + val KEY_SEPARATORS = Regex("[-_.]") + + // Same idea as the database inspector's column fragments: app keys like `auth_token` or + // `apiKey` never match the HTTP field list exactly. + val SENSITIVE_KEY_FRAGMENTS = + setOf( + "password", + "passwd", + "secret", + "token", + "auth", + "credential", + "session", + "cookie", + "apikey", + "privatekey", + "accesskey", + ) + val SENSITIVE_KEY_NAMES = + RedactionPolicy.recommended().sensitiveFieldNames.mapTo(mutableSetOf()) { it.lowercase() } + val COLLAPSED_SENSITIVE_KEY_NAMES = SENSITIVE_KEY_NAMES.mapTo(mutableSetOf()) { it.replace(KEY_SEPARATORS, "") } } } diff --git a/sdk/full/src/main/kotlin/io/devconsole/AndroidRemoteConfigOverrideStore.kt b/sdk/full/src/main/kotlin/io/devconsole/AndroidRemoteConfigOverrideStore.kt new file mode 100644 index 0000000..095d129 --- /dev/null +++ b/sdk/full/src/main/kotlin/io/devconsole/AndroidRemoteConfigOverrideStore.kt @@ -0,0 +1,135 @@ +/** + * @author Shakib + * @since 04/11/26 + */ +package io.devconsole + +import android.content.Context +import android.content.SharedPreferences +import io.devconsole.remoteconfig.InMemoryRemoteConfigOverrideStore +import io.devconsole.remoteconfig.RemoteConfigOverrideListener +import io.devconsole.remoteconfig.RemoteConfigOverrideStore + +/** + * A [RemoteConfigOverrideStore] that keeps live overrides in memory and mirrors them to app-private + * SharedPreferences, so the values a developer is debugging with survive a process restart. + * + * Constructed without a [Context] because the facade owns one as a field before a runtime exists; + * [attach] supplies the context once, on the first [PlatformFacadeProvider.initialize]. Later calls + * are no-ops, which keeps a re-initialize from reloading the file over overrides the developer has + * edited since. + */ +internal class AndroidRemoteConfigOverrideStore : RemoteConfigOverrideStore { + private val delegate = InMemoryRemoteConfigOverrideStore() + private val lock = Any() + private var preferences: SharedPreferences? = null + + /** + * Binds this store to [context]'s SharedPreferences and merges the persisted overrides in. + * + * Persisted values never overwrite one set in memory before attach: an override applied during + * the window before initialize is user intent from the same session, and is the newer fact. + * Everything the store knows is written back afterwards, so a losing persisted value is + * replaced by the winning one rather than lingering in the file. + */ + fun attach(context: Context) { + val target = + runCatching { + context.applicationContext.getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE) + }.getOrNull() ?: return + synchronized(lock) { + if (preferences != null) return + preferences = target + loadPersisted(target) + writeAll(target) + } + } + + override fun overrides(): Map> = delegate.overrides() + + override fun setOverride( + providerId: String, + key: String, + value: String, + ) { + delegate.setOverride(providerId, key, value) + persist() + } + + override fun clearOverride( + providerId: String, + key: String, + ) { + delegate.clearOverride(providerId, key) + persist() + } + + override fun clearAll() { + delegate.clearAll() + persist() + } + + override fun addListener(listener: RemoteConfigOverrideListener) = delegate.addListener(listener) + + override fun removeListener(listener: RemoteConfigOverrideListener) = delegate.removeListener(listener) + + /** Invalid persisted keys/values are skipped; a corrupt file must never fail the host's initialize. */ + private fun loadPersisted(prefs: SharedPreferences) { + val existing = delegate.overrides() + val persisted = runCatching { prefs.all }.getOrDefault(emptyMap()) + persisted + .mapNotNull { (prefKey, value) -> + when (val stored = value) { + is String -> + decodeOverrideKey(prefKey)?.let { (providerId, key) -> + Triple(providerId, key, stored) + } + else -> null + } + }.filterNot { (providerId, key, _) -> existing[providerId]?.containsKey(key) == true } + .forEach { (providerId, key, value) -> runCatching { delegate.setOverride(providerId, key, value) } } + } + + private fun persist() { + synchronized(lock) { + preferences?.let(::writeAll) + } + } + + private fun writeAll(prefs: SharedPreferences) { + runCatching { + val editor = prefs.edit().clear() + delegate.overrides().forEach { (providerId, values) -> + values.forEach { (key, value) -> + editor.putString(encodeOverrideKey(providerId, key), value) + } + } + editor.apply() + } + } +} + +private const val PREFERENCES_NAME = "devconsole_remote_config_overrides" +private const val SEPARATOR = ':' + +private fun encodeOverrideKey( + providerId: String, + key: String, +): String = "${providerId.length}$SEPARATOR$providerId$key" + +/** + * The leading length is what makes the encoding reversible for a provider id containing the + * separator: the id's own colon cannot be mistaken for the one after its length. + */ +private fun decodeOverrideKey(encoded: String): Pair? { + val separatorIndex = encoded.indexOf(SEPARATOR) + val providerIdLength = if (separatorIndex > 0) encoded.substring(0, separatorIndex).toIntOrNull() else null + val providerIdStart = separatorIndex + 1 + val providerIdEnd = providerIdStart + (providerIdLength ?: 0) + val valid = providerIdLength != null && providerIdLength > 0 && providerIdEnd < encoded.length + return if (valid) { + encoded.substring(providerIdStart, providerIdEnd) to encoded.substring(providerIdEnd) + } else { + null + } +} diff --git a/sdk/full/src/main/kotlin/io/devconsole/CaptureGate.kt b/sdk/full/src/main/kotlin/io/devconsole/CaptureGate.kt new file mode 100644 index 0000000..987e459 --- /dev/null +++ b/sdk/full/src/main/kotlin/io/devconsole/CaptureGate.kt @@ -0,0 +1,35 @@ +/** + * @author Shakib + * @since 03/11/26 + */ +package io.devconsole + +import java.util.concurrent.atomic.AtomicBoolean + +/** + * Shared in-memory pause/resume gate consulted by live capture paths. + * + * When paused, new network transactions (those whose ID has not already been recorded), new socket + * connections, push events, and log lines are dropped before reaching any store or the timeline. + * Updates to an already-recorded network transaction still apply so in-flight requests finish cleanly. + */ +internal class CaptureGate( + initialPaused: Boolean = false, +) { + private val paused = AtomicBoolean(initialPaused) + + fun isPaused(): Boolean = paused.get() + + /** + * Updates the pause state and returns `true` when this call changed the state from its previous + * value, or `false` when it was already set to [value]. + */ + fun setPaused(value: Boolean): Boolean = paused.getAndSet(value) != value + + fun allowsNewCapture(): Boolean = !paused.get() + + fun allowsNetworkTransaction( + transactionId: String, + alreadyRecorded: (String) -> Boolean, + ): Boolean = !paused.get() || alreadyRecorded(transactionId) +} diff --git a/sdk/full/src/main/kotlin/io/devconsole/CapturePayloadCodec.kt b/sdk/full/src/main/kotlin/io/devconsole/CapturePayloadCodec.kt index a22ed0b..f557e5d 100644 --- a/sdk/full/src/main/kotlin/io/devconsole/CapturePayloadCodec.kt +++ b/sdk/full/src/main/kotlin/io/devconsole/CapturePayloadCodec.kt @@ -84,6 +84,7 @@ internal object CapturePayloadCodec { "url" to str(connection?.url), "openedAtEpochMs" to num(connection?.openedAtEpochMs), "reconnectAttempt" to num(connection?.reconnectAttempt), + "protocol" to str(connection?.protocol?.wireName), ), ) } diff --git a/sdk/full/src/main/kotlin/io/devconsole/CaptureTimeline.kt b/sdk/full/src/main/kotlin/io/devconsole/CaptureTimeline.kt index 0a02362..03a727e 100644 --- a/sdk/full/src/main/kotlin/io/devconsole/CaptureTimeline.kt +++ b/sdk/full/src/main/kotlin/io/devconsole/CaptureTimeline.kt @@ -121,10 +121,12 @@ internal class TeeingNetworkTransactionStore( private val bridge: CaptureTimelineBridge, private val activeSessionId: () -> String? = { null }, private val liveCaptureLock: Any = Any(), + private val captureGate: CaptureGate = CaptureGate(), ) : NetworkTransactionStore by delegate { override fun record(transaction: NetworkTransaction) { synchronized(liveCaptureLock) { if (transaction.sessionId != null && transaction.sessionId != activeSessionId()) return + if (!captureGate.allowsNetworkTransaction(transaction.id) { delegate.find(it) != null }) return delegate.record(transaction) val request = transaction.capture.request val status = transaction.capture.response?.statusCode @@ -179,6 +181,7 @@ internal class TeeingSocketStore( private val delegate: SocketStore, private val bridge: CaptureTimelineBridge, private val liveCaptureLock: Any = Any(), + private val captureGate: CaptureGate = CaptureGate(), ) : SocketStore by delegate { private val lifecycleKeys = linkedSetOf() @@ -188,6 +191,7 @@ internal class TeeingSocketStore( override fun open(connection: SocketConnection) { synchronized(liveCaptureLock) { + if (!captureGate.allowsNewCapture() && delegate.connection(connection.id) == null) return delegate.open(connection) emitLifecycleOnce( SocketLifecycleEvent( @@ -331,9 +335,11 @@ internal class TeeingPushStore( private val delegate: PushStore, private val bridge: CaptureTimelineBridge, private val liveCaptureLock: Any = Any(), + private val captureGate: CaptureGate = CaptureGate(), ) : PushStore by delegate { override fun append(event: PushEvent) { synchronized(liveCaptureLock) { + if (!captureGate.allowsNewCapture()) return delegate.append(event) // Fail-open: a push can be recorded before the runtime session exists (no // sessionIdOverride here, so bridge.emit falls back to resolving one), which throws diff --git a/sdk/full/src/main/kotlin/io/devconsole/ComposerCollectionJson.kt b/sdk/full/src/main/kotlin/io/devconsole/ComposerCollectionJson.kt new file mode 100644 index 0000000..127d8fb --- /dev/null +++ b/sdk/full/src/main/kotlin/io/devconsole/ComposerCollectionJson.kt @@ -0,0 +1,171 @@ +/** + * @author Shakib + * @since 03/11/26 + * + * One small to/from pair per composer type keeps the codec readable; splitting it would scatter the format. + */ +@file:Suppress("TooManyFunctions") + +package io.devconsole + +import io.devconsole.composer.ComposerBinaryBody +import io.devconsole.composer.ComposerBodyType +import io.devconsole.composer.ComposerCollection +import io.devconsole.composer.ComposerMultipartPart +import io.devconsole.composer.ComposerQueryParameter +import io.devconsole.composer.ComposerRequest +import io.devconsole.composer.ComposerVariable +import org.json.JSONArray +import org.json.JSONObject + +// JSON codec for persisted composer collections; secret variable values are blanked on write. + +private const val DEFAULT_TIMEOUT_MS = 15_000 +private const val HEX_RADIX = 16 +private const val NIBBLE_BITS = 4 + +internal fun ComposerCollection.toJson(): JSONObject = + JSONObject() + .put("name", name) + .put("request", request.toJson()) + +private fun ComposerRequest.toJson(): JSONObject { + val json = JSONObject() + json.put("method", method) + json.put("url", url) + json.put("headers", headers.toJsonObject()) + json.put("body", body ?: JSONObject.NULL) + json.put("bodyType", bodyType.name) + json.put("timeoutMs", timeoutMs) + json.put("followRedirects", followRedirects) + json.put("query", query.map(ComposerQueryParameter::toJson).toJsonArray()) + json.put("formFields", formFields.toJsonObject()) + json.put("multipartParts", multipartParts.map(ComposerMultipartPart::toJson).toJsonArray()) + json.put("variables", variables.map(ComposerVariable::toJson).toJsonArray()) + binaryBody?.let { json.put("binaryBody", it.toJson()) } + return json +} + +private fun ComposerQueryParameter.toJson(): JSONObject = + JSONObject() + .put("name", name) + .put("value", value) + +private fun ComposerMultipartPart.toJson(): JSONObject { + val json = JSONObject() + json.put("name", name) + json.put("value", value) + fileName?.let { json.put("fileName", it) } + contentType?.let { json.put("contentType", it) } + return json +} + +private fun ComposerBinaryBody.toJson(): JSONObject = + JSONObject() + .put("fileName", fileName) + .put("contentType", contentType) + .put("bytes", byteArrayToHex(bytes)) + +private fun ComposerVariable.toJson(): JSONObject = + JSONObject() + .put("name", name) + .put("value", if (secret) "" else value) + .put("secret", secret) + +private fun Map.toJsonObject(): JSONObject = + JSONObject().apply { + forEach { (key, value) -> put(key, value) } + } + +private fun List.toJsonArray(): JSONArray = + JSONArray().apply { + forEach { put(it) } + } + +internal fun JSONObject.toComposerRequest(): ComposerRequest { + val method = getString("method") + val url = getString("url") + val headers = optJSONObject("headers")?.toStringMap() ?: emptyMap() + val body = if (isNull("body")) null else optString("body", "") + val bodyTypeName = optString("bodyType", ComposerBodyType.NONE.name) + val bodyType = runCatching { ComposerBodyType.valueOf(bodyTypeName) }.getOrDefault(ComposerBodyType.NONE) + val timeoutMs = optInt("timeoutMs", DEFAULT_TIMEOUT_MS) + val followRedirects = optBoolean("followRedirects", true) + val query = optJSONArray("query")?.toQueryList() ?: emptyList() + val formFields = optJSONObject("formFields")?.toStringMap() ?: emptyMap() + val multipartParts = optJSONArray("multipartParts")?.toMultipartList() ?: emptyList() + val variables = optJSONArray("variables")?.toVariableList() ?: emptyList() + val binaryBody = optJSONObject("binaryBody")?.toBinaryBody() + return ComposerRequest( + method = method, + url = url, + headers = headers, + body = body, + query = query, + bodyType = bodyType, + formFields = formFields, + multipartParts = multipartParts, + binaryBody = binaryBody, + timeoutMs = timeoutMs, + followRedirects = followRedirects, + variables = variables, + ) +} + +private fun JSONObject.toStringMap(): Map = + buildMap { + keys().forEach { key -> put(key, getString(key)) } + } + +private fun JSONArray.toQueryList(): List = + List(length()) { index -> + val item = getJSONObject(index) + ComposerQueryParameter(item.getString("name"), item.getString("value")) + } + +private fun JSONArray.toMultipartList(): List = + List(length()) { index -> + val item = getJSONObject(index) + ComposerMultipartPart( + name = item.getString("name"), + value = item.getString("value"), + fileName = if (item.isNull("fileName")) null else item.optString("fileName"), + contentType = if (item.isNull("contentType")) null else item.optString("contentType"), + ) + } + +private fun JSONObject.toBinaryBody(): ComposerBinaryBody = + ComposerBinaryBody( + fileName = getString("fileName"), + contentType = getString("contentType"), + bytes = hexToByteArray(optString("bytes", "")), + ) + +private fun JSONArray.toVariableList(): List = + List(length()) { index -> + val item = getJSONObject(index) + ComposerVariable( + name = item.getString("name"), + value = item.optString("value", ""), + secret = item.optBoolean("secret", false), + ) + } + +private fun byteArrayToHex(bytes: ByteArray): String = + buildString(bytes.size * 2) { + for (byte in bytes) { + append("%02x".format(byte)) + } + } + +private fun hexToByteArray(hex: String): ByteArray { + val digits = hex.map { Character.digit(it, HEX_RADIX) } + val valid = digits.size % 2 == 0 && digits.none { it == -1 } + return if (valid) { + ByteArray(digits.size / 2) { index -> + ((digits[index * 2] shl NIBBLE_BITS) + digits[index * 2 + 1]).toByte() + } + } else { + byteArrayOf() + } +} diff --git a/sdk/full/src/main/kotlin/io/devconsole/CrashCapture.kt b/sdk/full/src/main/kotlin/io/devconsole/CrashCapture.kt index 208fe61..d45424f 100644 --- a/sdk/full/src/main/kotlin/io/devconsole/CrashCapture.kt +++ b/sdk/full/src/main/kotlin/io/devconsole/CrashCapture.kt @@ -14,6 +14,7 @@ import io.devconsole.timeline.TimelineAppender import kotlinx.coroutines.CancellationException import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withTimeoutOrNull +import java.io.File import java.util.UUID import java.util.concurrent.atomic.AtomicBoolean import java.util.concurrent.atomic.AtomicLong @@ -42,8 +43,11 @@ internal enum class CrashKind { UNCAUGHT, ANR } * round trips, not three -- before the previously installed handler -- and, downstream of it, the * host's own crash reporter -- ever runs. That is a description of the normal-case latency, not a * hard ceiling against a genuinely wedged transaction. + * + * Suppressions: every collaborator is injected so the capture path stays unit-testable, and + * install/record/persist/pending-crash recovery all share the same crash-path state. */ -@Suppress("LongParameterList") // Every collaborator is injected so the capture path stays unit-testable. +@Suppress("LongParameterList", "TooManyFunctions") internal class CrashCapture( private val sessionId: () -> String, private val redaction: RedactionEngine, @@ -63,6 +67,7 @@ internal class CrashCapture( * cost the crash record itself -- and never extends the synchronous crash-path budget either. */ private val evidenceStore: () -> EvidenceStore? = { null }, + private val pendingCrashFile: () -> File? = { null }, ) { constructor( sessionId: String, @@ -74,6 +79,8 @@ internal class CrashCapture( private val installed = AtomicBoolean(false) + @Volatile private var enabled = true + @Volatile private var previousHandler: Thread.UncaughtExceptionHandler? = null /** @@ -81,25 +88,89 @@ internal class CrashCapture( * crash reporter would be a far worse bug than anything this captures. */ fun install() { + enabled = true if (!installed.compareAndSet(false, true)) return previousHandler = Thread.getDefaultUncaughtExceptionHandler() - Thread.setDefaultUncaughtExceptionHandler { thread, throwable -> - try { - runCatching { - record( - CrashKind.UNCAUGHT, - thread.name, - throwable.stackTraceToString(), - describe(throwable), - ) + val chainedHandler = + Thread.UncaughtExceptionHandler { thread, throwable -> + if (!enabled) { + previousHandler?.uncaughtException(thread, throwable) + return@UncaughtExceptionHandler + } + try { + val event = + runCatching { + createEvent( + CrashKind.UNCAUGHT, + thread.name, + throwable.stackTraceToString(), + describe(throwable), + ) + }.getOrNull() + if (event == null) { + writePendingCrash(throwable) + } else { + runCatching { appender()?.append(event) } + if (!persistNow(event, CrashKind.UNCAUGHT, thread.name)) writePendingCrash(throwable) + } + } finally { + runCatching { markCrashed() } + runCatching { previousHandler?.uncaughtException(thread, throwable) } } - } finally { - runCatching { markCrashed() } } - previousHandler?.uncaughtException(thread, throwable) + Thread.setDefaultUncaughtExceptionHandler(chainedHandler) + installedHandler = chainedHandler + } + + @Volatile private var installedHandler: Thread.UncaughtExceptionHandler? = null + + fun disable() { + enabled = false + if (Thread.getDefaultUncaughtExceptionHandler() === installedHandler) { + Thread.setDefaultUncaughtExceptionHandler(previousHandler) } } + fun importPendingCrash( + file: File, + sessionId: String, + ) { + runCatching { + PendingCrashFile.read(file)?.let { (summary, trace) -> + persistPendingCrash(file, sessionId, summary, trace) + } + }.onFailure { logcatInfo("DevConsole", "Pending crash import failed: ${it.javaClass.simpleName}") } + } + + private fun persistPendingCrash( + file: File, + sessionId: String, + summary: String, + trace: String, + ) { + val event = + StoredEvent( + id = UUID.randomUUID().toString(), + sessionId = sessionId, + sequence = nextSequence(), + pluginId = PLUGIN_ID, + type = "uncaught", + wallTimeMs = System.currentTimeMillis(), + monoTimeNs = System.nanoTime(), + severity = SEVERITY_ERROR, + summary = + redaction.redactText( + "Previous launch crashed before storage was ready - $summary", + SUMMARY_CHARS, + ), + tagsJson = "{\"kind\":\"UNCAUGHT\",\"thread\":\"previous-launch\"}", + payloadJson = payloadJson(trace), + ) + val eventStore = store() ?: return + runBlocking { eventStore.insert(listOf(event)) } + file.delete() + } + /** * Called from [AnrWatchdog]'s own daemon thread. Wrapped in [runCatching] exactly like the * uncaught-exception path in [install] -- a failure while *capturing* an ANR must never itself @@ -119,28 +190,33 @@ internal class CrashCapture( stackTrace: String, summary: String, ) { - val event = - StoredEvent( - id = UUID.randomUUID().toString(), - sessionId = sessionId(), - sequence = nextSequence(), - pluginId = PLUGIN_ID, - type = kind.name.lowercase(), - wallTimeMs = System.currentTimeMillis(), - monoTimeNs = System.nanoTime(), - severity = SEVERITY_ERROR, - summary = summary.take(SUMMARY_CHARS), - tagsJson = """{"kind":"${kind.name}","thread":"${threadName.escapeJson()}"}""", - payloadJson = payloadJson(stackTrace), - ) + val event = createEvent(kind, threadName, stackTrace, summary) // A throwing appender must never escape record(): on the ANR watchdog thread there is no - // caller-side try/catch the way install()'s uncaught-exception handler has one, so an - // unguarded throw here would itself become an uncaught exception and -- once install() has - // run -- take the whole host process down over a failed *capture* of a stall. + // caller-side try/catch the way install()'s uncaught-exception handler has one. runCatching { appender()?.append(event) } persistNow(event, kind, threadName) } + private fun createEvent( + kind: CrashKind, + threadName: String, + stackTrace: String, + summary: String, + ): StoredEvent = + StoredEvent( + id = UUID.randomUUID().toString(), + sessionId = sessionId(), + sequence = nextSequence(), + pluginId = PLUGIN_ID, + type = kind.name.lowercase(), + wallTimeMs = System.currentTimeMillis(), + monoTimeNs = System.nanoTime(), + severity = SEVERITY_ERROR, + summary = redaction.redactText(summary.take(SUMMARY_CHARS), SUMMARY_CHARS), + tagsJson = """{"kind":"${kind.name}","thread":"${threadName.escapeJson()}"}""", + payloadJson = payloadJson(stackTrace), + ) + /** * Flags [event] into the evidence tray, kind CRASH, keyed by the crash event's own id so a * later manual re-flag through `POST /api/v1/evidence` (same subject id) is idempotent against @@ -244,16 +320,17 @@ internal class CrashCapture( event: StoredEvent, kind: CrashKind, threadName: String, - ) { + ): Boolean = runCatching { runBlocking { withTimeoutOrNull(PERSIST_TIMEOUT_MS) { - store()?.insert(listOf(event)) + val eventStore = store() ?: return@withTimeoutOrNull false + eventStore.insert(listOf(event)) autoFlagCrash(event, kind, threadName) + true } } - } - } + }.getOrDefault(false) == true private fun markCrashed() { val activeSessionId = sessionId() @@ -272,6 +349,17 @@ internal class CrashCapture( return "${throwable.javaClass.simpleName}: $detail" } + private fun writePendingCrash(throwable: Throwable) { + runCatching { + val file = pendingCrashFile() ?: return + PendingCrashFile.write( + file, + describe(throwable).take(SUMMARY_CHARS), + throwable.stackTraceToString().take(policy().maxStackChars.coerceAtLeast(1)), + ) + } + } + private companion object { const val PLUGIN_ID = "crash" const val SEVERITY_ERROR = 4 diff --git a/sdk/full/src/main/kotlin/io/devconsole/DevConsoleForegroundService.kt b/sdk/full/src/main/kotlin/io/devconsole/DevConsoleForegroundService.kt index 496efdf..19d8e50 100644 --- a/sdk/full/src/main/kotlin/io/devconsole/DevConsoleForegroundService.kt +++ b/sdk/full/src/main/kotlin/io/devconsole/DevConsoleForegroundService.kt @@ -4,6 +4,7 @@ */ package io.devconsole +import android.app.Notification import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent @@ -41,11 +42,23 @@ internal class DevConsoleForegroundService : Service() { runCatching { promoteToForeground(intent.getStringExtra(EXTRA_ENDPOINT_URL).orEmpty()) }.onFailure { - // API 31+ can throw ForegroundServiceStartNotAllowedException/SecurityException - // from a background start; without a matching startForeground call the OS - // watchdog kills the process for "did not call startForeground in time" -- stop - // ourselves first so that never fires. + // Keep the started-service contract satisfied when notification setup fails. logcatInfo("DevConsole", "Foreground promotion failed: ${it.javaClass.simpleName}") + runCatching { + ServiceCompat.startForeground( + this, + NOTIFICATION_ID, + fallbackNotification(), + foregroundServiceType(), + ) + }.onFailure { promotionFailure -> + if (!isForegroundStartNotAllowed(promotionFailure)) { + logcatInfo( + "DevConsole", + "Foreground fallback failed: ${promotionFailure.javaClass.simpleName}", + ) + } + } stopSelf() } } @@ -60,27 +73,43 @@ internal class DevConsoleForegroundService : Service() { // the correct "no type" sentinel ServiceCompat.startForeground expects below API 34; androidx's // own ServiceCompat internals suppress the same warning. private fun promoteToForeground(endpointUrl: String) { - createNotificationChannel() val notification = - NotificationCompat - .Builder(this, CHANNEL_ID) - .setSmallIcon(R.drawable.devconsole_notification) - .setLargeIcon(BitmapFactory.decodeResource(resources, R.drawable.devconsole_logo)) - .setContentTitle("Dev Console server running") - .setContentText(endpointUrl) - .setOngoing(true) - .setContentIntent(hostLaunchIntent()) - .addAction(0, "Stop server", stopActionIntent()) - .build() - val foregroundServiceType = - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) { - ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE - } else { - ServiceInfo.FOREGROUND_SERVICE_TYPE_NONE - } - ServiceCompat.startForeground(this, NOTIFICATION_ID, notification, foregroundServiceType) + runCatching { + createNotificationChannel() + NotificationCompat + .Builder(this, CHANNEL_ID) + .setSmallIcon(R.drawable.devconsole_notification) + .setLargeIcon(BitmapFactory.decodeResource(resources, R.drawable.devconsole_logo)) + .setContentTitle("Dev Console server running") + .setContentText(endpointUrl) + .setOngoing(true) + .setContentIntent(hostLaunchIntent()) + .addAction(0, "Stop server", stopActionIntent()) + .build() + }.getOrElse { fallbackNotification() } + ServiceCompat.startForeground(this, NOTIFICATION_ID, notification, foregroundServiceType()) } + @Suppress("DEPRECATION") // FOREGROUND_SERVICE_TYPE_NONE: see promoteToForeground. + private fun foregroundServiceType(): Int = + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) { + ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE + } else { + ServiceInfo.FOREGROUND_SERVICE_TYPE_NONE + } + + private fun fallbackNotification(): Notification = + NotificationCompat + .Builder(this, CHANNEL_ID) + .setSmallIcon(android.R.drawable.stat_notify_sync) + .setContentTitle("Dev Console") + .setContentText("Server is stopping") + .setOngoing(true) + .build() + + private fun isForegroundStartNotAllowed(error: Throwable): Boolean = + error.javaClass.name == "android.app.ForegroundServiceStartNotAllowedException" + private fun stopServerAndSelf() { // Same public stop path the dashboard uses; PlatformFacadeProvider's stopLocked will also // call stopService, which is a harmless no-op once this instance has stopped itself. diff --git a/sdk/full/src/main/kotlin/io/devconsole/DevConsoleInitializer.kt b/sdk/full/src/main/kotlin/io/devconsole/DevConsoleInitializer.kt index b429c9a..9b8ae46 100644 --- a/sdk/full/src/main/kotlin/io/devconsole/DevConsoleInitializer.kt +++ b/sdk/full/src/main/kotlin/io/devconsole/DevConsoleInitializer.kt @@ -6,7 +6,9 @@ import android.content.ContentValues import android.content.pm.ApplicationInfo import android.database.Cursor import android.net.Uri +import android.os.Build import io.devconsole.api.DevConsoleState +import java.io.File /** * Auto-initializes DevConsole on app startup in debug builds so developers do not need @@ -15,7 +17,7 @@ import io.devconsole.api.DevConsoleState class DevConsoleInitializer : ContentProvider() { override fun onCreate(): Boolean { val app = context?.applicationContext as? Application - if (app != null && app.isDebuggable() && DevConsole.state().value is DevConsoleState.Uninitialized) { + if (app != null && shouldInitialize(app)) { // Zero-config startup: the runtime is ready (state/timeline/capture) without the host // writing any Application.onCreate boilerplate. The browser server itself is never // auto-started -- call DevConsole.startBrowser()/startBrowserAsync() explicitly. @@ -24,12 +26,29 @@ class DevConsoleInitializer : ContentProvider() { return true } + private fun shouldInitialize(app: Application): Boolean = + app.isDebuggable() && isMainProcess(app) && DevConsole.state().value is DevConsoleState.Uninitialized + /** * Runtime backstop, independent of the Gradle variant policy: if `sdk:full` ever reaches a * non-debuggable build, auto-initialization must not happen anyway. */ private fun Application.isDebuggable(): Boolean = applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE != 0 + private fun isMainProcess(application: Application): Boolean = + isMainProcessName( + currentProcessName = if (Build.VERSION.SDK_INT >= 28) Application.getProcessName() else readProcessName(), + applicationProcessName = application.applicationInfo.processName, + packageName = application.packageName, + ) + + private fun readProcessName(): String? = + runCatching { + File( + "/proc/self/cmdline", + ).readText().substringBefore('\u0000').trim().takeIf(String::isNotEmpty) + }.getOrNull() + override fun query( uri: Uri, projection: Array?, @@ -57,4 +76,16 @@ class DevConsoleInitializer : ContentProvider() { selection: String?, selectionArgs: Array?, ): Int = 0 + + internal companion object { + /** Auto-init belongs to the app's main process only; `:remote`-style processes skip it. */ + fun isMainProcessName( + currentProcessName: String?, + applicationProcessName: String?, + packageName: String, + ): Boolean { + val expected = applicationProcessName?.takeIf(String::isNotBlank) ?: packageName + return currentProcessName == expected + } + } } diff --git a/sdk/full/src/main/kotlin/io/devconsole/FileComposerCollectionStore.kt b/sdk/full/src/main/kotlin/io/devconsole/FileComposerCollectionStore.kt new file mode 100644 index 0000000..177cad8 --- /dev/null +++ b/sdk/full/src/main/kotlin/io/devconsole/FileComposerCollectionStore.kt @@ -0,0 +1,136 @@ +/** + * @author Shakib + * @since 03/11/26 + */ +package io.devconsole + +import io.devconsole.composer.ComposerCollection +import io.devconsole.composer.ComposerCollectionStore +import io.devconsole.composer.ComposerRequest +import io.devconsole.composer.InMemoryComposerCollectionStore +import org.json.JSONArray +import org.json.JSONObject +import java.io.File +import java.io.FileOutputStream +import java.io.OutputStreamWriter +import java.nio.charset.StandardCharsets + +/** + * File-backed [ComposerCollectionStore] that keeps an in-memory delegate as the source of truth, + * lazily deserializes from disk on first access, and persists state atomically after every save or remove. + */ +internal class FileComposerCollectionStore( + private val file: File, + private val delegate: InMemoryComposerCollectionStore = InMemoryComposerCollectionStore(), +) : ComposerCollectionStore { + private val lock = Any() + private var loaded = false + + override fun save( + name: String, + request: ComposerRequest, + ): ComposerCollection = + synchronized(lock) { + ensureLoaded() + val collection = delegate.save(name, request) + persistLocked() + collection + } + + override fun collections(): List = + synchronized(lock) { + ensureLoaded() + delegate.collections() + } + + override fun remove(id: String): Boolean = + synchronized(lock) { + ensureLoaded() + val removed = delegate.remove(id) + if (removed) { + persistLocked() + } + removed + } + + private fun ensureLoaded() { + if (loaded) return + loaded = true + loadFromDisk() + } + + private fun loadFromDisk() { + if (!file.exists()) return + val restored = + runCatching { + val root = JSONObject(file.readText(StandardCharsets.UTF_8)) + // A newer-version file is set aside rather than overwritten on the next save. + check(root.optInt(KEY_VERSION, -1) == CURRENT_VERSION) { "Unsupported collections file version" } + val array = root.getJSONArray(KEY_COLLECTIONS) + List(array.length()) { index -> + val item = array.getJSONObject(index) + item.getString("name") to item.getJSONObject("request").toComposerRequest() + } + }.getOrNull() + if (restored == null) { + quarantineCorruptFile() + } else { + restored.forEach { (name, request) -> delegate.save(name, request) } + } + } + + private fun quarantineCorruptFile() { + runCatching { + val corrupt = file.resolveSibling(file.name + CORRUPT_EXTENSION) + if (file.renameTo(corrupt)) return@runCatching + file.inputStream().use { input -> + corrupt.outputStream().use(input::copyTo) + } + file.delete() + } + } + + private fun persistLocked() { + runCatching { + file.parentFile?.mkdirs() + val root = JSONObject() + root.put(KEY_VERSION, CURRENT_VERSION) + val array = JSONArray() + for (collection in delegate.collections()) { + array.put(collection.toJson()) + } + root.put(KEY_COLLECTIONS, array) + val tmp = file.resolveSibling(file.name + TMP_EXTENSION) + writeStringToFile(tmp, root.toString()) + moveAtomically(tmp, file) + } + } + + private fun writeStringToFile( + target: File, + content: String, + ) { + OutputStreamWriter(FileOutputStream(target), StandardCharsets.UTF_8).use { writer -> + writer.write(content) + } + } + + private fun moveAtomically( + source: File, + destination: File, + ) { + if (source.renameTo(destination)) return + source.inputStream().use { input -> + destination.outputStream().use(input::copyTo) + } + source.delete() + } + + private companion object { + private const val CURRENT_VERSION = 1 + private const val KEY_VERSION = "v" + private const val KEY_COLLECTIONS = "collections" + private const val TMP_EXTENSION = ".tmp" + private const val CORRUPT_EXTENSION = ".corrupt" + } +} diff --git a/sdk/full/src/main/kotlin/io/devconsole/FullInspectorDataSource.kt b/sdk/full/src/main/kotlin/io/devconsole/FullInspectorDataSource.kt index 65d775d..f5c3b12 100644 --- a/sdk/full/src/main/kotlin/io/devconsole/FullInspectorDataSource.kt +++ b/sdk/full/src/main/kotlin/io/devconsole/FullInspectorDataSource.kt @@ -2,7 +2,7 @@ * @author Shakib * @since 24/07/26 */ -@file:Suppress("TooManyFunctions") // Adapter of many small engine→UI mapper functions. +@file:Suppress("TooManyFunctions", "LargeClass") // Cohesive adapter of the full runtime's inspector capabilities. package io.devconsole @@ -51,6 +51,8 @@ import io.devconsole.socket.SocketConnection import io.devconsole.socket.SocketMessage import io.devconsole.socket.SocketPayload import io.devconsole.socket.SocketProtocol +import io.devconsole.socket.SocketSendRequest +import io.devconsole.socket.SocketSendResult import io.devconsole.socket.SocketStore import io.devconsole.state.FeatureFlag import io.devconsole.state.FeatureFlagProvider @@ -83,6 +85,7 @@ import io.devconsole.ui.compose.InspectorFileListingUi import io.devconsole.ui.compose.InspectorFilePreviewUi import io.devconsole.ui.compose.InspectorHealthUi import io.devconsole.ui.compose.InspectorLogUi +import io.devconsole.ui.compose.InspectorMockActionType import io.devconsole.ui.compose.InspectorMockRuleUi import io.devconsole.ui.compose.InspectorPreferenceEntryUi import io.devconsole.ui.compose.InspectorPreferenceFileUi @@ -92,6 +95,7 @@ import io.devconsole.ui.compose.InspectorRemoteConfigEntryUi import io.devconsole.ui.compose.InspectorRemoteConfigUi import io.devconsole.ui.compose.InspectorRetentionUi import io.devconsole.ui.compose.InspectorServerStartPermissionProvider +import io.devconsole.ui.compose.InspectorSessionCaptures import io.devconsole.ui.compose.InspectorSessionUi import io.devconsole.ui.compose.InspectorSnapshot import io.devconsole.ui.compose.InspectorSocketFrameUi @@ -132,6 +136,12 @@ internal class FullInspectorDataSource( * which reads as "no remote config" rather than as an error. */ private val remoteConfigRegistry: RemoteConfigRegistry? = null, + /** + * Whether the developer may edit local overrides on this surface. Wired by + * `PlatformFacadeProvider` to the live STATE-category/feature-flag capability pair, so turning + * either off withdraws the editor without tearing the registry down. + */ + private val remoteConfigOverridesEditable: () -> Boolean = { false }, /** * 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 @@ -149,6 +159,11 @@ internal class FullInspectorDataSource( /** Backed by `SessionAuthority.revokeIfPresent`; returns false for an unknown/already-expired id. */ private val revokePrincipalHandler: (id: String) -> Boolean = { false }, private val retainedCaptures: RetainedCaptureQuery? = null, + /** Past-run network/socket/push views; null keeps every past run's traffic tabs empty. */ + private val retainedSessions: RetainedSessionCaptures? = null, + /** Same delete/pin as the dashboard's run controls; false means the run was refused. */ + private val deleteRunHandler: suspend (sessionId: String) -> Boolean = { false }, + private val pinRunHandler: suspend (sessionId: String, pinned: Boolean) -> Boolean = { _, _ -> false }, /** * Resolves a real [java.io.File] for the Compose Files screen's Share action. `FileInspector` * itself never exposes `java.io.File` (it stays platform-neutral), so this comes from @@ -211,9 +226,8 @@ internal class FullInspectorDataSource( override suspend fun logsForSession(sessionId: String?): List = retainedCaptures - ?.events(sessionId) + ?.events(sessionId, pluginIds = setOf(LOGS_PLUGIN_ID, CRASH_PLUGIN_ID)) .orEmpty() - .filter { it.pluginId == LOGS_PLUGIN_ID || it.pluginId == CRASH_PLUGIN_ID } .asReversed() .take(SNAPSHOT_LOG_LIMIT) .map { it.toLogUi() } @@ -221,13 +235,68 @@ internal class FullInspectorDataSource( /** Session-scoped counterpart of [logsForSession] for the Crashes tab; same retained-store read, crash-only. */ override suspend fun crashesForSession(sessionId: String?): List = retainedCaptures - ?.events(sessionId) + ?.events(sessionId, pluginIds = setOf(CRASH_PLUGIN_ID)) .orEmpty() - .filter { it.pluginId == CRASH_PLUGIN_ID } .asReversed() .take(SNAPSHOT_LOG_LIMIT) .map { it.toCrashUi() } + override suspend fun setSessionPinned( + sessionId: String, + pinned: Boolean, + ): InspectorCommandResult = + if (runCatching { pinRunHandler(sessionId, pinned) }.getOrDefault(false)) { + InspectorCommandResult.Success(summary = if (pinned) "Run pinned" else "Run unpinned") + } else { + InspectorCommandResult.Invalid("This run cannot be pinned") + } + + override suspend fun deleteSession(sessionId: String): InspectorCommandResult = + if (runCatching { deleteRunHandler(sessionId) }.getOrDefault(false)) { + InspectorCommandResult.Success(summary = "Run deleted") + } else { + InspectorCommandResult.Invalid("This run cannot be deleted") + } + + override suspend fun capturesForSession(sessionId: String?): InspectorSessionCaptures { + val categories = configSupplier()?.captureCategories ?: CaptureCategory.all() + val retained = retainedSessions + return when { + sessionId == null -> + InspectorSessionCaptures( + transactions = transactionsFor(categories, InspectorTrafficQuery()), + sockets = socketsFor(categories), + pushEvents = pushEventsFor(categories), + ) + retained == null -> InspectorSessionCaptures() + else -> retained.capturesFor(sessionId, categories) + } + } + + private suspend fun RetainedSessionCaptures.capturesFor( + sessionId: String, + categories: Set, + ): InspectorSessionCaptures = + InspectorSessionCaptures( + transactions = + if (CaptureCategory.NETWORK in categories) { + networkStore(sessionId).page(InspectorTrafficQuery().toEngineQuery()).transactions.map { it.toUi() } + } else { + emptyList() + }, + sockets = + sockets(sessionId) + .filter { it.protocol.enabledIn(categories) } + .take(SNAPSHOT_SOCKET_LIMIT) + .map { it.toUi() }, + pushEvents = + if (CaptureCategory.PUSH in categories) { + pushEvents(sessionId).take(SNAPSHOT_PUSH_LIMIT).map { it.toUi() } + } else { + emptyList() + }, + ) + override suspend fun flaggedTransactionIds(): Set { val store = evidenceStore ?: return emptySet() return store @@ -454,6 +523,8 @@ internal class FullInspectorDataSource( source = entry.source.wireName, redacted = entry.redacted, truncated = entry.truncated, + providerValue = entry.providerValue, + providerSource = entry.providerSource?.wireName, ) }, lastFetchEpochMs = snapshot.fetchInfo.lastFetchEpochMs, @@ -466,20 +537,39 @@ internal class FullInspectorDataSource( private fun readStateProviders(): List { val registry = stateRegistry ?: return emptyList() - return registry.providerIds().mapNotNull { id -> - val snapshot = registry.snapshot(id) ?: return@mapNotNull null - InspectorStateProviderUi( - id = id, - entries = - snapshot.values.map { (key, value) -> - InspectorStateEntryUi( - key = key, - value = value.toDisplay(), - redacted = value is StateValue.Redacted, + return registry + .providerIds() + .map { id -> + val snapshot = runCatching { registry.snapshot(id) } + snapshot.fold( + onSuccess = { value -> + if (value == null) return@map null + InspectorStateProviderUi( + id = id, + entries = + value.values.map { (key, stateValue) -> + InspectorStateEntryUi( + key, + stateValue.toDisplay(), + stateValue is StateValue.Redacted, + ) + }, ) }, - ) - } + onFailure = { error -> + InspectorStateProviderUi( + id, + listOf( + InspectorStateEntryUi( + "error", + error.message ?: "Provider unavailable", + false, + ), + ), + ) + }, + ) + }.filterNotNull() } private fun readLogs(): List { @@ -539,9 +629,13 @@ internal class FullInspectorDataSource( ) return try { val execution = composerExecutor.execute(composerRequest) { url -> permitsComposerHost(config, url) } + val statusCode = execution.response.statusCode + val summary = + "${request.method} ${request.url} -> $statusCode" + + (execution.response.durationMs?.let { " · $it ms" } ?: "") InspectorCommandResult.Success( - summary = "${request.method} ${request.url} -> ${execution.response.statusCode}", - statusCode = execution.response.statusCode, + summary = summary, + statusCode = statusCode, body = execution.response.body, ) } catch (rejected: ComposerDestinationRejectedException) { @@ -566,64 +660,127 @@ internal class FullInspectorDataSource( override fun mockRules(): List = mockEngine.rules().map { it.toUi(mockEngine.stats(it.id)) } /** - * Invalid id/status/scope/delay input surfaces as [InspectorCommandResult.Invalid]; an invalid - * path or body regular expression is only discovered when [MockEngine.upsert] compiles it, so - * that failure surfaces as [InspectorCommandResult.Failed] instead. A positive [InspectorMockRuleUi.delayMs] - * wraps the response in [MockAction.Delay], mirroring what the browser dashboard's mock-rule form - * can express; zero or absent stays a plain [MockAction.StaticResponse]. + * Builds the [MockAction] named by [InspectorMockRuleUi.actionType] and carries the rule's + * predicates. Invalid id/status/scope/delay or an out-of-range throttle/timeout/map-remote value + * surfaces as [InspectorCommandResult.Invalid]; an invalid path or body regular expression is + * only discovered when [MockEngine.upsert] compiles it, so that failure surfaces as + * [InspectorCommandResult.Failed] instead. [InspectorMockActionType.OTHER] is refused rather than + * clobbering a sequence/template rule the form cannot express. */ override fun upsertMockRule(rule: InspectorMockRuleUi): InspectorCommandResult = withMocksCapability { - if (!rule.id.matches(MOCK_RULE_ID_PATTERN)) { - return@withMocksCapability InspectorCommandResult.Invalid( - "Mock rule id must match ${MOCK_RULE_ID_PATTERN.pattern}", - ) + when (val built = rule.buildMockAction()) { + is MockActionBuild.Invalid -> InspectorCommandResult.Invalid(built.message) + is MockActionBuild.Ready -> saveMockRule(rule, built.action) } - if (rule.statusCode !in MIN_STATUS_CODE..MAX_STATUS_CODE) { - return@withMocksCapability InspectorCommandResult.Invalid("Response status must be between 100 and 599") - } - if (rule.delayMs != null && rule.delayMs !in 0..MAX_MOCK_RULE_DELAY_MS) { - return@withMocksCapability InspectorCommandResult.Invalid( - "Delay must be between 0 and $MAX_MOCK_RULE_DELAY_MS ms", - ) + } + + /** + * Validates [rule] into a [MockAction] (or a readable [MockActionBuild.Invalid]), translating + * the engine constructors' `IllegalArgumentException` ranges into Invalid rather than Failed. + */ + private fun InspectorMockRuleUi.buildMockAction(): MockActionBuild { + val validationMessage = + when { + !id.matches(MOCK_RULE_ID_PATTERN) -> "Mock rule id must match ${MOCK_RULE_ID_PATTERN.pattern}" + statusCode !in MIN_STATUS_CODE..MAX_STATUS_CODE -> "Response status must be between 100 and 599" + delayMs?.let { it !in 0..MAX_MOCK_RULE_DELAY_MS } == true -> + "Delay must be between 0 and $MAX_MOCK_RULE_DELAY_MS ms" + actionType == InspectorMockActionType.OTHER -> "This rule's action can't be edited on device" + queryPredicates.keys.any(String::isBlank) || headerPredicates.keys.any(String::isBlank) -> + "Match condition keys must not be blank" + else -> null } - val scope = - runCatching { MockScope.valueOf(rule.scope) } - .getOrElse { - return@withMocksCapability InspectorCommandResult.Invalid("Unknown mock scope ${rule.scope}") - } - rule.headers.forEach { (name, value) -> - val nameOk = name.matches(MOCK_HEADER_NAME_PATTERN) - val valueOk = value.all { it == '\t' || it in ' '..'~' } - if (!nameOk || !valueOk) { - // Mirrors the server route's boundary check: OkHttp would throw for these - // characters on the host app's request thread at interception time. - return@withMocksCapability InspectorCommandResult.Invalid("Invalid response header: $name") - } + return validationMessage?.let { MockActionBuild.Invalid(it) } + ?: runCatching { MockActionBuild.Ready(buildMockActionOrThrow()) } + .getOrElse { MockActionBuild.Invalid(it.mockRuleMessage()) } + } + + private fun InspectorMockRuleUi.buildMockActionOrThrow(): MockAction { + val staticResponse = MockAction.StaticResponse(statusCode, body, headers) + return when (actionType) { + InspectorMockActionType.STATIC -> { + val delay = delayMs?.takeIf { it > 0 } + if (delay != null) MockAction.Delay(delay, staticResponse) else staticResponse } - val staticResponse = MockAction.StaticResponse(rule.statusCode, rule.body, rule.headers) - val delayMs = rule.delayMs - val action = - if (delayMs != null && delayMs > 0) MockAction.Delay(delayMs, staticResponse) else staticResponse - val engineRule = - MockRule( - id = rule.id.trim(), - priority = rule.priority, - method = rule.method?.uppercase()?.takeIf(String::isNotBlank), - scheme = rule.scheme?.lowercase()?.takeIf(String::isNotBlank), - host = rule.host?.takeIf(String::isNotBlank), - path = rule.pathPattern.takeIf(String::isNotBlank) ?: DEFAULT_MOCK_RULE_PATH, - scope = scope, - action = action, - // Set only by mockRuleDraftFromTransaction's "Mock this response" flow; carried - // through untouched by the create/edit form's other fields (never user-editable). - sourceBodySnapshot = rule.sourceBodySnapshot, - ).withPersistence(MockRulePersistence(enabled = rule.enabled)) - runCatching { mockEngine.upsert(engineRule) }.fold( - onSuccess = { InspectorCommandResult.Success(summary = "Mock rule ${engineRule.id} saved") }, - onFailure = { InspectorCommandResult.Failed(it.mockRuleMessage()) }, - ) + InspectorMockActionType.STATUS_OVERRIDE -> MockAction.StatusOverride(statusCode) + InspectorMockActionType.BODY_REPLACEMENT -> MockAction.BodyReplacement(body) + InspectorMockActionType.CONNECTION_FAILURE -> + MockAction.ConnectionFailure( + failureMessage?.takeIf(String::isNotBlank) ?: MockAction.ConnectionFailure().message, + ) + InspectorMockActionType.TIMEOUT -> MockAction.Timeout(timeoutMs ?: DEFAULT_MOCK_TIMEOUT_MS) + InspectorMockActionType.THROTTLE -> + MockAction.Throttle( + bytesPerSecond = requireNotNull(throttleBytesPerSecond) { "Throttle rate is required" }, + latencyMs = throttleLatencyMs ?: 0, + ) + InspectorMockActionType.MAP_REMOTE -> + MockAction.MapRemote( + scheme = remoteScheme?.trim()?.takeIf(String::isNotBlank)?.lowercase(Locale.US), + host = remoteHost?.trim()?.takeIf(String::isNotBlank), + port = remotePort, + path = remotePath?.trim()?.takeIf(String::isNotBlank), + ) + // Unreachable: buildMockAction refuses OTHER before this point. + InspectorMockActionType.OTHER -> MockAction.Passthrough + } + } + + private fun saveMockRule( + rule: InspectorMockRuleUi, + action: MockAction, + ): InspectorCommandResult { + val scope = runCatching { MockScope.valueOf(rule.scope) }.getOrNull() + // Mirrors the server route's boundary check: OkHttp would throw for these characters on the + // host app's request thread at interception time. + val invalidHeader = + rule.headers.entries + .firstOrNull { (name, value) -> !isValidMockHeader(name, value) } + ?.key + return when { + scope == null -> InspectorCommandResult.Invalid("Unknown mock scope ${rule.scope}") + invalidHeader != null -> InspectorCommandResult.Invalid("Invalid response header: $invalidHeader") + else -> persistMockRule(rule, scope, action) } + } + + private fun isValidMockHeader( + name: String, + value: String, + ): Boolean = name.matches(MOCK_HEADER_NAME_PATTERN) && value.all { it == '\t' || it in ' '..'~' } + + private fun persistMockRule( + rule: InspectorMockRuleUi, + scope: MockScope, + action: MockAction, + ): InspectorCommandResult { + val previousRule = mockEngine.rules().firstOrNull { it.id == rule.id } + val engineRule = + MockRule( + id = rule.id.trim(), + priority = rule.priority, + method = rule.method?.uppercase()?.takeIf(String::isNotBlank), + scheme = rule.scheme?.lowercase()?.takeIf(String::isNotBlank), + host = rule.host?.takeIf(String::isNotBlank), + path = rule.pathPattern.takeIf(String::isNotBlank) ?: DEFAULT_MOCK_RULE_PATH, + queryPredicates = rule.queryPredicates, + headerPredicates = rule.headerPredicates, + bodyPredicate = rule.bodyPredicate?.takeIf(String::isNotBlank), + scope = scope, + action = action, + // Set only by mockRuleDraftFromTransaction's "Mock this response" flow; carried + // through untouched by the create/edit form's other fields (never user-editable). + sourceBodySnapshot = rule.sourceBodySnapshot, + ).withPersistence( + previousRule?.persistence?.copy(enabled = rule.enabled) + ?: MockRulePersistence(enabled = rule.enabled), + ) + return runCatching { mockEngine.upsert(engineRule) }.fold( + onSuccess = { InspectorCommandResult.Success(summary = "Mock rule ${engineRule.id} saved") }, + onFailure = { InspectorCommandResult.Failed(it.mockRuleMessage()) }, + ) + } override fun deleteMockRule(id: String): InspectorCommandResult = withMocksCapability { @@ -743,6 +900,49 @@ internal class FullInspectorDataSource( } } + override fun supportsRemoteConfigOverrides(): Boolean = + remoteConfigRegistry != null && remoteConfigOverridesEditable() + + override fun setRemoteConfigOverride( + providerId: String, + key: String, + value: String, + ): InspectorCommandResult = + withRemoteConfigOverrides("Override applied") { + remoteConfigRegistry?.overrides?.setOverride(providerId, key, value) + } + + override fun clearRemoteConfigOverride( + providerId: String, + key: String, + ): InspectorCommandResult = + withRemoteConfigOverrides("Override cleared") { + remoteConfigRegistry?.overrides?.clearOverride(providerId, key) + } + + override fun clearAllRemoteConfigOverrides(): InspectorCommandResult = + withRemoteConfigOverrides("All overrides cleared") { + remoteConfigRegistry?.overrides?.clearAll() + } + + /** + * The store rejects a blank/over-long key or value with [IllegalArgumentException] -- user input + * errors, not bugs -- so they surface as [InspectorCommandResult.Invalid] instead of reaching + * the UI, matching [setFeatureFlag]'s treatment of the same class of failure. + */ + private inline fun withRemoteConfigOverrides( + summary: String, + mutation: () -> Unit, + ): InspectorCommandResult = + if (!supportsRemoteConfigOverrides()) { + InspectorCommandResult.Unavailable + } else { + runCatching(mutation).fold( + onSuccess = { InspectorCommandResult.Success(summary = summary) }, + onFailure = { InspectorCommandResult.Invalid(it.message ?: "Invalid remote config override") }, + ) + } + override fun setPreference( file: String, key: String, @@ -843,6 +1043,32 @@ internal class FullInspectorDataSource( return InspectorCommandResult.Success(summary = "Captured requests cleared") } + /** The full runtime always owns a live capture gate, so the More screen's Capture group is shown. */ + override fun supportsCaptureControl(): Boolean = true + + override fun isCapturePaused(): Boolean = DevConsole.isCapturePaused() + + /** + * Delegates to [DevConsole.setCapturePaused], which returns false while the runtime is disabled + * or not yet initialized; that reads as a plain failure here rather than a silent no-op. + */ + override fun setCapturePaused(paused: Boolean): InspectorCommandResult = + if (DevConsole.setCapturePaused(paused)) { + InspectorCommandResult.Success(summary = if (paused) "Capture paused" else "Capture resumed") + } else { + InspectorCommandResult.Failed("Capture control is unavailable") + } + + /** + * Delegates to [DevConsole.purgeCapturedData]; the success summary reports the exact counts the + * runtime removed so the snackbar says what actually happened. + */ + override suspend fun purgeCapturedData(): InspectorCommandResult { + val result = runCatching { DevConsole.purgeCapturedData() }.getOrNull() + if (result == null) return InspectorCommandResult.Failed("Could not purge captured data") + return InspectorCommandResult.Success(summary = purgeSummaryText(result)) + } + /** * Ungated by capability: exports read already-captured, already-redacted data, the same as * [listFiles]/[previewFile]/[listTables] above. @@ -878,6 +1104,34 @@ internal class FullInspectorDataSource( InspectorCommandResult.Invalid("Unknown or already-expired browser $id") } + /** + * The adapter-facing registry, shared by every [io.devconsole.socket.SocketRecorder] copy (see + * `SocketRecorder.senders`) and by the HTTP send route, so a connection this screen offers to + * write to is exactly one the browser could write to too. + */ + override fun socketSendProtocol(connectionId: String): String? = + DevConsole + .socketRecorder() + .senders + .protocol(connectionId) + ?.wireName + + override fun sendSocketFrame( + connectionId: String, + text: String, + topic: String?, + qos: Int, + retained: Boolean, + ): InspectorCommandResult { + val request = SocketSendRequest(text = text, topic = topic, qos = qos, retained = retained) + return when (val result = DevConsole.socketRecorder().senders.send(connectionId, request)) { + SocketSendResult.Sent -> InspectorCommandResult.Success(summary = "Frame sent") + SocketSendResult.NotConnected -> InspectorCommandResult.Invalid("Connection is not open") + is SocketSendResult.Rejected -> InspectorCommandResult.Invalid(result.reason) + SocketSendResult.Unsupported -> InspectorCommandResult.Unavailable + } + } + private companion object { const val SNAPSHOT_SOCKET_LIMIT = 100 const val SNAPSHOT_PUSH_LIMIT = 200 @@ -905,7 +1159,18 @@ private fun InspectorTrafficQuery.toEngineQuery(): NetworkTransactionQuery { ?.takeIf(String::isNotBlank) ?.let(::setOf) .orEmpty() - return NetworkTransactionQuery(limit = SNAPSHOT_TRANSACTION_LIMIT, methods = methods).withFilters(filters) + val hosts = + host + ?.trim() + ?.lowercase() + ?.takeIf(String::isNotEmpty) + ?.let(::setOf) + .orEmpty() + return NetworkTransactionQuery( + limit = SNAPSHOT_TRANSACTION_LIMIT, + methods = methods, + hosts = hosts, + ).withFilters(filters) } /** Empty permits any host; otherwise use an exact-host allow-list match. */ @@ -925,7 +1190,9 @@ private fun NetworkTransaction.toUi(): InspectorTransactionUi { method = request.method, host = request.url.host, path = request.url.path, - statusCode = response?.statusCode, + // Adapters record a call that never got a response as status 0 plus an error; the inspector + // renders a missing status as "ERR", so 0 must not reach it as if it were a real code. + statusCode = response?.statusCode?.takeIf { it > 0 }, durationMs = durationMs, startedAtEpochMs = startedAtEpochMs, requestHeaders = request.headers, @@ -936,6 +1203,7 @@ private fun NetworkTransaction.toUi(): InspectorTransactionUi { url = request.url.display, requestBodyKind = request.body.toUiKind(), requestBodyTruncated = request.body.isTruncated(), + responseBodyTruncated = response?.body?.isTruncated() ?: false, timingPhases = response?.metadata?.timings.toUi(), isMocked = tags["mocked"] == "true", mockRuleId = tags["mockRuleId"], @@ -994,8 +1262,10 @@ private fun CaptureRule.toUi(): InspectorCaptureRuleUi = private fun Throwable.captureRuleMessage(): String = message ?: javaClass.simpleName private fun MockRule.toUi(stats: MockRuleStats): InspectorMockRuleUi { - val delay = action as? MockAction.Delay - val staticResponse = (delay?.next ?: action) as? MockAction.StaticResponse + val throttle = action as? MockAction.Throttle + val timeout = action as? MockAction.Timeout + val failure = action as? MockAction.ConnectionFailure + val remote = action as? MockAction.MapRemote return InspectorMockRuleUi( id = id, method = method, @@ -1005,38 +1275,128 @@ private fun MockRule.toUi(stats: MockRuleStats): InspectorMockRuleUi { host = host, priority = priority, scope = scope.name, - statusCode = staticResponse?.statusCode ?: DEFAULT_STATIC_STATUS, - body = staticResponse?.body.orEmpty(), + statusCode = action.uiStatusCode(), + body = action.uiBody(), enabled = persistence.enabled, - headers = staticResponse?.headers.orEmpty(), - delayMs = delay?.durationMs, + headers = action.uiHeaders(), + delayMs = (action as? MockAction.Delay)?.durationMs, hitCount = stats.hitCount, lastHitEpochMs = stats.lastHitEpochMs, sourceBodySnapshot = sourceBodySnapshot, + actionType = action.uiActionType(), + timeoutMs = timeout?.durationMs, + failureMessage = failure?.message, + throttleBytesPerSecond = throttle?.bytesPerSecond, + throttleLatencyMs = throttle?.latencyMs, + remoteScheme = remote?.scheme, + remoteHost = remote?.host, + remotePath = remote?.path, + remotePort = remote?.port, + queryPredicates = queryPredicates, + headerPredicates = headerPredicates, + bodyPredicate = bodyPredicate, ) } +/** + * The action shape the on-device form can rebuild. A [MockAction.Delay] is only representable when + * it wraps a plain static response; a [MockAction.Throttle] only when its next action is the default + * passthrough. Everything else is [InspectorMockActionType.OTHER] and stays read-only on device. + */ +private fun MockAction.uiActionType(): InspectorMockActionType = + when (this) { + is MockAction.StaticResponse -> InspectorMockActionType.STATIC + is MockAction.Delay -> + if (next is MockAction.StaticResponse) InspectorMockActionType.STATIC else InspectorMockActionType.OTHER + is MockAction.StatusOverride -> InspectorMockActionType.STATUS_OVERRIDE + is MockAction.BodyReplacement -> InspectorMockActionType.BODY_REPLACEMENT + is MockAction.ConnectionFailure -> InspectorMockActionType.CONNECTION_FAILURE + is MockAction.Timeout -> InspectorMockActionType.TIMEOUT + is MockAction.Throttle -> + if (next == MockAction.Passthrough) InspectorMockActionType.THROTTLE else InspectorMockActionType.OTHER + is MockAction.MapRemote -> InspectorMockActionType.MAP_REMOTE + is MockAction.Sequence, is MockAction.TemplateResponse, MockAction.Passthrough -> + InspectorMockActionType.OTHER + } + +private fun MockAction.uiStatusCode(): Int = + when (this) { + is MockAction.StaticResponse -> statusCode + is MockAction.Delay -> next.uiStatusCode() + is MockAction.StatusOverride -> statusCode + is MockAction.TemplateResponse -> statusCode + else -> DEFAULT_STATIC_STATUS + } + +private fun MockAction.uiBody(): String = + when (this) { + is MockAction.StaticResponse -> body + is MockAction.Delay -> next.uiBody() + is MockAction.BodyReplacement -> body + is MockAction.TemplateResponse -> template + else -> "" + } + +private fun MockAction.uiHeaders(): Map = + when (this) { + is MockAction.StaticResponse -> headers + is MockAction.Delay -> next.uiHeaders() + is MockAction.TemplateResponse -> headers + else -> emptyMap() + } + private fun Throwable.mockRuleMessage(): String = message ?: javaClass.simpleName private const val DEFAULT_STATIC_STATUS = 200 private const val DEFAULT_MOCK_RULE_PATH = ".*" +private const val DEFAULT_MOCK_TIMEOUT_MS = 1_000L private const val MIN_STATUS_CODE = 100 private const val MAX_STATUS_CODE = 599 private const val MAX_MOCK_RULE_DELAY_MS = 30_000L private val MOCK_RULE_ID_PATTERN = Regex("[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}") +private sealed interface MockActionBuild { + data class Ready( + val action: MockAction, + ) : MockActionBuild + + data class Invalid( + val message: String, + ) : MockActionBuild +} + private fun MockAction.toLabel(): String = when (this) { is MockAction.StaticResponse -> "Static response ($statusCode)" is MockAction.TemplateResponse -> "Template response ($statusCode)" - is MockAction.Delay -> "Delay (${durationMs}ms)" + is MockAction.Delay -> "Delay (${durationMs}ms) → ${next.toLabel()}" is MockAction.ConnectionFailure -> "Connection failure" is MockAction.Timeout -> "Timeout (${durationMs}ms)" is MockAction.StatusOverride -> "Status override ($statusCode)" is MockAction.BodyReplacement -> "Body replacement" + is MockAction.Sequence -> "Sequence (${steps.size} steps)" + is MockAction.MapRemote -> "Map remote (${listOfNotNull(scheme, host, port, path).joinToString(":")})" + is MockAction.Throttle -> + buildString { + append("Throttle ").append(throttleRateLabel(bytesPerSecond)) + if (latencyMs > 0) append(" · +").append(latencyMs).append(" ms") + if (next != MockAction.Passthrough) append(" → ").append(next.toLabel()) + } MockAction.Passthrough -> "Passthrough" } +private const val BYTES_PER_KILOBYTE = 1_024L + +/** `65536` reads as `64 KB/s`; whole KB/MB only when exact, so a precise rate is never rounded away. */ +private fun throttleRateLabel(bytesPerSecond: Long): String { + val kb = BYTES_PER_KILOBYTE + return when { + bytesPerSecond % (kb * kb) == 0L -> "${bytesPerSecond / (kb * kb)} MB/s" + bytesPerSecond % kb == 0L -> "${bytesPerSecond / kb} KB/s" + else -> "$bytesPerSecond B/s" + } +} + private fun SocketConnection.toUi(): InspectorSocketUi = InspectorSocketUi( id = id, diff --git a/sdk/full/src/main/kotlin/io/devconsole/InspectorExporter.kt b/sdk/full/src/main/kotlin/io/devconsole/InspectorExporter.kt index 375a159..3c23e68 100644 --- a/sdk/full/src/main/kotlin/io/devconsole/InspectorExporter.kt +++ b/sdk/full/src/main/kotlin/io/devconsole/InspectorExporter.kt @@ -7,6 +7,7 @@ package io.devconsole import android.content.Context import io.devconsole.export.DEFAULT_EXPORT_LIMIT_BYTES import io.devconsole.export.EventExportWriter +import io.devconsole.export.ExportAttachmentSource import io.devconsole.export.ExportRequest import io.devconsole.export.ExportResult import io.devconsole.network.ExportSelection @@ -73,6 +74,7 @@ sealed interface ExportOutcome { internal data class SessionExportSources( val annotationsSupplier: () -> TimelineAnnotations = { InMemoryTimelineAnnotations() }, val attachmentReader: suspend (String) -> ByteArray? = { null }, + val attachmentMetadataReader: suspend (String) -> io.devconsole.storage.api.StoredAttachment? = { null }, ) internal class AndroidInspectorExporter( @@ -139,7 +141,7 @@ internal class AndroidInspectorExporter( EventExportWriter(exportRedaction ?: RedactionEngine(RedactionPolicy.default())).writeAsync( ExportRequest(sessionId = sessionId, events = events, destination = timelinePart) .withAnnotations(events.associate { it.id to annotations.get(it.id) }) - .withAttachments(collectAttachments(events)), + .withAttachmentSources(attachmentSources(events)), ) } when (timelineResult) { @@ -199,20 +201,32 @@ internal class AndroidInspectorExporter( * effort, skipping (never failing the whole export over) an id the reader can't produce bytes * for. */ - private suspend fun collectAttachments(events: List): Map = + private suspend fun attachmentSources(events: List): Map = buildMap { - events - .mapNotNull(StoredEvent::attachmentId) - .distinct() - .forEach { attachmentId -> - try { - sessionExportSources.attachmentReader(attachmentId)?.let { put(attachmentId, it) } - } catch (cancelled: CancellationException) { - throw cancelled - } catch (_: Exception) { - // A missing/corrupt attachment degrades this export, not the host app. - } + events.mapNotNull(StoredEvent::attachmentId).distinct().forEach { attachmentId -> + try { + val metadata = sessionExportSources.attachmentMetadataReader(attachmentId) + val source = + if (metadata != null) { + ExportAttachmentSource(metadata.storedLength, metadata.mimeType) { + sessionExportSources.attachmentReader(attachmentId)?.inputStream() + } + } else { + // No metadata reader (or no row): fall back to one bounded read for the size. + sessionExportSources.attachmentReader(attachmentId)?.let { bytes -> + ExportAttachmentSource( + bytes.size.toLong(), + "application/octet-stream", + ) { bytes.inputStream() } + } + } + source?.let { put(attachmentId, it) } + } catch (cancelled: CancellationException) { + throw cancelled + } catch (_: Exception) { + // A missing/corrupt attachment degrades this export, not the host app. } + } } /** diff --git a/sdk/full/src/main/kotlin/io/devconsole/PendingCrashFile.kt b/sdk/full/src/main/kotlin/io/devconsole/PendingCrashFile.kt new file mode 100644 index 0000000..dd810d3 --- /dev/null +++ b/sdk/full/src/main/kotlin/io/devconsole/PendingCrashFile.kt @@ -0,0 +1,55 @@ +/** + * @author Shakib + * @since 03/11/26 + */ +package io.devconsole + +import java.io.BufferedWriter +import java.io.File +import java.io.FileOutputStream +import java.io.OutputStreamWriter +import java.nio.charset.StandardCharsets + +/** Read and write the small escaped crash record left for the next process launch. */ +internal object PendingCrashFile { + fun write( + file: File, + summary: String, + stackTrace: String, + ) { + file.parentFile?.mkdirs() + BufferedWriter(OutputStreamWriter(FileOutputStream(file), StandardCharsets.UTF_8)).use { out -> + out.write(summary.escapePendingField()) + out.newLine() + out.write(stackTrace.escapePendingField()) + } + } + + fun read(file: File): Pair? { + if (!file.isFile) return null + val fields = file.readText(StandardCharsets.UTF_8).split('\n', limit = 2) + val trace = fields.getOrNull(1)?.unescapePendingField().orEmpty() + return fields.firstOrNull()?.unescapePendingField()?.let { summary -> summary to trace } + } + + private fun String.escapePendingField(): String = replace("\\", "\\\\").replace("\n", "\\n").replace("\r", "\\r") + + private fun String.unescapePendingField(): String = + buildString(length) { + var index = 0 + while (index < this@unescapePendingField.length) { + val current = this@unescapePendingField[index] + if (current == '\\' && index + 1 < this@unescapePendingField.length) { + when (val escaped = this@unescapePendingField[index + 1]) { + 'n' -> append('\n') + 'r' -> append('\r') + else -> append(escaped) + } + index += 2 + } else { + append(current) + index++ + } + } + } +} diff --git a/sdk/full/src/main/kotlin/io/devconsole/PersistentTimeline.kt b/sdk/full/src/main/kotlin/io/devconsole/PersistentTimeline.kt index ba5bc80..c8686fb 100644 --- a/sdk/full/src/main/kotlin/io/devconsole/PersistentTimeline.kt +++ b/sdk/full/src/main/kotlin/io/devconsole/PersistentTimeline.kt @@ -99,8 +99,11 @@ internal class PersistentTimeline( } override fun append(event: StoredEvent) { - if (!delegate.contains(event.id)) { - (delegate as? TimelineAppender)?.append(event) + val appender = delegate as? TimelineAppender + if (delegate is InMemoryTimeline) { + appender?.append(event) + } else if (!delegate.contains(event.id)) { + appender?.append(event) } val writerToUse = synchronized(persistenceLock) { diff --git a/sdk/full/src/main/kotlin/io/devconsole/PlatformFacadeProvider.kt b/sdk/full/src/main/kotlin/io/devconsole/PlatformFacadeProvider.kt index eca9000..cdf7e19 100644 --- a/sdk/full/src/main/kotlin/io/devconsole/PlatformFacadeProvider.kt +++ b/sdk/full/src/main/kotlin/io/devconsole/PlatformFacadeProvider.kt @@ -21,8 +21,10 @@ import io.devconsole.api.DevConsoleFacadeProvider import io.devconsole.api.DevConsoleState import io.devconsole.api.InitResult import io.devconsole.api.InspectorOpenResult +import io.devconsole.api.PurgeResult import io.devconsole.api.ScreenshotPolicy import io.devconsole.api.ScreenshotResult +import io.devconsole.api.SessionExportResult import io.devconsole.api.StartRequest import io.devconsole.api.StartResult import io.devconsole.api.StopReason @@ -39,6 +41,8 @@ import io.devconsole.network.NetworkAttachmentPayload import io.devconsole.network.NetworkCaptureFactory import io.devconsole.network.NetworkCursorCodec import io.devconsole.network.NetworkTransactionRecorder +import io.devconsole.network.NetworkTransactionStore +import io.devconsole.network.isTextualContentType import io.devconsole.push.InMemoryPushStore import io.devconsole.push.PushEvent import io.devconsole.push.PushInput @@ -60,6 +64,8 @@ import io.devconsole.server.api.ServerStartResult import io.devconsole.server.api.SessionAuthority import io.devconsole.server.api.SessionCodeAuthority import io.devconsole.server.api.SessionCodeInfo +import io.devconsole.server.ktor.CaptureControl +import io.devconsole.server.ktor.CapturePurgeSummary import io.devconsole.server.ktor.KtorLocalServerEngine import io.devconsole.socket.InMemorySocketStore import io.devconsole.socket.SocketProtocol @@ -159,6 +165,16 @@ internal class PlatformFacadeProvider : DevConsoleFacadeProvider { onPublished = runtime::recordPublishedEvent, ) private val sessionMarkerRecorder = SessionMarkerRecorder(captureBridge) + private val captureGate = CaptureGate() + + // Completed runs only: the live run is always served from the in-memory stores below. + private val retainedSessions = + RetainedSessionCaptures( + events = { sessionId -> + RetainedCaptureQuery({ eventStore }, runtime::currentSessionId).eventsForExport(sessionId) + }, + cursorCodec = NetworkCursorCodec(randomCursorSecret()), + ) private var sessionMarkerMonitor: AndroidSessionMarkerMonitor? = null private val reportingPersistenceDrop = AtomicBoolean(false) private val liveCaptureLock = Any() @@ -172,14 +188,20 @@ internal class PlatformFacadeProvider : DevConsoleFacadeProvider { captureBridge, { runtime.currentSessionId() }, liveCaptureLock, + captureGate, ) private val inMemorySocketStore = InMemorySocketStore() - private val socketStore = TeeingSocketStore(inMemorySocketStore, captureBridge, liveCaptureLock) + private val socketStore = TeeingSocketStore(inMemorySocketStore, captureBridge, liveCaptureLock, captureGate) private val inMemoryPushStore = InMemoryPushStore() - private val pushStore = TeeingPushStore(inMemoryPushStore, captureBridge, liveCaptureLock) + private val pushStore = TeeingPushStore(inMemoryPushStore, captureBridge, liveCaptureLock, captureGate) private val stateRegistry = StateRegistry() - private val remoteConfigRegistry = RemoteConfigRegistry() - private val mockEngineInstance = MockEngine(emptyList()).withOutcomeSink(::recordMockOutcome) + private val remoteConfigOverrideStore = AndroidRemoteConfigOverrideStore() + private val remoteConfigRegistry = RemoteConfigRegistry(remoteConfigOverrideStore) + + // Body predicates are offered in both rule editors, so the debug runtime has to honour them; + // the OkHttp interceptor only copies a body when a live rule has one (see requestBodyLimitBytes). + private val mockEngineInstance = + MockEngine(emptyList(), bodyMatchingEnabled = true).withOutcomeSink(::recordMockOutcome) /** Handed back by [mockEngine] instead of [mockEngineInstance] while MOCKS is off. Never mutated. */ private val disabledMockEngine = MockEngine(emptyList(), enabled = false) @@ -227,7 +249,7 @@ internal class PlatformFacadeProvider : DevConsoleFacadeProvider { private val gatedPushStore = object : PushStore by pushStore { override fun append(event: PushEvent) { - if (categoryEnabled(CaptureCategory.PUSH)) pushStore.append(event) + if (categoryEnabled(CaptureCategory.PUSH) && captureGate.allowsNewCapture()) pushStore.append(event) } } private val pushRecorderInstance = PushRecorder(redaction, gatedPushStore) @@ -250,6 +272,8 @@ internal class PlatformFacadeProvider : DevConsoleFacadeProvider { @Volatile private var activeConfig: DevConsoleConfig? = null + @Volatile private var inspectorExporter: InspectorExporter? = null + private val crashCapture = CrashCapture( ::activeSessionId, @@ -261,6 +285,7 @@ internal class PlatformFacadeProvider : DevConsoleFacadeProvider { breadcrumbs = { breadcrumbs }, policy = { activeConfig?.crashPolicy ?: CrashPolicy() }, evidenceStore = { roomEvidenceStore.takeIf { durableSessionReady.get() } }, + pendingCrashFile = { application.filesDir.resolve("devconsole/pending-crash.json") }, ) private val anrWatchdog = AnrWatchdog(onAnr = crashCapture::recordAnr) @@ -273,7 +298,11 @@ internal class PlatformFacadeProvider : DevConsoleFacadeProvider { private val logRecorderInstance = LogRecorder( redaction, - LogSink { entry -> if (categoryEnabled(CaptureCategory.LOGS)) timelineLogSink.emit(entry) }, + LogSink { entry -> + if (categoryEnabled(CaptureCategory.LOGS) && captureGate.allowsNewCapture()) { + timelineLogSink.emit(entry) + } + }, ) private fun recordMockOutcome(outcome: MockOutcome) { @@ -317,7 +346,13 @@ internal class PlatformFacadeProvider : DevConsoleFacadeProvider { eventId = payload.transactionId, mimeType = payload.contentType, bytes = payload.bytes, - isRedacted = true, + isRedacted = isTextualContentType(payload.contentType), + redactionApplicability = + if (isTextualContentType(payload.contentType)) { + RedactionApplicability.APPLIED + } else { + RedactionApplicability.NOT_APPLICABLE + }, ).withSourceMetadata( originalLength = payload.originalLength, truncated = payload.truncated, @@ -575,6 +610,10 @@ internal class PlatformFacadeProvider : DevConsoleFacadeProvider { roomEventStore?.withSessionFirstRetention() roomAttachmentStore?.withSessionFirstRetention() durableSessionReady.set(true) + crashCapture.importPendingCrash( + application.filesDir.resolve("devconsole/pending-crash.json"), + expectedSessionId, + ) if (runtime.state.value is DevConsoleState.Running) { (cachedTimeline as? PersistentTimeline)?.setPersistenceReady(true) } @@ -710,6 +749,8 @@ internal class PlatformFacadeProvider : DevConsoleFacadeProvider { .serverMetadata() .copy(captureCategories = CaptureCategory.wireNames(config.captureCategories)) if (!mockPersistenceBound) { + // Deliberately synchronous: persisted mock rules must be active before the host's first + // request, so this small SharedPreferences read stays on the initializing thread. runCatching { val mockRuleStore = AndroidMockRuleStore(application) mockEngineInstance.bindPersistence( @@ -739,6 +780,9 @@ internal class PlatformFacadeProvider : DevConsoleFacadeProvider { // by the config, so the new config's set is the whole truth. stateRegistry.clear() remoteConfigRegistry.clear() + // Idempotent: loads the file on the first initialize only, so a later re-initialize + // cannot overwrite overrides the developer has edited since. + remoteConfigOverrideStore.attach(application) // 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) } } @@ -761,6 +805,8 @@ internal class PlatformFacadeProvider : DevConsoleFacadeProvider { // host's handler, so a disabled category skips installation entirely too. if (config.crashPolicy.crashCaptureEnabled && config.capturesCategory(CaptureCategory.CRASHES)) { crashCapture.install() + } else { + crashCapture.disable() } return result } @@ -791,6 +837,9 @@ internal class PlatformFacadeProvider : DevConsoleFacadeProvider { featureFlagsSupplier = { if (::featureFlags.isInitialized) featureFlags else null }, stateRegistry = stateRegistry, remoteConfigRegistry = remoteConfigRegistry, + remoteConfigOverridesEditable = { + activeConfig?.editingCapabilities?.featureFlags == true && categoryEnabled(CaptureCategory.STATE) + }, // 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 @@ -810,10 +859,13 @@ internal class PlatformFacadeProvider : DevConsoleFacadeProvider { SessionExportSources( annotationsSupplier = { timelineAnnotations }, attachmentReader = { attachmentId -> roomAttachmentStore?.read(attachmentId) }, + attachmentMetadataReader = { attachmentId -> + roomAttachmentStore?.metadata(attachmentId) + }, ), - ).apply { exportRedaction = redaction }, + ).apply { exportRedaction = redaction }.also { inspectorExporter = it }, healthSupplier = { runtime.health.value.toInspectorHealthUi() }, - sessionsSupplier = { storedSessions.toInspectorSessions() }, + sessionsSupplier = { storedSessions.toInspectorSessions(runtime.currentSessionId()) }, browserSupplier = { activeConfig?.toInspectorBrowserUi( lastStarted?.endpoint, @@ -829,6 +881,9 @@ internal class PlatformFacadeProvider : DevConsoleFacadeProvider { retentionSupplier = { activeConfig?.retentionPolicy?.toInspectorRetentionUi() }, revokePrincipalHandler = sessionAuthority::revokeIfPresent, retainedCaptures = RetainedCaptureQuery({ eventStore }, runtime::currentSessionId), + retainedSessions = retainedSessions, + deleteRunHandler = ::deleteRetainedRun, + pinRunHandler = ::pinRetainedRun, shareableFileResolver = fileInspectorInstance::resolveShareableFile, evidenceStore = roomEvidenceStore, evidenceSessionId = ::currentOrFallbackSessionId, @@ -943,6 +998,34 @@ internal class PlatformFacadeProvider : DevConsoleFacadeProvider { } } + private fun sdkHealthSnapshot(): SdkHealthSnapshot = + runtime.health.value.let { health -> + SdkHealthSnapshot( + initializationCount = health.initializationCount, + publishedEventCount = health.publishedEventCount, + droppedEventCount = health.droppedEventCount, + state = health.state.javaClass.simpleName, + ) + } + + /** The facade's own pause/purge, seen through the server module's [CaptureControl] contract. */ + private fun captureControlBridge(): CaptureControl = + object : CaptureControl { + override fun isPaused(): Boolean = this@PlatformFacadeProvider.isCapturePaused() + + override fun setPaused(paused: Boolean): Boolean = this@PlatformFacadeProvider.setCapturePaused(paused) + + override suspend fun purge(): CapturePurgeSummary = + this@PlatformFacadeProvider.purgeCapturedData().let { purged -> + CapturePurgeSummary( + networkTransactions = purged.networkTransactions, + socketConnections = purged.socketConnections, + pushEvents = purged.pushEvents, + retainedRunsDeleted = purged.retainedRunsDeleted, + ) + } + } + /** The one-time construction half of [buildOrReconfigureServerEngine], split out for length alone. */ @Suppress("LongParameterList") private fun createServerEngine( @@ -959,16 +1042,7 @@ internal class PlatformFacadeProvider : DevConsoleFacadeProvider { sessionAuthority = sessionAuthority, sessionCodeAuthority = sessionCodeAuthority, metadata = { metadata }, - sdkHealth = { - runtime.health.value.let { health -> - SdkHealthSnapshot( - initializationCount = health.initializationCount, - publishedEventCount = health.publishedEventCount, - droppedEventCount = health.droppedEventCount, - state = health.state.javaClass.simpleName, - ) - } - }, + sdkHealth = ::sdkHealthSnapshot, networkTransactions = networkStore, socketStore = socketStore, pushStore = pushStore, @@ -982,6 +1056,11 @@ internal class PlatformFacadeProvider : DevConsoleFacadeProvider { // 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) }, + captureControl = captureControlBridge(), + // The adapter-facing registry, so the dashboard can write on exactly the connections the + // OkHttp and Paho adapters opened here -- never a second registry the adapters never see. + socketSenders = socketRecorderInstance.senders, + remoteConfigOverrides = remoteConfigOverrideStore, featureFlags = featureFlags, featureFlagsEditable = featureFlagsEditable, mockEngine = mockEngineInstance, @@ -994,14 +1073,9 @@ internal class PlatformFacadeProvider : DevConsoleFacadeProvider { databaseEditable = config.editingCapabilities.database, fileInspector = gatedFileInspector, filesEditable = config.editingCapabilities.files, - timeline = - persistentTimeline( - application, - config.storagePolicy, - config.retentionPolicy, - config.eventBufferCapacity, - ), + timeline = serverTimeline(application, config), composerEnabled = config.composerEnabled, + composerCollections = composerCollectionStore(application), composerAllowedHosts = config.composerAllowedHosts, composerHostsEditable = config.composerHostsEditable, stateMutationsEnabled = config.stateMutationsEnabled, @@ -1014,11 +1088,57 @@ internal class PlatformFacadeProvider : DevConsoleFacadeProvider { sessionsProvider = { sessionStore?.sessions().orEmpty() }, screenshotCapture = ::captureScreenshot, ).withRetainedCaptures(RetainedCaptureQuery({ eventStore }, runtime::currentSessionId)) + .withRetainedNetworkTransactions(::retainedNetworkStore) + .withRunControls(delete = ::deleteRetainedRun, pin = ::pinRetainedRun) .withNetworkProtection(config.networkProtection) .withBrowserSecurity(config.browserSecurity) .withAttachmentReader { attachmentId -> roomAttachmentStore?.read(attachmentId) } .withAttachmentMetadataReader { attachmentId -> roomAttachmentStore?.metadata(attachmentId) } + /** Split out of [createServerEngine] to keep that constructor within detekt's method-length limit. */ + private fun serverTimeline( + application: Application, + config: DevConsoleConfig, + ): Timeline = + persistentTimeline( + application, + config.storagePolicy, + config.retentionPolicy, + config.eventBufferCapacity, + ) + + /** Split out of [createServerEngine] to keep that constructor within detekt's method-length limit. */ + private fun composerCollectionStore(application: Application): FileComposerCollectionStore = + FileComposerCollectionStore(File(application.filesDir, "devconsole/composer-collections.json")) + + /** Deletes a finished run with its captures; the live run is refused by the store itself. */ + private suspend fun deleteRetainedRun(sessionId: String): Boolean { + val store = sessionStore ?: return false + val deleted = sessionId != runtime.currentSessionId() && store.delete(sessionId) + if (deleted) { + retainedSessions.forget(sessionId) + storedSessions = store.sessions() + } + return deleted + } + + private suspend fun pinRetainedRun( + sessionId: String, + pinned: Boolean, + ): Boolean { + val store = sessionStore ?: return false + val changed = store.setPinned(sessionId, pinned) + if (changed) storedSessions = store.sessions() + return changed + } + + /** A known, completed run's network store; null for the live run or one retention already pruned. */ + private suspend fun retainedNetworkStore(sessionId: String): NetworkTransactionStore? { + val known = sessionId != runtime.currentSessionId() && sessionStore?.session(sessionId) != null + if (!known) retainedSessions.forget(sessionId) + return if (known) retainedSessions.networkStore(sessionId) else null + } + override fun state(): StateFlow = runtime.state override suspend fun startBrowser(request: StartRequest): StartResult = @@ -1070,7 +1190,7 @@ internal class PlatformFacadeProvider : DevConsoleFacadeProvider { if (!durableSessionReady.get() && bootstrapJob?.isActive != true) { scheduleSessionBootstrap(application) } - durableSessionReady.get() + sessionReadyForStart(true, durableSessionReady.get(), bootstrapJob?.isActive == true) } if (!sessionReady) { // A Room/bootstrap failure must not take down the developer server. Captures stay @@ -1310,6 +1430,25 @@ internal class PlatformFacadeProvider : DevConsoleFacadeProvider { override fun registerRemoteConfigProvider(provider: RemoteConfigProvider): Boolean = categoryEnabled(CaptureCategory.STATE) && safely { remoteConfigRegistry.register(provider) } + /** + * Reads the developer's local override without ever throwing into the host: a config read runs + * on the host's own request path, where a debugging tool must never be the reason a call fails. + */ + override fun remoteConfigOverride( + key: String, + providerId: String?, + ): String? = + runCatching { + if (providerId != null) { + remoteConfigRegistry.overrideValue(providerId, key) + } else { + remoteConfigOverrideStore + .overrides() + .values + .firstNotNullOfOrNull { overrides -> overrides[key] } + } + }.getOrNull() + /** * 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. @@ -1408,6 +1547,75 @@ internal class PlatformFacadeProvider : DevConsoleFacadeProvider { return runCatching { flags.value(key) }.getOrDefault("") } + @Synchronized + override fun setCapturePaused(paused: Boolean): Boolean { + val state = runtime.state.value + if (state is DevConsoleState.Uninitialized || state is DevConsoleState.DisabledForBuild) return false + if (captureGate.setPaused(paused)) { + runCatching { sessionMarkerRecorder.captureStateChanged(paused) } + } + return true + } + + override fun isCapturePaused(): Boolean = captureGate.isPaused() + + override suspend fun purgeCapturedData(): PurgeResult { + var networkRemoved = 0 + var socketRemoved = 0 + var pushRemoved = 0 + var retainedDeleted = 0 + runCatching { + synchronized(liveCaptureLock) { + networkRemoved = networkTransactionStore.statusDistribution().values.sum() + socketRemoved = inMemorySocketStore.connections().size + pushRemoved = inMemoryPushStore.events().size + networkTransactionStore.clear() + inMemorySocketStore.clear() + socketStore.resetSession() + inMemoryPushStore.clear() + } + } + runCatching { + withContext(Dispatchers.IO) { + val store = sessionStore + if (store != null) { + val activeId = runtime.currentSessionId() + store + .sessions() + .filter { it.id != activeId && !it.pinned && it.status in PURGEABLE_RUN_STATUSES } + .forEach { session -> + val deleted = runCatching { store.delete(session.id) }.getOrDefault(false) + if (deleted) { + retainedDeleted++ + runCatching { retainedSessions.forget(session.id) } + } + } + storedSessions = runCatching { store.sessions() }.getOrDefault(emptyList()) + } + } + } + return PurgeResult( + networkTransactions = networkRemoved, + socketConnections = socketRemoved, + pushEvents = pushRemoved, + retainedRunsDeleted = retainedDeleted, + ) + } + + override suspend fun exportSession(): SessionExportResult { + val state = runtime.state.value + val runtimeActive = state !is DevConsoleState.Uninitialized && state !is DevConsoleState.DisabledForBuild + val exporter = inspectorExporter?.takeIf { runtimeActive } ?: return SessionExportResult.Disabled + return runCatching { + when (val outcome = withContext(Dispatchers.IO) { exporter.exportSessionZip() }) { + is ExportOutcome.Written -> SessionExportResult.Exported(File(outcome.path)) + is ExportOutcome.Failed -> SessionExportResult.Failed(outcome.message) + } + }.getOrElse { failure -> + SessionExportResult.Failed(failure.message ?: failure.javaClass.simpleName) + } + } + /** Registration must happen exactly once per Application, regardless of how many times [initialize] runs. */ private fun registerActivityTrackerOnce(application: Application) { if (activityTrackerRegistered.compareAndSet(false, true)) { @@ -1524,7 +1732,17 @@ internal class PlatformFacadeProvider : DevConsoleFacadeProvider { /** Device/app metadata for the evidence bundle's session.json; honestly null before a durable session exists. */ private suspend fun currentSessionSnapshot(): StoredSession? = sessionStore?.session(activeSessionId()) - private companion object { + internal companion object { + /** + * A start is only "durable session unavailable" when there is a store but no bootstrap is + * ready or in flight; an in-flight bootstrap enables durable writes when it completes. + */ + fun sessionReadyForStart( + sessionStoreAvailable: Boolean, + durableReady: Boolean, + bootstrapInFlight: Boolean, + ): Boolean = !sessionStoreAvailable || durableReady || bootstrapInFlight + const val DATABASE_NAME = "devconsole-events.db" const val DEVCONSOLE_DIRECTORY = "devconsole" const val BOOTSTRAP_TIMEOUT_MS = 5_000L @@ -1551,7 +1769,7 @@ private fun io.devconsole.core.SdkHealth.toInspectorHealthUi(): InspectorHealthU ) /** Durable app-run rows replace the old synthetic marker-derived session list. */ -private fun List.toInspectorSessions(): List = +private fun List.toInspectorSessions(currentSessionId: String?): List = sortedByDescending(StoredSession::startedAtMs).map { session -> InspectorSessionUi( id = session.id, @@ -1560,6 +1778,8 @@ private fun List.toInspectorSessions(): List status = session.status.name, recordCount = session.recordCount, estimatedBytes = session.estimatedBytes, + isCurrent = session.id == currentSessionId, + pinned = session.pinned, ) } @@ -1635,6 +1855,9 @@ private fun io.devconsole.api.RetentionPolicy.toInspectorRetentionUi(): Inspecto private const val CURSOR_SECRET_BYTES = 16 +/** Runs [PlatformFacadeProvider.purgeCapturedData] may delete: finished ones, never the live run or a pinned one. */ +private val PURGEABLE_RUN_STATUSES = setOf(StoredSessionStatus.COMPLETED, StoredSessionStatus.CRASHED) + private fun randomCursorSecret(): ByteArray = ByteArray(CURSOR_SECRET_BYTES).also(SecureRandom()::nextBytes) /** diff --git a/sdk/full/src/main/kotlin/io/devconsole/PurgeSummaryText.kt b/sdk/full/src/main/kotlin/io/devconsole/PurgeSummaryText.kt new file mode 100644 index 0000000..88934c4 --- /dev/null +++ b/sdk/full/src/main/kotlin/io/devconsole/PurgeSummaryText.kt @@ -0,0 +1,34 @@ +/** + * @author Shakib + * @since 04/11/26 + */ +package io.devconsole + +import io.devconsole.api.PurgeResult + +/** + * Human-readable summary of what [DevConsole.purgeCapturedData] removed, naming only what was actually + * removed, e.g. "Removed 12 requests, 2 connections and 1 old run" or "Removed 8 old runs". A purge + * that found nothing says so instead of listing four zeros. + */ +internal fun purgeSummaryText(result: PurgeResult): String { + val parts = + listOf( + result.networkTransactions to "request", + result.socketConnections to "connection", + result.pushEvents to "push event", + result.retainedRunsDeleted to "old run", + ).filter { (count, _) -> count > 0 } + .map { (count, noun) -> countPhrase(count, noun) } + return when (parts.size) { + 0 -> "Nothing to purge" + 1 -> "Removed ${parts.single()}" + else -> "Removed ${parts.dropLast(1).joinToString(", ")} and ${parts.last()}" + } +} + +/** "1 request" / "12 requests": the count plus its singular or plural noun. */ +private fun countPhrase( + count: Int, + singular: String, +): String = "$count $singular" + if (count == 1) "" else "s" diff --git a/sdk/full/src/main/kotlin/io/devconsole/RecoveringDevConsoleDatabase.kt b/sdk/full/src/main/kotlin/io/devconsole/RecoveringDevConsoleDatabase.kt index 8e642fb..374785b 100644 --- a/sdk/full/src/main/kotlin/io/devconsole/RecoveringDevConsoleDatabase.kt +++ b/sdk/full/src/main/kotlin/io/devconsole/RecoveringDevConsoleDatabase.kt @@ -67,6 +67,7 @@ internal class RecoveringDevConsoleDatabase( .addMigrations(DevConsoleDatabase.MIGRATION_2_3) .addMigrations(DevConsoleDatabase.MIGRATION_3_4) .addMigrations(DevConsoleDatabase.MIGRATION_4_5) + .addMigrations(DevConsoleDatabase.MIGRATION_5_6) .addCallback(IncrementalVacuumCallback) .build() diff --git a/sdk/full/src/main/kotlin/io/devconsole/RedactingRemoteConfig.kt b/sdk/full/src/main/kotlin/io/devconsole/RedactingRemoteConfig.kt index eb2da03..db8d18a 100644 --- a/sdk/full/src/main/kotlin/io/devconsole/RedactingRemoteConfig.kt +++ b/sdk/full/src/main/kotlin/io/devconsole/RedactingRemoteConfig.kt @@ -33,15 +33,17 @@ internal class RedactingRemoteConfig( * 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) - } + private fun redact(entry: RemoteConfigEntry): RemoteConfigEntry { + val sensitive = isSensitive(entry.key) + // Still run a non-sensitive key's value through the engine: it can hold a bearer token, + // and the engine's text patterns are what catch that. providerValue is the value a surface + // shows *behind* an active override, so it needs exactly the same treatment -- otherwise a + // secret the provider resolved would be displayed raw the moment a developer overrides it. + val value = if (sensitive) replacement else redaction.redactText(entry.value) + val providerValue = entry.providerValue?.let { if (sensitive) replacement else redaction.redactText(it) } + if (!sensitive && value == entry.value && providerValue == entry.providerValue) return entry + return entry.copy(value = value, redacted = true, providerValue = providerValue) + } /** * Matches separator-insensitively, which the raw policy does not. diff --git a/sdk/full/src/main/kotlin/io/devconsole/RetainedCaptureDecoder.kt b/sdk/full/src/main/kotlin/io/devconsole/RetainedCaptureDecoder.kt new file mode 100644 index 0000000..c4112b8 --- /dev/null +++ b/sdk/full/src/main/kotlin/io/devconsole/RetainedCaptureDecoder.kt @@ -0,0 +1,190 @@ +/** + * @author Shakib + * @since 03/11/26 + */ +package io.devconsole + +import io.devconsole.network.BodyPreview +import io.devconsole.network.CaptureBodyMetadata +import io.devconsole.network.CapturedRequest +import io.devconsole.network.CapturedRequestMetadata +import io.devconsole.network.CapturedResponse +import io.devconsole.network.CapturedResponseMetadata +import io.devconsole.network.NetworkCapture +import io.devconsole.network.NetworkTimingPhases +import io.devconsole.network.NetworkTransaction +import io.devconsole.network.NetworkUrl +import io.devconsole.push.PushEvent +import io.devconsole.socket.SocketMessage +import org.json.JSONObject + +private const val SUPPORTED_VERSION = 1 +private const val KIND_NETWORK = "network" +private const val KIND_SOCKET_MESSAGE = "socket.message" +private const val KIND_SOCKET_LIFECYCLE = "socket.lifecycle" +private const val KIND_PUSH = "push" + +/** + * Decodes persisted timeline payloads originally encoded by [CapturePayloadCodec]. + */ +internal object RetainedCaptureDecoder { + fun network(payloadJson: String?): NetworkTransaction? = + safeDecode(payloadJson, KIND_NETWORK, ::decodeNetworkTransaction) + + fun socketMessage(payloadJson: String?): SocketMessage? = + safeDecode(payloadJson, KIND_SOCKET_MESSAGE, ::decodeSocketMessage) + + fun socketLifecycle(payloadJson: String?): RetainedSocketLifecycle? = + safeDecode(payloadJson, KIND_SOCKET_LIFECYCLE, ::decodeSocketLifecycle) + + fun push(payloadJson: String?): PushEvent? = safeDecode(payloadJson, KIND_PUSH, ::decodePushEvent) +} + +private inline fun safeDecode( + payloadJson: String?, + expectedKind: String, + decode: (JSONObject) -> T, +): T? = + if (payloadJson.isNullOrBlank()) { + null + } else { + runCatching { + val root = JSONObject(payloadJson) + val version = root.optInt("v", -1) + val kind = root.optString("kind", "") + if (version in 1..SUPPORTED_VERSION && kind == expectedKind) { + root.optJSONObject("data")?.let(decode) + } else { + null + } + }.getOrNull() + } + +private fun decodeNetworkTransaction(data: JSONObject): NetworkTransaction { + val id = data.getString("id") + val startedAtEpochMs = data.getLong("startedAtEpochMs") + val completedAtEpochMs = data.optLongOrNull("completedAtEpochMs") + val sessionId = data.optStringOrNull("sessionId") + val reqJson = data.getJSONObject("request") + val resJson = data.optJSONObject("response") + + val request = decodeRequest(reqJson) + val response = resJson?.let(::decodeResponse) + val capture = NetworkCapture(request, response) + + return NetworkTransaction( + id = id, + startedAtEpochMs = startedAtEpochMs, + completedAtEpochMs = completedAtEpochMs, + capture = capture, + ).withSessionId(sessionId) +} + +private fun decodeRequest(json: JSONObject): CapturedRequest { + val method = json.getString("method") + val urlJson = json.getJSONObject("url") + val url = + NetworkUrl( + scheme = urlJson.optString("scheme", ""), + host = urlJson.optString("host", ""), + path = urlJson.optString("path", ""), + query = urlJson.optJSONObject("query")?.toRetainedStringMap().orEmpty(), + ) + val headers = json.optJSONObject("headers")?.toRetainedStringMap().orEmpty() + val (bodyPreview, bodyMeta) = decodeBody(json.optJSONObject("body")) + val contentType = json.optStringOrNull("contentType") + val correlationId = json.optStringOrNull("correlationId") + val pluginId = json.optString("pluginId", "network") + val threadName = json.optStringOrNull("threadName") + val tags = json.optJSONObject("tags")?.toRetainedStringMap().orEmpty() + val attachmentId = json.optStringOrNull("attachmentId") + + return CapturedRequest( + method = method, + url = url, + headers = headers, + body = bodyPreview, + contentType = contentType, + correlationId = correlationId, + pluginId = pluginId, + ).withAttachmentId(attachmentId) + .withMetadata( + CapturedRequestMetadata( + threadName = threadName, + body = bodyMeta, + tags = tags, + ), + ) +} + +private fun decodeResponse(json: JSONObject): CapturedResponse { + val statusCode = json.getInt("statusCode") + val headers = json.optJSONObject("headers")?.toRetainedStringMap().orEmpty() + val (bodyPreview, bodyMeta) = decodeBody(json.optJSONObject("body")) + val contentType = json.optStringOrNull("contentType") + val protocol = json.optStringOrNull("protocol") + val error = json.optStringOrNull("error") + val fromCache = json.optBoolean("fromCache", false) + val exceptionClass = json.optStringOrNull("exceptionClass") + val timings = decodeTimings(json.optJSONObject("timings")) + val attachmentId = json.optStringOrNull("attachmentId") + + return CapturedResponse( + statusCode = statusCode, + headers = headers, + body = bodyPreview, + contentType = contentType, + protocol = protocol, + error = error, + ).withAttachmentId(attachmentId) + .withMetadata( + CapturedResponseMetadata( + body = bodyMeta, + timings = timings, + fromCache = fromCache, + exceptionClass = exceptionClass, + ), + ) +} + +private fun decodeBody(json: JSONObject?): Pair { + if (json == null) return BodyPreview.Absent to CaptureBodyMetadata() + val kind = json.optString("kind", "absent") + val truncated = json.optBoolean("truncated", false) + val preview = + when (kind) { + "text" -> + BodyPreview.Text( + value = json.optString("preview", ""), + truncated = truncated, + ) + "binary" -> + BodyPreview.Binary( + length = json.optLong("length", 0L), + truncated = truncated, + ) + else -> BodyPreview.Absent + } + val metadata = + CaptureBodyMetadata( + declaredLength = json.optLongOrNull("declaredLength"), + capturedBytes = json.optInt("capturedBytes", 0), + truncated = json.optBoolean("metadataTruncated", false), + omittedReason = json.optStringOrNull("omittedReason"), + ) + return preview to metadata +} + +private fun decodeTimings(json: JSONObject?): NetworkTimingPhases = + if (json == null) { + NetworkTimingPhases() + } else { + NetworkTimingPhases( + dnsMs = json.optLongOrNull("dnsMs"), + connectMs = json.optLongOrNull("connectMs"), + tlsMs = json.optLongOrNull("tlsMs"), + sendMs = json.optLongOrNull("sendMs"), + waitMs = json.optLongOrNull("waitMs"), + receiveMs = json.optLongOrNull("receiveMs"), + ) + } diff --git a/sdk/full/src/main/kotlin/io/devconsole/RetainedNetworkStores.kt b/sdk/full/src/main/kotlin/io/devconsole/RetainedNetworkStores.kt new file mode 100644 index 0000000..e8241fe --- /dev/null +++ b/sdk/full/src/main/kotlin/io/devconsole/RetainedNetworkStores.kt @@ -0,0 +1,88 @@ +/** + * @author Shakib + * @since 03/11/26 + */ +package io.devconsole + +import io.devconsole.network.InMemoryNetworkTransactionStore +import io.devconsole.network.NetworkCursorCodec +import io.devconsole.network.NetworkTransaction +import io.devconsole.storage.api.StoredEvent +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock + +/** + * Builds and caches in-memory transaction stores for historical/retained sessions. + * Completed sessions never change, so caching is safe; the active/live session + * must not be served from here. + */ +internal class RetainedNetworkStores( + private val events: suspend (sessionId: String) -> List, + private val cursorCodec: NetworkCursorCodec, + private val maxCachedSessions: Int = DEFAULT_MAX_CACHED_SESSIONS, +) { + private val mutex = Mutex() + private val lock = Any() + private val cache = + object : LinkedHashMap( + maxCachedSessions, + LOAD_FACTOR, + true, + ) { + override fun removeEldestEntry( + eldest: MutableMap.MutableEntry?, + ): Boolean = size > maxCachedSessions + } + + /** A run with no decodable network captures yields an empty store, not null. */ + suspend fun storeFor(sessionId: String): InMemoryNetworkTransactionStore = + mutex.withLock { + val cached = synchronized(lock) { cache[sessionId] } + if (cached != null) return@withLock cached + + val store = buildStore(sessionId) + synchronized(lock) { + cache[sessionId] = store + } + store + } + + private suspend fun buildStore(sessionId: String): InMemoryNetworkTransactionStore { + val transactions = + events(sessionId) + .asSequence() + .filter { it.pluginId == PLUGIN_NETWORK } + .mapNotNull { RetainedCaptureDecoder.network(it.payloadJson) } + .sortedBy(NetworkTransaction::startedAtEpochMs) + .toList() + + val capacity = transactions.size.coerceAtLeast(1) + val store = + InMemoryNetworkTransactionStore( + cursorCodec = cursorCodec, + maxTransactions = capacity, + ).withByteCapacity(DEFAULT_STORE_BYTE_CAPACITY) + + transactions.forEach(store::record) + return store + } + + fun invalidate(sessionId: String) { + synchronized(lock) { + cache.remove(sessionId) + } + } + + fun clear() { + synchronized(lock) { + cache.clear() + } + } + + private companion object { + const val DEFAULT_MAX_CACHED_SESSIONS = 4 + const val LOAD_FACTOR = 0.75f + const val PLUGIN_NETWORK = "network" + const val DEFAULT_STORE_BYTE_CAPACITY = 64L * 1024L * 1024L + } +} diff --git a/sdk/full/src/main/kotlin/io/devconsole/RetainedSessionCaptures.kt b/sdk/full/src/main/kotlin/io/devconsole/RetainedSessionCaptures.kt new file mode 100644 index 0000000..9f45529 --- /dev/null +++ b/sdk/full/src/main/kotlin/io/devconsole/RetainedSessionCaptures.kt @@ -0,0 +1,102 @@ +/** + * @author Shakib + * @since 03/11/26 + */ +package io.devconsole + +import io.devconsole.network.InMemoryNetworkTransactionStore +import io.devconsole.network.NetworkCursorCodec +import io.devconsole.push.PushEvent +import io.devconsole.socket.SocketConnection +import io.devconsole.socket.SocketConnectionState +import io.devconsole.socket.SocketLifecycleType +import io.devconsole.socket.SocketMessage +import io.devconsole.socket.SocketProtocol +import io.devconsole.storage.api.StoredEvent + +/** Read-only network/socket/push views of a completed run, rebuilt from [CapturePayloadCodec] payloads. */ +internal class RetainedSessionCaptures( + private val events: suspend (sessionId: String) -> List, + cursorCodec: NetworkCursorCodec, +) { + private val networkStores = RetainedNetworkStores(events, cursorCodec) + + suspend fun networkStore(sessionId: String): InMemoryNetworkTransactionStore = networkStores.storeFor(sessionId) + + suspend fun sockets(sessionId: String): List = + rebuildSocketConnections(events(sessionId).filter { it.pluginId == SOCKET_PLUGIN_ID }) + + suspend fun pushEvents(sessionId: String): List = + events(sessionId) + .asSequence() + .filter { it.pluginId == PUSH_PLUGIN_ID } + .mapNotNull { RetainedCaptureDecoder.push(it.payloadJson) } + .sortedByDescending(PushEvent::receivedAtEpochMs) + .toList() + + /** Drops a cached network view, e.g. after the run's events were pruned or deleted. */ + fun forget(sessionId: String) = networkStores.invalidate(sessionId) + + private companion object { + const val SOCKET_PLUGIN_ID = "websocket" + const val PUSH_PLUGIN_ID = "push" + } +} + +/** Newest-opened first, matching the live socket store's own ordering. */ +internal fun rebuildSocketConnections(events: List): List { + val lifecycles = linkedMapOf>() + val messages = linkedMapOf>() + events.forEach { event -> + val message = RetainedCaptureDecoder.socketMessage(event.payloadJson) + if (message != null) { + messages.getOrPut(message.connectionId, ::mutableListOf) += message + } else { + RetainedCaptureDecoder.socketLifecycle(event.payloadJson)?.let { lifecycle -> + lifecycles.getOrPut(lifecycle.event.connectionId, ::mutableListOf) += lifecycle + } + } + } + return (lifecycles.keys + messages.keys) + .map { id -> rebuildConnection(id, lifecycles[id].orEmpty(), messages[id].orEmpty()) } + .sortedByDescending(SocketConnection::openedAtEpochMs) +} + +private fun rebuildConnection( + id: String, + lifecycles: List, + messages: List, +): SocketConnection { + val ordered = lifecycles.sortedBy { it.event.timestampEpochMs } + val frames = messages.sortedBy(SocketMessage::timestampEpochMs) + val last = ordered.lastOrNull()?.event + val terminal = last?.takeIf { it.type in TERMINAL_LIFECYCLE_TYPES } + val openedAt = + ordered.firstOrNull()?.event?.timestampEpochMs + ?: frames.firstOrNull()?.timestampEpochMs + ?: 0L + return SocketConnection( + id = id, + url = ordered.firstNotNullOfOrNull(RetainedSocketLifecycle::url).orEmpty(), + openedAtEpochMs = openedAt, + closedAtEpochMs = terminal?.timestampEpochMs, + state = last?.type?.toConnectionState() ?: SocketConnectionState.OPEN, + error = ordered.lastOrNull { it.event.error != null }?.event?.error, + messages = frames, + protocol = ordered.firstOrNull()?.protocol ?: SocketProtocol.WEBSOCKET, + ).withLifecycleEvents(ordered.map(RetainedSocketLifecycle::event)) +} + +private val TERMINAL_LIFECYCLE_TYPES = + setOf(SocketLifecycleType.CLOSED, SocketLifecycleType.FAILED, SocketLifecycleType.CANCELLED) + +private fun SocketLifecycleType.toConnectionState(): SocketConnectionState = + when (this) { + SocketLifecycleType.CREATED -> SocketConnectionState.CREATED + SocketLifecycleType.OPENED -> SocketConnectionState.OPEN + SocketLifecycleType.CLOSING -> SocketConnectionState.CLOSING + SocketLifecycleType.CLOSED, + SocketLifecycleType.FAILED, + SocketLifecycleType.CANCELLED, + -> SocketConnectionState.CLOSED + } diff --git a/sdk/full/src/main/kotlin/io/devconsole/RetainedSocketPushDecoding.kt b/sdk/full/src/main/kotlin/io/devconsole/RetainedSocketPushDecoding.kt new file mode 100644 index 0000000..cdb7361 --- /dev/null +++ b/sdk/full/src/main/kotlin/io/devconsole/RetainedSocketPushDecoding.kt @@ -0,0 +1,142 @@ +/** + * @author Shakib + * @since 03/11/26 + */ +package io.devconsole + +import io.devconsole.push.PushEvent +import io.devconsole.push.PushLifecycle +import io.devconsole.push.PushNotification +import io.devconsole.socket.BinaryPreviewEncoding +import io.devconsole.socket.SocketDirection +import io.devconsole.socket.SocketFrameType +import io.devconsole.socket.SocketLifecycleEvent +import io.devconsole.socket.SocketLifecycleType +import io.devconsole.socket.SocketMessage +import io.devconsole.socket.SocketMessageMetadata +import io.devconsole.socket.SocketPayload +import io.devconsole.socket.SocketProtocol +import io.devconsole.socket.SocketTextFormat +import org.json.JSONObject + +// Socket and push halves of [RetainedCaptureDecoder], plus the null-tolerant JSON readers both halves share. + +internal fun decodeSocketMessage(data: JSONObject): SocketMessage { + val connectionId = data.getString("connectionId") + val timestampEpochMs = data.getLong("timestampEpochMs") + val direction = SocketDirection.valueOf(data.getString("direction")) + val contentType = data.optStringOrNull("contentType") + val frameType = data.optStringOrNull("frameType")?.let(SocketFrameType::valueOf) ?: SocketFrameType.TEXT + val textFormat = data.optStringOrNull("textFormat")?.let(SocketTextFormat::valueOf) ?: SocketTextFormat.TEXT + val payload = decodeSocketPayload(data.getJSONObject("payload")) + + return SocketMessage( + connectionId = connectionId, + direction = direction, + timestampEpochMs = timestampEpochMs, + payload = payload, + contentType = contentType, + ).withMetadata( + SocketMessageMetadata( + frameType = frameType, + textFormat = textFormat, + ), + ) +} + +private fun decodeSocketPayload(payloadJson: JSONObject): SocketPayload { + val kind = payloadJson.optString("kind") + val truncated = payloadJson.optBoolean("truncated", false) + return if (kind == "binary") { + val binary = + SocketPayload.Binary( + length = payloadJson.optLong("length", 0L), + truncated = truncated, + ) + val preview = payloadJson.optStringOrNull("preview") + val previewEncoding = payloadJson.optStringOrNull("previewEncoding")?.let(BinaryPreviewEncoding::valueOf) + if (preview != null && previewEncoding != null) { + binary.withPreview(preview, previewEncoding) + } else { + binary + } + } else { + SocketPayload.Text( + preview = payloadJson.optString("preview", ""), + truncated = truncated, + ) + } +} + +/** A persisted socket lifecycle event plus the connection identity it was captured with. */ +internal data class RetainedSocketLifecycle( + val event: SocketLifecycleEvent, + val url: String?, + val protocol: SocketProtocol, +) + +internal fun decodeSocketLifecycle(data: JSONObject): RetainedSocketLifecycle { + val event = + SocketLifecycleEvent( + connectionId = data.getString("connectionId"), + type = SocketLifecycleType.valueOf(data.getString("type")), + timestampEpochMs = data.getLong("timestampEpochMs"), + code = data.optIntOrNull("code"), + reason = data.optStringOrNull("reason"), + error = data.optStringOrNull("error"), + ) + return RetainedSocketLifecycle( + event = event, + url = data.optStringOrNull("url"), + protocol = SocketProtocol.fromWireName(data.optStringOrNull("protocol")), + ) +} + +internal fun decodePushEvent(data: JSONObject): PushEvent { + val provider = data.getString("provider") + val eventData = data.optJSONObject("data")?.toRetainedStringMap().orEmpty() + val messageId = data.optStringOrNull("messageId") + val source = data.optStringOrNull("source") + val sentAtEpochMs = data.optLongOrNull("sentAtEpochMs") + val receivedAtEpochMs = data.optLong("receivedAtEpochMs", 0L) + val rawMetadata = data.optJSONObject("rawMetadata")?.toRetainedStringMap().orEmpty() + val lifecycle = data.optStringOrNull("lifecycle")?.let(PushLifecycle::valueOf) ?: PushLifecycle.RECEIVED + val simulated = data.optBoolean("simulated", false) + val notification = + data.optJSONObject("notification")?.let { notifJson -> + PushNotification( + title = notifJson.optStringOrNull("title"), + body = notifJson.optStringOrNull("body"), + channelId = notifJson.optStringOrNull("channelId"), + imageUrl = notifJson.optStringOrNull("imageUrl"), + ) + } + + return PushEvent( + provider = provider, + data = eventData, + messageId = messageId, + source = source, + sentAtEpochMs = sentAtEpochMs, + receivedAtEpochMs = receivedAtEpochMs, + notification = notification, + rawMetadata = rawMetadata, + lifecycle = lifecycle, + simulated = simulated, + ) +} + +internal fun JSONObject.optStringOrNull(name: String): String? = + if (!has(name) || isNull(name)) null else getString(name) + +internal fun JSONObject.optLongOrNull(name: String): Long? = if (!has(name) || isNull(name)) null else getLong(name) + +internal fun JSONObject.optIntOrNull(name: String): Int? = if (!has(name) || isNull(name)) null else getInt(name) + +internal fun JSONObject.toRetainedStringMap(): Map = + buildMap { + keys().forEach { name -> + val value = optStringOrNull(name) + if (value != null) put(name, value) + } + } diff --git a/sdk/full/src/main/kotlin/io/devconsole/ScreenshotCapture.kt b/sdk/full/src/main/kotlin/io/devconsole/ScreenshotCapture.kt index db19cc7..757e68b 100644 --- a/sdk/full/src/main/kotlin/io/devconsole/ScreenshotCapture.kt +++ b/sdk/full/src/main/kotlin/io/devconsole/ScreenshotCapture.kt @@ -16,8 +16,9 @@ import android.view.Window import android.view.WindowManager import androidx.annotation.RequiresApi import io.devconsole.api.ScreenshotPolicy -import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.suspendCancellableCoroutine +import kotlinx.coroutines.withContext import kotlinx.coroutines.withTimeoutOrNull import java.io.ByteArrayOutputStream import kotlin.coroutines.resume @@ -85,12 +86,8 @@ internal enum class CaptureAttemptResult { SUCCESS, SECURE, FAILED } * while hardening this path; the `ERROR_SOURCE_NO_DATA` -> [CapturedScreenshot.SecureWindow] mapping * and the re-check-before-copy ordering are implemented per the documented `PixelCopy` contract and * covered by Robolectric unit tests only, not verified against real hardware. - * - **A timed-out `PixelCopy` request cannot be cancelled.** [capture] bounds the wait and recycles its - * bitmap on timeout, but `PixelCopy.request` has no cancel API; if the system-side copy is still - * in flight when the timeout fires, it is racing a bitmap this class has already recycled. This is - * believed low-risk in practice (a `PixelCopy` copy is a single-frame operation, not the kind of - * thing a stalled main thread should be able to delay), but it is not something this class can rule - * out from application code. + * - **A timed-out `PixelCopy` request cannot be cancelled.** On timeout its bitmap is abandoned without + * recycling; the system can finish writing safely and GC will reclaim the bitmap afterward. */ internal class ScreenshotCapture( private val mainHandler: Handler = Handler(Looper.getMainLooper()), @@ -131,26 +128,19 @@ internal class ScreenshotCapture( runCatching { bitmapFactory(width, height) } .getOrElse { return CapturedScreenshot.Failed("Unable to allocate capture bitmap: ${it.message}") } - // Every branch below owns the bitmap and must either hand it to encode() or recycle it -- - // including external cancellation of this coroutine, which is why the timed section is wrapped - // in try/catch rather than relying solely on the `null` (timeout) result of withTimeoutOrNull. + // PixelCopy has no cancellation API, so neither a timeout nor caller cancellation may recycle + // the destination bitmap: the native copy could still be writing into it. GC reclaims it. val outcome = - try { - withTimeoutOrNull(captureTimeoutMs) { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { - captureWithPixelCopy(window, bitmap) - } else { - captureWithCanvas(window, decorView, bitmap) - } + withTimeoutOrNull(captureTimeoutMs) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + captureWithPixelCopy(window, bitmap) + } else { + captureWithCanvas(window, decorView, bitmap) } - } catch (cancelled: CancellationException) { - bitmap.recycle() - throw cancelled } return when (outcome) { null -> { - bitmap.recycle() CapturedScreenshot.Failed("Screenshot capture timed out after ${captureTimeoutMs}ms", timedOut = true) } CaptureAttemptResult.SUCCESS -> encode(bitmap, policy) @@ -165,12 +155,12 @@ internal class ScreenshotCapture( } } - private fun encode( + private suspend fun encode( bitmap: Bitmap, policy: ScreenshotPolicy, ): CapturedScreenshot { val scaled = bitmap.downscaledTo(policy.maxLongestEdgePx) - val png = pngEncoder(scaled) + val png = withContext(Dispatchers.IO) { pngEncoder(scaled) } val widthPx = scaled.width val heightPx = scaled.height if (scaled !== bitmap) bitmap.recycle() diff --git a/sdk/full/src/main/kotlin/io/devconsole/SessionMarkers.kt b/sdk/full/src/main/kotlin/io/devconsole/SessionMarkers.kt index d3c12aa..e231345 100644 --- a/sdk/full/src/main/kotlin/io/devconsole/SessionMarkers.kt +++ b/sdk/full/src/main/kotlin/io/devconsole/SessionMarkers.kt @@ -80,6 +80,13 @@ internal class SessionMarkerRecorder( severity = EventSeverity.WARN, ) + fun captureStateChanged(paused: Boolean) = + if (paused) { + emit("system.capture.paused", "Capture paused") + } else { + emit("system.capture.resumed", "Capture resumed") + } + private fun emit( type: String, summary: String, diff --git a/sdk/full/src/test/kotlin/io/devconsole/AndroidDatabaseInspectorTest.kt b/sdk/full/src/test/kotlin/io/devconsole/AndroidDatabaseInspectorTest.kt index 0f37f9a..283722f 100644 --- a/sdk/full/src/test/kotlin/io/devconsole/AndroidDatabaseInspectorTest.kt +++ b/sdk/full/src/test/kotlin/io/devconsole/AndroidDatabaseInspectorTest.kt @@ -45,6 +45,14 @@ class AndroidDatabaseInspectorTest { assertFalse(names.any { it.endsWith("-shm") }) } + @Test + fun `devconsole's own capture database is neither listed nor queryable`() { + application.openOrCreateDatabase("devconsole-events.db", Context.MODE_PRIVATE, null).close() + + assertFalse("devconsole-events.db" in inspector.databases()) + assertNull(inspector.tables("devconsole-events.db")) + } + @Test fun `default policy preserves columns covered by built in personal data heuristics`() { val unmasked = AndroidDatabaseInspector(application, RedactionEngine(RedactionPolicy.default())) @@ -75,6 +83,22 @@ class AndroidDatabaseInspectorTest { assertFalse(result.truncated) } + @Test + fun `query truncates large text cells and reports blob byte length`() { + val db = application.openOrCreateDatabase("demo.db", Context.MODE_PRIVATE, null) + db.execSQL("CREATE TABLE IF NOT EXISTS payloads (id INTEGER PRIMARY KEY, payload TEXT, image BLOB)") + db.execSQL( + "INSERT INTO payloads (id, payload, image) VALUES (1, ?, ?)", + arrayOf("x".repeat(8_000), byteArrayOf(1, 2, 3)), + ) + db.close() + + val result = requireNotNull(inspector.query("demo.db", "payloads")) + + assertEquals(4_096, result.rows.single()[1].length) + assertEquals("[blob 3 bytes]", result.rows.single()[2]) + } + @Test fun `query includes each row's rowid for safe per-row edits`() { val db = application.openOrCreateDatabase("demo.db", Context.MODE_PRIVATE, null) diff --git a/sdk/full/src/test/kotlin/io/devconsole/AndroidMockRuleStoreTest.kt b/sdk/full/src/test/kotlin/io/devconsole/AndroidMockRuleStoreTest.kt index 0505483..602652c 100644 --- a/sdk/full/src/test/kotlin/io/devconsole/AndroidMockRuleStoreTest.kt +++ b/sdk/full/src/test/kotlin/io/devconsole/AndroidMockRuleStoreTest.kt @@ -20,6 +20,7 @@ class AndroidMockRuleStoreTest { private val application: Application = ApplicationProvider.getApplicationContext() private val preferencesName = "mock-rule-test-${UUID.randomUUID()}" + @Suppress("LongMethod") // One end-to-end scenario; splitting it would hide the ordering it checks. @Test fun `round trips every supported durable mock action and compatibility metadata`() { val store = AndroidMockRuleStore(application, preferencesName) @@ -39,6 +40,25 @@ class AndroidMockRuleStoreTest { MockAction.ConnectionFailure("offline"), MockAction.Timeout(100), MockAction.BodyReplacement("replacement"), + MockAction.Sequence( + steps = + listOf( + MockAction.StaticResponse(503, "retry"), + MockAction.StaticResponse(200, "ok"), + ), + loop = true, + ), + MockAction.MapRemote( + scheme = "https", + host = "staging.api.test", + port = 8443, + path = "/v2/orders", + ), + MockAction.Throttle( + bytesPerSecond = 65_536, + latencyMs = 50, + next = MockAction.StaticResponse(200, "throttled"), + ), MockAction.Passthrough, ) val rules = diff --git a/sdk/full/src/test/kotlin/io/devconsole/AndroidPreferencesInspectorTest.kt b/sdk/full/src/test/kotlin/io/devconsole/AndroidPreferencesInspectorTest.kt index 77df027..ea07da3 100644 --- a/sdk/full/src/test/kotlin/io/devconsole/AndroidPreferencesInspectorTest.kt +++ b/sdk/full/src/test/kotlin/io/devconsole/AndroidPreferencesInspectorTest.kt @@ -44,6 +44,30 @@ class AndroidPreferencesInspectorTest { assertEquals("INT", file.entries.first { it.key == "launches" }.type) } + @Test + fun `devconsole's own preference files are never listed or writable`() { + listOf("io.devconsole.mock_rules", "devconsole.ui").forEach { name -> + application + .getSharedPreferences(name, Context.MODE_PRIVATE) + .edit() + .putString("k", "v") + .commit() + } + application + .getSharedPreferences("host_prefs", Context.MODE_PRIVATE) + .edit() + .putString("k", "v") + .commit() + + val names = inspector.files().map { it.name } + + assertTrue("host_prefs" in names) + assertFalse("io.devconsole.mock_rules" in names) + assertFalse("devconsole.ui" in names) + assertFalse(inspector.put("io.devconsole.mock_rules", "rules", "[]", "STRING")) + assertFalse(inspector.remove("devconsole.ui", "k")) + } + @Test fun `string values are redacted while primitives are shown verbatim`() { application @@ -63,6 +87,29 @@ class AndroidPreferencesInspectorTest { assertFalse(countEntry.redacted) } + @Test + fun `sensitive key variants are redacted consistently`() { + application + .getSharedPreferences("variant_prefs", Context.MODE_PRIVATE) + .edit() + .putString("auth_token", "auth-secret") + .putString("apiKey", "api-secret") + .putString("private.key", "private-secret") + .commit() + + val entries = + inspector + .files() + .first { it.name == "variant_prefs" } + .entries + .associateBy { it.key } + + listOf("auth_token", "apiKey", "private.key").forEach { key -> + assertEquals("", entries.getValue(key).value) + assertTrue(entries.getValue(key).redacted) + } + } + @Test fun `default policy preserves token looking preference values`() { application diff --git a/sdk/full/src/test/kotlin/io/devconsole/AndroidRemoteConfigOverrideStoreTest.kt b/sdk/full/src/test/kotlin/io/devconsole/AndroidRemoteConfigOverrideStoreTest.kt new file mode 100644 index 0000000..aefb5ce --- /dev/null +++ b/sdk/full/src/test/kotlin/io/devconsole/AndroidRemoteConfigOverrideStoreTest.kt @@ -0,0 +1,98 @@ +/** + * @author Shakib + * @since 04/11/26 + */ +package io.devconsole + +import android.app.Application +import android.content.Context +import androidx.test.core.app.ApplicationProvider +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34]) +class AndroidRemoteConfigOverrideStoreTest { + private val application: Application = ApplicationProvider.getApplicationContext() + + private fun preferences() = + application.getSharedPreferences("devconsole_remote_config_overrides", Context.MODE_PRIVATE) + + @Before + fun clearPersistedOverrides() { + preferences().edit().clear().commit() + } + + @Test + fun `persists overrides and reloads them into a fresh store`() { + val store = AndroidRemoteConfigOverrideStore() + store.attach(application) + store.setOverride("firebase", "flag", "true") + store.setOverride("firebase", "other", "1") + + val reloaded = AndroidRemoteConfigOverrideStore() + reloaded.attach(application) + + assertEquals(mapOf("firebase" to mapOf("flag" to "true", "other" to "1")), reloaded.overrides()) + } + + @Test + fun `an override set before attach wins over the persisted one`() { + val first = AndroidRemoteConfigOverrideStore() + first.attach(application) + first.setOverride("firebase", "flag", "persisted") + + val second = AndroidRemoteConfigOverrideStore() + second.setOverride("firebase", "flag", "in-memory") + second.attach(application) + + assertEquals("in-memory", second.overrides().getValue("firebase").getValue("flag")) + val reread = AndroidRemoteConfigOverrideStore() + reread.attach(application) + assertEquals("in-memory", reread.overrides().getValue("firebase").getValue("flag")) + } + + @Test + fun `clearOverride and clearAll remove the persisted entries`() { + val store = AndroidRemoteConfigOverrideStore() + store.attach(application) + store.setOverride("firebase", "flag", "true") + store.setOverride("firebase", "other", "1") + + store.clearOverride("firebase", "flag") + + assertFalse(preferences().all.containsValue("true")) + store.clearAll() + assertTrue(preferences().all.isEmpty()) + assertTrue(store.overrides().isEmpty()) + } + + @Test + fun `provider ids containing a colon round-trip through the pref encoding`() { + val store = AndroidRemoteConfigOverrideStore() + store.attach(application) + store.setOverride("firebase:prod", "flag:sub", "value") + + val reloaded = AndroidRemoteConfigOverrideStore() + reloaded.attach(application) + + assertEquals("value", reloaded.overrides().getValue("firebase:prod").getValue("flag:sub")) + } + + @Test + fun `corrupt pref entries are ignored rather than failing attach`() { + preferences().edit().putString("not-a-valid-key", "value").commit() + preferences().edit().putString("99:short", "value").commit() + + val store = AndroidRemoteConfigOverrideStore() + store.attach(application) + + assertTrue(store.overrides().isEmpty()) + } +} diff --git a/sdk/full/src/test/kotlin/io/devconsole/CaptureGateTest.kt b/sdk/full/src/test/kotlin/io/devconsole/CaptureGateTest.kt new file mode 100644 index 0000000..cc743ec --- /dev/null +++ b/sdk/full/src/test/kotlin/io/devconsole/CaptureGateTest.kt @@ -0,0 +1,144 @@ +/** + * @author Shakib + * @since 03/11/26 + */ +package io.devconsole + +import io.devconsole.network.InMemoryNetworkTransactionStore +import io.devconsole.network.NetworkCaptureFactory +import io.devconsole.network.NetworkCursorCodec +import io.devconsole.network.NetworkRequestInput +import io.devconsole.network.NetworkResponseInput +import io.devconsole.network.NetworkTransaction +import io.devconsole.push.InMemoryPushStore +import io.devconsole.push.PushEvent +import io.devconsole.security.RedactionEngine +import io.devconsole.security.RedactionPolicy +import io.devconsole.socket.InMemorySocketStore +import io.devconsole.socket.SocketConnection +import io.devconsole.socket.SocketDirection +import io.devconsole.socket.SocketMessage +import io.devconsole.socket.SocketPayload +import io.devconsole.storage.api.StoredEvent +import io.devconsole.timeline.TimelineAppender +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test +import java.util.concurrent.atomic.AtomicLong + +class CaptureGateTest { + private val collected = mutableListOf() + private val appender = + object : TimelineAppender { + override fun append(event: StoredEvent) { + collected.add(event) + } + } + private val sequence = AtomicLong(0) + private val bridge = CaptureTimelineBridge("session-1", { appender }, { null }, sequence::incrementAndGet) + private val factory = NetworkCaptureFactory(RedactionEngine(RedactionPolicy.recommended())) + + @Suppress("LongMethod") // One end-to-end scenario; splitting it would hide the ordering it checks. + @Test + fun `paused gate drops new network transaction ids but allows updates to already recorded ids`() { + val gate = CaptureGate() + val store = + TeeingNetworkTransactionStore( + delegate = InMemoryNetworkTransactionStore(NetworkCursorCodec(ByteArray(16))), + bridge = bridge, + captureGate = gate, + ) + val initialCapture = factory.capture(NetworkRequestInput("GET", "https://api.test/inflight"), null) + store.record( + NetworkTransaction( + "tx-inflight", + startedAtEpochMs = 10L, + completedAtEpochMs = null, + capture = initialCapture, + ), + ) + assertEquals(1, collected.size) + + assertTrue(gate.setPaused(true)) + assertFalse(gate.setPaused(true)) + assertTrue(gate.isPaused()) + + val blockedCapture = + factory.capture(NetworkRequestInput("GET", "https://api.test/new"), NetworkResponseInput(200)) + store.record( + NetworkTransaction( + "tx-new", + startedAtEpochMs = 20L, + completedAtEpochMs = 25L, + capture = blockedCapture, + ), + ) + assertNull(store.find("tx-new")) + assertEquals(1, collected.size) + + val completedCapture = + factory.capture(NetworkRequestInput("GET", "https://api.test/inflight"), NetworkResponseInput(200)) + store.record( + NetworkTransaction( + "tx-inflight", + startedAtEpochMs = 10L, + completedAtEpochMs = 30L, + capture = completedCapture, + ), + ) + val updated = store.find("tx-inflight") + assertNotNull(updated) + assertEquals(200, updated?.capture?.response?.statusCode) + assertEquals(2, collected.size) + + assertTrue(gate.setPaused(false)) + assertFalse(gate.isPaused()) + + store.record( + NetworkTransaction( + "tx-after-resume", + startedAtEpochMs = 40L, + completedAtEpochMs = 45L, + capture = blockedCapture, + ), + ) + assertNotNull(store.find("tx-after-resume")) + assertEquals(3, collected.size) + } + + @Test + fun `paused gate drops new socket connections and push events`() { + val gate = CaptureGate(initialPaused = true) + val socketStore = TeeingSocketStore(InMemorySocketStore(), bridge, captureGate = gate) + val pushStore = TeeingPushStore(InMemoryPushStore(), bridge, captureGate = gate) + + socketStore.open(SocketConnection(id = "c1", url = "wss://api.test/ws", openedAtEpochMs = 10L)) + socketStore.append( + SocketMessage( + connectionId = "c1", + direction = SocketDirection.SENT, + timestampEpochMs = 11L, + payload = SocketPayload.Text("hello"), + ), + ) + pushStore.append(PushEvent(provider = "fcm", data = emptyMap(), messageId = "p1")) + + assertNull(socketStore.connection("c1")) + assertTrue(pushStore.events().isEmpty()) + assertTrue(collected.isEmpty()) + } + + @Test + fun `session marker recorder emits capture paused and capture resumed system events`() { + val markers = SessionMarkerRecorder(bridge) + + markers.captureStateChanged(paused = true) + markers.captureStateChanged(paused = false) + + assertEquals(listOf("system.capture.paused", "system.capture.resumed"), collected.map(StoredEvent::type)) + assertEquals(listOf("Capture paused", "Capture resumed"), collected.map(StoredEvent::summary)) + } +} diff --git a/sdk/full/src/test/kotlin/io/devconsole/CrashCaptureTest.kt b/sdk/full/src/test/kotlin/io/devconsole/CrashCaptureTest.kt index 783956a..af881f1 100644 --- a/sdk/full/src/test/kotlin/io/devconsole/CrashCaptureTest.kt +++ b/sdk/full/src/test/kotlin/io/devconsole/CrashCaptureTest.kt @@ -23,6 +23,7 @@ import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config +import java.nio.file.Files import java.util.concurrent.atomic.AtomicInteger import kotlin.system.measureTimeMillis @@ -104,6 +105,63 @@ class CrashCaptureTest { ) } + @Test + fun `the exception summary is redacted`() { + val capture = capture() + val original = Thread.getDefaultUncaughtExceptionHandler() + Thread.setDefaultUncaughtExceptionHandler { _, _ -> } + try { + capture.install() + Thread.getDefaultUncaughtExceptionHandler()!!.uncaughtException( + Thread.currentThread(), + IllegalStateException("Failed https://api.test/login?password=topsecret123"), + ) + assertFalse("topsecret123" in appended.single().summary) + } finally { + capture.disable() + Thread.setDefaultUncaughtExceptionHandler(original) + } + } + + @Test + fun `pending crash file round trips through import`() { + val file = Files.createTempDirectory("devconsole-crash").resolve("pending-crash.json").toFile() + val pending = + CrashCapture( + sessionId = { "session" }, + redaction = RedactionEngine(RedactionPolicy.recommended()), + appender = { null }, + store = { null }, + sessionStore = { null }, + pendingCrashFile = { file }, + ) + val original = Thread.getDefaultUncaughtExceptionHandler() + Thread.setDefaultUncaughtExceptionHandler { _, _ -> } + try { + pending.install() + Thread.getDefaultUncaughtExceptionHandler()!!.uncaughtException( + Thread.currentThread(), + IllegalStateException("Failed https://api.test/login?password=topsecret123"), + ) + assertTrue(file.isFile) + val importer = + CrashCapture( + sessionId = "next", + redaction = RedactionEngine(RedactionPolicy.recommended()), + appender = { appender }, + store = { store }, + ) + importer.importPendingCrash(file, "next") + assertFalse(file.exists()) + assertEquals("next", persisted.single().sessionId) + assertFalse("topsecret123" in persisted.single().summary) + } finally { + pending.disable() + Thread.setDefaultUncaughtExceptionHandler(original) + file.parentFile?.deleteRecursively() + } + } + @Test fun `the payload is valid JSON with an empty breadcrumbs array when none is wired`() { capture().recordAnr("main", "\tat Foo.bar") diff --git a/sdk/full/src/test/kotlin/io/devconsole/DevConsoleInitializerTest.kt b/sdk/full/src/test/kotlin/io/devconsole/DevConsoleInitializerTest.kt new file mode 100644 index 0000000..98e2c3a --- /dev/null +++ b/sdk/full/src/test/kotlin/io/devconsole/DevConsoleInitializerTest.kt @@ -0,0 +1,18 @@ +/** + * @author Shakib + * @since 04/11/26 + */ +package io.devconsole + +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class DevConsoleInitializerTest { + @Test + fun `main process decision accepts configured name or package fallback`() { + assertTrue(DevConsoleInitializer.isMainProcessName("app", "app", "app")) + assertFalse(DevConsoleInitializer.isMainProcessName("app:remote", "app", "app")) + assertTrue(DevConsoleInitializer.isMainProcessName("app", null, "app")) + } +} diff --git a/sdk/full/src/test/kotlin/io/devconsole/FileComposerCollectionStoreTest.kt b/sdk/full/src/test/kotlin/io/devconsole/FileComposerCollectionStoreTest.kt new file mode 100644 index 0000000..d176e1d --- /dev/null +++ b/sdk/full/src/test/kotlin/io/devconsole/FileComposerCollectionStoreTest.kt @@ -0,0 +1,197 @@ +/** + * @author Shakib + * @since 03/11/26 + */ +package io.devconsole + +import io.devconsole.composer.ComposerBinaryBody +import io.devconsole.composer.ComposerBodyType +import io.devconsole.composer.ComposerCollectionStore +import io.devconsole.composer.ComposerMultipartPart +import io.devconsole.composer.ComposerQueryParameter +import io.devconsole.composer.ComposerRequest +import io.devconsole.composer.ComposerVariable +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import java.io.File +import java.nio.charset.StandardCharsets + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34]) +class FileComposerCollectionStoreTest { + @get:Rule + val tempFolder = TemporaryFolder() + + @Test + fun `save two collections then reload in new store instance returns both with identical fields`() { + val file = File(tempFolder.newFolder(), "composer-collections.json") + val store1: ComposerCollectionStore = FileComposerCollectionStore(file) + + val req1 = sampleJsonRequest() + val req2 = sampleMultipartRequest() + + store1.save("First", req1) + store1.save("Second", req2) + + assertTrue(file.exists()) + + val store2: ComposerCollectionStore = FileComposerCollectionStore(file) + val collections = store2.collections() + assertEquals(2, collections.size) + + val first = collections.first { it.name == "First" } + assertEquals("POST", first.request.method) + assertEquals("https://api.test/v1/resource", first.request.url) + assertEquals(mapOf("Authorization" to "Bearer test-token", "X-Custom" to "1"), first.request.headers) + assertEquals("{\"key\":\"value\"}", first.request.body) + assertEquals(ComposerBodyType.JSON, first.request.bodyType) + assertEquals(1, first.request.query.size) + assertEquals("page", first.request.query[0].name) + assertEquals("1", first.request.query[0].value) + assertEquals(10_000, first.request.timeoutMs) + assertFalse(first.request.followRedirects) + assertEquals(listOf(ComposerVariable("env", "prod", secret = false)), first.request.variables) + + val second = collections.first { it.name == "Second" } + assertEquals("PUT", second.request.method) + assertEquals("https://api.test/v2/upload", second.request.url) + assertEquals(ComposerBodyType.MULTIPART, second.request.bodyType) + assertEquals(mapOf("field" to "val"), second.request.formFields) + assertEquals(1, second.request.multipartParts.size) + assertEquals("doc.txt", second.request.multipartParts[0].fileName) + // Redaction never persists raw binary uploads; only the file identity survives. + assertEquals("blob.bin", second.request.binaryBody?.fileName) + assertEquals( + 0, + second.request.binaryBody + ?.bytes + ?.size, + ) + } + + @Test + fun `remove persists changes across store instances`() { + val file = File(tempFolder.newFolder(), "composer-collections.json") + val store1: ComposerCollectionStore = FileComposerCollectionStore(file) + + val col1 = store1.save("Req 1", ComposerRequest(method = "GET", url = "https://api.test/1")) + val col2 = store1.save("Req 2", ComposerRequest(method = "GET", url = "https://api.test/2")) + + assertTrue(store1.remove(col1.id)) + + val store2: ComposerCollectionStore = FileComposerCollectionStore(file) + val remaining = store2.collections() + assertEquals(1, remaining.size) + assertEquals(col2.name, remaining[0].name) + assertEquals(col2.request.url, remaining[0].request.url) + } + + @Test + fun `corrupt file starts empty and creates corrupt backup copy`() { + val folder = tempFolder.newFolder() + val file = File(folder, "composer-collections.json") + file.writeText("{ not-valid-json ", StandardCharsets.UTF_8) + + val store: ComposerCollectionStore = FileComposerCollectionStore(file) + val collections = store.collections() + assertTrue(collections.isEmpty()) + + val corruptFile = File(folder, "composer-collections.json.corrupt") + assertTrue(corruptFile.exists()) + assertEquals("{ not-valid-json ", corruptFile.readText(StandardCharsets.UTF_8)) + } + + @Test + fun `unknown version file is set aside and starts empty`() { + val folder = tempFolder.newFolder() + val file = File(folder, "composer-collections.json") + file.writeText("{\"v\":999,\"collections\":[]}", StandardCharsets.UTF_8) + + val store: ComposerCollectionStore = FileComposerCollectionStore(file) + val collections = store.collections() + assertTrue(collections.isEmpty()) + assertTrue(File(folder, "composer-collections.json.corrupt").exists()) + } + + @Test + fun `collection containing a secret variable value does not have secret in file text`() { + val file = File(tempFolder.newFolder(), "composer-collections.json") + val store: ComposerCollectionStore = FileComposerCollectionStore(file) + + val secretValue = "super-secret-password-12345" + val request = + ComposerRequest( + method = "POST", + url = "https://api.test/login", + variables = + listOf( + ComposerVariable(name = "password", value = secretValue, secret = true), + ComposerVariable(name = "username", value = "admin", secret = false), + ), + ) + + store.save("Login", request) + + val fileText = file.readText(StandardCharsets.UTF_8) + assertFalse(fileText.contains(secretValue)) + assertTrue(fileText.contains("admin")) + assertTrue(fileText.contains("password")) + + val store2: ComposerCollectionStore = FileComposerCollectionStore(file) + val loaded = store2.collections().single() + val secretVar = loaded.request.variables.first { it.name == "password" } + assertTrue(secretVar.secret) + assertEquals("", secretVar.value) + } + + private fun sampleJsonRequest(): ComposerRequest = + ComposerRequest( + method = "POST", + url = "https://api.test/v1/resource", + headers = mapOf("Authorization" to "Bearer test-token", "X-Custom" to "1"), + body = "{\"key\":\"value\"}", + query = listOf(ComposerQueryParameter("page", "1")), + bodyType = ComposerBodyType.JSON, + formFields = emptyMap(), + multipartParts = emptyList(), + timeoutMs = 10_000, + followRedirects = false, + variables = listOf(ComposerVariable("env", "prod", secret = false)), + ) + + private fun sampleMultipartRequest(): ComposerRequest = + ComposerRequest( + method = "PUT", + url = "https://api.test/v2/upload", + headers = mapOf("Content-Type" to "multipart/form-data"), + body = null, + query = emptyList(), + bodyType = ComposerBodyType.MULTIPART, + formFields = mapOf("field" to "val"), + multipartParts = + listOf( + ComposerMultipartPart( + name = "file", + value = "content", + fileName = "doc.txt", + contentType = "text/plain", + ), + ), + binaryBody = + ComposerBinaryBody( + fileName = "blob.bin", + contentType = "application/octet-stream", + bytes = byteArrayOf(0x01, 0x02, 0x03), + ), + timeoutMs = 20_000, + followRedirects = true, + variables = emptyList(), + ) +} diff --git a/sdk/full/src/test/kotlin/io/devconsole/FullFacadeTest.kt b/sdk/full/src/test/kotlin/io/devconsole/FullFacadeTest.kt index eb4566a..dccfab8 100644 --- a/sdk/full/src/test/kotlin/io/devconsole/FullFacadeTest.kt +++ b/sdk/full/src/test/kotlin/io/devconsole/FullFacadeTest.kt @@ -122,13 +122,20 @@ class FullFacadeTest { runTest { val provider = PlatformFacadeProvider() provider.initialize(ApplicationProvider.getApplicationContext(), DevConsoleConfig.default()) - val request = StartRequest(BindingMode.LOOPBACK, 8890..8893) + // An OS-assigned free port, not a fixed range: with the configuration cache Gradle runs the + // debug and release unit-test JVMs side by side, and a shared fixed range let one variant + // grab the port during the other's restart window. A one-port range also makes "reclaims" + // strict -- the restart cannot quietly fall forward to a neighbour. + val port = java.net.ServerSocket(0).use { it.localPort } + val request = StartRequest(BindingMode.LOOPBACK, port..port) - val first = provider.startBrowser(request) as StartResult.Started - val second = provider.startBrowser(request) as StartResult.Started + val first = provider.startBrowser(request) + assertTrue("first start: $first", first is StartResult.Started) + val second = provider.startBrowser(request) + assertTrue("restart: $second", second is StartResult.Started) - assertTrue(first.endpoint.port in request.portRange) - assertEquals(first.endpoint.port, second.endpoint.port) + assertEquals(port, (first as StartResult.Started).endpoint.port) + assertEquals(port, (second as StartResult.Started).endpoint.port) assertEquals(DevConsoleState.Running, provider.state().value) provider.stop(StopReason.UserRequested) } diff --git a/sdk/full/src/test/kotlin/io/devconsole/FullInspectorDataSourceTest.kt b/sdk/full/src/test/kotlin/io/devconsole/FullInspectorDataSourceTest.kt index f78c3a4..41208a9 100644 --- a/sdk/full/src/test/kotlin/io/devconsole/FullInspectorDataSourceTest.kt +++ b/sdk/full/src/test/kotlin/io/devconsole/FullInspectorDataSourceTest.kt @@ -26,6 +26,13 @@ import io.devconsole.network.NetworkTransaction import io.devconsole.push.InMemoryPushStore import io.devconsole.push.PushEvent import io.devconsole.push.PushLifecycle +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 io.devconsole.server.api.DatabaseExecResult @@ -68,9 +75,12 @@ import io.devconsole.ui.compose.InspectorBrowserUi import io.devconsole.ui.compose.InspectorCommandResult import io.devconsole.ui.compose.InspectorComposerRequest import io.devconsole.ui.compose.InspectorHealthUi +import io.devconsole.ui.compose.InspectorMockActionType +import io.devconsole.ui.compose.InspectorMockRuleUi import io.devconsole.ui.compose.InspectorRetentionUi import io.devconsole.ui.compose.InspectorSessionUi import io.devconsole.ui.compose.InspectorSqlResultUi +import io.devconsole.ui.compose.InspectorTrafficQuery import kotlinx.coroutines.test.runTest import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse @@ -144,6 +154,42 @@ class FullInspectorDataSourceTest { .build(), ) + @Suppress("LongParameterList") // A flat mirror of InspectorMockRuleUi's action/predicate fields. + private fun mockRuleUi( + id: String, + actionType: InspectorMockActionType = InspectorMockActionType.STATIC, + statusCode: Int = 200, + body: String = "", + failureMessage: String? = null, + timeoutMs: Long? = null, + throttleBytesPerSecond: Long? = null, + throttleLatencyMs: Long? = null, + remoteScheme: String? = null, + remoteHost: String? = null, + remotePort: Int? = null, + remotePath: String? = null, + queryPredicates: Map = emptyMap(), + headerPredicates: Map = emptyMap(), + bodyPredicate: String? = null, + ): InspectorMockRuleUi = + InspectorMockRuleUi( + id = id, + actionType = actionType, + statusCode = statusCode, + body = body, + failureMessage = failureMessage, + timeoutMs = timeoutMs, + throttleBytesPerSecond = throttleBytesPerSecond, + throttleLatencyMs = throttleLatencyMs, + remoteScheme = remoteScheme, + remoteHost = remoteHost, + remotePort = remotePort, + remotePath = remotePath, + queryPredicates = queryPredicates, + headerPredicates = headerPredicates, + bodyPredicate = bodyPredicate, + ) + private class FakeFileInspector( private val rootsData: List = listOf("files"), private val listing: FileListingData? = null, @@ -519,6 +565,30 @@ class FullInspectorDataSourceTest { assertNull(store.find("tx-1")) } + @Test + fun `snapshot traffic query narrows captures to the requested host`() { + val store = networkStore() + recordTransaction( + store, + "tx-api", + startedAtEpochMs = 0, + completedAtEpochMs = 5, + url = "https://api.example.test/orders", + ) + recordTransaction( + store, + "tx-other", + startedAtEpochMs = 10, + completedAtEpochMs = 15, + url = "https://other.example.test/orders", + ) + val source = FullInspectorDataSource(store, MockEngine(emptyList()), configSupplier = { null }) + + val filtered = source.snapshot(InspectorTrafficQuery(host = "api.example.test")) + + assertEquals(listOf("tx-api"), filtered.transactions.map { it.id }) + } + /** * Evidence is durable and materialized at flag time -- clearing the live capture buffer must not * take collected bug evidence with it. @@ -939,6 +1009,141 @@ class FullInspectorDataSourceTest { assertTrue(mockEngine.rules().isEmpty()) } + @Suppress("LongMethod") // One row per editable action type; splitting would duplicate the fixture. + @Test + fun `upsertMockRule builds every editable action type and mockRules round-trips it`() { + val mockEngine = MockEngine(emptyList()) + val source = FullInspectorDataSource(networkStore(), mockEngine, configSupplier = { configWith(mocks = true) }) + + val results = + listOf( + source.upsertMockRule(mockRuleUi("static", statusCode = 201, body = "{}")), + source.upsertMockRule( + mockRuleUi("status", InspectorMockActionType.STATUS_OVERRIDE, statusCode = 503), + ), + source.upsertMockRule( + mockRuleUi("body", InspectorMockActionType.BODY_REPLACEMENT, body = """{"x":1}"""), + ), + source.upsertMockRule( + mockRuleUi("connect", InspectorMockActionType.CONNECTION_FAILURE, failureMessage = "offline"), + ), + source.upsertMockRule( + mockRuleUi("timeout", InspectorMockActionType.TIMEOUT, timeoutMs = 2_500), + ), + source.upsertMockRule( + mockRuleUi( + "throttle", + InspectorMockActionType.THROTTLE, + throttleBytesPerSecond = 65_536, + throttleLatencyMs = 120, + ), + ), + source.upsertMockRule( + mockRuleUi( + "remote", + InspectorMockActionType.MAP_REMOTE, + remoteScheme = "https", + remoteHost = "staging.test", + remotePort = 8443, + remotePath = "/v2", + ), + ), + ) + results.forEach { assertTrue(it is InspectorCommandResult.Success) } + + val actions = mockEngine.rules().associate { it.id to it.action } + assertTrue(actions.getValue("static") is MockAction.StaticResponse) + assertEquals(503, (actions.getValue("status") as MockAction.StatusOverride).statusCode) + assertEquals("""{"x":1}""", (actions.getValue("body") as MockAction.BodyReplacement).body) + assertEquals("offline", (actions.getValue("connect") as MockAction.ConnectionFailure).message) + assertEquals(2_500L, (actions.getValue("timeout") as MockAction.Timeout).durationMs) + val throttle = actions.getValue("throttle") as MockAction.Throttle + assertEquals(65_536L, throttle.bytesPerSecond) + assertEquals(120L, throttle.latencyMs) + assertTrue(throttle.next == MockAction.Passthrough) + val remote = actions.getValue("remote") as MockAction.MapRemote + assertEquals("https", remote.scheme) + assertEquals("staging.test", remote.host) + assertEquals(8443, remote.port) + assertEquals("/v2", remote.path) + + val ui = source.mockRules().associateBy { it.id } + assertEquals(InspectorMockActionType.STATUS_OVERRIDE, ui.getValue("status").actionType) + assertEquals(503, ui.getValue("status").statusCode) + assertEquals(InspectorMockActionType.BODY_REPLACEMENT, ui.getValue("body").actionType) + assertEquals("""{"x":1}""", ui.getValue("body").body) + assertEquals(InspectorMockActionType.CONNECTION_FAILURE, ui.getValue("connect").actionType) + assertEquals("offline", ui.getValue("connect").failureMessage) + assertEquals(InspectorMockActionType.TIMEOUT, ui.getValue("timeout").actionType) + assertEquals(2_500L, ui.getValue("timeout").timeoutMs) + assertEquals(InspectorMockActionType.THROTTLE, ui.getValue("throttle").actionType) + assertEquals(65_536L, ui.getValue("throttle").throttleBytesPerSecond) + assertEquals(120L, ui.getValue("throttle").throttleLatencyMs) + assertEquals(InspectorMockActionType.MAP_REMOTE, ui.getValue("remote").actionType) + assertEquals("https", ui.getValue("remote").remoteScheme) + assertEquals("staging.test", ui.getValue("remote").remoteHost) + assertEquals(8443, ui.getValue("remote").remotePort) + assertEquals("/v2", ui.getValue("remote").remotePath) + } + + @Test + fun `upsertMockRule carries query, header and body predicates into the engine rule`() { + val mockEngine = MockEngine(emptyList()) + val source = FullInspectorDataSource(networkStore(), mockEngine, configSupplier = { configWith(mocks = true) }) + + source.upsertMockRule( + mockRuleUi( + "predicated", + queryPredicates = mapOf("page" to "2"), + headerPredicates = mapOf("Accept" to "application/json"), + bodyPredicate = ".*paid.*", + ), + ) + + val engineRule = mockEngine.rules().single() + assertEquals(mapOf("page" to "2"), engineRule.queryPredicates) + assertEquals(mapOf("Accept" to "application/json"), engineRule.headerPredicates) + assertEquals(".*paid.*", engineRule.bodyPredicate) + + val ui = source.mockRules().single() + assertEquals(mapOf("page" to "2"), ui.queryPredicates) + assertEquals(mapOf("Accept" to "application/json"), ui.headerPredicates) + assertEquals(".*paid.*", ui.bodyPredicate) + } + + @Test + fun `upsertMockRule refuses an other action and leaves the stored sequence rule untouched`() { + val sequenceAction = + MockAction.Sequence( + listOf(MockAction.StaticResponse(200, "first"), MockAction.StaticResponse(500, "second")), + ) + val mockEngine = MockEngine(listOf(MockRule(id = "seq", priority = 0, action = sequenceAction))) + val source = FullInspectorDataSource(networkStore(), mockEngine, configSupplier = { configWith(mocks = true) }) + + val result = + source.upsertMockRule( + mockRuleUi("seq", InspectorMockActionType.OTHER, body = "clobbered"), + ) + + assertTrue(result is InspectorCommandResult.Invalid) + assertEquals(sequenceAction, mockEngine.rules().single().action) + assertEquals(InspectorMockActionType.OTHER, source.mockRules().single().actionType) + } + + @Test + fun `upsertMockRule rejects an out-of-range throttle rate`() { + val mockEngine = MockEngine(emptyList()) + val source = FullInspectorDataSource(networkStore(), mockEngine, configSupplier = { configWith(mocks = true) }) + + val result = + source.upsertMockRule( + mockRuleUi("throttle", InspectorMockActionType.THROTTLE, throttleBytesPerSecond = 0), + ) + + assertTrue(result is InspectorCommandResult.Invalid) + assertTrue(mockEngine.rules().isEmpty()) + } + @Test fun `execute is disabled when requestExecution capability is off`() { val mockEngine = MockEngine(emptyList()) @@ -1627,6 +1832,25 @@ class FullInspectorDataSourceTest { assertTrue(token.redacted) } + @Test + fun `snapshot converts a state provider exception to an error entry`() { + val registry = StateRegistry() + registry.register(stateProvider("broken") { error("host provider failed") }) + val source = + FullInspectorDataSource( + networkStore(), + MockEngine(emptyList()), + configSupplier = { null }, + stateRegistry = registry, + ) + + val provider = source.snapshot().stateProviders.single() + + assertEquals("broken", provider.id) + assertEquals("error", provider.entries.single().key) + assertEquals("host provider failed", provider.entries.single().value) + } + @Test fun `snapshot yields empty state providers when no registry is supplied`() { val source = @@ -1639,6 +1863,107 @@ class FullInspectorDataSourceTest { assertTrue(source.snapshot().stateProviders.isEmpty()) } + private fun fixedRemoteConfigProvider(): RemoteConfigProvider = + object : RemoteConfigProvider { + override val id = "firebase" + + override fun snapshot(): RemoteConfigSnapshot = + RemoteConfigSnapshot( + providerId = id, + entries = listOf(RemoteConfigEntry("flag", "false", RemoteConfigSource.REMOTE)), + fetchInfo = + RemoteConfigFetchInfo( + lastFetchEpochMs = 1_000, + status = RemoteConfigFetchStatus.SUCCESS, + minimumFetchIntervalSeconds = 60, + ), + ) + } + + private fun remoteConfigSource(editable: Boolean = true): FullInspectorDataSource = + FullInspectorDataSource( + networkStore(), + MockEngine(emptyList()), + configSupplier = { configWith(featureFlags = true) }, + remoteConfigRegistry = RemoteConfigRegistry().apply { register(fixedRemoteConfigProvider()) }, + remoteConfigOverridesEditable = { editable }, + ) + + @Test + fun `setRemoteConfigOverride applies locally and clear restores the provider value`() { + val source = remoteConfigSource() + assertTrue(source.supportsRemoteConfigOverrides()) + + assertTrue(source.setRemoteConfigOverride("firebase", "flag", "true") is InspectorCommandResult.Success) + + val overridden = + source + .snapshot() + .remoteConfig + .single() + .entries + .single() + assertEquals("true", overridden.value) + assertEquals("override", overridden.source) + assertEquals("false", overridden.providerValue) + assertEquals("remote", overridden.providerSource) + + assertTrue(source.clearRemoteConfigOverride("firebase", "flag") is InspectorCommandResult.Success) + + val restored = + source + .snapshot() + .remoteConfig + .single() + .entries + .single() + assertEquals("false", restored.value) + assertNull(restored.providerValue) + assertNull(restored.providerSource) + } + + @Test + fun `clearAllRemoteConfigOverrides removes every override`() { + val source = remoteConfigSource() + source.setRemoteConfigOverride("firebase", "flag", "true") + source.setRemoteConfigOverride("firebase", "extra", "1") + + assertTrue(source.clearAllRemoteConfigOverrides() is InspectorCommandResult.Success) + assertTrue( + source + .snapshot() + .remoteConfig + .single() + .entries + .none { it.overridden }, + ) + } + + @Test + fun `setRemoteConfigOverride reports Invalid rather than throwing for a blank key`() { + val source = remoteConfigSource() + + val result = source.setRemoteConfigOverride("firebase", " ", "value") + + assertTrue(result is InspectorCommandResult.Invalid) + } + + @Test + fun `remote config override mutations are Unavailable when editing is not allowed`() { + val source = remoteConfigSource(editable = false) + + assertFalse(source.supportsRemoteConfigOverrides()) + assertEquals( + InspectorCommandResult.Unavailable, + source.setRemoteConfigOverride("firebase", "flag", "true"), + ) + assertEquals( + InspectorCommandResult.Unavailable, + source.clearRemoteConfigOverride("firebase", "flag"), + ) + assertEquals(InspectorCommandResult.Unavailable, source.clearAllRemoteConfigOverrides()) + } + @Test fun `setFeatureFlag is disabled and leaves the provider untouched when featureFlags capability is off`() { val flags = SessionFeatureFlags(listOf(FeatureFlag("dark_mode", false))) diff --git a/sdk/full/src/test/kotlin/io/devconsole/PersistentTimelineTest.kt b/sdk/full/src/test/kotlin/io/devconsole/PersistentTimelineTest.kt index 04ed565..afe92f2 100644 --- a/sdk/full/src/test/kotlin/io/devconsole/PersistentTimelineTest.kt +++ b/sdk/full/src/test/kotlin/io/devconsole/PersistentTimelineTest.kt @@ -12,6 +12,7 @@ import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.test.runTest import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse import org.junit.Test class PersistentTimelineTest { @@ -50,7 +51,8 @@ class PersistentTimelineTest { val page = timeline.page(TimelineQuery()) as TimelinePage.Success assertEquals(setOf("persisted", "live"), page.events.map(StoredEvent::id).toSet()) - assertEquals(0, store.inserted.size) + // The live append is mirrored asynchronously by the started writer; only hydrated rows must never be. + assertFalse(synchronized(store) { store.inserted.toList() }.any { it.id == "persisted" }) } @Test @@ -128,7 +130,7 @@ class PersistentTimelineTest { val inserted = mutableListOf() override suspend fun insert(events: List): EventStoreWriteResult { - inserted += events + synchronized(this) { inserted += events } return EventStoreWriteResult.Success(events.size) } diff --git a/sdk/full/src/test/kotlin/io/devconsole/PlatformFacadeProviderCaptureControlTest.kt b/sdk/full/src/test/kotlin/io/devconsole/PlatformFacadeProviderCaptureControlTest.kt new file mode 100644 index 0000000..2d77188 --- /dev/null +++ b/sdk/full/src/test/kotlin/io/devconsole/PlatformFacadeProviderCaptureControlTest.kt @@ -0,0 +1,101 @@ +/** + * @author Shakib + * @since 03/11/26 + */ +package io.devconsole + +import io.devconsole.api.PurgeResult +import io.devconsole.api.SessionExportResult +import io.devconsole.network.InMemoryNetworkTransactionStore +import io.devconsole.network.NetworkCaptureFactory +import io.devconsole.network.NetworkRequestInput +import io.devconsole.network.NetworkResponseInput +import io.devconsole.network.NetworkTransaction +import io.devconsole.push.InMemoryPushStore +import io.devconsole.push.PushEvent +import io.devconsole.security.RedactionEngine +import io.devconsole.security.RedactionPolicy +import io.devconsole.socket.InMemorySocketStore +import io.devconsole.socket.SocketConnection +import kotlinx.coroutines.runBlocking +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +/** Pause/export/purge on the full provider; Robolectric because the provider's ANR watchdog needs a main Looper. */ +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34]) +class PlatformFacadeProviderCaptureControlTest { + @Test + fun `uninitialized full PlatformFacadeProvider reports disabled pause and export states`() { + val provider = PlatformFacadeProvider() + + assertFalse(provider.isCapturePaused()) + assertFalse(provider.setCapturePaused(true)) + assertFalse(provider.isCapturePaused()) + assertEquals(SessionExportResult.Disabled, runBlocking { provider.exportSession() }) + } + + @Test + fun `purgeCapturedData counts and clears in-memory stores`() { + val provider = PlatformFacadeProvider() + val networkStore = + PlatformFacadeProvider::class.java + .getDeclaredField("networkTransactionStore") + .apply { isAccessible = true } + .get(provider) as InMemoryNetworkTransactionStore + val socketStore = + PlatformFacadeProvider::class.java + .getDeclaredField("inMemorySocketStore") + .apply { isAccessible = true } + .get(provider) as InMemorySocketStore + val pushStore = + PlatformFacadeProvider::class.java + .getDeclaredField("inMemoryPushStore") + .apply { isAccessible = true } + .get(provider) as InMemoryPushStore + + val capture = + NetworkCaptureFactory(RedactionEngine(RedactionPolicy.recommended())) + .capture(NetworkRequestInput("GET", "https://api.test/items"), NetworkResponseInput(200)) + networkStore.record( + NetworkTransaction( + "tx-1", + startedAtEpochMs = 1L, + completedAtEpochMs = 2L, + capture = capture, + ), + ) + networkStore.record( + NetworkTransaction( + "tx-2", + startedAtEpochMs = 3L, + completedAtEpochMs = 4L, + capture = capture, + ), + ) + socketStore.open(SocketConnection(id = "sock-1", url = "wss://api.test/ws", openedAtEpochMs = 1L)) + pushStore.append(PushEvent(provider = "fcm", data = emptyMap(), messageId = "msg-1")) + + val purged = runBlocking { provider.purgeCapturedData() } + + assertEquals( + PurgeResult( + networkTransactions = 2, + socketConnections = 1, + pushEvents = 1, + retainedRunsDeleted = 0, + ), + purged, + ) + assertNull(networkStore.find("tx-1")) + assertNull(networkStore.find("tx-2")) + assertTrue(socketStore.connections().isEmpty()) + assertTrue(pushStore.events().isEmpty()) + } +} diff --git a/sdk/full/src/test/kotlin/io/devconsole/PlatformFacadeProviderSessionReadyTest.kt b/sdk/full/src/test/kotlin/io/devconsole/PlatformFacadeProviderSessionReadyTest.kt new file mode 100644 index 0000000..cbf5fe7 --- /dev/null +++ b/sdk/full/src/test/kotlin/io/devconsole/PlatformFacadeProviderSessionReadyTest.kt @@ -0,0 +1,19 @@ +/** + * @author Shakib + * @since 03/11/26 + */ +package io.devconsole + +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class PlatformFacadeProviderSessionReadyTest { + @Test + fun `ready or in-flight bootstrap keeps durable session available`() { + assertTrue(PlatformFacadeProvider.sessionReadyForStart(true, durableReady = true, bootstrapInFlight = false)) + assertTrue(PlatformFacadeProvider.sessionReadyForStart(true, durableReady = false, bootstrapInFlight = true)) + assertTrue(PlatformFacadeProvider.sessionReadyForStart(false, durableReady = false, bootstrapInFlight = false)) + assertFalse(PlatformFacadeProvider.sessionReadyForStart(true, durableReady = false, bootstrapInFlight = false)) + } +} diff --git a/sdk/full/src/test/kotlin/io/devconsole/PurgeSummaryTextTest.kt b/sdk/full/src/test/kotlin/io/devconsole/PurgeSummaryTextTest.kt new file mode 100644 index 0000000..0753ec4 --- /dev/null +++ b/sdk/full/src/test/kotlin/io/devconsole/PurgeSummaryTextTest.kt @@ -0,0 +1,50 @@ +/** + * @author Shakib + * @since 04/11/26 + */ +package io.devconsole + +import io.devconsole.api.PurgeResult +import org.junit.Assert.assertEquals +import org.junit.Test + +class PurgeSummaryTextTest { + @Test + fun `plural counts read naturally`() { + val result = + PurgeResult( + networkTransactions = 12, + socketConnections = 2, + pushEvents = 0, + retainedRunsDeleted = 1, + ) + + assertEquals("Removed 12 requests, 2 connections and 1 old run", purgeSummaryText(result)) + } + + @Test + fun `singular counts use singular nouns`() { + val result = + PurgeResult( + networkTransactions = 1, + socketConnections = 1, + pushEvents = 1, + retainedRunsDeleted = 1, + ) + + assertEquals("Removed 1 request, 1 connection, 1 push event and 1 old run", purgeSummaryText(result)) + } + + @Test + fun `a single non-zero count is named alone`() { + val result = + PurgeResult(networkTransactions = 0, socketConnections = 0, pushEvents = 0, retainedRunsDeleted = 8) + + assertEquals("Removed 8 old runs", purgeSummaryText(result)) + } + + @Test + fun `an empty purge says nothing was purged`() { + assertEquals("Nothing to purge", purgeSummaryText(PurgeResult.NOTHING)) + } +} diff --git a/sdk/full/src/test/kotlin/io/devconsole/RetainedCaptureDecoderTest.kt b/sdk/full/src/test/kotlin/io/devconsole/RetainedCaptureDecoderTest.kt new file mode 100644 index 0000000..045ab17 --- /dev/null +++ b/sdk/full/src/test/kotlin/io/devconsole/RetainedCaptureDecoderTest.kt @@ -0,0 +1,396 @@ +/** + * @author Shakib + * @since 03/11/26 + */ +package io.devconsole + +import io.devconsole.network.BodyPreview +import io.devconsole.network.CaptureBodyMetadata +import io.devconsole.network.CapturedRequest +import io.devconsole.network.CapturedRequestMetadata +import io.devconsole.network.CapturedResponse +import io.devconsole.network.CapturedResponseMetadata +import io.devconsole.network.NetworkCapture +import io.devconsole.network.NetworkTimingPhases +import io.devconsole.network.NetworkTransaction +import io.devconsole.network.NetworkUrl +import io.devconsole.push.PushEvent +import io.devconsole.push.PushLifecycle +import io.devconsole.push.PushNotification +import io.devconsole.socket.BinaryPreviewEncoding +import io.devconsole.socket.SocketDirection +import io.devconsole.socket.SocketFrameType +import io.devconsole.socket.SocketLifecycleEvent +import io.devconsole.socket.SocketLifecycleType +import io.devconsole.socket.SocketMessage +import io.devconsole.socket.SocketMessageMetadata +import io.devconsole.socket.SocketPayload +import io.devconsole.socket.SocketTextFormat +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34]) +class RetainedCaptureDecoderTest { + @Test + fun `round trips text body GET with query, headers, and timings`() { + val request = sampleGetRequest() + val response = sampleGetResponse() + + val original = + NetworkTransaction( + id = "tx-get-1", + startedAtEpochMs = 1_000L, + completedAtEpochMs = 1_130L, + capture = NetworkCapture(request, response), + ).withSessionId("session-abc") + + val encoded = CapturePayloadCodec.network(original) + assertNotNull(encoded) + + val decoded = RetainedCaptureDecoder.network(encoded) + assertNotNull(decoded) + + assertEquals(original.id, decoded!!.id) + assertEquals(original.startedAtEpochMs, decoded.startedAtEpochMs) + assertEquals(original.completedAtEpochMs, decoded.completedAtEpochMs) + assertEquals(original.sessionId, decoded.sessionId) + + val decReq = decoded.capture.request + assertEquals(request.method, decReq.method) + assertEquals(request.url, decReq.url) + assertEquals(request.headers, decReq.headers) + assertEquals(request.body, decReq.body) + assertEquals(request.contentType, decReq.contentType) + assertEquals(request.correlationId, decReq.correlationId) + assertEquals(request.pluginId, decReq.pluginId) + assertEquals(request.attachmentId, decReq.attachmentId) + assertEquals(request.metadata, decReq.metadata) + + val decResp = decoded.capture.response + assertNotNull(decResp) + assertEquals(response.statusCode, decResp!!.statusCode) + assertEquals(response.headers, decResp.headers) + assertEquals(response.body, decResp.body) + assertEquals(response.contentType, decResp.contentType) + assertEquals(response.protocol, decResp.protocol) + assertEquals(response.error, decResp.error) + assertEquals(response.attachmentId, decResp.attachmentId) + assertEquals(response.metadata, decResp.metadata) + } + + @Test + fun `round trips binary body POST`() { + val request = + CapturedRequest( + method = "POST", + url = NetworkUrl("https", "upload.example.com", "/files", emptyMap()), + headers = mapOf("Content-Type" to "application/octet-stream"), + body = BodyPreview.Binary(length = 2048L, truncated = true), + contentType = "application/octet-stream", + correlationId = "corr-post", + pluginId = "network", + ).withMetadata( + CapturedRequestMetadata( + body = CaptureBodyMetadata(declaredLength = 2048L, capturedBytes = 512, truncated = true), + ), + ) + + val response = + CapturedResponse( + statusCode = 201, + headers = mapOf("Content-Type" to "application/octet-stream"), + body = BodyPreview.Binary(length = 100L, truncated = false), + contentType = "application/octet-stream", + protocol = "HTTP/2", + error = null, + ).withMetadata( + CapturedResponseMetadata( + body = CaptureBodyMetadata(declaredLength = 100L, capturedBytes = 100, truncated = false), + ), + ) + + val original = + NetworkTransaction( + id = "tx-post-bin", + startedAtEpochMs = 2_000L, + completedAtEpochMs = 2_500L, + capture = NetworkCapture(request, response), + ).withSessionId("session-post") + + val encoded = CapturePayloadCodec.network(original) + val decoded = RetainedCaptureDecoder.network(encoded) + assertNotNull(decoded) + + assertEquals(original.id, decoded!!.id) + assertEquals(original.capture.request.body, decoded.capture.request.body) + assertEquals(original.capture.response?.body, decoded.capture.response?.body) + assertEquals(original.capture.request.metadata.body, decoded.capture.request.metadata.body) + assertEquals( + original.capture.response + ?.metadata + ?.body, + decoded.capture.response + ?.metadata + ?.body, + ) + } + + @Test + fun `round trips absent body failed request with error set and no response`() { + val request = + CapturedRequest( + method = "GET", + url = NetworkUrl("http", "broken.test", "/down", emptyMap()), + headers = emptyMap(), + body = BodyPreview.Absent, + contentType = null, + correlationId = null, + pluginId = "network", + ) + + val original = + NetworkTransaction( + id = "tx-failed", + startedAtEpochMs = 3_000L, + completedAtEpochMs = null, + capture = NetworkCapture(request, response = null), + ) + + val encoded = CapturePayloadCodec.network(original) + val decoded = RetainedCaptureDecoder.network(encoded) + assertNotNull(decoded) + + assertEquals("tx-failed", decoded!!.id) + assertNull(decoded.completedAtEpochMs) + assertNull(decoded.capture.response) + assertEquals(BodyPreview.Absent, decoded.capture.request.body) + } + + @Test + fun `round trips socket text message`() { + val message = + SocketMessage( + connectionId = "conn-1", + direction = SocketDirection.SENT, + timestampEpochMs = 12345L, + payload = SocketPayload.Text("hello world", truncated = false), + contentType = "application/json", + ).withMetadata( + SocketMessageMetadata( + frameType = SocketFrameType.TEXT, + textFormat = SocketTextFormat.JSON, + ), + ) + + val encoded = CapturePayloadCodec.socketMessage(message) + val decoded = RetainedCaptureDecoder.socketMessage(encoded) + assertNotNull(decoded) + + assertEquals(message.connectionId, decoded!!.connectionId) + assertEquals(message.direction, decoded.direction) + assertEquals(message.timestampEpochMs, decoded.timestampEpochMs) + assertEquals(message.contentType, decoded.contentType) + assertEquals(message.payload, decoded.payload) + assertEquals(message.metadata, decoded.metadata) + } + + @Test + fun `round trips socket binary message with preview`() { + val binaryPayload = + SocketPayload + .Binary(length = 256L, truncated = true) + .withPreview("deadbeef", BinaryPreviewEncoding.HEX) + val message = + SocketMessage( + connectionId = "conn-bin", + direction = SocketDirection.RECEIVED, + timestampEpochMs = 54321L, + payload = binaryPayload, + contentType = "application/octet-stream", + ).withMetadata( + SocketMessageMetadata( + frameType = SocketFrameType.BINARY, + textFormat = SocketTextFormat.TEXT, + ), + ) + + val encoded = CapturePayloadCodec.socketMessage(message) + val decoded = RetainedCaptureDecoder.socketMessage(encoded) + assertNotNull(decoded) + + assertEquals(message.connectionId, decoded!!.connectionId) + val decPayload = decoded.payload as SocketPayload.Binary + assertEquals(binaryPayload.length, decPayload.length) + assertEquals(binaryPayload.truncated, decPayload.truncated) + assertEquals(binaryPayload.preview, decPayload.preview) + assertEquals(binaryPayload.previewEncoding, decPayload.previewEncoding) + assertEquals(message.metadata, decoded.metadata) + } + + @Test + fun `round trips socket lifecycle event and url`() { + val event = + SocketLifecycleEvent( + connectionId = "conn-lifecycle", + type = SocketLifecycleType.CLOSED, + timestampEpochMs = 99999L, + code = 1000, + reason = "Normal closure", + error = null, + ) + val connectionUrl = "wss://echo.websocket.org" + + val encoded = + CapturePayloadCodec.socketLifecycle( + event = event, + connection = + io.devconsole.socket.SocketConnection( + id = event.connectionId, + url = connectionUrl, + openedAtEpochMs = 90000L, + ), + ) + + val decoded = RetainedCaptureDecoder.socketLifecycle(encoded) + assertNotNull(decoded) + val (decodedEvent, decodedUrl) = decoded!! + + assertEquals(event, decodedEvent) + assertEquals(connectionUrl, decodedUrl) + } + + @Test + fun `round trips push event with notification`() { + val event = + PushEvent( + provider = "fcm", + data = mapOf("k1" to "v1", "k2" to "v2"), + messageId = "msg-123", + source = "network", + sentAtEpochMs = 10000L, + receivedAtEpochMs = 10050L, + notification = + PushNotification( + title = "Alert", + body = "System warning", + channelId = "alerts_channel", + imageUrl = "https://img.test/pic.png", + ), + rawMetadata = mapOf("ttl" to "60"), + lifecycle = PushLifecycle.DISPLAYED, + simulated = false, + ) + + val encoded = CapturePayloadCodec.push(event) + val decoded = RetainedCaptureDecoder.push(encoded) + assertNotNull(decoded) + + assertEquals(event, decoded) + } + + @Test + fun `round trips push event without notification`() { + val event = + PushEvent( + provider = "local", + data = emptyMap(), + messageId = null, + source = null, + sentAtEpochMs = null, + receivedAtEpochMs = 20000L, + notification = null, + rawMetadata = emptyMap(), + lifecycle = PushLifecycle.RECEIVED, + simulated = true, + ) + + val encoded = CapturePayloadCodec.push(event) + val decoded = RetainedCaptureDecoder.push(encoded) + assertNotNull(decoded) + + assertEquals(event, decoded) + } + + @Test + fun `corrupted and invalid payloads return null without throwing`() { + assertNull(RetainedCaptureDecoder.network(null)) + assertNull(RetainedCaptureDecoder.network("")) + assertNull(RetainedCaptureDecoder.network("{")) + assertNull(RetainedCaptureDecoder.network("""{"v":1,"kind":"wrong_kind","data":{}}""")) + assertNull(RetainedCaptureDecoder.network("""{"v":2,"kind":"network","data":{}}""")) + + assertNull(RetainedCaptureDecoder.socketMessage(null)) + assertNull(RetainedCaptureDecoder.socketMessage("")) + assertNull(RetainedCaptureDecoder.socketMessage("{")) + assertNull(RetainedCaptureDecoder.socketMessage("""{"v":1,"kind":"push","data":{}}""")) + assertNull(RetainedCaptureDecoder.socketMessage("""{"v":2,"kind":"socket.message","data":{}}""")) + + assertNull(RetainedCaptureDecoder.socketLifecycle(null)) + assertNull(RetainedCaptureDecoder.socketLifecycle("")) + assertNull(RetainedCaptureDecoder.socketLifecycle("{")) + assertNull(RetainedCaptureDecoder.socketLifecycle("""{"v":1,"kind":"network","data":{}}""")) + assertNull(RetainedCaptureDecoder.socketLifecycle("""{"v":2,"kind":"socket.lifecycle","data":{}}""")) + + assertNull(RetainedCaptureDecoder.push(null)) + assertNull(RetainedCaptureDecoder.push("")) + assertNull(RetainedCaptureDecoder.push("{")) + assertNull(RetainedCaptureDecoder.push("""{"v":1,"kind":"socket.message","data":{}}""")) + assertNull(RetainedCaptureDecoder.push("""{"v":2,"kind":"push","data":{}}""")) + } + + private fun sampleGetRequest(): CapturedRequest = + CapturedRequest( + method = "GET", + url = NetworkUrl("https", "api.example.com", "/items", mapOf("page" to "1", "sort" to "desc")), + headers = mapOf("Authorization" to "Bearer token", "Accept" to "application/json"), + body = BodyPreview.Text("request text", truncated = false), + contentType = "application/json", + correlationId = "corr-123", + pluginId = "network", + ).withAttachmentId("att-req-1") + .withMetadata( + CapturedRequestMetadata( + threadName = "main-thread", + body = CaptureBodyMetadata(declaredLength = 12L, capturedBytes = 12, truncated = false), + tags = mapOf("tag1" to "val1"), + ), + ) + + private fun sampleGetResponse(): CapturedResponse = + CapturedResponse( + statusCode = 200, + headers = mapOf("Content-Type" to "application/json"), + body = BodyPreview.Text("response text", truncated = true), + contentType = "application/json", + protocol = "HTTP/1.1", + error = null, + ).withAttachmentId("att-resp-1") + .withMetadata( + CapturedResponseMetadata( + body = + CaptureBodyMetadata( + declaredLength = 100L, + capturedBytes = 13, + truncated = true, + omittedReason = "truncated-body", + ), + timings = + NetworkTimingPhases( + dnsMs = 10L, + connectMs = 20L, + tlsMs = 30L, + sendMs = 5L, + waitMs = 50L, + receiveMs = 15L, + ), + fromCache = false, + exceptionClass = null, + ), + ) +} diff --git a/sdk/full/src/test/kotlin/io/devconsole/RetainedNetworkStoresTest.kt b/sdk/full/src/test/kotlin/io/devconsole/RetainedNetworkStoresTest.kt new file mode 100644 index 0000000..71defe6 --- /dev/null +++ b/sdk/full/src/test/kotlin/io/devconsole/RetainedNetworkStoresTest.kt @@ -0,0 +1,220 @@ +/** + * @author Shakib + * @since 03/11/26 + */ +package io.devconsole + +import io.devconsole.network.BodyPreview +import io.devconsole.network.CapturedRequest +import io.devconsole.network.CapturedResponse +import io.devconsole.network.NetworkCapture +import io.devconsole.network.NetworkCursorCodec +import io.devconsole.network.NetworkTransaction +import io.devconsole.network.NetworkTransactionQuery +import io.devconsole.network.NetworkUrl +import io.devconsole.storage.api.StoredEvent +import kotlinx.coroutines.test.runTest +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotNull +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import java.util.concurrent.atomic.AtomicInteger + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34]) +class RetainedNetworkStoresTest { + private val codecKey = "0123456789abcdef0123456789abcdef".toByteArray() + private val cursorCodec = NetworkCursorCodec(codecKey) + + private fun sampleTransaction( + id: String, + method: String, + startedAtEpochMs: Long, + ): NetworkTransaction { + val req = + CapturedRequest( + method = method, + url = NetworkUrl("https", "test.io", "/res/$id", emptyMap()), + headers = emptyMap(), + body = BodyPreview.Absent, + contentType = null, + correlationId = null, + pluginId = "network", + ) + val resp = + CapturedResponse( + statusCode = 200, + headers = emptyMap(), + body = BodyPreview.Absent, + contentType = null, + protocol = "HTTP/1.1", + error = null, + ) + return NetworkTransaction( + id = id, + startedAtEpochMs = startedAtEpochMs, + completedAtEpochMs = startedAtEpochMs + 50L, + capture = NetworkCapture(req, resp), + ) + } + + private fun storedEvent( + id: String, + pluginId: String, + payloadJson: String?, + timestamp: Long, + ) = StoredEvent( + id = id, + sessionId = "session-1", + sequence = timestamp, + pluginId = pluginId, + type = "timeline", + wallTimeMs = timestamp, + monoTimeNs = timestamp * 1_000_000L, + severity = 0, + summary = "event $id", + correlationId = null, + tagsJson = "{}", + payloadJson = payloadJson, + attachmentId = null, + ) + + @Test + fun `loads transactions newest first and skips logs and malformed network payloads`() = + runTest { + val tx1 = sampleTransaction("tx-1", "GET", 1_000L) + val tx2 = sampleTransaction("tx-2", "POST", 2_000L) + + val eventsList = + listOf( + storedEvent("e1", "network", CapturePayloadCodec.network(tx1), 1_000L), + storedEvent("e2", "logs", """{"log":"some log"}""", 1_500L), + storedEvent("e3", "network", "malformed json {", 1_800L), + storedEvent("e4", "network", CapturePayloadCodec.network(tx2), 2_000L), + ) + + val stores = + RetainedNetworkStores( + events = { eventsList }, + cursorCodec = cursorCodec, + ) + + val store = stores.storeFor("session-1") + assertNotNull(store) + + val page = store.page(NetworkTransactionQuery()) + assertEquals(2, page.transactions.size) + // Store ordering is newest-first (descending startedAtEpochMs) + assertEquals("tx-2", page.transactions[0].id) + assertEquals("tx-1", page.transactions[1].id) + + // Query filters work (e.g. method filter) + val postPage = store.page(NetworkTransactionQuery(methods = setOf("POST"))) + assertEquals(1, postPage.transactions.size) + assertEquals("tx-2", postPage.transactions[0].id) + } + + @Test + fun `caches session store and invalidate forces reload`() = + runTest { + val callCount = AtomicInteger(0) + val tx = sampleTransaction("tx-cached", "GET", 10_000L) + val eventsList = + listOf( + storedEvent("e-c", "network", CapturePayloadCodec.network(tx), 10_000L), + ) + + val stores = + RetainedNetworkStores( + events = { + callCount.incrementAndGet() + eventsList + }, + cursorCodec = cursorCodec, + ) + + val storeFirst = stores.storeFor("session-cached") + assertNotNull(storeFirst) + assertEquals(1, callCount.get()) + + // Second call should return cached store without calling events again + val storeSecond = stores.storeFor("session-cached") + assertNotNull(storeSecond) + assertEquals(1, callCount.get()) + + // Invalidate forces reload on next access + stores.invalidate("session-cached") + val storeThird = stores.storeFor("session-cached") + assertNotNull(storeThird) + assertEquals(2, callCount.get()) + } + + @Test + fun `session with no decodable network events yields an empty store`() = + runTest { + val eventsList = + listOf( + storedEvent("e-log", "logs", """{"log":"hello"}""", 5_000L), + storedEvent("e-bad-net", "network", "invalid", 6_000L), + ) + + val stores = + RetainedNetworkStores( + events = { eventsList }, + cursorCodec = cursorCodec, + ) + + val store = stores.storeFor("empty-session") + assertEquals(0, store.page(NetworkTransactionQuery()).transactions.size) + } + + @Test + fun `evicts least recently used session when cache limit is exceeded`() = + runTest { + val callCount = AtomicInteger(0) + + fun eventsFor(sessionId: String) = + listOf( + storedEvent( + id = "e-$sessionId", + pluginId = "network", + payloadJson = CapturePayloadCodec.network(sampleTransaction("tx-$sessionId", "GET", 1_000L)), + timestamp = 1_000L, + ), + ) + + val stores = + RetainedNetworkStores( + events = { sessionId -> + callCount.incrementAndGet() + eventsFor(sessionId) + }, + cursorCodec = cursorCodec, + maxCachedSessions = 2, + ) + + assertNotNull(stores.storeFor("s1")) + assertEquals(1, callCount.get()) + + assertNotNull(stores.storeFor("s2")) + assertEquals(2, callCount.get()) + + // Accessing s1 marks s1 as MRU + assertNotNull(stores.storeFor("s1")) + assertEquals(2, callCount.get()) + + // Adding s3 evicts s2 (since s1 was accessed more recently) + assertNotNull(stores.storeFor("s3")) + assertEquals(3, callCount.get()) + + // s1 should still be cached + assertNotNull(stores.storeFor("s1")) + assertEquals(3, callCount.get()) + + // s2 was evicted, so accessing s2 should reload + assertNotNull(stores.storeFor("s2")) + assertEquals(4, callCount.get()) + } +} diff --git a/sdk/full/src/test/kotlin/io/devconsole/RetainedSessionCapturesTest.kt b/sdk/full/src/test/kotlin/io/devconsole/RetainedSessionCapturesTest.kt new file mode 100644 index 0000000..594d42b --- /dev/null +++ b/sdk/full/src/test/kotlin/io/devconsole/RetainedSessionCapturesTest.kt @@ -0,0 +1,115 @@ +/** + * @author Shakib + * @since 03/11/26 + */ +package io.devconsole + +import io.devconsole.network.NetworkCursorCodec +import io.devconsole.push.PushEvent +import io.devconsole.socket.SocketConnection +import io.devconsole.socket.SocketConnectionState +import io.devconsole.socket.SocketDirection +import io.devconsole.socket.SocketLifecycleEvent +import io.devconsole.socket.SocketLifecycleType +import io.devconsole.socket.SocketMessage +import io.devconsole.socket.SocketPayload +import io.devconsole.socket.SocketProtocol +import io.devconsole.storage.api.StoredEvent +import kotlinx.coroutines.test.runTest +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34]) +class RetainedSessionCapturesTest { + private val wsConnection = SocketConnection(id = "ws-1", url = "wss://chat.test/live", openedAtEpochMs = 100L) + private val mqttConnection = + SocketConnection(id = "mq-1", url = "tcp://broker.test", openedAtEpochMs = 500L, protocol = SocketProtocol.MQTT) + + @Test + fun `rebuilds connections with frames, final state and protocol, newest opened first`() { + val events = + listOf( + lifecycle(SocketLifecycleEvent("ws-1", SocketLifecycleType.OPENED, 100L), wsConnection), + frame(SocketMessage("ws-1", SocketDirection.SENT, 150L, SocketPayload.Text("hi", truncated = false))), + frame( + SocketMessage("ws-1", SocketDirection.RECEIVED, 160L, SocketPayload.Text("yo", truncated = false)), + ), + lifecycle( + SocketLifecycleEvent("ws-1", SocketLifecycleType.FAILED, 200L, error = "reset"), + wsConnection, + ), + lifecycle(SocketLifecycleEvent("mq-1", SocketLifecycleType.OPENED, 500L), mqttConnection), + ) + + val connections = rebuildSocketConnections(events) + + assertEquals(listOf("mq-1", "ws-1"), connections.map(SocketConnection::id)) + val ws = connections.last() + assertEquals("wss://chat.test/live", ws.url) + assertEquals(SocketConnectionState.CLOSED, ws.state) + assertEquals(200L, ws.closedAtEpochMs) + assertEquals("reset", ws.error) + assertEquals(1, ws.sentCount) + assertEquals(1, ws.receivedCount) + assertEquals(SocketProtocol.WEBSOCKET, ws.protocol) + val mqtt = connections.first() + assertEquals(SocketConnectionState.OPEN, mqtt.state) + assertEquals(SocketProtocol.MQTT, mqtt.protocol) + } + + @Test + fun `push events come back newest first and other plugins are ignored`() = + runTest { + val events = + listOf( + storedEvent("push", CapturePayloadCodec.push(push("older", 10L))), + storedEvent("push", CapturePayloadCodec.push(push("newer", 20L))), + storedEvent("logs", """{"log":"noise"}"""), + ) + val captures = RetainedSessionCaptures({ events }, NetworkCursorCodec(ByteArray(16))) + + assertEquals(listOf("newer", "older"), captures.pushEvents("run-1").map(PushEvent::messageId)) + assertTrue(captures.sockets("run-1").isEmpty()) + } + + private fun push( + messageId: String, + receivedAt: Long, + ) = PushEvent(provider = "fcm", data = mapOf("k" to "v"), messageId = messageId, receivedAtEpochMs = receivedAt) + + private fun lifecycle( + event: SocketLifecycleEvent, + connection: SocketConnection, + ) = storedEvent("websocket", CapturePayloadCodec.socketLifecycle(event, connection)) + + private fun frame(message: SocketMessage) = storedEvent("websocket", CapturePayloadCodec.socketMessage(message)) + + private var sequence = 0L + + private fun storedEvent( + pluginId: String, + payloadJson: String?, + ): StoredEvent { + sequence++ + return StoredEvent( + id = "e-$sequence", + sessionId = "run-1", + sequence = sequence, + pluginId = pluginId, + type = "timeline", + wallTimeMs = sequence, + monoTimeNs = sequence, + severity = 0, + summary = "event $sequence", + correlationId = null, + tagsJson = "{}", + payloadJson = payloadJson, + attachmentId = null, + ) + } +} diff --git a/sdk/full/src/test/kotlin/io/devconsole/ScreenshotCaptureTest.kt b/sdk/full/src/test/kotlin/io/devconsole/ScreenshotCaptureTest.kt index d3f3a77..0e7d6a5 100644 --- a/sdk/full/src/test/kotlin/io/devconsole/ScreenshotCaptureTest.kt +++ b/sdk/full/src/test/kotlin/io/devconsole/ScreenshotCaptureTest.kt @@ -208,7 +208,7 @@ class ScreenshotCaptureTest { // --- Finding 2: bounded capture + no leaked bitmap ---------------------------------------------- @Test - fun `a capture that never resolves times out, reports timedOut, and recycles its bitmap`() = + fun `a capture that never resolves times out without recycling the pending destination bitmap`() = runTest { var capturedBitmap: Bitmap? = null val handler = SwallowingHandler(Looper.getMainLooper()) @@ -230,11 +230,14 @@ class ScreenshotCaptureTest { assertTrue("expected a Failed result, got $result", result is CapturedScreenshot.Failed) result as CapturedScreenshot.Failed assertTrue(result.timedOut) - assertTrue("bitmap must not be leaked past a timeout", requireNotNull(capturedBitmap).isRecycled) + assertTrue( + "timed-out PixelCopy destination must remain valid for a pending write", + !requireNotNull(capturedBitmap).isRecycled, + ) } @Test - fun `cancelling an in-flight capture recycles the bitmap instead of leaking it`() = + fun `cancelling an in-flight capture leaves its pending destination valid`() = runTest { val allocated = CountDownLatch(1) var capturedBitmap: Bitmap? = null @@ -258,7 +261,7 @@ class ScreenshotCaptureTest { assertTrue("expected the capture bitmap to be allocated", allocated.await(5, TimeUnit.SECONDS)) job.cancelAndJoin() - assertTrue("bitmap must not be leaked past cancellation", requireNotNull(capturedBitmap).isRecycled) + assertTrue("cancelled PixelCopy destination must remain valid", !requireNotNull(capturedBitmap).isRecycled) } /** Robolectric's window is 0x0 until laid out; force a real decor-view size for tests that need one. */ diff --git a/sdk/logs-timber/api/logs-timber.api b/sdk/logs-timber/api/logs-timber.api new file mode 100644 index 0000000..bae816e --- /dev/null +++ b/sdk/logs-timber/api/logs-timber.api @@ -0,0 +1,29 @@ +public final class io/devconsole/logs/timber/DevConsoleLog { + public static final field INSTANCE Lio/devconsole/logs/timber/DevConsoleLog; + public static final fun d (Ljava/lang/String;Ljava/lang/String;)I + public static final fun d (Ljava/lang/String;Ljava/lang/String;Ljava/lang/Throwable;)I + public static synthetic fun d$default (Ljava/lang/String;Ljava/lang/String;Ljava/lang/Throwable;ILjava/lang/Object;)I + public static final fun e (Ljava/lang/String;Ljava/lang/String;)I + public static final fun e (Ljava/lang/String;Ljava/lang/String;Ljava/lang/Throwable;)I + public static synthetic fun e$default (Ljava/lang/String;Ljava/lang/String;Ljava/lang/Throwable;ILjava/lang/Object;)I + public static final fun i (Ljava/lang/String;Ljava/lang/String;)I + public static final fun i (Ljava/lang/String;Ljava/lang/String;Ljava/lang/Throwable;)I + public static synthetic fun i$default (Ljava/lang/String;Ljava/lang/String;Ljava/lang/Throwable;ILjava/lang/Object;)I + public static final fun install (Lio/devconsole/logs/LogRecorder;)V + public static final fun v (Ljava/lang/String;Ljava/lang/String;)I + public static final fun v (Ljava/lang/String;Ljava/lang/String;Ljava/lang/Throwable;)I + public static synthetic fun v$default (Ljava/lang/String;Ljava/lang/String;Ljava/lang/Throwable;ILjava/lang/Object;)I + public static final fun w (Ljava/lang/String;Ljava/lang/String;)I + public static final fun w (Ljava/lang/String;Ljava/lang/String;Ljava/lang/Throwable;)I + public static synthetic fun w$default (Ljava/lang/String;Ljava/lang/String;Ljava/lang/Throwable;ILjava/lang/Object;)I + public static final fun wtf (Ljava/lang/String;Ljava/lang/String;)I + public static final fun wtf (Ljava/lang/String;Ljava/lang/String;Ljava/lang/Throwable;)I + public static synthetic fun wtf$default (Ljava/lang/String;Ljava/lang/String;Ljava/lang/Throwable;ILjava/lang/Object;)I +} + +public final class io/devconsole/logs/timber/DevConsoleTimberTree : timber/log/Timber$Tree { + public fun (Lio/devconsole/logs/LogRecorder;)V + public fun (Lio/devconsole/logs/LogRecorder;I)V + public synthetic fun (Lio/devconsole/logs/LogRecorder;IILkotlin/jvm/internal/DefaultConstructorMarker;)V +} + diff --git a/sdk/logs-timber/build.gradle.kts b/sdk/logs-timber/build.gradle.kts new file mode 100644 index 0000000..fef6e57 --- /dev/null +++ b/sdk/logs-timber/build.gradle.kts @@ -0,0 +1,16 @@ +plugins { + id("devconsole.android.library") + id("devconsole.quality") + id("devconsole.publishing") +} + +android { + namespace = "io.devconsole.logs.timber" + defaultConfig { consumerProguardFiles("consumer-rules.pro") } + testOptions { unitTests.isReturnDefaultValues = true } +} + +dependencies { + api(project(":sdk:logs")) + api("com.jakewharton.timber:timber:5.0.1") +} diff --git a/sdk/logs-timber/consumer-rules.pro b/sdk/logs-timber/consumer-rules.pro new file mode 100644 index 0000000..260aff1 --- /dev/null +++ b/sdk/logs-timber/consumer-rules.pro @@ -0,0 +1,2 @@ +# No consumer ProGuard rules are required: both bridges only reference Timber and the platform log +# API, neither of which is stripped or renamed in a way a host would need to keep. diff --git a/sdk/logs-timber/src/main/kotlin/io/devconsole/logs/timber/DevConsoleLog.kt b/sdk/logs-timber/src/main/kotlin/io/devconsole/logs/timber/DevConsoleLog.kt new file mode 100644 index 0000000..03a5d41 --- /dev/null +++ b/sdk/logs-timber/src/main/kotlin/io/devconsole/logs/timber/DevConsoleLog.kt @@ -0,0 +1,95 @@ +/** + * @author Shakib + * @since 04/11/26 + */ +package io.devconsole.logs.timber + +import android.util.Log +import io.devconsole.logs.LogLevel +import io.devconsole.logs.LogRecorder + +/** + * Drop-in replacement for [Log] whose calls also reach the DevConsole timeline. + * + * Each method delegates to the matching [Log] method first and returns that result unchanged, then + * forwards the same line to the [LogRecorder] installed by [install]. Forwarding is a no-op until + * [install] is called, and in protected variants the installed recorder is DevConsole's disabled + * one, so nothing is captured — the platform log call is unaffected either way. + */ +object DevConsoleLog { + @Volatile + private var recorder: LogRecorder? = null + + /** Installs [recorder] as the destination for all subsequent lines. Safe to call from any thread. */ + @JvmStatic + fun install(recorder: LogRecorder) { + this.recorder = recorder + } + + /** Logs a verbose line through [Log] and the installed recorder, returning [Log]'s result. */ + @JvmStatic + @JvmOverloads + fun v( + tag: String, + msg: String, + tr: Throwable? = null, + ): Int = forward(LogLevel.VERBOSE, tag, msg, tr) { Log.v(tag, msg, tr) } + + /** Logs a debug line through [Log] and the installed recorder, returning [Log]'s result. */ + @JvmStatic + @JvmOverloads + fun d( + tag: String, + msg: String, + tr: Throwable? = null, + ): Int = forward(LogLevel.DEBUG, tag, msg, tr) { Log.d(tag, msg, tr) } + + /** Logs an info line through [Log] and the installed recorder, returning [Log]'s result. */ + @JvmStatic + @JvmOverloads + fun i( + tag: String, + msg: String, + tr: Throwable? = null, + ): Int = forward(LogLevel.INFO, tag, msg, tr) { Log.i(tag, msg, tr) } + + /** Logs a warning line through [Log] and the installed recorder, returning [Log]'s result. */ + @JvmStatic + @JvmOverloads + fun w( + tag: String, + msg: String, + tr: Throwable? = null, + ): Int = forward(LogLevel.WARN, tag, msg, tr) { Log.w(tag, msg, tr) } + + /** Logs an error line through [Log] and the installed recorder, returning [Log]'s result. */ + @JvmStatic + @JvmOverloads + fun e( + tag: String, + msg: String, + tr: Throwable? = null, + ): Int = forward(LogLevel.ERROR, tag, msg, tr) { Log.e(tag, msg, tr) } + + /** Logs an assert line through [Log] and the installed recorder, returning [Log]'s result. */ + @JvmStatic + @JvmOverloads + fun wtf( + tag: String, + msg: String, + tr: Throwable? = null, + ): Int = forward(LogLevel.ASSERT, tag, msg, tr) { Log.wtf(tag, msg, tr) } + + private inline fun forward( + level: LogLevel, + tag: String, + msg: String, + tr: Throwable?, + platformCall: () -> Int, + ): Int { + val result = platformCall() + val installed = recorder + runCatching { installed?.record(level, tag, msg, tr) } + return result + } +} diff --git a/sdk/logs-timber/src/main/kotlin/io/devconsole/logs/timber/DevConsoleTimberTree.kt b/sdk/logs-timber/src/main/kotlin/io/devconsole/logs/timber/DevConsoleTimberTree.kt new file mode 100644 index 0000000..a923817 --- /dev/null +++ b/sdk/logs-timber/src/main/kotlin/io/devconsole/logs/timber/DevConsoleTimberTree.kt @@ -0,0 +1,74 @@ +/** + * @author Shakib + * @since 04/11/26 + */ +package io.devconsole.logs.timber + +import android.util.Log +import io.devconsole.logs.LogLevel +import io.devconsole.logs.LogRecorder +import timber.log.Timber + +// Top-level private, not companion consts: a companion `const` compiles to a public static field +// on the tree class and would leak into the published API. +private const val DEFAULT_TAG: String = "Timber" +private const val TIMBER_STACK_TRACE_SEPARATOR: String = "\n" + +/** + * A [Timber.Tree] that forwards every planted log line to a [LogRecorder], so the host's existing + * Timber calls join the DevConsole timeline without touching the call sites. + * + * Priorities at or above [minimumPriority] are recorded; anything lower is dropped. Android + * priorities map one-to-one onto [LogLevel], and an unrecognised priority is recorded as + * [LogLevel.DEBUG]. Timber appends a throwable's stack trace to `message` before calling [log], so + * that appended copy is stripped here and the throwable is passed to the recorder instead — the + * entry then carries the stack trace exactly once, redacted as its own field. + * + * This module contains no capture runtime: it only forwards to whatever [LogRecorder] the host + * passes in, which is DevConsole's disabled recorder in protected variants, so it is release-safe + * and is deliberately absent from the Gradle plugin's protected artifact lists. + */ +class DevConsoleTimberTree + @JvmOverloads + constructor( + private val recorder: LogRecorder, + private val minimumPriority: Int = Log.VERBOSE, + ) : Timber.Tree() { + override fun isLoggable( + tag: String?, + priority: Int, + ): Boolean = priority >= minimumPriority + + override fun log( + priority: Int, + tag: String?, + message: String, + t: Throwable?, + ) { + runCatching { + recorder.record( + level = priority.toLogLevel(), + tag = tag ?: DEFAULT_TAG, + message = message.withoutTimberStackTrace(t), + throwable = t, + ) + } + } + + private fun String.withoutTimberStackTrace(throwable: Throwable?): String { + if (throwable == null) return this + val stackTrace = throwable.stackTraceToString() + return if (this == stackTrace) "" else removeSuffix(TIMBER_STACK_TRACE_SEPARATOR + stackTrace) + } + + private fun Int.toLogLevel(): LogLevel = + when (this) { + Log.VERBOSE -> LogLevel.VERBOSE + Log.DEBUG -> LogLevel.DEBUG + Log.INFO -> LogLevel.INFO + Log.WARN -> LogLevel.WARN + Log.ERROR -> LogLevel.ERROR + Log.ASSERT -> LogLevel.ASSERT + else -> LogLevel.DEBUG + } + } diff --git a/sdk/logs-timber/src/test/kotlin/io/devconsole/logs/timber/DevConsoleLogTest.kt b/sdk/logs-timber/src/test/kotlin/io/devconsole/logs/timber/DevConsoleLogTest.kt new file mode 100644 index 0000000..3577601 --- /dev/null +++ b/sdk/logs-timber/src/test/kotlin/io/devconsole/logs/timber/DevConsoleLogTest.kt @@ -0,0 +1,86 @@ +/** + * @author Shakib + * @since 04/11/26 + */ +package io.devconsole.logs.timber + +import io.devconsole.logs.LogEntry +import io.devconsole.logs.LogLevel +import io.devconsole.logs.LogRecorder +import io.devconsole.logs.LogSink +import io.devconsole.security.RedactionEngine +import io.devconsole.security.RedactionPolicy +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +class DevConsoleLogTest { + private val redaction = RedactionEngine(RedactionPolicy.recommended()) + private val emitted = mutableListOf() + private val recorder = LogRecorder(redaction, LogSink(emitted::add), nowEpochMs = { FIXED_TIME_MS }) + + @After + fun tearDown() { + DevConsoleLog.install(LogRecorder(redaction, LogSink {}, enabled = false)) + } + + @Test + fun `records every level with its android counterpart`() { + DevConsoleLog.install(recorder) + + DevConsoleLog.v("Tag", "verbose") + DevConsoleLog.d("Tag", "debug") + DevConsoleLog.i("Tag", "info") + DevConsoleLog.w("Tag", "warn") + DevConsoleLog.e("Tag", "error") + DevConsoleLog.wtf("Tag", "assert") + + assertEquals( + listOf( + LogLevel.VERBOSE, + LogLevel.DEBUG, + LogLevel.INFO, + LogLevel.WARN, + LogLevel.ERROR, + LogLevel.ASSERT, + ), + emitted.map { it.level }, + ) + } + + @Test + fun `forwards the tag message and stack trace`() { + DevConsoleLog.install(recorder) + val failure = IllegalStateException("boom") + + DevConsoleLog.w("Checkout", "Payment declined", failure) + + val entry = emitted.single() + assertEquals(LogLevel.WARN, entry.level) + assertEquals("Checkout", entry.tag) + assertEquals("Payment declined", entry.message) + assertTrue(requireNotNull(entry.stackTrace).contains("IllegalStateException")) + } + + @Test + fun `returns the platform log result`() { + DevConsoleLog.install(recorder) + + assertEquals(PLATFORM_LOG_RESULT, DevConsoleLog.i("Tag", "info")) + } + + @Test + fun `records nothing while the installed recorder is disabled`() { + DevConsoleLog.install(LogRecorder(redaction, LogSink(emitted::add), enabled = false)) + + DevConsoleLog.i("Tag", "info") + + assertTrue(emitted.isEmpty()) + } + + private companion object { + const val FIXED_TIME_MS = 42L + const val PLATFORM_LOG_RESULT = 0 + } +} diff --git a/sdk/logs-timber/src/test/kotlin/io/devconsole/logs/timber/DevConsoleTimberTreeTest.kt b/sdk/logs-timber/src/test/kotlin/io/devconsole/logs/timber/DevConsoleTimberTreeTest.kt new file mode 100644 index 0000000..6de59a7 --- /dev/null +++ b/sdk/logs-timber/src/test/kotlin/io/devconsole/logs/timber/DevConsoleTimberTreeTest.kt @@ -0,0 +1,120 @@ +/** + * @author Shakib + * @since 04/11/26 + */ +package io.devconsole.logs.timber + +import android.util.Log +import io.devconsole.logs.LogEntry +import io.devconsole.logs.LogLevel +import io.devconsole.logs.LogRecorder +import io.devconsole.logs.LogSink +import io.devconsole.security.RedactionEngine +import io.devconsole.security.RedactionPolicy +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test +import timber.log.Timber + +class DevConsoleTimberTreeTest { + private val redaction = RedactionEngine(RedactionPolicy.recommended()) + private val emitted = mutableListOf() + private val recorder = LogRecorder(redaction, LogSink(emitted::add), nowEpochMs = { FIXED_TIME_MS }) + + @After + fun tearDown() { + Timber.uprootAll() + } + + @Test + fun `records an info line under the fallback tag`() { + Timber.plant(DevConsoleTimberTree(recorder)) + + Timber.i("Cart opened with 3 items") + + val entry = emitted.single() + assertEquals(LogLevel.INFO, entry.level) + assertEquals(FALLBACK_TAG, entry.tag) + assertEquals("Cart opened with 3 items", entry.message) + assertNull(entry.stackTrace) + } + + @Test + fun `maps every android priority`() { + Timber.plant(DevConsoleTimberTree(recorder)) + val expected = + mapOf( + Log.VERBOSE to LogLevel.VERBOSE, + Log.DEBUG to LogLevel.DEBUG, + Log.INFO to LogLevel.INFO, + Log.WARN to LogLevel.WARN, + Log.ERROR to LogLevel.ERROR, + Log.ASSERT to LogLevel.ASSERT, + ) + + expected.keys.forEach { priority -> Timber.log(priority, "priority $priority") } + + assertEquals(expected.values.toList(), emitted.map { it.level }) + } + + @Test + fun `records an unknown priority as debug`() { + Timber.plant(DevConsoleTimberTree(recorder)) + + Timber.log(UNKNOWN_PRIORITY, "unmapped priority") + + assertEquals(LogLevel.DEBUG, emitted.single().level) + } + + @Test + fun `uses an explicit timber tag`() { + Timber.plant(DevConsoleTimberTree(recorder)) + + Timber.tag("Checkout").i("Cart opened with 3 items") + + assertEquals("Checkout", emitted.single().tag) + } + + @Test + fun `strips timber's appended stack trace and passes the throwable instead`() { + Timber.plant(DevConsoleTimberTree(recorder)) + val failure = IllegalStateException("Card issuer returned code 05") + + Timber.e(failure, "Payment declined") + + val entry = emitted.single() + assertEquals(LogLevel.ERROR, entry.level) + assertEquals("Payment declined", entry.message) + assertTrue(requireNotNull(entry.stackTrace).contains("IllegalStateException")) + } + + @Test + fun `records only the stack trace when the message is empty`() { + Timber.plant(DevConsoleTimberTree(recorder)) + val failure = IllegalStateException("Card issuer returned code 05") + + Timber.e(failure) + + val entry = emitted.single() + assertEquals("", entry.message) + assertTrue(requireNotNull(entry.stackTrace).contains("IllegalStateException")) + } + + @Test + fun `drops lines below the minimum priority`() { + Timber.plant(DevConsoleTimberTree(recorder, Log.WARN)) + + Timber.d("dropped") + Timber.w("kept") + + assertEquals(listOf(LogLevel.WARN), emitted.map { it.level }) + } + + private companion object { + const val FIXED_TIME_MS = 42L + const val UNKNOWN_PRIORITY = 99 + const val FALLBACK_TAG = "Timber" + } +} diff --git a/sdk/mocks-okhttp-noop/api/mocks-okhttp-noop.api b/sdk/mocks-okhttp-noop/api/mocks-okhttp-noop.api index deae00e..5239dbd 100644 --- a/sdk/mocks-okhttp-noop/api/mocks-okhttp-noop.api +++ b/sdk/mocks-okhttp-noop/api/mocks-okhttp-noop.api @@ -3,3 +3,8 @@ public final class io/devconsole/mocks/okhttp/DevConsoleMockInterceptor : okhttp public fun intercept (Lokhttp3/Interceptor$Chain;)Lokhttp3/Response; } +public final class io/devconsole/mocks/okhttp/MockFailureMarker : java/lang/RuntimeException { + public fun (Ljava/util/Map;)V + public final fun getTags ()Ljava/util/Map; +} + diff --git a/sdk/mocks-okhttp-noop/src/main/kotlin/io/devconsole/mocks/okhttp/MockFailureMarker.kt b/sdk/mocks-okhttp-noop/src/main/kotlin/io/devconsole/mocks/okhttp/MockFailureMarker.kt new file mode 100644 index 0000000..142e2fa --- /dev/null +++ b/sdk/mocks-okhttp-noop/src/main/kotlin/io/devconsole/mocks/okhttp/MockFailureMarker.kt @@ -0,0 +1,9 @@ +/** + * @author Shakib + * @since 03/11/26 + */ +package io.devconsole.mocks.okhttp + +class MockFailureMarker( + val tags: Map, +) : RuntimeException("DevConsole mock failure", null, false, false) diff --git a/sdk/mocks-okhttp/api/mocks-okhttp.api b/sdk/mocks-okhttp/api/mocks-okhttp.api index deae00e..5239dbd 100644 --- a/sdk/mocks-okhttp/api/mocks-okhttp.api +++ b/sdk/mocks-okhttp/api/mocks-okhttp.api @@ -3,3 +3,8 @@ public final class io/devconsole/mocks/okhttp/DevConsoleMockInterceptor : okhttp public fun intercept (Lokhttp3/Interceptor$Chain;)Lokhttp3/Response; } +public final class io/devconsole/mocks/okhttp/MockFailureMarker : java/lang/RuntimeException { + public fun (Ljava/util/Map;)V + public final fun getTags ()Ljava/util/Map; +} + diff --git a/sdk/mocks-okhttp/src/main/kotlin/io/devconsole/mocks/okhttp/DevConsoleMockInterceptor.kt b/sdk/mocks-okhttp/src/main/kotlin/io/devconsole/mocks/okhttp/DevConsoleMockInterceptor.kt index b70907b..01cdc35 100644 --- a/sdk/mocks-okhttp/src/main/kotlin/io/devconsole/mocks/okhttp/DevConsoleMockInterceptor.kt +++ b/sdk/mocks-okhttp/src/main/kotlin/io/devconsole/mocks/okhttp/DevConsoleMockInterceptor.kt @@ -8,14 +8,18 @@ import io.devconsole.network.NetworkCaptureContext import okhttp3.Headers import okhttp3.Interceptor import okhttp3.Protocol +import okhttp3.Request import okhttp3.Response import okhttp3.ResponseBody.Companion.toResponseBody +import okio.Buffer import java.io.IOException -import java.net.SocketTimeoutException +import java.util.concurrent.atomic.AtomicBoolean class DevConsoleMockInterceptor( private val engine: MockEngine, ) : Interceptor { + private val rejectedHeaderLogged = AtomicBoolean(false) + override fun intercept(chain: Interceptor.Chain): Response { val request = chain.request() // `installDevConsole` wires one of these by default, so a host that also kept its own manual @@ -37,6 +41,7 @@ class DevConsoleMockInterceptor( request.url.queryParameter(name).orEmpty() }, headers = request.headers.toFoldedMap(), + body = request.bodyPreviewForMatching(engine.requestBodyLimitBytes()), ), ) val matched = decision as? MockDecision.Matched @@ -52,37 +57,59 @@ class DevConsoleMockInterceptor( NetworkCaptureContext(existing + mapOf("mocked" to "true", "mockRuleId" to it.rule.id)), ).build() } ?: request - return applyAction(action, taggedRequest, chain) + return try { + applyAction(action, taggedRequest, chain) + } catch (error: IOException) { + // Only failures the mock itself simulated are re-tagged; a real network failure from + // chain.proceed propagates untouched (and is never retried here). + // The host must still see the exact exception type it would get (e.g. SocketTimeoutException), + // so the mock tags ride along as a suppressed marker instead of a wrapper. + if (matched != null && action.simulatesFailure()) { + error.addSuppressed( + MockFailureMarker(taggedRequest.tag(NetworkCaptureContext::class.java)?.tags.orEmpty()), + ) + } + throw error + } } + /** + * A UTF-8 copy of the request body for body predicates, or `null` when none is needed or it + * cannot be read safely. One-shot and duplex bodies are never read (reading would consume them), + * and a body of unknown or oversized length is skipped rather than buffered. + */ + private fun Request.bodyPreviewForMatching(limitBytes: Int?): String? { + val requestBody = body?.takeUnless { it.isOneShot() || it.isDuplex() } + val length = requestBody?.let { runCatching { it.contentLength() }.getOrDefault(-1L) } ?: -1L + val readable = requestBody != null && limitBytes != null && length in 0..limitBytes + return if (readable) runCatching { Buffer().also(requestBody::writeTo).readUtf8() }.getOrNull() else null + } + + private fun MockAction.simulatesFailure(): Boolean = + when (this) { + is MockAction.ConnectionFailure, is MockAction.Timeout -> true + is MockAction.Delay -> next.simulatesFailure() + is MockAction.Throttle -> next.simulatesFailure() + is MockAction.Sequence -> steps.any { it.simulatesFailure() } + else -> false + } + private fun applyAction( action: MockAction, request: okhttp3.Request, chain: Interceptor.Chain, ): Response = when (action) { - is MockAction.StaticResponse -> - Response - .Builder() - .request(request) - .protocol(Protocol.HTTP_1_1) - .code(action.statusCode) - .message("DevConsole mock") - .apply { action.headers.forEach { (name, value) -> header(name, value) } } - .body(action.body.toResponseBody()) - .build() + is MockAction.StaticResponse -> buildStaticResponse(action, request) ?: chain.proceed(request) is MockAction.Delay -> { - Thread.sleep(action.durationMs) + cancellableSleep(action.durationMs, chain) applyAction(action.next, request, chain) } is MockAction.ConnectionFailure -> throw IOException(action.message) - is MockAction.Timeout -> { - Thread.sleep(action.durationMs) - throw SocketTimeoutException("DevConsole simulated timeout after ${action.durationMs}ms") - } + is MockAction.Timeout -> simulateTimeout(action, chain) is MockAction.StatusOverride -> chain @@ -101,10 +128,57 @@ class DevConsoleMockInterceptor( hostResponse.newBuilder().body(action.body.toResponseBody(mediaType)).build() } - is MockAction.TemplateResponse -> chain.proceed(request) // Template actions are resolved by MockEngine. + is MockAction.MapRemote -> proceedToRemappedUrl(action, request, chain) + + is MockAction.Throttle -> { + cancellableSleep(action.latencyMs, chain) + applyAction(action.next, request, chain).withThrottledBody(action.bytesPerSecond, chain) + } + + // Sequence steps and templates are resolved by MockEngine before they reach the interceptor. + is MockAction.Sequence -> chain.proceed(request) + is MockAction.TemplateResponse -> chain.proceed(request) MockAction.Passthrough -> chain.proceed(request) } + @Suppress("TooGenericExceptionCaught") // A malformed mock response must not break the host's real network request. + private fun buildStaticResponse( + action: MockAction.StaticResponse, + request: okhttp3.Request, + ): Response? = + try { + Response + .Builder() + .request(request) + .protocol(Protocol.HTTP_1_1) + .code(action.statusCode) + .message("DevConsole mock") + .apply { + action.headers.forEach { (name, value) -> + runCatching { header(name, value) }.onFailure(::logRejectedHeaderOnce) + } + }.body(mockResponseBody(action.body, action.headers)) + .build() + } catch (error: Exception) { + logRejectedHeaderOnce(error) + null + } + + private fun logRejectedHeaderOnce(error: Throwable) { + if (rejectedHeaderLogged.compareAndSet(false, true)) { + runCatching { + System.err.println( + "DevConsole skipped an invalid mock response header or response: ${error.message}", + ) + } + } + } + /** `Headers.get` returns only the last value for a repeated name; fold repeats like HTTP does. */ private fun Headers.toFoldedMap(): Map = names().associateWith { values(it).joinToString(", ") } } + +/** Attached (suppressed) to a failure a mock rule simulated, so capture can tag it as mocked. */ +class MockFailureMarker( + val tags: Map, +) : RuntimeException("DevConsole mock failure", null, false, false) diff --git a/sdk/mocks-okhttp/src/main/kotlin/io/devconsole/mocks/okhttp/MockActionTransport.kt b/sdk/mocks-okhttp/src/main/kotlin/io/devconsole/mocks/okhttp/MockActionTransport.kt new file mode 100644 index 0000000..7d81165 --- /dev/null +++ b/sdk/mocks-okhttp/src/main/kotlin/io/devconsole/mocks/okhttp/MockActionTransport.kt @@ -0,0 +1,158 @@ +/** + * @author Shakib + * @since 03/11/26 + */ +package io.devconsole.mocks.okhttp + +import io.devconsole.mocks.MockAction +import io.devconsole.network.NetworkCaptureContext +import okhttp3.Interceptor +import okhttp3.MediaType +import okhttp3.MediaType.Companion.toMediaTypeOrNull +import okhttp3.Response +import okhttp3.ResponseBody +import okhttp3.ResponseBody.Companion.toResponseBody +import okio.Buffer +import okio.BufferedSource +import okio.ForwardingSource +import okio.Source +import okio.buffer +import java.io.IOException +import java.net.SocketTimeoutException + +// Stateless OkHttp plumbing behind the timing and rewrite mock actions of [DevConsoleMockInterceptor]. + +private const val CALL_DEADLINE_NANOS_PER_MILLISECOND = 1_000_000L +private const val SLEEP_SLICE_MS = 50L +private const val MILLIS_PER_SECOND = 1_000L + +internal fun simulateTimeout( + action: MockAction.Timeout, + chain: Interceptor.Chain, +): Nothing { + // Never outlive the call's own deadline: OkHttp would report that as its own timeout instead. + val callTimeout = chain.call().timeout() + val untilCallDeadlineMs = + if (callTimeout.hasDeadline()) { + (callTimeout.deadlineNanoTime() - System.nanoTime()).coerceAtLeast(0L) / + CALL_DEADLINE_NANOS_PER_MILLISECOND + } else { + action.durationMs + } + cancellableSleep(minOf(action.durationMs, untilCallDeadlineMs), chain) + throw SocketTimeoutException("DevConsole simulated timeout after ${action.durationMs}ms") +} + +internal fun proceedToRemappedUrl( + action: MockAction.MapRemote, + request: okhttp3.Request, + chain: Interceptor.Chain, +): Response { + val newUrl = + request.url + .newBuilder() + .apply { + action.scheme?.let(::scheme) + action.host?.let(::host) + action.port?.let(::port) + action.path?.let(::encodedPath) + }.build() + val existing = request.tag(NetworkCaptureContext::class.java)?.tags.orEmpty() + val rewrittenRequest = + request + .newBuilder() + .url(newUrl) + .tag( + NetworkCaptureContext::class.java, + NetworkCaptureContext(existing + ("mapRemote" to newUrl.toString())), + ).build() + return chain + .proceed(rewrittenRequest) + .newBuilder() + .request(rewrittenRequest) + .build() +} + +internal fun Response.withThrottledBody( + bytesPerSecond: Long, + chain: Interceptor.Chain, +): Response { + val originalBody = body ?: return this + return newBuilder().body(throttledBody(originalBody, bytesPerSecond, chain)).build() +} + +internal fun throttledBody( + originalBody: ResponseBody, + bytesPerSecond: Long, + chain: Interceptor.Chain, +): ResponseBody { + val throttledSource = ThrottledSource(originalBody.source(), bytesPerSecond, chain).buffer() + return ThrottledResponseBody(originalBody, throttledSource) +} + +/** Keeps the declared Content-Type verbatim (String.toResponseBody would append a charset). */ +internal fun mockResponseBody( + body: String, + headers: Map, +): ResponseBody { + val mediaType = headers.declaredMediaType() + return body.toByteArray(mediaType?.charset() ?: Charsets.UTF_8).toResponseBody(mediaType) +} + +private fun Map.declaredMediaType(): MediaType? = + entries.firstOrNull { it.key.equals("Content-Type", ignoreCase = true) }?.value?.toMediaTypeOrNull() + +internal fun cancellableSleep( + durationMs: Long, + chain: Interceptor.Chain, +) { + var remaining = durationMs + while (remaining > 0) { + if (chain.call().isCanceled()) throw IOException("Canceled") + val slice = minOf(remaining, SLEEP_SLICE_MS) + try { + Thread.sleep(slice) + } catch (error: InterruptedException) { + Thread.currentThread().interrupt() + throw IOException("Canceled", error) + } + remaining -= slice + } + ensureCallActive(chain) +} + +internal fun ensureCallActive(chain: Interceptor.Chain) { + if (chain.call().isCanceled()) throw IOException("Canceled") +} + +/** Paces reads to [bytesPerSecond], in slices short enough to notice a cancelled call promptly. */ +private class ThrottledSource( + delegate: Source, + private val bytesPerSecond: Long, + private val chain: Interceptor.Chain, +) : ForwardingSource(delegate) { + override fun read( + sink: Buffer, + byteCount: Long, + ): Long { + ensureCallActive(chain) + val maxChunk = (bytesPerSecond * SLEEP_SLICE_MS / MILLIS_PER_SECOND).coerceAtLeast(1L) + val bytesRead = super.read(sink, minOf(byteCount, maxChunk)) + if (bytesRead > 0L) { + val sleepMs = (bytesRead * MILLIS_PER_SECOND + bytesPerSecond - 1L) / bytesPerSecond + cancellableSleep(sleepMs, chain) + } + return bytesRead + } +} + +private class ThrottledResponseBody( + private val original: ResponseBody, + private val throttledSource: BufferedSource, +) : ResponseBody() { + override fun contentType(): MediaType? = original.contentType() + + override fun contentLength(): Long = original.contentLength() + + override fun source(): BufferedSource = throttledSource +} diff --git a/sdk/mocks-okhttp/src/test/kotlin/io/devconsole/mocks/okhttp/DevConsoleMockInterceptorTest.kt b/sdk/mocks-okhttp/src/test/kotlin/io/devconsole/mocks/okhttp/DevConsoleMockInterceptorTest.kt index a38537c..629fa6d 100644 --- a/sdk/mocks-okhttp/src/test/kotlin/io/devconsole/mocks/okhttp/DevConsoleMockInterceptorTest.kt +++ b/sdk/mocks-okhttp/src/test/kotlin/io/devconsole/mocks/okhttp/DevConsoleMockInterceptorTest.kt @@ -5,14 +5,85 @@ import io.devconsole.mocks.MockEngine import io.devconsole.mocks.MockOutcome import io.devconsole.mocks.MockRule import io.devconsole.network.NetworkCaptureContext +import okhttp3.MediaType.Companion.toMediaType import okhttp3.OkHttpClient import okhttp3.Request +import okhttp3.RequestBody.Companion.toRequestBody import okhttp3.mockwebserver.MockResponse import okhttp3.mockwebserver.MockWebServer import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue import org.junit.Test +import java.util.concurrent.CountDownLatch +import java.util.concurrent.TimeUnit class DevConsoleMockInterceptorTest { + @Test fun `invalid response header does not crash and real call proceeds`() { + val server = MockWebServer() + server.start() + try { + server.enqueue(MockResponse().setBody("real")) + val engine = MockEngine(emptyList()) + val upsert = + runCatching { + engine.upsert( + MockRule( + "bad", + 1, + path = "/", + action = MockAction.StaticResponse(200, "mock", mapOf("X-Bad" to "café")), + ), + ) + } + assertTrue(upsert.isFailure) + val client = + OkHttpClient + .Builder() + .addInterceptor( + DevConsoleMockInterceptor(engine), + ).build() + val response = client.newCall(Request.Builder().url(server.url("/")).build()).execute() + assertEquals("real", response.body!!.string()) + assertEquals(1, server.requestCount) + } finally { + server.close() + } + } + + @Test fun `cancellation during delay aborts promptly`() { + val client = + OkHttpClient + .Builder() + .addInterceptor( + DevConsoleMockInterceptor( + MockEngine(listOf(MockRule("slow", 1, path = "/", action = MockAction.Delay(30_000)))), + ), + ).build() + val finished = CountDownLatch(1) + val call = client.newCall(Request.Builder().url("https://api.test/").build()) + call.enqueue( + object : okhttp3.Callback { + override fun onFailure( + call: okhttp3.Call, + e: java.io.IOException, + ) { + finished.countDown() + } + + override fun onResponse( + call: okhttp3.Call, + response: okhttp3.Response, + ) { + response.close() + finished.countDown() + } + }, + ) + Thread.sleep(100) + call.cancel() + assertTrue(finished.await(2, TimeUnit.SECONDS)) + } + @Test fun `returns a static response for a matching rule`() { val outcomes = mutableListOf() val client = @@ -139,4 +210,144 @@ class DevConsoleMockInterceptorTest { assertEquals("a, b|a", response.body!!.string()) } + + @Test fun `mapRemote rewrites host port and path while preserving query and tags`() { + val targetServer = MockWebServer() + targetServer.start() + try { + targetServer.enqueue(MockResponse().setResponseCode(200).setBody("from-remote")) + val targetUrl = targetServer.url("/v2/orders") + val engine = + MockEngine( + listOf( + MockRule( + id = "remap", + priority = 1, + path = "/v1/orders", + action = + MockAction.MapRemote( + scheme = targetUrl.scheme, + host = targetUrl.host, + port = targetUrl.port, + path = "/v2/orders", + ), + ), + ), + ) + val client = + OkHttpClient + .Builder() + .addInterceptor(DevConsoleMockInterceptor(engine)) + .build() + + val response = + client + .newCall( + Request + .Builder() + .url("http://original.invalid:9999/v1/orders?page=2&filter=active") + .build(), + ).execute() + + assertEquals(200, response.code) + assertEquals("from-remote", response.body!!.string()) + val recorded = targetServer.takeRequest(2, TimeUnit.SECONDS)!! + assertEquals("/v2/orders?page=2&filter=active", recorded.path) + val tags = response.request.tag(NetworkCaptureContext::class.java)!!.tags + assertEquals("true", tags["mocked"]) + assertEquals("remap", tags["mockRuleId"]) + assertEquals("$targetUrl?page=2&filter=active", tags["mapRemote"]) + } finally { + targetServer.close() + } + } + + @Test fun `throttle delivers full body intact and enforces bandwidth rate`() { + val bodyText = "x".repeat(200) + val engine = + MockEngine( + listOf( + MockRule( + id = "throttled", + priority = 1, + path = "/download", + action = + MockAction.Throttle( + bytesPerSecond = 1_000, + latencyMs = 20, + next = MockAction.StaticResponse(200, bodyText, mapOf("Content-Type" to "text/plain")), + ), + ), + ), + ) + val client = + OkHttpClient + .Builder() + .addInterceptor(DevConsoleMockInterceptor(engine)) + .build() + + val startNanos = System.nanoTime() + val response = client.newCall(Request.Builder().url("https://api.test/download").build()).execute() + val responseBody = response.body!! + assertEquals(bodyText.length.toLong(), responseBody.contentLength()) + assertEquals("text/plain", responseBody.contentType().toString()) + val content = responseBody.string() + val elapsedMs = (System.nanoTime() - startNanos) / 1_000_000L + + assertEquals(bodyText, content) + assertTrue("Expected at least 150ms for 200B at 1000B/s + 20ms latency, got ${elapsedMs}ms", elapsedMs >= 150L) + } + + @Test fun `body predicate sees the request body and leaves it intact for the real call`() { + val server = MockWebServer() + server.start() + try { + server.enqueue(MockResponse().setBody("real")) + val engine = + MockEngine( + listOf( + MockRule( + "paid", + 1, + method = "POST", + path = "/orders", + bodyPredicate = ".*\"paid\":true.*", + action = MockAction.StaticResponse(402, "mocked"), + ), + ), + bodyMatchingEnabled = true, + ) + val client = OkHttpClient.Builder().addInterceptor(DevConsoleMockInterceptor(engine)).build() + val json = "application/json".toMediaType() + + val matched = + client + .newCall( + Request + .Builder() + .url( + server.url("/orders"), + ).post("{\"paid\":true}".toRequestBody(json)) + .build(), + ).execute() + assertEquals(402, matched.code) + assertEquals("mocked", matched.body!!.string()) + assertEquals(0, server.requestCount) + + val passed = + client + .newCall( + Request + .Builder() + .url( + server.url("/orders"), + ).post("{\"paid\":false}".toRequestBody(json)) + .build(), + ).execute() + assertEquals("real", passed.body!!.string()) + assertEquals("{\"paid\":false}", server.takeRequest().body.readUtf8()) + } finally { + server.close() + } + } } diff --git a/sdk/mocks/api/mocks.api b/sdk/mocks/api/mocks.api index c5eb81a..e0a8615 100644 --- a/sdk/mocks/api/mocks.api +++ b/sdk/mocks/api/mocks.api @@ -49,6 +49,25 @@ public final class io/devconsole/mocks/MockAction$Delay : io/devconsole/mocks/Mo public fun toString ()Ljava/lang/String; } +public final class io/devconsole/mocks/MockAction$MapRemote : io/devconsole/mocks/MockAction { + public fun ()V + public fun (Ljava/lang/String;Ljava/lang/String;Ljava/lang/Integer;Ljava/lang/String;)V + public synthetic fun (Ljava/lang/String;Ljava/lang/String;Ljava/lang/Integer;Ljava/lang/String;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1 ()Ljava/lang/String; + public final fun component2 ()Ljava/lang/String; + public final fun component3 ()Ljava/lang/Integer; + public final fun component4 ()Ljava/lang/String; + public final fun copy (Ljava/lang/String;Ljava/lang/String;Ljava/lang/Integer;Ljava/lang/String;)Lio/devconsole/mocks/MockAction$MapRemote; + public static synthetic fun copy$default (Lio/devconsole/mocks/MockAction$MapRemote;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Integer;Ljava/lang/String;ILjava/lang/Object;)Lio/devconsole/mocks/MockAction$MapRemote; + public fun equals (Ljava/lang/Object;)Z + public final fun getHost ()Ljava/lang/String; + public final fun getPath ()Ljava/lang/String; + public final fun getPort ()Ljava/lang/Integer; + public final fun getScheme ()Ljava/lang/String; + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + public final class io/devconsole/mocks/MockAction$Passthrough : io/devconsole/mocks/MockAction { public static final field INSTANCE Lio/devconsole/mocks/MockAction$Passthrough; public fun equals (Ljava/lang/Object;)Z @@ -56,6 +75,20 @@ public final class io/devconsole/mocks/MockAction$Passthrough : io/devconsole/mo public fun toString ()Ljava/lang/String; } +public final class io/devconsole/mocks/MockAction$Sequence : io/devconsole/mocks/MockAction { + public fun (Ljava/util/List;Z)V + public synthetic fun (Ljava/util/List;ZILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1 ()Ljava/util/List; + public final fun component2 ()Z + public final fun copy (Ljava/util/List;Z)Lio/devconsole/mocks/MockAction$Sequence; + public static synthetic fun copy$default (Lio/devconsole/mocks/MockAction$Sequence;Ljava/util/List;ZILjava/lang/Object;)Lio/devconsole/mocks/MockAction$Sequence; + public fun equals (Ljava/lang/Object;)Z + public final fun getLoop ()Z + public final fun getSteps ()Ljava/util/List; + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + public final class io/devconsole/mocks/MockAction$StaticResponse : io/devconsole/mocks/MockAction { public fun (ILjava/lang/String;Ljava/util/Map;)V public synthetic fun (ILjava/lang/String;Ljava/util/Map;ILkotlin/jvm/internal/DefaultConstructorMarker;)V @@ -99,6 +132,22 @@ public final class io/devconsole/mocks/MockAction$TemplateResponse : io/devconso public fun toString ()Ljava/lang/String; } +public final class io/devconsole/mocks/MockAction$Throttle : io/devconsole/mocks/MockAction { + public fun (JJLio/devconsole/mocks/MockAction;)V + public synthetic fun (JJLio/devconsole/mocks/MockAction;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1 ()J + public final fun component2 ()J + public final fun component3 ()Lio/devconsole/mocks/MockAction; + public final fun copy (JJLio/devconsole/mocks/MockAction;)Lio/devconsole/mocks/MockAction$Throttle; + public static synthetic fun copy$default (Lio/devconsole/mocks/MockAction$Throttle;JJLio/devconsole/mocks/MockAction;ILjava/lang/Object;)Lio/devconsole/mocks/MockAction$Throttle; + public fun equals (Ljava/lang/Object;)Z + public final fun getBytesPerSecond ()J + public final fun getLatencyMs ()J + public final fun getNext ()Lio/devconsole/mocks/MockAction; + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + public final class io/devconsole/mocks/MockAction$Timeout : io/devconsole/mocks/MockAction { public fun ()V public fun (J)V @@ -147,6 +196,7 @@ public final class io/devconsole/mocks/MockEngine { public final fun isEnabled ()Z public final fun persist (Lio/devconsole/mocks/MockRuleStore;Ljava/lang/String;Ljava/lang/String;)V public final fun remove (Ljava/lang/String;)Z + public final fun requestBodyLimitBytes ()Ljava/lang/Integer; public final fun restore (Lio/devconsole/mocks/MockRuleStore;Ljava/lang/String;Ljava/lang/String;)V public final fun rules ()Ljava/util/List; public final fun setEnabled (Ljava/lang/String;Z)Z diff --git a/sdk/mocks/src/main/kotlin/io/devconsole/mocks/MockEngine.kt b/sdk/mocks/src/main/kotlin/io/devconsole/mocks/MockEngine.kt index 2d11813..47adb6c 100644 --- a/sdk/mocks/src/main/kotlin/io/devconsole/mocks/MockEngine.kt +++ b/sdk/mocks/src/main/kotlin/io/devconsole/mocks/MockEngine.kt @@ -3,6 +3,10 @@ package io.devconsole.mocks import com.google.re2j.Pattern import java.util.concurrent.atomic.AtomicBoolean +private const val HEADER_VALUE_MIN_CODE = 32 +private const val HEADER_VALUE_MAX_CODE = 126 +private const val HEADER_NAME_MIN_CODE = 33 + data class MockRequest( val method: String, val scheme: String, @@ -59,11 +63,69 @@ sealed interface MockAction { val body: String, ) : MockAction + data class Sequence( + val steps: List, + val loop: Boolean = false, + ) : MockAction { + init { + require(steps.isNotEmpty()) { "Sequence steps must not be empty" } + require(steps.size <= MAX_SEQUENCE_STEPS) { "Sequence may contain at most $MAX_SEQUENCE_STEPS steps" } + require(steps.none { it is Sequence }) { "Sequence steps must not contain another Sequence" } + } + } + + data class MapRemote( + val scheme: String? = null, + val host: String? = null, + val port: Int? = null, + val path: String? = null, + ) : MockAction { + init { + require(scheme != null || host != null || port != null || path != null) { + "MapRemote must specify at least one of scheme, host, port, or path" + } + require(scheme == null || scheme in ALLOWED_SCHEMES) { + "MapRemote scheme must be http or https" + } + require(port == null || port in MIN_PORT..MAX_PORT) { + "MapRemote port must be between $MIN_PORT and $MAX_PORT" + } + require(host == null || (host.isNotBlank() && '/' !in host)) { + "MapRemote host must not be blank or contain '/'" + } + require(path == null || path.startsWith('/')) { + "MapRemote path must start with '/'" + } + } + } + + data class Throttle( + val bytesPerSecond: Long, + val latencyMs: Long = 0, + val next: MockAction = Passthrough, + ) : MockAction { + init { + require(bytesPerSecond in MIN_THROTTLE_BPS..MAX_THROTTLE_BPS) { + "Throttle bytesPerSecond must be between $MIN_THROTTLE_BPS and $MAX_THROTTLE_BPS" + } + require(latencyMs in 0..MAX_DELAY_MS) { + "Throttle latencyMs must be between 0 and $MAX_DELAY_MS ms" + } + require(next !is Throttle) { "Throttle next must not be another Throttle" } + } + } + data object Passthrough : MockAction private companion object { const val MAX_DELAY_MS = 30_000L const val DEFAULT_TIMEOUT_MS = 1_000L + private const val MAX_SEQUENCE_STEPS = 20 + private const val MIN_PORT = 1 + private const val MAX_PORT = 65_535 + private const val MIN_THROTTLE_BPS = 1L + private const val MAX_THROTTLE_BPS = 104_857_600L + private val ALLOWED_SCHEMES = setOf("http", "https") } } @@ -172,11 +234,14 @@ class MockEngine( private val rules = initialRules.toMutableList() private val compiledRules = initialRules.associate { it.id to it.compile() }.toMutableMap() private val stats = mutableMapOf() + private val sequenceCounters = mutableMapOf() private val enabled = AtomicBoolean(enabled) @Volatile private var outcomeSink: MockOutcomeSink = MockOutcomeSink {} private var persistenceBinding: PersistenceBinding? = null + private val persistenceLock = Any() + private val mutationLock = Any() init { require(maxBodyPredicateBytes >= 0) { "maxBodyPredicateBytes must not be negative" } @@ -184,6 +249,18 @@ class MockEngine( fun isEnabled(): Boolean = enabled.get() + /** + * The most request-body bytes worth handing to [decide], or `null` when no body is needed. + * + * A body is only needed when body matching is on and at least one enabled rule has a body + * predicate. Adapters use this to skip copying request bodies on every call. + */ + @Synchronized + fun requestBodyLimitBytes(): Int? = + maxBodyPredicateBytes.takeIf { + bodyMatchingEnabled && enabled.get() && rules.any { it.persistence.enabled && it.bodyPredicate != null } + } + fun setEnabled(value: Boolean) { enabled.set(value) } @@ -243,13 +320,22 @@ class MockEngine( store.save(rules.toDurableRules(currentAppVersion, installationId)) } - @Synchronized fun clearSessionRules() { - val removedIds = rules.filter { it.scope == MockScope.SESSION }.map(MockRule::id).toSet() - rules.removeAll { it.id in removedIds } - compiledRules.keys.removeAll(removedIds) - // Same contract as remove(): a rule recreated under a cleared id must start at 0 hits — - // an inherited count from the previous session would be a fabricated number. - stats.keys.removeAll(removedIds) + fun clearSessionRules() { + synchronized(mutationLock) { + val (ids, updated) = + synchronized(this) { + val ids = rules.filter { it.scope == MockScope.SESSION }.map(MockRule::id).toSet() + ids to rules.filterNot { it.id in ids } + } + persistSnapshot(updated) + synchronized(this) { + rules.removeAll { it.id in ids } + compiledRules.keys.removeAll(ids) + stats.keys.removeAll(ids) + sequenceCounters.keys.removeAll(ids) + } + // Removed rules also lose their hit stats, so recreating an id starts at zero. + } } @Synchronized fun rules(): List = rules.toList() @@ -260,15 +346,26 @@ class MockEngine( /** Every rule's hit stats, keyed by rule id -- unmatched rules are simply absent, not zero-filled. */ @Synchronized fun statsSnapshot(): Map = stats.toMap() - @Synchronized fun upsert(rule: MockRule) { + fun upsert(rule: MockRule) { + validateActionHeaders(rule.action) val compiled = rule.compile() - val persistedRule = persistenceBinding?.prepare(rule) ?: rule - val index = rules.indexOfFirst { it.id == persistedRule.id } - val updated = rules.toMutableList() - if (index >= 0) updated[index] = persistedRule else updated += persistedRule - persistenceBinding?.save(updated) - if (index >= 0) rules[index] = persistedRule else rules += persistedRule - compiledRules[persistedRule.id] = compiled + synchronized(mutationLock) { + val (persistedRule, updated) = + synchronized(this) { + val persistedRule = persistenceBinding?.prepare(rule) ?: rule + val updated = rules.toMutableList() + val index = updated.indexOfFirst { it.id == persistedRule.id } + if (index >= 0) updated[index] = persistedRule else updated += persistedRule + persistedRule to updated + } + persistSnapshot(updated) + synchronized(this) { + rules.clear() + rules.addAll(updated) + compiledRules[persistedRule.id] = compiled + sequenceCounters.remove(persistedRule.id) + } + } } /** @@ -276,24 +373,41 @@ class MockEngine( * like [upsert]. Matching already honors [MockRule.persistence]'s `enabled` flag in [decide], * so this is the only mutation a rule-level toggle needs. Returns false when [id] is unknown. */ - @Synchronized fun setEnabled( id: String, enabled: Boolean, ): Boolean { - val rule = rules.firstOrNull { it.id == id } ?: return false - upsert(rule.withPersistence(rule.persistence.copy(enabled = enabled))) - return true + return synchronized(mutationLock) { + val rule = synchronized(this) { rules.firstOrNull { it.id == id } } ?: return@synchronized false + upsert(rule.withPersistence(rule.persistence.copy(enabled = enabled))) + true + } } - @Synchronized fun remove(id: String): Boolean { - if (rules.none { it.id == id }) return false - val updated = rules.filterNot { it.id == id } - persistenceBinding?.save(updated) - compiledRules.remove(id) - stats.remove(id) - return rules.removeAll { it.id == id } + return synchronized(mutationLock) { + val updated: List? = + synchronized(this) { + if (rules.none { it.id == id }) null else rules.filterNot { it.id == id } + } + if (updated == null) return@synchronized false + persistSnapshot(updated) + synchronized(this) { + compiledRules.keys.removeAll { it !in updated.map(MockRule::id) } + stats.keys.removeAll { it == id } + sequenceCounters.remove(id) + rules.clear() + rules.addAll(updated) + } + true + } + } + + /** Mutations serialize here while persistence runs outside the engine monitor. */ + private fun persistSnapshot(snapshot: List) { + synchronized(persistenceLock) { + persistenceBinding?.save(snapshot) + } } @Synchronized @@ -336,7 +450,12 @@ class MockEngine( ).firstOrNull() ?.value ?.first ?: return passthrough(MockPassthroughReason.NO_MATCH) - when (val resolution = rule.action.resolve(request)) { + val selectedAction = + when (val action = rule.action) { + is MockAction.Sequence -> nextSequenceStep(rule.id, action) + else -> action + } + when (val resolution = selectedAction.resolve(request)) { is ActionResolution.Resolved -> { emit(MockOutcome.Matched(rule.id, resolution.action.javaClass.simpleName)) recordHit(rule.id) @@ -383,17 +502,40 @@ class MockEngine( queryPredicates.size * 10 + headerPredicates.size * 10 + @Synchronized + private fun nextSequenceStep( + ruleId: String, + sequence: MockAction.Sequence, + ): MockAction { + val index = sequenceCounters[ruleId] ?: 0 + sequenceCounters[ruleId] = index + 1 + val steps = sequence.steps + return when { + index < steps.size -> steps[index] + sequence.loop -> steps[index % steps.size] + else -> steps.last() + } + } + private fun MockAction.resolve(request: MockRequest): ActionResolution = when (this) { is MockAction.TemplateResponse -> - render(template, request) - ?.let { ActionResolution.Resolved(MockAction.StaticResponse(statusCode, it, headers)) } - ?: ActionResolution.Invalid("Template contains an unknown or unresolved placeholder") + when (val rendered = render(template, request)) { + is RenderedTemplate.Text -> + ActionResolution.Resolved(MockAction.StaticResponse(statusCode, rendered.value, headers)) + is RenderedTemplate.UnknownPlaceholder -> + ActionResolution.Invalid("Unknown template placeholder ${rendered.placeholder}") + } is MockAction.Delay -> when (val nested = next.resolve(request)) { is ActionResolution.Resolved -> ActionResolution.Resolved(copy(next = nested.action)) is ActionResolution.Invalid -> nested } + is MockAction.Throttle -> + when (val nested = next.resolve(request)) { + is ActionResolution.Resolved -> ActionResolution.Resolved(copy(next = nested.action)) + is ActionResolution.Invalid -> nested + } else -> ActionResolution.Resolved(this) } @@ -415,39 +557,66 @@ class MockEngine( stats[ruleId] = previous.copy(hitCount = previous.hitCount + 1, lastHitEpochMs = System.currentTimeMillis()) } + /** + * Fills `{{method}}`, `{{scheme}}`, `{{host}}`, `{{path}}`, `{{body}}`, `{{query.name}}` and + * `{{header.name}}`. A known placeholder whose value the request simply lacks (no such header, + * query parameter or body) renders as empty text -- e.g. OkHttp adds `User-Agent` only after + * application interceptors run, and that must not silently turn the whole rule off. Only an + * unknown placeholder (a typo) fails the rule, and the error names it. + * + * [Regex.replace] is single-pass, so a request value that itself contains `{{...}}` is inserted + * verbatim and never re-expanded. + */ private fun render( template: String, request: MockRequest, - ): String? { - var invalid = false + ): RenderedTemplate { + var unknown: String? = null val rendered = PLACEHOLDER.replace(template) { match -> - val namespace = match.groupValues[1] - val key = match.groupValues[2].takeIf(String::isNotEmpty) val value = - when (namespace) { - "method" -> request.method.takeIf { key == null } - "scheme" -> request.scheme.takeIf { key == null } - "host" -> request.host.takeIf { key == null } - "path" -> request.path.takeIf { key == null } - "body" -> request.body.takeIf { key == null } - "query" -> key?.let(request.query::get) - "header" -> - key?.let { name -> - request.headers.entries - .firstOrNull { it.key.equals(name, true) } - ?.value - } - else -> null - } - if (value == null) { - invalid = true - match.value - } else { - value - } + placeholderValue(match.groupValues[1], match.groupValues[2].takeIf(String::isNotEmpty), request) + if (value == null && unknown == null) unknown = match.value + value ?: match.value + } + return unknown?.let(RenderedTemplate::UnknownPlaceholder) ?: RenderedTemplate.Text(rendered) + } + + /** `null` only for a placeholder that is not one of the documented forms. */ + private fun placeholderValue( + namespace: String, + key: String?, + request: MockRequest, + ): String? = + if (key == null) { + when (namespace) { + "method" -> request.method + "scheme" -> request.scheme + "host" -> request.host + "path" -> request.path + "body" -> request.body.orEmpty() + else -> null + } + } else { + when (namespace) { + "query" -> request.query[key].orEmpty() + "header" -> + request.headers.entries + .firstOrNull { it.key.equals(key, true) } + ?.value + .orEmpty() + else -> null } - return rendered.takeUnless { invalid || PLACEHOLDER.containsMatchIn(it) } + } + + private sealed interface RenderedTemplate { + data class Text( + val value: String, + ) : RenderedTemplate + + data class UnknownPlaceholder( + val placeholder: String, + ) : RenderedTemplate } private companion object { @@ -472,6 +641,37 @@ class MockEngine( ) } + private fun validateActionHeaders(action: MockAction) { + val headers = + when (action) { + is MockAction.StaticResponse -> action.headers + is MockAction.TemplateResponse -> action.headers + else -> emptyMap() + } + action.nestedActions().forEach(::validateActionHeaders) + headers.forEach { (name, value) -> + require( + name.isNotEmpty() && + name.all { + it.code in HEADER_NAME_MIN_CODE..HEADER_VALUE_MAX_CODE && it !in "()<>@,;:\\\"/[]?={} \t" + }, + ) { + "Invalid mock response header name: $name" + } + require(value.all { it == '\t' || it.code in HEADER_VALUE_MIN_CODE..HEADER_VALUE_MAX_CODE }) { + "Invalid mock response header value for $name" + } + } + } + + private fun MockAction.nestedActions(): List = + when (this) { + is MockAction.Delay -> listOf(next) + is MockAction.Throttle -> listOf(next) + is MockAction.Sequence -> steps + else -> emptyList() + } + private data class CompiledRule( val path: Pattern, val body: Pattern?, diff --git a/sdk/mocks/src/test/kotlin/io/devconsole/mocks/MockEngineTest.kt b/sdk/mocks/src/test/kotlin/io/devconsole/mocks/MockEngineTest.kt index 8c80cd0..a96383d 100644 --- a/sdk/mocks/src/test/kotlin/io/devconsole/mocks/MockEngineTest.kt +++ b/sdk/mocks/src/test/kotlin/io/devconsole/mocks/MockEngineTest.kt @@ -3,8 +3,37 @@ package io.devconsole.mocks import org.junit.Assert.assertEquals import org.junit.Assert.assertTrue import org.junit.Test +import java.util.concurrent.CountDownLatch +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicInteger +import java.util.concurrent.atomic.AtomicReference class MockEngineTest { + @Test fun `rejects invalid mock response header values during upsert`() { + val engine = MockEngine(emptyList()) + val result = + runCatching { + engine.upsert( + MockRule( + "invalid", + 1, + action = + MockAction.StaticResponse( + 200, + "body", + mapOf( + "X-Note" to "café", + ), + ), + ), + ) + } + + assertTrue(result.isFailure) + assertTrue(result.exceptionOrNull()!!.message!!.contains("Invalid mock response header value")) + assertTrue(engine.rules().isEmpty()) + } + @Test fun `mock engine is enabled by default`() { assertTrue(MockEngine(emptyList()).isEnabled()) @@ -106,6 +135,49 @@ class MockEngineTest { ) } + @Test fun `asks adapters for a body only when a live rule has a body predicate`() { + val plain = MockRule("plain", 1) + val bodyRule = MockRule("body", 1, bodyPredicate = "accepted") + assertEquals(null, MockEngine(listOf(bodyRule)).requestBodyLimitBytes()) + assertEquals(null, MockEngine(listOf(plain), bodyMatchingEnabled = true).requestBodyLimitBytes()) + val engine = MockEngine(listOf(plain, bodyRule), bodyMatchingEnabled = true, maxBodyPredicateBytes = 64) + assertEquals(64, engine.requestBodyLimitBytes()) + engine.setEnabled(false) + assertEquals(null, engine.requestBodyLimitBytes()) + } + + @Test fun `template renders a missing header or query value as empty instead of failing the rule`() { + val engine = + MockEngine( + listOf( + MockRule( + "tpl", + 1, + action = + MockAction.TemplateResponse( + 200, + "ua=[{{header.User-Agent}}] page=[{{query.page}}] {{body}}", + ), + ), + ), + ) + val decision = engine.decide(MockRequest("GET", "https", "api.test", "/", headers = mapOf("X" to "{{path}}"))) + val action = (decision as MockDecision.Matched).action as MockAction.StaticResponse + assertEquals("ua=[] page=[] ", action.body) + } + + @Test fun `unknown template placeholder names itself in the evaluation error`() { + val outcomes = mutableListOf() + val engine = + MockEngine(listOf(MockRule("typo", 1, action = MockAction.TemplateResponse(200, "{{pathh}}")))) + .withOutcomeSink { outcomes += it } + assertTrue(engine.decide(MockRequest("GET", "https", "api.test", "/")) is MockDecision.Passthrough) + assertEquals( + "Unknown template placeholder {{pathh}}", + (outcomes.single() as MockOutcome.EvaluationError).message, + ) + } + @Test fun `clears only session-scoped rules`() { val engine = MockEngine( @@ -348,4 +420,202 @@ class MockEngineTest { assertTrue(result.isFailure) assertTrue(engine.rules().isEmpty()) } + + @Test + fun `serialized persistence keeps the later rule mutation on disk`() { + val firstSaveStarted = CountDownLatch(1) + val releaseFirstSave = CountDownLatch(1) + val saveCount = AtomicInteger() + val savedRules = AtomicReference>(emptyList()) + val store = + object : MockRuleStore { + override fun load(): List = savedRules.get() + + override fun save(rules: List) { + if (saveCount.incrementAndGet() == 1) { + firstSaveStarted.countDown() + check(releaseFirstSave.await(2, TimeUnit.SECONDS)) + } + savedRules.set(rules) + } + } + val engine = MockEngine(emptyList()) + engine.bindPersistence(store, currentAppVersion = "1", installationId = "install-a") + + val first = Thread { engine.upsert(MockRule("first", 1, scope = MockScope.PERSISTENT_INTERNAL)) } + first.start() + assertTrue(firstSaveStarted.await(2, TimeUnit.SECONDS)) + val second = Thread { engine.upsert(MockRule("second", 1, scope = MockScope.PERSISTENT_INTERNAL)) } + second.start() + releaseFirstSave.countDown() + first.join(2_000) + second.join(2_000) + + assertTrue(!first.isAlive) + assertTrue(!second.isAlive) + assertEquals(listOf("first", "second"), savedRules.get().map(MockRule::id)) + } + + @Test + fun `sequence non-loop sticks to last step after exhausting steps`() { + val step0 = MockAction.StaticResponse(503, "first") + val step1 = MockAction.StaticResponse(200, "second") + val engine = + MockEngine( + listOf( + MockRule( + "seq", + 1, + path = "/orders", + action = MockAction.Sequence(listOf(step0, step1), loop = false), + ), + ), + ) + val request = MockRequest("GET", "https", "api.test", "/orders") + + assertEquals(step0, (engine.decide(request) as MockDecision.Matched).action) + assertEquals(step1, (engine.decide(request) as MockDecision.Matched).action) + assertEquals(step1, (engine.decide(request) as MockDecision.Matched).action) + } + + @Test + fun `sequence loop wraps around to first step`() { + val step0 = MockAction.StaticResponse(500, "fail") + val step1 = MockAction.StaticResponse(200, "ok") + val engine = + MockEngine( + listOf( + MockRule( + "seq-loop", + 1, + path = "/orders", + action = MockAction.Sequence(listOf(step0, step1), loop = true), + ), + ), + ) + val request = MockRequest("GET", "https", "api.test", "/orders") + + assertEquals(step0, (engine.decide(request) as MockDecision.Matched).action) + assertEquals(step1, (engine.decide(request) as MockDecision.Matched).action) + assertEquals(step0, (engine.decide(request) as MockDecision.Matched).action) + assertEquals(step1, (engine.decide(request) as MockDecision.Matched).action) + } + + @Test + fun `sequence counter resets on upsert removal and clearSessionRules`() { + val step0 = MockAction.StaticResponse(503, "first") + val step1 = MockAction.StaticResponse(200, "second") + val rule = + MockRule( + "seq", + 1, + path = "/orders", + scope = MockScope.SESSION, + action = MockAction.Sequence(listOf(step0, step1), loop = false), + ) + val engine = MockEngine(listOf(rule)) + val request = MockRequest("GET", "https", "api.test", "/orders") + + assertEquals(step0, (engine.decide(request) as MockDecision.Matched).action) + assertEquals(step1, (engine.decide(request) as MockDecision.Matched).action) + + engine.upsert(rule.copy(priority = 2)) + assertEquals(step0, (engine.decide(request) as MockDecision.Matched).action) + + engine.clearSessionRules() + engine.upsert(rule) + assertEquals(step0, (engine.decide(request) as MockDecision.Matched).action) + } + + @Test + fun `resolves nested template inside sequence step and throttle next`() { + val engine = + MockEngine( + listOf( + MockRule( + "nested", + 1, + path = "/orders", + action = + MockAction.Sequence( + listOf( + MockAction.TemplateResponse(200, "step:{{path}}"), + MockAction.Throttle( + bytesPerSecond = 1_024, + latencyMs = 10, + next = MockAction.TemplateResponse(201, "throttled:{{method}}"), + ), + ), + ), + ), + ), + ) + val request = MockRequest("POST", "https", "api.test", "/orders") + + assertEquals( + MockAction.StaticResponse(200, "step:/orders"), + (engine.decide(request) as MockDecision.Matched).action, + ) + assertEquals( + MockAction.Throttle( + bytesPerSecond = 1_024, + latencyMs = 10, + next = MockAction.StaticResponse(201, "throttled:POST"), + ), + (engine.decide(request) as MockDecision.Matched).action, + ) + } + + @Test + fun `validates sequence mapRemote throttle init and nested headers`() { + assertTrue(runCatching { MockAction.Sequence(emptyList()) }.isFailure) + assertTrue( + runCatching { + MockAction.Sequence(List(21) { MockAction.Passthrough }) + }.isFailure, + ) + assertTrue( + runCatching { + MockAction.Sequence(listOf(MockAction.Sequence(listOf(MockAction.Passthrough)))) + }.isFailure, + ) + + assertTrue(runCatching { MockAction.MapRemote() }.isFailure) + assertTrue(runCatching { MockAction.MapRemote(scheme = "ftp") }.isFailure) + assertTrue(runCatching { MockAction.MapRemote(port = 0) }.isFailure) + assertTrue(runCatching { MockAction.MapRemote(port = 70_000) }.isFailure) + assertTrue(runCatching { MockAction.MapRemote(host = " ") }.isFailure) + assertTrue(runCatching { MockAction.MapRemote(host = "bad/host") }.isFailure) + assertTrue(runCatching { MockAction.MapRemote(path = "no-slash") }.isFailure) + assertEquals("staging.test", MockAction.MapRemote(host = "staging.test").host) + + assertTrue(runCatching { MockAction.Throttle(bytesPerSecond = 0) }.isFailure) + assertTrue(runCatching { MockAction.Throttle(bytesPerSecond = 104_857_601) }.isFailure) + assertTrue(runCatching { MockAction.Throttle(bytesPerSecond = 100, latencyMs = -1) }.isFailure) + assertTrue(runCatching { MockAction.Throttle(bytesPerSecond = 100, latencyMs = 30_001) }.isFailure) + assertTrue( + runCatching { + MockAction.Throttle(bytesPerSecond = 100, next = MockAction.Throttle(bytesPerSecond = 100)) + }.isFailure, + ) + + val engine = MockEngine(emptyList()) + val badHeaderAction = MockAction.StaticResponse(200, "ok", mapOf("X-Bad" to "café")) + assertTrue( + runCatching { + engine.upsert(MockRule("seq-bad", 1, action = MockAction.Sequence(listOf(badHeaderAction)))) + }.isFailure, + ) + assertTrue( + runCatching { + engine.upsert( + MockRule( + "throttle-bad", + 1, + action = MockAction.Throttle(bytesPerSecond = 1_000, next = badHeaderAction), + ), + ) + }.isFailure, + ) + } } diff --git a/sdk/network-ktor/api/network-ktor.api b/sdk/network-ktor/api/network-ktor.api index 3510bed..1b8f094 100644 --- a/sdk/network-ktor/api/network-ktor.api +++ b/sdk/network-ktor/api/network-ktor.api @@ -8,3 +8,13 @@ public final class io/devconsole/network/ktor/DevConsoleKtorClientPluginKt { public static final fun getDevConsoleKtorClientPlugin ()Lio/ktor/client/plugins/api/ClientPlugin; } +public final class io/devconsole/network/ktor/DevConsoleKtorMocksConfig { + public fun ()V + public final fun getMockEngine ()Lio/devconsole/mocks/MockEngine; + public final fun setMockEngine (Lio/devconsole/mocks/MockEngine;)V +} + +public final class io/devconsole/network/ktor/DevConsoleKtorMocksKt { + public static final fun getDevConsoleKtorMocks ()Lio/ktor/client/plugins/api/ClientPlugin; +} + diff --git a/sdk/network-ktor/build.gradle.kts b/sdk/network-ktor/build.gradle.kts index c74a22b..857f9ee 100644 --- a/sdk/network-ktor/build.gradle.kts +++ b/sdk/network-ktor/build.gradle.kts @@ -6,10 +6,12 @@ plugins { android { namespace = "io.devconsole.network.ktor" + defaultConfig { consumerProguardFiles("consumer-rules.pro") } } dependencies { api(project(":sdk:network")) + implementation(project(":sdk:mocks")) implementation("io.ktor:ktor-client-core:3.0.3") testImplementation("io.ktor:ktor-client-mock:3.0.3") testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.9.0") diff --git a/sdk/network-ktor/consumer-rules.pro b/sdk/network-ktor/consumer-rules.pro new file mode 100644 index 0000000..73a6842 --- /dev/null +++ b/sdk/network-ktor/consumer-rules.pro @@ -0,0 +1 @@ +-keep class io.devconsole.internal.enabled.NetworkKtorCaptureMarker { *; } diff --git a/sdk/network-ktor/src/main/kotlin/io/devconsole/internal/enabled/NetworkKtorCaptureMarker.kt b/sdk/network-ktor/src/main/kotlin/io/devconsole/internal/enabled/NetworkKtorCaptureMarker.kt new file mode 100644 index 0000000..be010e2 --- /dev/null +++ b/sdk/network-ktor/src/main/kotlin/io/devconsole/internal/enabled/NetworkKtorCaptureMarker.kt @@ -0,0 +1,9 @@ +/** + * @author Shakib + * @since 04/11/26 + */ +package io.devconsole.internal.enabled + +internal object NetworkKtorCaptureMarker { + const val SIGNATURE = "DEVCONSOLE_ENABLED_NETWORK_KTOR_V1" +} diff --git a/sdk/network-ktor/src/main/kotlin/io/devconsole/network/ktor/DevConsoleKtorClientPlugin.kt b/sdk/network-ktor/src/main/kotlin/io/devconsole/network/ktor/DevConsoleKtorClientPlugin.kt index c7ed5e1..72d72c2 100644 --- a/sdk/network-ktor/src/main/kotlin/io/devconsole/network/ktor/DevConsoleKtorClientPlugin.kt +++ b/sdk/network-ktor/src/main/kotlin/io/devconsole/network/ktor/DevConsoleKtorClientPlugin.kt @@ -1,5 +1,6 @@ package io.devconsole.network.ktor +import io.devconsole.network.NetworkCaptureContext import io.devconsole.network.NetworkRequestInput import io.devconsole.network.NetworkRequestMetadata import io.devconsole.network.NetworkResponseInput @@ -130,6 +131,13 @@ class DevConsoleKtorClientConfig { private val startedAtKey = AttributeKey("DevConsoleStartedAt") +/** + * Adapter-neutral tags a Ktor plugin attached to the outgoing request, read back here into + * [NetworkRequestMetadata.tags]. `DevConsoleKtorMocks` is the only writer today; the key lives here + * so capture does not have to depend on the mocks plugin being installed. + */ +internal val devConsoleKtorCaptureContextKey = AttributeKey("DevConsoleKtorCaptureContext") + /** * Reads up to [MAX_KTOR_RESPONSE_BODY_CAPTURE_BYTES] (+1 to detect overflow without guessing at * `isClosedForRead` edge states) from the capture half of the split and records the transaction @@ -241,6 +249,11 @@ private fun prepareTransaction(response: HttpResponse): PendingKtorTransaction { threadName = Thread.currentThread().name, bodyLength = request.headers[HttpHeaders.ContentLength]?.toLongOrNull(), bodyOmittedReason = if (capturedRequestBody != null) null else "ktor-pipeline-metadata-only", + tags = + request.attributes + .getOrNull(devConsoleKtorCaptureContextKey) + ?.tags + .orEmpty(), ), ) diff --git a/sdk/network-ktor/src/main/kotlin/io/devconsole/network/ktor/DevConsoleKtorMocks.kt b/sdk/network-ktor/src/main/kotlin/io/devconsole/network/ktor/DevConsoleKtorMocks.kt new file mode 100644 index 0000000..ffc5514 --- /dev/null +++ b/sdk/network-ktor/src/main/kotlin/io/devconsole/network/ktor/DevConsoleKtorMocks.kt @@ -0,0 +1,169 @@ +/** + * @author Shakib + * @since 04/11/26 + */ +package io.devconsole.network.ktor + +import io.devconsole.mocks.MockDecision +import io.devconsole.mocks.MockEngine +import io.devconsole.mocks.MockRequest +import io.devconsole.network.NetworkCaptureContext +import io.ktor.client.HttpClient +import io.ktor.client.call.HttpClientCall +import io.ktor.client.plugins.HttpSend +import io.ktor.client.plugins.Sender +import io.ktor.client.plugins.api.createClientPlugin +import io.ktor.client.plugins.plugin +import io.ktor.client.request.HttpRequestBuilder +import io.ktor.client.request.HttpRequestData +import io.ktor.client.request.HttpSendPipeline +import io.ktor.http.Headers +import io.ktor.http.HeadersBuilder +import io.ktor.http.content.OutgoingContent +import io.ktor.http.encodedPath +import io.ktor.util.pipeline.PipelinePhase + +internal const val MOCKED_CAPTURE_TAG = "mocked" +internal const val MOCK_RULE_ID_CAPTURE_TAG = "mockRuleId" +internal const val MAPPED_REMOTE_CAPTURE_TAG = "mapRemote" +internal const val MOCKED_CAPTURE_TAG_VALUE = "true" + +private const val HEADER_VALUE_SEPARATOR = ", " + +/** + * Applies DevConsole [MockEngine] rules to Ktor client calls, mirroring + * `DevConsoleMockInterceptor` on OkHttp. + * + * Install it next to [DevConsoleKtorClientPlugin] and hand it the host's engine: + * + * ``` + * val client = HttpClient { + * install(DevConsoleKtorClientPlugin) { recorder = DevConsole.networkRecorder() } + * install(DevConsoleKtorMocks) { mockEngine = DevConsole.mockEngine() } + * } + * ``` + * + * Interception happens in the `HttpSend` plugin rather than the engine or the receive pipeline. + * `HttpSend` owns request execution, so returning a synthetic call from here short-circuits the + * network without bypassing the receive pipeline that [DevConsoleKtorClientPlugin] hooks -- a + * mocked response is therefore captured as an ordinary transaction, tagged `mocked=true` and + * `mockRuleId=`, exactly like the OkHttp adapter. + */ +public val DevConsoleKtorMocks = + createClientPlugin("DevConsoleKtorMocks", ::DevConsoleKtorMocksConfig) { + val engine = + requireNotNull(pluginConfig.mockEngine) { + "DevConsoleKtorMocks requires mockEngine = DevConsole.mockEngine()" + } + val httpClient = client + httpClient.plugin(HttpSend).intercept { request -> + sendOrMock(httpClient, engine, request) + } + // Status overrides and body replacements rewrite the engine's call before `Receive`, so + // DevConsoleKtorClientPlugin captures the response the app sees. + val rewritePhase = PipelinePhase("DevConsoleMockRewrite") + httpClient.sendPipeline.insertPhaseAfter(HttpSendPipeline.Engine, rewritePhase) + httpClient.sendPipeline.intercept(rewritePhase) { call -> + val rewrite = context.attributes.getOrNull(mockResponseRewriteKey) ?: return@intercept + if (call is HttpClientCall) proceedWith(call.rewriteMockedResponse(httpClient, context, rewrite)) + } + } + +/** + * Configuration for [DevConsoleKtorMocks]. + */ +public class DevConsoleKtorMocksConfig { + /** + * The DevConsole mock engine consulted for every outgoing call. Required: installing the plugin + * without it fails immediately. When the engine is globally disabled, every call proceeds + * untouched. + */ + public var mockEngine: MockEngine? = null +} + +/** + * Decides once per call and either returns a synthetic response or hands the request to the rest + * of the send pipeline. A matching rule always tags the request, including when its action ends in + * a passthrough, so capture reports the rule that fired. + */ +private suspend fun Sender.sendOrMock( + client: HttpClient, + engine: MockEngine, + request: HttpRequestBuilder, +): HttpClientCall { + val decision = runCatching { engine.decide(request.toMockRequest(engine)) }.getOrNull() + val matched = decision as? MockDecision.Matched ?: return execute(request) + request.markMocked(matched.rule.id) + return applyMockAction(client, matched.action, request) +} + +private fun HttpRequestBuilder.toMockRequest(engine: MockEngine): MockRequest = + MockRequest( + method = method.value, + scheme = url.protocol.name, + host = url.host, + path = url.encodedPath, + query = url.parameters.entries().associate { (name, values) -> name to values.firstOrNull().orEmpty() }, + headers = + headers.build().entries().associate { (name, values) -> + name to values.joinToString(HEADER_VALUE_SEPARATOR) + }, + body = bodyPreviewForMatching(engine.requestBodyLimitBytes()), + ) + +/** + * A readable copy of the request body for body predicates, or `null` when none is needed or the + * body cannot be read safely. Streaming content ([OutgoingContent.ReadChannelContent] and + * [OutgoingContent.WriteChannelContent]) is never touched, and a body of unknown or oversized + * length is skipped rather than buffered -- the same rules the OkHttp adapter applies to one-shot + * and duplex request bodies. At `HttpSend` time a `setBody("...")` value is still raw, so `String` + * and `ByteArray` bodies are accepted too. + */ +private fun HttpRequestBuilder.bodyPreviewForMatching(limitBytes: Int?): String? { + if (limitBytes == null) return null + return when (val content = body) { + is String -> content.takeIf { it.utf8Size() <= limitBytes } + is ByteArray -> content.takeIf { it.size <= limitBytes }?.decodeToString() + is OutgoingContent.ByteArrayContent -> content.textWithin(limitBytes) + else -> null + } +} + +private fun OutgoingContent.ByteArrayContent.textWithin(limitBytes: Int): String? { + val declaredLength = contentLength + val bytes = + if (declaredLength != null && declaredLength in 0L..limitBytes.toLong()) { + runCatching { bytes() }.getOrNull() + } else { + null + } + return bytes?.takeIf { it.size <= limitBytes }?.decodeToString() +} + +private fun String.utf8Size(): Int = encodeToByteArray().size + +private fun HttpRequestBuilder.markMocked(ruleId: String) { + updateMockTags( + mapOf( + MOCKED_CAPTURE_TAG to MOCKED_CAPTURE_TAG_VALUE, + MOCK_RULE_ID_CAPTURE_TAG to ruleId, + ), + ) +} + +internal fun HttpRequestBuilder.markMappedRemote(url: String) { + updateMockTags(mapOf(MAPPED_REMOTE_CAPTURE_TAG to url)) +} + +private fun HttpRequestBuilder.updateMockTags(tags: Map) { + val existing = attributes.getOrNull(devConsoleKtorCaptureContextKey)?.tags.orEmpty() + attributes.put(devConsoleKtorCaptureContextKey, NetworkCaptureContext(existing + tags)) +} + +internal fun HttpRequestBuilder.toMockRequestData(): HttpRequestData = build() + +internal fun Map.toKtorHeaders(): Headers = + HeadersBuilder() + .apply { + forEach { (name, value) -> runCatching { append(name, value) } } + }.build() diff --git a/sdk/network-ktor/src/main/kotlin/io/devconsole/network/ktor/KtorMockActionExecutor.kt b/sdk/network-ktor/src/main/kotlin/io/devconsole/network/ktor/KtorMockActionExecutor.kt new file mode 100644 index 0000000..4c099af --- /dev/null +++ b/sdk/network-ktor/src/main/kotlin/io/devconsole/network/ktor/KtorMockActionExecutor.kt @@ -0,0 +1,200 @@ +/** + * @author Shakib + * @since 04/11/26 + */ +package io.devconsole.network.ktor + +import io.devconsole.mocks.MockAction +import io.ktor.client.HttpClient +import io.ktor.client.call.HttpClientCall +import io.ktor.client.plugins.Sender +import io.ktor.client.request.HttpRequestBuilder +import io.ktor.client.request.HttpRequestData +import io.ktor.client.request.HttpResponseData +import io.ktor.http.Headers +import io.ktor.http.HttpProtocolVersion +import io.ktor.http.HttpStatusCode +import io.ktor.http.URLProtocol +import io.ktor.http.encodedPath +import io.ktor.util.date.GMTDate +import io.ktor.utils.io.ByteChannel +import io.ktor.utils.io.ByteReadChannel +import io.ktor.utils.io.InternalAPI +import io.ktor.utils.io.writeFully +import kotlinx.coroutines.Job +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import java.io.IOException +import java.net.SocketTimeoutException + +private const val THROTTLE_CHUNKS_PER_SECOND = 10L +private const val MILLIS_PER_SECOND = 1_000L + +/** + * Applies one already-resolved [MockAction] to [request]. `MockEngine.decide` resolves templates + * and sequence steps before returning, so those branches are defensive passthroughs only. + */ +internal suspend fun Sender.applyMockAction( + client: HttpClient, + action: MockAction, + request: HttpRequestBuilder, +): HttpClientCall = + when (action) { + is MockAction.StaticResponse -> staticResponseOrProceed(client, action, request) + + is MockAction.Delay -> { + delay(action.durationMs) + applyMockAction(client, action.next, request) + } + + is MockAction.ConnectionFailure -> throw IOException(action.message) + + is MockAction.Timeout -> simulateTimeout(action) + + is MockAction.StatusOverride -> executeRewritten(request, MockResponseRewrite.Status(action.statusCode)) + + is MockAction.BodyReplacement -> executeRewritten(request, MockResponseRewrite.Body(action.body)) + + is MockAction.MapRemote -> proceedToRemappedUrl(action, request) + + is MockAction.Throttle -> applyThrottle(client, action, request) + + is MockAction.TemplateResponse, is MockAction.Sequence, MockAction.Passthrough -> execute(request) + } + +private suspend fun Sender.staticResponseOrProceed( + client: HttpClient, + action: MockAction.StaticResponse, + request: HttpRequestBuilder, +): HttpClientCall = + runCatching { + buildMockCall( + client = client, + requestData = request.toMockRequestData(), + statusCode = action.statusCode, + headers = action.headers.toKtorHeaders(), + body = ByteReadChannel(action.body.encodeToByteArray()), + ) + }.getOrNull()?.received(client) ?: execute(request) + +private suspend fun simulateTimeout(action: MockAction.Timeout): Nothing { + delay(action.durationMs) + // SocketTimeoutException is an IOException and is what OkHttp's adapter throws, so a host's + // existing timeout handling sees the same failure class it would from a real call. + throw SocketTimeoutException("DevConsole simulated timeout after ${action.durationMs}ms") +} + +private suspend fun Sender.proceedToRemappedUrl( + action: MockAction.MapRemote, + request: HttpRequestBuilder, +): HttpClientCall { + action.scheme?.let { request.url.protocol = URLProtocol.createOrDefault(it) } + action.host?.let { request.url.host = it } + action.port?.let { request.url.port = it } + action.path?.let { request.url.encodedPath = it } + request.markMappedRemote(request.url.build().toString()) + return execute(request) +} + +/** + * Latency is applied for every throttle rule. A static payload is also paced at + * [MockAction.Throttle.bytesPerSecond] through a channel that emits bounded chunks. Pacing an + * engine-produced body (a throttle wrapping passthrough) is left unsimulated: the response channel + * belongs to the engine and there is no supported point in the client pipeline to re-wrap it + * without buffering the host's stream, so that case keeps only the latency. + */ +private suspend fun Sender.applyThrottle( + client: HttpClient, + action: MockAction.Throttle, + request: HttpRequestBuilder, +): HttpClientCall { + delay(action.latencyMs) + val next = action.next + val throttledStatic = + (next as? MockAction.StaticResponse)?.let { static -> + runCatching { + buildMockCall( + client = client, + requestData = request.toMockRequestData(), + statusCode = static.statusCode, + headers = static.headers.toKtorHeaders(), + body = client.pacedBodyChannel(static.body, action.bytesPerSecond), + ) + }.getOrNull() + } + return throttledStatic?.received(client) ?: applyMockAction(client, next, request) +} + +private fun HttpClient.pacedBodyChannel( + body: String, + bytesPerSecond: Long, +): ByteReadChannel { + val channel = ByteChannel(autoFlush = true) + launch { + try { + val bytes = body.encodeToByteArray() + var offset = 0 + while (offset < bytes.size) { + val remaining = (bytes.size - offset).toLong() + val chunkLength = + (bytesPerSecond / THROTTLE_CHUNKS_PER_SECOND) + .coerceAtLeast(1L) + .coerceAtMost(remaining) + .toInt() + channel.writeFully(bytes.copyOfRange(offset, offset + chunkLength)) + offset += chunkLength + delay((chunkLength * MILLIS_PER_SECOND + bytesPerSecond - 1L) / bytesPerSecond) + } + } finally { + channel.flushAndClose() + } + } + return channel +} + +/** + * Builds a synthetic call around [requestData]. Ktor 3 has no public constructor for a response + * that never touched an engine: [HttpResponse] is abstract, and the concrete call/response pair is + * assembled by the `@InternalAPI` [HttpClientCall] constructor from a public [HttpResponseData]. + * This is the smallest surface that produces one. Returned from `HttpSend`, it never reaches the + * send pipeline's `Receive` phase, so [MockHttpClientCall.received] runs the receive pipeline + * itself -- that is where capture and body saving hook in. + * + * [HttpResponseData.callContext] gets its own child job: the response completes that job when its + * body drains, and reusing the client's job would complete the whole client. + */ +@OptIn(InternalAPI::class) +private fun buildMockCall( + client: HttpClient, + requestData: HttpRequestData, + statusCode: Int, + headers: Headers, + body: ByteReadChannel, +): MockHttpClientCall = + MockHttpClientCall( + client = client, + requestData = requestData, + responseData = + HttpResponseData( + statusCode = HttpStatusCode.fromValue(statusCode), + requestTime = GMTDate(), + headers = headers, + version = HttpProtocolVersion.HTTP_1_1, + body = body, + callContext = client.coroutineContext + Job(client.coroutineContext[Job]), + ), + ) + +/** + * A call that never went through the send pipeline. [received] does what `HttpClient`'s own + * `Receive` interceptor does for engine calls: runs the receive pipeline and keeps its response. + */ +@OptIn(InternalAPI::class) +private class MockHttpClientCall( + client: HttpClient, + requestData: HttpRequestData, + responseData: HttpResponseData, +) : HttpClientCall(client, requestData, responseData) { + suspend fun received(client: HttpClient): HttpClientCall = + apply { response = client.receivePipeline.execute(Unit, response) } +} diff --git a/sdk/network-ktor/src/main/kotlin/io/devconsole/network/ktor/MockResponseRewrite.kt b/sdk/network-ktor/src/main/kotlin/io/devconsole/network/ktor/MockResponseRewrite.kt new file mode 100644 index 0000000..14fdd06 --- /dev/null +++ b/sdk/network-ktor/src/main/kotlin/io/devconsole/network/ktor/MockResponseRewrite.kt @@ -0,0 +1,110 @@ +/** + * @author Shakib + * @since 04/11/26 + */ +package io.devconsole.network.ktor + +import io.ktor.client.HttpClient +import io.ktor.client.call.HttpClientCall +import io.ktor.client.plugins.Sender +import io.ktor.client.request.HttpRequestBuilder +import io.ktor.client.request.HttpResponseData +import io.ktor.http.Headers +import io.ktor.http.HeadersBuilder +import io.ktor.http.HttpHeaders +import io.ktor.http.HttpStatusCode +import io.ktor.util.AttributeKey +import io.ktor.utils.io.ByteReadChannel +import io.ktor.utils.io.InternalAPI +import io.ktor.utils.io.cancel + +/** + * How a passthrough response is rewritten. The rewrite is not applied here: it rides on the request + * and [rewriteMockedResponse] applies it between the engine and the receive pipeline, so capture + * records the response the app actually gets rather than the one the server sent. + */ +internal sealed interface MockResponseRewrite { + data class Status( + val statusCode: Int, + ) : MockResponseRewrite + + data class Body( + val body: String, + ) : MockResponseRewrite +} + +internal val mockResponseRewriteKey = AttributeKey("DevConsoleMockResponseRewrite") + +internal suspend fun Sender.executeRewritten( + request: HttpRequestBuilder, + rewrite: MockResponseRewrite, +): HttpClientCall { + request.attributes.put(mockResponseRewriteKey, rewrite) + return execute(request) +} + +/** + * Applies a pending [MockResponseRewrite] to the engine's call. Runs in the send pipeline after + * the engine and before `Receive`; any failure keeps the real call untouched. + */ +@OptIn(InternalAPI::class) +internal fun HttpClientCall.rewriteMockedResponse( + client: HttpClient, + request: HttpRequestBuilder, + rewrite: MockResponseRewrite, +): HttpClientCall = + runCatching { + when (rewrite) { + is MockResponseRewrite.Status -> + replaceResponse(client, request, status = HttpStatusCode.fromValue(rewrite.statusCode)) + + is MockResponseRewrite.Body -> { + val bytes = rewrite.body.encodeToByteArray() + // The server's body is discarded, so release it; and its length and encoding no + // longer describe the replacement (a gzip Content-Encoding would make the + // ContentEncoding plugin try to inflate plain text). + response.rawContent.cancel(null) + replaceResponse( + client = client, + request = request, + headers = response.headers.withReplacedBodyLength(bytes.size), + body = ByteReadChannel(bytes), + ) + } + } + }.getOrDefault(this) + +private fun Headers.withReplacedBodyLength(length: Int): Headers = + HeadersBuilder() + .apply { + appendAll(this@withReplacedBodyLength) + remove(HttpHeaders.ContentLength) + remove(HttpHeaders.ContentEncoding) + append(HttpHeaders.ContentLength, length.toString()) + }.build() + +/** + * Rebuilds a real call with an overridden status or body. The original call's coroutine context is + * reused so completing the rebuilt response also completes the call it replaces. + */ +@OptIn(InternalAPI::class) +private fun HttpClientCall.replaceResponse( + client: HttpClient, + request: HttpRequestBuilder, + status: HttpStatusCode = response.status, + headers: Headers = response.headers, + body: ByteReadChannel = response.rawContent, +): HttpClientCall = + HttpClientCall( + client = client, + requestData = request.toMockRequestData(), + responseData = + HttpResponseData( + statusCode = status, + requestTime = response.requestTime, + headers = headers, + version = response.version, + body = body, + callContext = response.coroutineContext, + ), + ) diff --git a/sdk/network-ktor/src/test/kotlin/io/devconsole/network/ktor/DevConsoleKtorMocksTest.kt b/sdk/network-ktor/src/test/kotlin/io/devconsole/network/ktor/DevConsoleKtorMocksTest.kt new file mode 100644 index 0000000..f2ad078 --- /dev/null +++ b/sdk/network-ktor/src/test/kotlin/io/devconsole/network/ktor/DevConsoleKtorMocksTest.kt @@ -0,0 +1,292 @@ +/** + * @author Shakib + * @since 04/11/26 + */ +package io.devconsole.network.ktor + +import io.devconsole.mocks.MockAction +import io.devconsole.mocks.MockRule +import io.devconsole.network.BodyPreview +import io.devconsole.network.InMemoryNetworkTransactionStore +import io.devconsole.network.NetworkCaptureFactory +import io.devconsole.network.NetworkCursorCodec +import io.devconsole.network.NetworkTransaction +import io.devconsole.network.NetworkTransactionQuery +import io.devconsole.network.NetworkTransactionRecorder +import io.devconsole.security.RedactionEngine +import io.devconsole.security.RedactionPolicy +import io.ktor.client.HttpClient +import io.ktor.client.engine.mock.respond +import io.ktor.client.request.get +import io.ktor.client.statement.bodyAsText +import io.ktor.http.HttpHeaders +import io.ktor.http.HttpStatusCode +import io.ktor.http.headersOf +import kotlinx.coroutines.runBlocking +import org.junit.Assert.assertEquals +import org.junit.Assert.assertThrows +import org.junit.Test +import java.io.IOException +import io.devconsole.mocks.MockEngine as DevConsoleMockEngine +import io.ktor.client.engine.mock.MockEngine as KtorMockEngine + +private const val MOCKED_BODY = "{\"mocked\":true}" +private const val NETWORK_BODY = "network" +private const val ORDER_PATH = "/orders" +private const val ORDER_URL = "https://api.test/orders" +private const val ORDER_RULE_PRIORITY = 10 +private const val DEFAULT_AWAIT_MAX_WAIT_MS = 2_000L +private const val AWAIT_POLL_INTERVAL_MS = 10L +private const val THROTTLE_BYTES_PER_SECOND = 1_024L + +class DevConsoleKtorMocksTest { + @Test + fun `static rule returns the mocked response without touching the network`() = + runBlocking { + var networkCalls = 0 + val networkEngine = + KtorMockEngine { _ -> + networkCalls++ + respond( + content = NETWORK_BODY, + status = HttpStatusCode.OK, + headers = headersOf(HttpHeaders.ContentType, "text/plain"), + ) + } + val client = httpClient(networkEngine, DevConsoleMockEngine(listOf(staticOrderRule()))) + + val response = client.get(ORDER_URL) + + assertEquals(HttpStatusCode.Created, response.status) + assertEquals(MOCKED_BODY, response.bodyAsText()) + assertEquals("application/json", response.headers[HttpHeaders.ContentType]) + assertEquals(0, networkCalls) + } + + @Test + fun `unmatched request reaches the network`() = + runBlocking { + var networkCalls = 0 + val networkEngine = + KtorMockEngine { _ -> + networkCalls++ + respond(content = NETWORK_BODY, status = HttpStatusCode.OK) + } + val client = + httpClient( + networkEngine, + DevConsoleMockEngine(listOf(staticOrderRule(host = "mocked.test"))), + ) + + val response = client.get(ORDER_URL) + + assertEquals(NETWORK_BODY, response.bodyAsText()) + assertEquals(1, networkCalls) + } + + @Test + fun `disabled engine reaches the network`() = + runBlocking { + var networkCalls = 0 + val networkEngine = + KtorMockEngine { _ -> + networkCalls++ + respond(content = NETWORK_BODY, status = HttpStatusCode.OK) + } + val client = + httpClient( + networkEngine, + DevConsoleMockEngine(initialRules = listOf(staticOrderRule()), enabled = false), + ) + + val response = client.get(ORDER_URL) + + assertEquals(NETWORK_BODY, response.bodyAsText()) + assertEquals(1, networkCalls) + } + + @Test + fun `failure action throws an IOException`() { + val client = + httpClient( + KtorMockEngine { _ -> respond(content = NETWORK_BODY, status = HttpStatusCode.OK) }, + DevConsoleMockEngine( + listOf( + staticOrderRule(action = MockAction.ConnectionFailure("simulated failure")), + ), + ), + ) + + assertThrows(IOException::class.java) { + runBlocking { client.get(ORDER_URL) } + } + } + + @Test + fun `map remote rewrites the host the network engine sees`() = + runBlocking { + var seenHost: String? = null + val networkEngine = + KtorMockEngine { request -> + seenHost = request.url.host + respond(content = "remapped", status = HttpStatusCode.OK) + } + val client = + httpClient( + networkEngine, + DevConsoleMockEngine( + listOf(staticOrderRule(action = MockAction.MapRemote(host = "remapped.test"))), + ), + ) + + val response = client.get(ORDER_URL) + + assertEquals("remapped", response.bodyAsText()) + assertEquals("remapped.test", seenHost) + } + + @Test + fun `mocked call is captured and tagged when the capture plugin is installed`() = + runBlocking { + val store = InMemoryNetworkTransactionStore(NetworkCursorCodec("1234567890123456".encodeToByteArray())) + val recorder = + NetworkTransactionRecorder( + factory = NetworkCaptureFactory(RedactionEngine(RedactionPolicy.recommended())), + store = store, + ) + var networkCalls = 0 + val networkEngine = + KtorMockEngine { _ -> + networkCalls++ + respond(content = NETWORK_BODY, status = HttpStatusCode.OK) + } + val client = httpClient(networkEngine, DevConsoleMockEngine(listOf(staticOrderRule())), recorder) + + val response = client.get(ORDER_URL) + assertEquals(MOCKED_BODY, response.bodyAsText()) + + val transaction = awaitTransaction(store) + assertEquals("true", transaction.capture.request.metadata.tags["mocked"]) + assertEquals("orders", transaction.capture.request.metadata.tags["mockRuleId"]) + assertEquals(MOCKED_BODY, (transaction.capture.response!!.body as BodyPreview.Text).value) + assertEquals(0, networkCalls) + } + + @Test + fun `status override reaches the app and the capture`() = + runBlocking { + val (store, recorder) = captureStore() + val networkEngine = KtorMockEngine { respond(content = NETWORK_BODY, status = HttpStatusCode.OK) } + val rule = staticOrderRule(action = MockAction.StatusOverride(HttpStatusCode.ServiceUnavailable.value)) + val client = httpClient(networkEngine, DevConsoleMockEngine(listOf(rule)), recorder) + + val response = client.get(ORDER_URL) + + assertEquals(HttpStatusCode.ServiceUnavailable, response.status) + assertEquals(NETWORK_BODY, response.bodyAsText()) + val transaction = awaitTransaction(store) + assertEquals(HttpStatusCode.ServiceUnavailable.value, transaction.capture.response!!.statusCode) + assertEquals("orders", transaction.capture.request.metadata.tags["mockRuleId"]) + } + + @Test + fun `body replacement reaches the app and the capture with a matching length`() = + runBlocking { + val (store, recorder) = captureStore() + val networkEngine = + KtorMockEngine { + respond( + content = NETWORK_BODY, + status = HttpStatusCode.OK, + headers = headersOf(HttpHeaders.ContentLength, NETWORK_BODY.length.toString()), + ) + } + val rule = staticOrderRule(action = MockAction.BodyReplacement(MOCKED_BODY)) + val client = httpClient(networkEngine, DevConsoleMockEngine(listOf(rule)), recorder) + + val response = client.get(ORDER_URL) + + assertEquals(MOCKED_BODY, response.bodyAsText()) + assertEquals(MOCKED_BODY.length.toString(), response.headers[HttpHeaders.ContentLength]) + val transaction = awaitTransaction(store) + assertEquals(MOCKED_BODY, (transaction.capture.response!!.body as BodyPreview.Text).value) + } + + @Test + fun `throttled static response is delivered in full and captured`() = + runBlocking { + val (store, recorder) = captureStore() + var networkCalls = 0 + val networkEngine = + KtorMockEngine { + networkCalls++ + respond(content = NETWORK_BODY) + } + val throttle = + MockAction.Throttle( + bytesPerSecond = THROTTLE_BYTES_PER_SECOND, + next = MockAction.StaticResponse(statusCode = HttpStatusCode.OK.value, body = MOCKED_BODY), + ) + val client = + httpClient(networkEngine, DevConsoleMockEngine(listOf(staticOrderRule(action = throttle))), recorder) + + assertEquals(MOCKED_BODY, client.get(ORDER_URL).bodyAsText()) + assertEquals( + "true", + awaitTransaction(store) + .capture.request.metadata.tags["mocked"], + ) + assertEquals(0, networkCalls) + } + + private fun captureStore(): Pair { + val store = InMemoryNetworkTransactionStore(NetworkCursorCodec("1234567890123456".encodeToByteArray())) + val recorder = + NetworkTransactionRecorder( + factory = NetworkCaptureFactory(RedactionEngine(RedactionPolicy.recommended())), + store = store, + ) + return store to recorder + } + + private fun httpClient( + networkEngine: KtorMockEngine, + mockEngine: DevConsoleMockEngine, + recorder: NetworkTransactionRecorder? = null, + ): HttpClient = + HttpClient(networkEngine) { + recorder?.let { install(DevConsoleKtorClientPlugin) { this.recorder = it } } + install(DevConsoleKtorMocks) { this.mockEngine = mockEngine } + } + + private fun staticOrderRule( + host: String = "api.test", + action: MockAction = + MockAction.StaticResponse( + statusCode = HttpStatusCode.Created.value, + body = MOCKED_BODY, + headers = mapOf(HttpHeaders.ContentType to "application/json"), + ), + ): MockRule = + MockRule( + id = "orders", + priority = ORDER_RULE_PRIORITY, + method = "GET", + host = host, + path = ORDER_PATH, + action = action, + ) + + private fun awaitTransaction( + store: InMemoryNetworkTransactionStore, + maxWaitMs: Long = DEFAULT_AWAIT_MAX_WAIT_MS, + ): NetworkTransaction { + val deadline = System.currentTimeMillis() + maxWaitMs + while (System.currentTimeMillis() < deadline) { + val transactions = store.page(NetworkTransactionQuery()).transactions + if (transactions.isNotEmpty()) return transactions.single() + Thread.sleep(AWAIT_POLL_INTERVAL_MS) + } + return store.page(NetworkTransactionQuery()).transactions.single() + } +} diff --git a/sdk/network-okhttp/src/main/kotlin/io/devconsole/network/okhttp/DevConsoleOkHttpInterceptor.kt b/sdk/network-okhttp/src/main/kotlin/io/devconsole/network/okhttp/DevConsoleOkHttpInterceptor.kt index 18aacb8..0199ef1 100644 --- a/sdk/network-okhttp/src/main/kotlin/io/devconsole/network/okhttp/DevConsoleOkHttpInterceptor.kt +++ b/sdk/network-okhttp/src/main/kotlin/io/devconsole/network/okhttp/DevConsoleOkHttpInterceptor.kt @@ -1,5 +1,6 @@ package io.devconsole.network.okhttp +import io.devconsole.mocks.okhttp.MockFailureMarker import io.devconsole.network.NetworkCaptureContext import io.devconsole.network.NetworkRequestInput import io.devconsole.network.NetworkRequestMetadata @@ -64,8 +65,15 @@ class DevConsoleOkHttpInterceptor // failure is best-effort and must never replace or suppress it. runCatching { val failureMessage = error.message ?: error.javaClass.simpleName + val failureRequest = + error.suppressed.filterIsInstance().firstOrNull()?.let { mockError -> + request + .newBuilder() + .tag(NetworkCaptureContext::class.java, NetworkCaptureContext(mockError.tags)) + .build() + } ?: request recorder.record( - request.toInput(), + failureRequest.toInput(), NetworkResponseInput(statusCode = 0, error = failureMessage) .withMetadata( NetworkResponseMetadata( diff --git a/sdk/network/api/network.api b/sdk/network/api/network.api index 0f08c88..0e68b39 100644 --- a/sdk/network/api/network.api +++ b/sdk/network/api/network.api @@ -76,6 +76,8 @@ public final class io/devconsole/network/CapturedRequest { public final fun getUrl ()Lio/devconsole/network/NetworkUrl; public fun hashCode ()I public fun toString ()Ljava/lang/String; + public final fun withAttachmentId (Ljava/lang/String;)Lio/devconsole/network/CapturedRequest; + public final fun withMetadata (Lio/devconsole/network/CapturedRequestMetadata;)Lio/devconsole/network/CapturedRequest; } public final class io/devconsole/network/CapturedRequestMetadata { @@ -115,6 +117,8 @@ public final class io/devconsole/network/CapturedResponse { public final fun getStatusCode ()I public fun hashCode ()I public fun toString ()Ljava/lang/String; + public final fun withAttachmentId (Ljava/lang/String;)Lio/devconsole/network/CapturedResponse; + public final fun withMetadata (Lio/devconsole/network/CapturedResponseMetadata;)Lio/devconsole/network/CapturedResponse; } public final class io/devconsole/network/CapturedResponseMetadata { @@ -135,6 +139,39 @@ public final class io/devconsole/network/CapturedResponseMetadata { public fun toString ()Ljava/lang/String; } +public final class io/devconsole/network/EndpointLatency { + public fun (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;IIJJJJ)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 ()I + public final fun component5 ()I + public final fun component6 ()J + public final fun component7 ()J + public final fun component8 ()J + public final fun component9 ()J + public final fun copy (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;IIJJJJ)Lio/devconsole/network/EndpointLatency; + public static synthetic fun copy$default (Lio/devconsole/network/EndpointLatency;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;IIJJJJILjava/lang/Object;)Lio/devconsole/network/EndpointLatency; + public fun equals (Ljava/lang/Object;)Z + public final fun getCount ()I + public final fun getErrorCount ()I + public final fun getHost ()Ljava/lang/String; + public final fun getMaxMs ()J + public final fun getMethod ()Ljava/lang/String; + public final fun getP50Ms ()J + public final fun getP95Ms ()J + public final fun getP99Ms ()J + public final fun getPathTemplate ()Ljava/lang/String; + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + +public final class io/devconsole/network/EndpointLatencyStats { + public static final field INSTANCE Lio/devconsole/network/EndpointLatencyStats; + public final fun from (Ljava/util/List;I)Ljava/util/List; + public static synthetic fun from$default (Lio/devconsole/network/EndpointLatencyStats;Ljava/util/List;IILjava/lang/Object;)Ljava/util/List; +} + public abstract interface class io/devconsole/network/ExportSelection { } @@ -505,19 +542,22 @@ public final class io/devconsole/network/NetworkTransactionPage { public final class io/devconsole/network/NetworkTransactionQuery { public static final field Companion Lio/devconsole/network/NetworkTransactionQuery$Companion; public static final field DEFAULT_PAGE_LIMIT I + public static final field MAX_BODY_QUERY_LENGTH I public static final field MAX_PAGE_LIMIT I public fun ()V - public fun (ILjava/lang/String;Ljava/util/Set;Ljava/util/Set;Ljava/util/Set;Ljava/lang/String;)V - public synthetic fun (ILjava/lang/String;Ljava/util/Set;Ljava/util/Set;Ljava/util/Set;Ljava/lang/String;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public fun (ILjava/lang/String;Ljava/util/Set;Ljava/util/Set;Ljava/util/Set;Ljava/lang/String;Ljava/lang/String;)V + public synthetic fun (ILjava/lang/String;Ljava/util/Set;Ljava/util/Set;Ljava/util/Set;Ljava/lang/String;Ljava/lang/String;ILkotlin/jvm/internal/DefaultConstructorMarker;)V public final fun component1 ()I public final fun component2 ()Ljava/lang/String; public final fun component3 ()Ljava/util/Set; public final fun component4 ()Ljava/util/Set; public final fun component5 ()Ljava/util/Set; public final fun component6 ()Ljava/lang/String; - public final fun copy (ILjava/lang/String;Ljava/util/Set;Ljava/util/Set;Ljava/util/Set;Ljava/lang/String;)Lio/devconsole/network/NetworkTransactionQuery; - public static synthetic fun copy$default (Lio/devconsole/network/NetworkTransactionQuery;ILjava/lang/String;Ljava/util/Set;Ljava/util/Set;Ljava/util/Set;Ljava/lang/String;ILjava/lang/Object;)Lio/devconsole/network/NetworkTransactionQuery; + public final fun component7 ()Ljava/lang/String; + public final fun copy (ILjava/lang/String;Ljava/util/Set;Ljava/util/Set;Ljava/util/Set;Ljava/lang/String;Ljava/lang/String;)Lio/devconsole/network/NetworkTransactionQuery; + public static synthetic fun copy$default (Lio/devconsole/network/NetworkTransactionQuery;ILjava/lang/String;Ljava/util/Set;Ljava/util/Set;Ljava/util/Set;Ljava/lang/String;Ljava/lang/String;ILjava/lang/Object;)Lio/devconsole/network/NetworkTransactionQuery; public fun equals (Ljava/lang/Object;)Z + public final fun getBodyQuery ()Ljava/lang/String; public final fun getCorrelationId ()Ljava/lang/String; public final fun getCursor ()Ljava/lang/String; public final fun getFilters ()Lio/devconsole/network/NetworkTransactionFilters; diff --git a/sdk/network/src/main/kotlin/io/devconsole/network/EndpointLatencyStats.kt b/sdk/network/src/main/kotlin/io/devconsole/network/EndpointLatencyStats.kt new file mode 100644 index 0000000..c3f3ff3 --- /dev/null +++ b/sdk/network/src/main/kotlin/io/devconsole/network/EndpointLatencyStats.kt @@ -0,0 +1,124 @@ +/** + * @author Shakib + * @since 03/11/26 + */ +package io.devconsole.network + +import kotlin.math.ceil + +data class EndpointLatency( + val method: String, + val host: String, + val pathTemplate: String, + val count: Int, + val errorCount: Int, + val p50Ms: Long, + val p95Ms: Long, + val p99Ms: Long, + val maxMs: Long, +) + +/** Per-endpoint latency percentiles over completed transactions, with numeric/UUID/opaque-id path segments folded. */ +object EndpointLatencyStats { + private const val DEFAULT_LIMIT = 100 + private const val HTTP_ERROR_STATUS = 400 + private const val P50 = 0.50 + private const val P95 = 0.95 + private const val P99 = 0.99 + private const val OPAQUE_ID_MIN_LENGTH = 16 + + private val UUID_REGEX = + Regex( + "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$", + ) + + fun from( + transactions: List, + limit: Int = DEFAULT_LIMIT, + ): List = + if (limit <= 0) { + emptyList() + } else { + transactions + .filter { it.completedAtEpochMs != null } + .groupBy(::endpointKey) + .map { (key, group) -> latencyOf(key, group) } + .sortedWith( + compareByDescending { it.p95Ms } + .thenByDescending { it.count } + .thenBy { it.host } + .thenBy { it.pathTemplate } + .thenBy { it.method }, + ).take(limit) + } + + private fun endpointKey(transaction: NetworkTransaction): EndpointKey = + EndpointKey( + method = + transaction.capture.request.method + .uppercase(), + host = + transaction.capture.request.url.host + .lowercase(), + pathTemplate = templatePath(transaction.capture.request.url.path), + ) + + private fun latencyOf( + key: EndpointKey, + group: List, + ): EndpointLatency { + val durations = + group + .map { tx -> (checkNotNull(tx.completedAtEpochMs) - tx.startedAtEpochMs).coerceAtLeast(0L) } + .sorted() + val errors = + group.count { tx -> + val response = tx.capture.response + response == null || response.error != null || response.statusCode >= HTTP_ERROR_STATUS + } + return EndpointLatency( + method = key.method, + host = key.host, + pathTemplate = key.pathTemplate, + count = group.size, + errorCount = errors, + p50Ms = nearestRank(durations, P50), + p95Ms = nearestRank(durations, P95), + p99Ms = nearestRank(durations, P99), + maxMs = durations.last(), + ) + } + + internal fun templatePath(rawPath: String): String { + val path = rawPath.ifBlank { "/" } + val normalized = if (path.startsWith('/')) path else "/$path" + return normalized + .split('/') + .mapIndexed { index, segment -> + if (index > 0 && segment.isNotEmpty() && isDynamicSegment(segment)) "{id}" else segment + }.joinToString("/") + } + + private fun isDynamicSegment(segment: String): Boolean = + segment.all(Char::isDigit) || UUID_REGEX.matches(segment) || isOpaqueId(segment) + + private fun isOpaqueId(segment: String): Boolean = + segment.length >= OPAQUE_ID_MIN_LENGTH && + segment.all { it in '0'..'9' || it in 'a'..'z' || it in 'A'..'Z' } && + segment.any(Char::isDigit) + + private fun nearestRank( + sortedDurations: List, + quantile: Double, + ): Long { + val n = sortedDurations.size + val index = (ceil(quantile * n).toInt() - 1).coerceIn(0, n - 1) + return sortedDurations[index] + } + + private data class EndpointKey( + val method: String, + val host: String, + val pathTemplate: String, + ) +} diff --git a/sdk/network/src/main/kotlin/io/devconsole/network/ExportSelection.kt b/sdk/network/src/main/kotlin/io/devconsole/network/ExportSelection.kt index 141c740..7602210 100644 --- a/sdk/network/src/main/kotlin/io/devconsole/network/ExportSelection.kt +++ b/sdk/network/src/main/kotlin/io/devconsole/network/ExportSelection.kt @@ -61,12 +61,38 @@ fun NetworkTransactionStore.resolveExportSelection( baseQuery: NetworkTransactionQuery = NetworkTransactionQuery(limit = NetworkTransactionQuery.MAX_PAGE_LIMIT), ): List? = when (selection) { - ExportSelection.All -> page(baseQuery).let { if (it.invalidCursor) null else it.transactions } + ExportSelection.All -> pageAll(baseQuery) is ExportSelection.Ids -> selection.ids.mapNotNull(::find) is ExportSelection.TimeRange -> - page( + pageAll( baseQuery.withFilters( baseQuery.filters.copy(fromEpochMs = selection.fromEpochMs, toEpochMs = selection.toEpochMs), ), - ).let { if (it.invalidCursor) null else it.transactions } + ) } + +private fun NetworkTransactionStore.pageAll(query: NetworkTransactionQuery): List? { + val results = mutableListOf() + var cursor: String? = query.cursor + var hasMore = true + while (hasMore) { + val pageQuery = + NetworkTransactionQuery( + limit = query.limit, + cursor = cursor, + methods = query.methods, + hosts = query.hosts, + statuses = query.statuses, + correlationId = query.correlationId, + ).withFilters(query.filters) + val page = page(pageQuery) + // An invalid cursor, or a page claiming more without a cursor to reach it, means the + // selection cannot be exported completely -- fail rather than return a silent partial. + val brokenPaging = page.invalidCursor || (page.hasMore && page.nextCursor == null) + if (brokenPaging) return null + results += page.transactions + hasMore = page.hasMore + cursor = page.nextCursor + } + return results +} diff --git a/sdk/network/src/main/kotlin/io/devconsole/network/NetworkCapture.kt b/sdk/network/src/main/kotlin/io/devconsole/network/NetworkCapture.kt index c72974a..b211c16 100644 --- a/sdk/network/src/main/kotlin/io/devconsole/network/NetworkCapture.kt +++ b/sdk/network/src/main/kotlin/io/devconsole/network/NetworkCapture.kt @@ -124,6 +124,21 @@ data class CapturedRequest( /** ID of the bounded, redacted body attachment, when one was persisted. */ var attachmentId: String? = null internal set + + /** Copy carrying persisted [metadata], e.g. when decoding retained history. */ + fun withMetadata(metadata: CapturedRequestMetadata): CapturedRequest = restoredCopy(metadata, attachmentId) + + /** Copy carrying a persisted [attachmentId], e.g. when decoding retained history. */ + fun withAttachmentId(attachmentId: String?): CapturedRequest = restoredCopy(metadata, attachmentId) + + private fun restoredCopy( + metadata: CapturedRequestMetadata, + attachmentId: String?, + ): CapturedRequest = + copy().also { + it.metadata = metadata + it.attachmentId = attachmentId + } } data class CapturedRequestMetadata( @@ -147,6 +162,21 @@ data class CapturedResponse( /** ID of the bounded, redacted body attachment, when one was persisted. */ var attachmentId: String? = null internal set + + /** Copy carrying persisted [metadata], e.g. when decoding retained history. */ + fun withMetadata(metadata: CapturedResponseMetadata): CapturedResponse = restoredCopy(metadata, attachmentId) + + /** Copy carrying a persisted [attachmentId], e.g. when decoding retained history. */ + fun withAttachmentId(attachmentId: String?): CapturedResponse = restoredCopy(metadata, attachmentId) + + private fun restoredCopy( + metadata: CapturedResponseMetadata, + attachmentId: String?, + ): CapturedResponse = + copy().also { + it.metadata = metadata + it.attachmentId = attachmentId + } } data class CapturedResponseMetadata( diff --git a/sdk/network/src/main/kotlin/io/devconsole/network/NetworkExport.kt b/sdk/network/src/main/kotlin/io/devconsole/network/NetworkExport.kt index 619da17..9f19a34 100644 --- a/sdk/network/src/main/kotlin/io/devconsole/network/NetworkExport.kt +++ b/sdk/network/src/main/kotlin/io/devconsole/network/NetworkExport.kt @@ -233,7 +233,15 @@ object NetworkExport { append(",\"send\":").append(timings.sendMs ?: -1) append(",\"wait\":").append(timings.waitMs ?: -1) append(",\"receive\":").append(timings.receiveMs ?: -1) - append("}}") + append('}') + val truncatedBodies = + listOfNotNull(requestBody as? BodyPreview.Text, responseBody as? BodyPreview.Text) + .count(BodyPreview.Text::truncated) + if (truncatedBodies > 0) { + val comment = "$truncatedBodies captured body preview(s) were truncated at capture" + append(",\"comment\":").append(comment.jsonQuoted()) + } + append('}') } /** Best-known response-body byte size: the host-declared length, else the captured length. */ diff --git a/sdk/network/src/main/kotlin/io/devconsole/network/NetworkTransactionStore.kt b/sdk/network/src/main/kotlin/io/devconsole/network/NetworkTransactionStore.kt index 593b6b1..9994799 100644 --- a/sdk/network/src/main/kotlin/io/devconsole/network/NetworkTransactionStore.kt +++ b/sdk/network/src/main/kotlin/io/devconsole/network/NetworkTransactionStore.kt @@ -28,24 +28,29 @@ data class NetworkTransactionQuery( val hosts: Set = emptySet(), val statuses: Set = emptySet(), val correlationId: String? = null, + val bodyQuery: String? = null, ) { var filters: NetworkTransactionFilters = NetworkTransactionFilters() private set fun withFilters(filters: NetworkTransactionFilters): NetworkTransactionQuery = copy().also { it.filters = filters } + internal fun normalizedBodyQuery(): String? = bodyQuery?.takeIf(String::isNotBlank)?.take(MAX_BODY_QUERY_LENGTH) + internal fun scope(): String = listOf( methods.map(String::uppercase).sorted().joinToString(","), hosts.map(String::lowercase).sorted().joinToString(","), statuses.sorted().joinToString(","), correlationId.orEmpty(), + normalizedBodyQuery()?.lowercase().orEmpty(), filters.scope(), ).joinToString("|") companion object { const val DEFAULT_PAGE_LIMIT = 100 const val MAX_PAGE_LIMIT = 500 + const val MAX_BODY_QUERY_LENGTH = 256 } } @@ -163,7 +168,8 @@ class InMemoryNetworkTransactionStore( override fun page(query: NetworkTransactionQuery): NetworkTransactionPage = synchronized(lock) { if (query.limit !in - 1..NetworkTransactionQuery.MAX_PAGE_LIMIT + 1..NetworkTransactionQuery.MAX_PAGE_LIMIT || + (query.bodyQuery != null && query.bodyQuery.length > NetworkTransactionQuery.MAX_BODY_QUERY_LENGTH) ) { return@synchronized NetworkTransactionPage(emptyList(), null, false, true) } @@ -174,6 +180,7 @@ class InMemoryNetworkTransactionStore( cursorCodec.decode(query.cursor, query.scope()) ?: return@synchronized NetworkTransactionPage(emptyList(), null, false, true) } + val bodyNeedle = query.normalizedBodyQuery() val matching = transactions .asSequence() @@ -190,6 +197,8 @@ class InMemoryNetworkTransactionStore( transaction.capture.response?.statusCode in query.statuses }.filter { transaction -> query.correlationId == null || transaction.capture.request.correlationId == query.correlationId + }.filter { transaction -> + bodyNeedle == null || transaction.matchesBody(bodyNeedle) }.filter { transaction -> transaction.matches(query.filters) } .sortedWith( compareByDescending { it.startedAtEpochMs }.thenByDescending { it.id }, @@ -253,6 +262,13 @@ private fun NetworkTransaction.matches(filters: NetworkTransactionFilters): Bool return true } +private fun NetworkTransaction.matchesBody(needle: String): Boolean = + capture.request.body.containsText(needle) || capture.response?.body.containsText(needle) + +/** Only text previews are searched; binary and omitted bodies never match. */ +private fun BodyPreview?.containsText(needle: String): Boolean = + (this as? BodyPreview.Text)?.value?.contains(needle, ignoreCase = true) == true + private fun NetworkTransaction.searchableText(): String = buildString { append(capture.request.method).append(' ') diff --git a/sdk/network/src/test/kotlin/io/devconsole/network/EndpointLatencyStatsTest.kt b/sdk/network/src/test/kotlin/io/devconsole/network/EndpointLatencyStatsTest.kt new file mode 100644 index 0000000..4ec8bd4 --- /dev/null +++ b/sdk/network/src/test/kotlin/io/devconsole/network/EndpointLatencyStatsTest.kt @@ -0,0 +1,136 @@ +/** + * @author Shakib + * @since 03/11/26 + */ +package io.devconsole.network + +import io.devconsole.security.RedactionEngine +import io.devconsole.security.RedactionPolicy +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +class EndpointLatencyStatsTest { + private val factory = NetworkCaptureFactory(RedactionEngine(RedactionPolicy.default())) + + @Test + fun `replaces numeric uuid and long alphanumeric digit segments with id placeholder`() { + val transactions = + listOf( + tx("1", "GET", "https://api.test/v1/orders/42198/items", 100, 120, 200), + tx( + "2", + "GET", + "https://api.test/v1/orders/550e8400-e29b-41d4-a716-446655440000/items", + 100, + 140, + 200, + ), + tx("3", "GET", "https://api.test/v1/orders/abc123def456ghi7/items", 100, 160, 200), + tx("4", "GET", "https://api.test/v1/orders/abcdefghijklmnop/items", 100, 110, 200), + ) + + val stats = EndpointLatencyStats.from(transactions) + + assertEquals(2, stats.size) + val templated = stats.first { it.pathTemplate == "/v1/orders/{id}/items" } + assertEquals(3, templated.count) + assertEquals(40L, templated.p50Ms) + assertEquals(60L, templated.p95Ms) + assertEquals(60L, templated.maxMs) + + val literalAlpha = stats.first { it.pathTemplate == "/v1/orders/abcdefghijklmnop/items" } + assertEquals(1, literalAlpha.count) + } + + @Test + fun `computes nearest-rank percentiles and ignores incomplete transactions`() { + val completed = + (1..20).map { index -> + tx( + id = "tx-$index", + method = "GET", + url = "https://api.test/v1/feed", + startedAt = 1000L, + completedAt = 1000L + (index * 10L), + status = 200, + ) + } + val pending = + tx( + id = "pending", + method = "GET", + url = "https://api.test/v1/feed", + startedAt = 1000L, + completedAt = null, + status = null, + ) + + val stats = EndpointLatencyStats.from(completed + pending) + + assertEquals(1, stats.size) + val entry = stats.single() + assertEquals(20, entry.count) + assertEquals(0, entry.errorCount) + assertEquals(100L, entry.p50Ms) + assertEquals(190L, entry.p95Ms) + assertEquals(200L, entry.p99Ms) + assertEquals(200L, entry.maxMs) + } + + @Test + fun `counts null response response error and status 400 or above as errors`() { + val transactions = + listOf( + tx("ok", "POST", "https://api.test/v1/pay", 10, 20, 200), + tx("bad-req", "POST", "https://api.test/v1/pay", 10, 30, 400), + tx("server-err", "POST", "https://api.test/v1/pay", 10, 40, 503), + tx("io-err", "POST", "https://api.test/v1/pay", 10, 50, 200, error = "reset"), + tx("no-resp", "POST", "https://api.test/v1/pay", 10, 60, null), + ) + + val entry = EndpointLatencyStats.from(transactions).single() + + assertEquals(5, entry.count) + assertEquals(4, entry.errorCount) + } + + @Test + fun `sorts by p95 descending then count descending and caps at limit`() { + val transactions = + listOf( + tx("a1", "GET", "https://api.test/fast-many", 0, 10, 200), + tx("a2", "GET", "https://api.test/fast-many", 0, 10, 200), + tx("b1", "GET", "https://api.test/fast-one", 0, 10, 200), + tx("c1", "GET", "https://api.test/slow", 0, 90, 200), + ) + + val all = EndpointLatencyStats.from(transactions) + assertEquals(listOf("/slow", "/fast-many", "/fast-one"), all.map { it.pathTemplate }) + + val limited = EndpointLatencyStats.from(transactions, limit = 2) + assertEquals(listOf("/slow", "/fast-many"), limited.map { it.pathTemplate }) + assertTrue(EndpointLatencyStats.from(transactions, limit = 0).isEmpty()) + } + + @Suppress("LongParameterList") // Positional fixture rows keep each test's table readable. + private fun tx( + id: String, + method: String, + url: String, + startedAt: Long, + completedAt: Long?, + status: Int?, + error: String? = null, + ): NetworkTransaction = + NetworkTransaction( + id = id, + startedAtEpochMs = startedAt, + completedAtEpochMs = completedAt, + capture = + factory.capture( + NetworkRequestInput(method, url), + status?.let { NetworkResponseInput(it, error = error) }, + ), + ) +} diff --git a/sdk/network/src/test/kotlin/io/devconsole/network/ExportSelectionTest.kt b/sdk/network/src/test/kotlin/io/devconsole/network/ExportSelectionTest.kt index f155a13..089065e 100644 --- a/sdk/network/src/test/kotlin/io/devconsole/network/ExportSelectionTest.kt +++ b/sdk/network/src/test/kotlin/io/devconsole/network/ExportSelectionTest.kt @@ -41,6 +41,16 @@ class ExportSelectionTest { assertEquals(setOf("a", "b"), resolved!!.map { it.id }.toSet()) } + @Test + fun `All pages beyond the first 500 transactions`() { + val store = store() + repeat(650) { index -> store.record(transaction("row-$index", index.toLong())) } + + val resolved = store.resolveExportSelection(ExportSelection.All) + + assertEquals(650, resolved!!.size) + } + @Test fun `Ids resolves exactly the named transactions and silently drops unknown ids`() { val store = store() diff --git a/sdk/network/src/test/kotlin/io/devconsole/network/InMemoryNetworkTransactionStoreTest.kt b/sdk/network/src/test/kotlin/io/devconsole/network/InMemoryNetworkTransactionStoreTest.kt index 02d486a..ab0fc09 100644 --- a/sdk/network/src/test/kotlin/io/devconsole/network/InMemoryNetworkTransactionStoreTest.kt +++ b/sdk/network/src/test/kotlin/io/devconsole/network/InMemoryNetworkTransactionStoreTest.kt @@ -221,6 +221,94 @@ class InMemoryNetworkTransactionStoreTest { assertEquals(listOf("after-clear"), store.page(NetworkTransactionQuery(limit = 10)).transactions.map { it.id }) } + @Suppress("LongMethod") // Three fixtures plus paging and scope assertions read best as one scenario. + @Test + fun `bodyQuery matches request and response text case-insensitively and ignores binary`() { + val store = InMemoryNetworkTransactionStore(NetworkCursorCodec("network-cursor-key".encodeToByteArray())) + val factory = NetworkCaptureFactory(RedactionEngine(RedactionPolicy.default())) + + store.record( + NetworkTransaction( + id = "req-match", + startedAtEpochMs = 100, + completedAtEpochMs = 110, + capture = + factory.capture( + NetworkRequestInput( + "POST", + "https://api.test/orders", + body = "{\"item\":\"MatchNeedle-Req\"}".encodeToByteArray(), + contentType = "application/json", + ), + NetworkResponseInput(200), + ), + ), + ) + store.record( + NetworkTransaction( + id = "res-match", + startedAtEpochMs = 200, + completedAtEpochMs = 210, + capture = + factory.capture( + NetworkRequestInput("GET", "https://api.test/orders/1"), + NetworkResponseInput( + 200, + body = "{\"status\":\"MATCHNEEDLE-RES\"}".encodeToByteArray(), + contentType = "application/json", + ), + ), + ), + ) + store.record( + NetworkTransaction( + id = "binary-ignored", + startedAtEpochMs = 300, + completedAtEpochMs = 310, + capture = + factory.capture( + NetworkRequestInput( + "POST", + "https://api.test/upload", + body = "matchneedle-binary".encodeToByteArray(), + contentType = "application/octet-stream", + ), + NetworkResponseInput( + 200, + body = "matchneedle-binary".encodeToByteArray(), + contentType = "image/png", + ), + ), + ), + ) + + val matched = store.page(NetworkTransactionQuery(limit = 10, bodyQuery = "matchneedle")) + assertEquals(listOf("res-match", "req-match"), matched.transactions.map { it.id }) + + val pagedFirst = store.page(NetworkTransactionQuery(limit = 1, bodyQuery = "matchneedle")) + assertEquals(listOf("res-match"), pagedFirst.transactions.map { it.id }) + assertTrue(pagedFirst.hasMore) + + val pagedSecond = + store.page( + NetworkTransactionQuery(limit = 1, cursor = pagedFirst.nextCursor, bodyQuery = "matchneedle"), + ) + assertEquals(listOf("req-match"), pagedSecond.transactions.map { it.id }) + assertNull(pagedSecond.nextCursor) + + val wrongScope = + store.page( + NetworkTransactionQuery(limit = 1, cursor = pagedFirst.nextCursor, bodyQuery = "different"), + ) + assertTrue(wrongScope.invalidCursor) + + val blankMatchesAll = store.page(NetworkTransactionQuery(limit = 10, bodyQuery = " ")) + assertEquals(3, blankMatchesAll.transactions.size) + + val tooLongRejected = store.page(NetworkTransactionQuery(limit = 10, bodyQuery = "a".repeat(257))) + assertTrue(tooLongRejected.invalidCursor) + } + private fun transaction( id: String, startedAt: Long, diff --git a/sdk/network/src/test/kotlin/io/devconsole/network/NetworkExportTest.kt b/sdk/network/src/test/kotlin/io/devconsole/network/NetworkExportTest.kt index 55b0eb1..cdae377 100644 --- a/sdk/network/src/test/kotlin/io/devconsole/network/NetworkExportTest.kt +++ b/sdk/network/src/test/kotlin/io/devconsole/network/NetworkExportTest.kt @@ -8,6 +8,22 @@ import org.junit.Assert.assertTrue import org.junit.Test class NetworkExportTest { + @Test + fun `HAR preserves request body previews beyond 64 KiB`() { + val marker = "TAIL_MARKER" + val body = "x".repeat(100 * 1024) + marker + val capture = + NetworkCaptureFactory(RedactionEngine(RedactionPolicy.recommended())).capture( + NetworkRequestInput("POST", "https://example.test/upload", body = body.encodeToByteArray()), + NetworkResponseInput(statusCode = 200), + ) + + val har = NetworkExport.toHarTransactions(listOf(NetworkTransaction("large", 1, 2, capture))) + + assertTrue(har.contains(marker)) + har.assertIsValidJson() + } + @Test fun `curl and har use only redacted capture fields`() { val capture = diff --git a/sdk/noop/api/noop.api b/sdk/noop/api/noop.api index 0fa96f0..0cc85f8 100644 --- a/sdk/noop/api/noop.api +++ b/sdk/noop/api/noop.api @@ -5,17 +5,24 @@ public final class io/devconsole/DevConsole { public static final fun captureScreenshotAsync (Lio/devconsole/DevConsoleCallback;)V public static final fun createIntent (Landroid/content/Context;)Landroid/content/Intent; public static final fun endpoint ()Lio/devconsole/api/BrowserEndpoint; + public static final fun exportSession (Lkotlin/coroutines/Continuation;)Ljava/lang/Object; public static final fun featureFlagStringValue (Ljava/lang/String;)Ljava/lang/String; public static final fun featureFlagValue (Ljava/lang/String;)Z public static final fun initialize (Landroid/app/Application;Lio/devconsole/api/DevConsoleConfig;)Lio/devconsole/api/InitResult; public static synthetic fun initialize$default (Landroid/app/Application;Lio/devconsole/api/DevConsoleConfig;ILjava/lang/Object;)Lio/devconsole/api/InitResult; + public static final fun isCapturePaused ()Z public static final fun logRecorder ()Lio/devconsole/logs/LogRecorder; public static final fun mockEngine ()Lio/devconsole/mocks/MockEngine; 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 purgeCapturedData (Lkotlin/coroutines/Continuation;)Ljava/lang/Object; 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 remoteConfigOverride (Ljava/lang/String;)Ljava/lang/String; + public static final fun remoteConfigOverride (Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; + public static synthetic fun remoteConfigOverride$default (Ljava/lang/String;Ljava/lang/String;ILjava/lang/Object;)Ljava/lang/String; + public static final fun setCapturePaused (Z)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; public static synthetic fun startBrowser$default (Lio/devconsole/api/StartRequest;Lkotlin/coroutines/Continuation;ILjava/lang/Object;)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 523fa18..ab3ded1 100644 --- a/sdk/noop/src/main/kotlin/io/devconsole/PlatformFacadeProvider.kt +++ b/sdk/noop/src/main/kotlin/io/devconsole/PlatformFacadeProvider.kt @@ -10,7 +10,9 @@ import io.devconsole.api.DevConsoleFacadeProvider import io.devconsole.api.DevConsoleState import io.devconsole.api.InitResult import io.devconsole.api.InspectorOpenResult +import io.devconsole.api.PurgeResult import io.devconsole.api.ScreenshotResult +import io.devconsole.api.SessionExportResult import io.devconsole.api.StartRequest import io.devconsole.api.StartResult import io.devconsole.api.StopReason @@ -92,6 +94,11 @@ internal class PlatformFacadeProvider : DevConsoleFacadeProvider { override fun registerRemoteConfigProvider(provider: RemoteConfigProvider): Boolean = false + override fun remoteConfigOverride( + key: String, + providerId: String?, + ): String? = null + override fun endpoint(): BrowserEndpoint? = null override fun accessInfo(): AccessInfo? = null @@ -110,6 +117,14 @@ internal class PlatformFacadeProvider : DevConsoleFacadeProvider { override fun featureFlagStringValue(key: String): String = declaredDefault(key) + override fun setCapturePaused(paused: Boolean): Boolean = false + + override fun isCapturePaused(): Boolean = false + + override suspend fun purgeCapturedData(): PurgeResult = PurgeResult.NOTHING + + override suspend fun exportSession(): SessionExportResult = SessionExportResult.Disabled + private fun declaredDefault(key: String): String = flags.firstOrNull { it.key == key }?.defaultValue.orEmpty() } diff --git a/sdk/noop/src/test/kotlin/io/devconsole/NoopFacadeProviderContractTest.kt b/sdk/noop/src/test/kotlin/io/devconsole/NoopFacadeProviderContractTest.kt index f693690..114925f 100644 --- a/sdk/noop/src/test/kotlin/io/devconsole/NoopFacadeProviderContractTest.kt +++ b/sdk/noop/src/test/kotlin/io/devconsole/NoopFacadeProviderContractTest.kt @@ -5,6 +5,12 @@ package io.devconsole import io.devconsole.api.DevConsoleFacadeProvider +import io.devconsole.api.PurgeResult +import io.devconsole.api.SessionExportResult +import kotlinx.coroutines.runBlocking +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull import org.junit.Assert.assertTrue import org.junit.Test import java.lang.reflect.Method @@ -54,4 +60,17 @@ class NoopFacadeProviderContractTest { interfaceClass.methods.filter { it.declaringClass == interfaceClass } private fun Method.signatureLabel(): String = "$name(${parameterTypes.joinToString(", ") { it.simpleName }})" + + @Test + fun `noop PlatformFacadeProvider returns documented disabled defaults for runtime control and export APIs`() { + val provider = PlatformFacadeProvider() + + assertFalse(provider.isCapturePaused()) + assertFalse(provider.setCapturePaused(true)) + assertFalse(provider.isCapturePaused()) + assertEquals(PurgeResult.NOTHING, runBlocking { provider.purgeCapturedData() }) + assertEquals(SessionExportResult.Disabled, runBlocking { provider.exportSession() }) + assertNull(provider.remoteConfigOverride("flag", null)) + assertNull(provider.remoteConfigOverride("flag", "firebase")) + } } diff --git a/sdk/noop/src/test/kotlin/io/devconsole/OkHttpAdapterFullNoopParityTest.kt b/sdk/noop/src/test/kotlin/io/devconsole/OkHttpAdapterFullNoopParityTest.kt index 1a1c71e..8699ed4 100644 --- a/sdk/noop/src/test/kotlin/io/devconsole/OkHttpAdapterFullNoopParityTest.kt +++ b/sdk/noop/src/test/kotlin/io/devconsole/OkHttpAdapterFullNoopParityTest.kt @@ -580,17 +580,19 @@ class OkHttpAdapterFullNoopParityTest { val parts = mutableListOf() var depth = 0 val current = StringBuilder() - for (character in text) { - when (character) { - '(', '{', '[' -> { + for ((index, character) in text.withIndex()) { + // Generic brackets count too (`Map`), but not the `>` of a lambda's `->`. + val isArrow = character == '>' && index > 0 && text[index - 1] == '-' + when { + character in "({[<" -> { depth++ current.append(character) } - ')', '}', ']' -> { + character in ")}]>" && !isArrow -> { depth-- current.append(character) } - delimiter -> + character == delimiter -> if (depth == 0) { parts.add(current.toString()) current.clear() diff --git a/sdk/remote-config/api/remote-config.api b/sdk/remote-config/api/remote-config.api index 730f608..24f231e 100644 --- a/sdk/remote-config/api/remote-config.api +++ b/sdk/remote-config/api/remote-config.api @@ -1,15 +1,36 @@ +public final class io/devconsole/remoteconfig/InMemoryRemoteConfigOverrideStore : io/devconsole/remoteconfig/RemoteConfigOverrideStore { + public static final field Companion Lio/devconsole/remoteconfig/InMemoryRemoteConfigOverrideStore$Companion; + public static final field MAX_KEY_LENGTH I + public fun ()V + public fun (Ljava/util/Map;)V + public synthetic fun (Ljava/util/Map;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public fun addListener (Lio/devconsole/remoteconfig/RemoteConfigOverrideListener;)V + public fun clearAll ()V + public fun clearOverride (Ljava/lang/String;Ljava/lang/String;)V + public fun overrides ()Ljava/util/Map; + public fun removeListener (Lio/devconsole/remoteconfig/RemoteConfigOverrideListener;)V + public fun setOverride (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V +} + +public final class io/devconsole/remoteconfig/InMemoryRemoteConfigOverrideStore$Companion { +} + 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 fun (Ljava/lang/String;Ljava/lang/String;Lio/devconsole/remoteconfig/RemoteConfigSource;ZZLjava/lang/String;Lio/devconsole/remoteconfig/RemoteConfigSource;)V + public synthetic fun (Ljava/lang/String;Ljava/lang/String;Lio/devconsole/remoteconfig/RemoteConfigSource;ZZLjava/lang/String;Lio/devconsole/remoteconfig/RemoteConfigSource;ILkotlin/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 final fun component6 ()Ljava/lang/String; + public final fun component7 ()Lio/devconsole/remoteconfig/RemoteConfigSource; + public final fun copy (Ljava/lang/String;Ljava/lang/String;Lio/devconsole/remoteconfig/RemoteConfigSource;ZZLjava/lang/String;Lio/devconsole/remoteconfig/RemoteConfigSource;)Lio/devconsole/remoteconfig/RemoteConfigEntry; + public static synthetic fun copy$default (Lio/devconsole/remoteconfig/RemoteConfigEntry;Ljava/lang/String;Ljava/lang/String;Lio/devconsole/remoteconfig/RemoteConfigSource;ZZLjava/lang/String;Lio/devconsole/remoteconfig/RemoteConfigSource;ILjava/lang/Object;)Lio/devconsole/remoteconfig/RemoteConfigEntry; public fun equals (Ljava/lang/Object;)Z public final fun getKey ()Ljava/lang/String; + public final fun getProviderSource ()Lio/devconsole/remoteconfig/RemoteConfigSource; + public final fun getProviderValue ()Ljava/lang/String; public final fun getRedacted ()Z public final fun getSource ()Lio/devconsole/remoteconfig/RemoteConfigSource; public final fun getTruncated ()Z @@ -51,6 +72,19 @@ public final class io/devconsole/remoteconfig/RemoteConfigFetchStatus : java/lan public static fun values ()[Lio/devconsole/remoteconfig/RemoteConfigFetchStatus; } +public abstract interface class io/devconsole/remoteconfig/RemoteConfigOverrideListener { + public abstract fun onOverridesChanged ()V +} + +public abstract interface class io/devconsole/remoteconfig/RemoteConfigOverrideStore { + public abstract fun addListener (Lio/devconsole/remoteconfig/RemoteConfigOverrideListener;)V + public abstract fun clearAll ()V + public abstract fun clearOverride (Ljava/lang/String;Ljava/lang/String;)V + public abstract fun overrides ()Ljava/util/Map; + public abstract fun removeListener (Lio/devconsole/remoteconfig/RemoteConfigOverrideListener;)V + public abstract fun setOverride (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V +} + public abstract interface class io/devconsole/remoteconfig/RemoteConfigProvider { public abstract fun getId ()Ljava/lang/String; public abstract fun snapshot ()Lio/devconsole/remoteconfig/RemoteConfigSnapshot; @@ -60,7 +94,11 @@ 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 fun (Lio/devconsole/remoteconfig/RemoteConfigOverrideStore;)V + public synthetic fun (Lio/devconsole/remoteconfig/RemoteConfigOverrideStore;ILkotlin/jvm/internal/DefaultConstructorMarker;)V public final fun clear ()V + public final fun getOverrides ()Lio/devconsole/remoteconfig/RemoteConfigOverrideStore; + public final fun overrideValue (Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; 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/RemoteConfig.kt b/sdk/remote-config/src/main/kotlin/io/devconsole/remoteconfig/RemoteConfig.kt index a6d5a46..0355dc9 100644 --- a/sdk/remote-config/src/main/kotlin/io/devconsole/remoteconfig/RemoteConfig.kt +++ b/sdk/remote-config/src/main/kotlin/io/devconsole/remoteconfig/RemoteConfig.kt @@ -41,15 +41,35 @@ enum class RemoteConfigSource( * [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. + * + * When a local override is active, [value] and [source] describe the override while [providerValue] + * and [providerSource] retain what the provider itself resolved. Keeping both is what lets a + * surface show "overridden: remote `false`" instead of presenting the override as if the server + * had published it -- the difference is exactly what a developer debugging config needs to see. */ 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. */ + /** + * True when the provider's value was withheld by redaction, so a surface can badge it rather + * than show it. With an override active it describes [providerValue], not the override itself. + */ val redacted: Boolean = false, - /** True when [value] was cut to [RemoteConfigRegistry.MAX_VALUE_LENGTH]. */ + /** + * True when the provider's value was cut to [RemoteConfigRegistry.MAX_VALUE_LENGTH]. With an + * override active it describes [providerValue], not the override itself, which is never cut. + */ val truncated: Boolean = false, + /** + * The provider's own value when an override replaced it, already capped to + * [RemoteConfigRegistry.MAX_VALUE_LENGTH]; null when no override is active. It is kept even + * though it is not served, so clearing the override visibly restores something rather than + * appearing to invent a value. + */ + val providerValue: String? = null, + /** The source the provider resolved [providerValue] from; null when no override is active. */ + val providerSource: RemoteConfigSource? = null, ) /** Outcome of the provider's most recent fetch attempt. */ diff --git a/sdk/remote-config/src/main/kotlin/io/devconsole/remoteconfig/RemoteConfigOverrides.kt b/sdk/remote-config/src/main/kotlin/io/devconsole/remoteconfig/RemoteConfigOverrides.kt new file mode 100644 index 0000000..3e3e7b0 --- /dev/null +++ b/sdk/remote-config/src/main/kotlin/io/devconsole/remoteconfig/RemoteConfigOverrides.kt @@ -0,0 +1,192 @@ +/** + * @author Shakib + * @since 04/11/26 + */ +package io.devconsole.remoteconfig + +/** + * Told whenever a local override is added, replaced, or removed. + * + * A surface renders the value it read a moment ago, so without this signal it would keep showing a + * stale value until something unrelated caused a refresh. Notification is deliberately a plain + * callback rather than a flow: the store is read from the Ktor thread and the inspector's + * dispatcher, and both already know how to schedule their own redraw. + */ +fun interface RemoteConfigOverrideListener { + fun onOverridesChanged() +} + +/** + * Holds the overrides a developer applies locally while debugging, kept apart from anything a + * Remote Config provider resolved. + * + * This is host-owned state rather than a field on [RemoteConfigRegistry] because an override is + * user intent that outlives a session, whereas provider registrations are torn down and rebuilt + * per session. Keeping the two separate is what lets a session end without discarding the values + * being debugged. + */ +interface RemoteConfigOverrideStore { + /** + * Every override, keyed provider id then config key. + * + * A copy is returned on purpose: the readers run on the Ktor thread and the inspector's + * dispatcher while a developer edits on the main thread, so handing out the live map would + * expose a view that can change mid-iteration. + */ + fun overrides(): Map> + + /** + * Applies [value] for [key] on [providerId], replacing any previous override for that pair. + * + * Throws [IllegalArgumentException] for a blank provider id or key, a key longer than + * [InMemoryRemoteConfigOverrideStore.MAX_KEY_LENGTH], or a value longer than + * [RemoteConfigRegistry.MAX_VALUE_LENGTH] -- the same cap the registry applies to provider + * values, so an override cannot smuggle in a payload the rest of the SDK refuses to carry. + */ + fun setOverride( + providerId: String, + key: String, + value: String, + ) + + /** Removes the override for [key] on [providerId]; a pair that was never overridden is a no-op. */ + fun clearOverride( + providerId: String, + key: String, + ) + + /** Removes every override for every provider. */ + fun clearAll() + + /** Registers [listener] for later changes; adding the same listener twice is a no-op. */ + fun addListener(listener: RemoteConfigOverrideListener) + + /** Unregisters [listener]; one that was never added is a no-op. */ + fun removeListener(listener: RemoteConfigOverrideListener) +} + +/** + * A [RemoteConfigOverrideStore] that keeps overrides in memory for the life of the process. + * + * Every mutation is guarded by one lock, and listeners are invoked only after it is released: + * notifying under the lock would make a listener that reads [overrides] deadlock, and a listener + * that throws would otherwise leave the store permanently locked. Listener failures are contained + * for the same reason -- a broken observer must not take the overrides down with it. + * + * Both levels are insertion-ordered so the dashboard lists providers and keys in the order the + * developer created them instead of shuffling on every read. + */ +class InMemoryRemoteConfigOverrideStore( + initial: Map> = emptyMap(), +) : RemoteConfigOverrideStore { + private val lock = Any() + private val byProvider = linkedMapOf>() + private val listeners = mutableListOf() + + init { + initial.forEach { (providerId, values) -> + values.forEach { (key, value) -> setOverride(providerId, key, value) } + } + } + + override fun overrides(): Map> = + synchronized(lock) { + byProvider.mapValues { (_, values) -> LinkedHashMap(values) } + } + + override fun setOverride( + providerId: String, + key: String, + value: String, + ) { + validateProviderId(providerId) + validateKey(key) + validateValue(value) + val changed = + synchronized(lock) { + val values = byProvider.getOrPut(providerId) { linkedMapOf() } + values.put(key, value) != value + } + if (changed) { + notifyListeners() + } + } + + override fun clearOverride( + providerId: String, + key: String, + ) { + validateProviderId(providerId) + validateKey(key) + val changed = + synchronized(lock) { + val values = byProvider[providerId] + val removed = values?.remove(key) != null + if (values != null && values.isEmpty()) { + byProvider.remove(providerId) + } + removed + } + if (changed) { + notifyListeners() + } + } + + override fun clearAll() { + val changed = + synchronized(lock) { + val hadOverrides = byProvider.isNotEmpty() + byProvider.clear() + hadOverrides + } + if (changed) { + notifyListeners() + } + } + + override fun addListener(listener: RemoteConfigOverrideListener) { + synchronized(lock) { + if (listener !in listeners) { + listeners.add(listener) + } + } + } + + override fun removeListener(listener: RemoteConfigOverrideListener) { + synchronized(lock) { listeners.remove(listener) } + } + + private fun notifyListeners() { + val snapshot = synchronized(lock) { listeners.toList() } + snapshot.forEach { listener -> + runCatching { listener.onOverridesChanged() } + } + } + + private fun validateProviderId(providerId: String) { + require(providerId.isNotBlank()) { "Remote config override provider id must not be blank" } + } + + private fun validateKey(key: String) { + require(key.isNotBlank()) { "Remote config override key must not be blank" } + require(key.length <= MAX_KEY_LENGTH) { + "Remote config override key must be at most $MAX_KEY_LENGTH characters" + } + } + + private fun validateValue(value: String) { + require(value.length <= RemoteConfigRegistry.MAX_VALUE_LENGTH) { + "Remote config override value must be at most ${RemoteConfigRegistry.MAX_VALUE_LENGTH} characters" + } + } + + companion object { + /** + * Keys longer than this are rejected rather than stored. An override key is echoed by + * every snapshot response; an unbounded one (a pasted document, a botched deep link) would + * bloat responses the same way an unbounded value would, and a real config key is far + * shorter than this. + */ + const val MAX_KEY_LENGTH: Int = 256 + } +} 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 b0ff6f8..4fbf4fe 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 @@ -10,8 +10,24 @@ package io.devconsole.remoteconfig * 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. + * + * Local overrides are layered on top of the normalized provider values, after the cap, so an + * override is the value a debugger sees while the provider's own result stays available on + * [RemoteConfigEntry.providerValue]. */ -class RemoteConfigRegistry { +class RemoteConfigRegistry( + /** + * Where local overrides live. Injected so a host can persist them and keep the same store + * across a session teardown; the default in-memory store suits hosts that do not need that. + */ + overrideStore: RemoteConfigOverrideStore = InMemoryRemoteConfigOverrideStore(), +) { + /** + * Local overrides layered on top of every provider snapshot. Public so a surface can edit them + * in place; [clear] deliberately leaves them untouched because they are user intent. + */ + val overrides: RemoteConfigOverrideStore = overrideStore + /** * 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 @@ -32,13 +48,31 @@ class RemoteConfigRegistry { } } - /** Drops every registration. Called when a session ends so a re-`initialize()` starts clean. */ + /** + * Drops every registration. Called when a session ends so a re-`initialize()` starts clean. + * + * Overrides are deliberately left in place: they are user intent, not session state, and the + * Android side persists them across a session teardown. Clearing them here would silently + * discard the values a developer is still debugging with. + */ fun clear() { synchronized(lock) { providers.clear() } } fun providerIds(): List = synchronized(lock) { providers.keys.toList() } + /** + * The override in force for [key] on [providerId], or null when none is set. + * + * Read straight from the override store rather than from a snapshot because an override must + * answer even when the provider is unavailable or never reported the key; deriving it from + * provider entries would make it disappear exactly when it is most useful. + */ + fun overrideValue( + providerId: String, + key: String, + ): String? = overrides.overrides()[providerId]?.get(key) + /** Null for an unknown id; a provider that throws yields an unavailable snapshot, never an exception. */ fun snapshot(id: String): RemoteConfigSnapshot? = synchronized(lock) { providers[id] }?.let { read(id, it) } @@ -57,32 +91,35 @@ class RemoteConfigRegistry { 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, - ) - } + runCatching { provider.snapshot().normalized(id, overrides.overrides()[id]) } + .getOrElse { failure -> unavailable(id, failure) } /** * 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. + * + * The cap runs before [withOverrides] so [RemoteConfigEntry.providerValue] records the same + * value the provider would have served, not the uncapped original. + * + * A snapshot that reports itself unavailable keeps the entries it reported (the contract says + * empty) instead of gaining override entries. The Firebase adapter reaches this state by + * returning rather than throwing, and inventing keys there would show config the provider + * never answered for. */ - 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) - } + private fun RemoteConfigSnapshot.normalized( + id: String, + overrides: Map?, + ): RemoteConfigSnapshot { + val capped = entries.map { it.capped() } + val revised = + if (unavailableReason == null) { + capped.withOverrides(overrides.orEmpty()) + } else { + capped + } + return copy(providerId = id, entries = revised) + } companion object { /** @@ -92,3 +129,69 @@ class RemoteConfigRegistry { const val MAX_VALUE_LENGTH: Int = 8 * 1024 } } + +/** + * An unavailable provider keeps an empty entry list even when overrides exist for it. Fabricating + * override entries here would present them as if the provider had reported the key, which is + * precisely the confusion the unavailable state exists to prevent. + */ +private fun unavailable( + id: String, + failure: Throwable, +): RemoteConfigSnapshot = + RemoteConfigSnapshot( + providerId = id, + entries = emptyList(), + fetchInfo = RemoteConfigFetchInfo.unknown(), + unavailableReason = + failure.message?.takeIf(String::isNotBlank) + ?: failure.javaClass.simpleName, + ) + +private fun RemoteConfigEntry.capped(): RemoteConfigEntry = + if (value.length <= RemoteConfigRegistry.MAX_VALUE_LENGTH) { + this + } else { + copy(value = value.take(RemoteConfigRegistry.MAX_VALUE_LENGTH), truncated = true) + } + +/** + * Applies this provider's overrides while preserving the provider's own ordering: reported keys + * stay where the provider put them, and keys the provider never reported are appended in key order + * so repeated reads produce a stable list rather than map-hash order. + */ +private fun List.withOverrides(overrides: Map): List { + if (overrides.isEmpty()) { + return this + } + val overridden = map { entry -> entry.withOverride(overrides[entry.key]) } + val reportedKeys = mapTo(mutableSetOf()) { it.key } + val added = + overrides.keys + .filterNot(reportedKeys::contains) + .sorted() + .map { key -> addedEntry(key, overrides.getValue(key)) } + return overridden + added +} + +private fun RemoteConfigEntry.withOverride(overrideValue: String?): RemoteConfigEntry = + if (overrideValue == null) { + this + } else { + copy( + value = overrideValue, + source = RemoteConfigSource.OVERRIDE, + providerValue = value, + providerSource = source, + ) + } + +private fun addedEntry( + key: String, + value: String, +): RemoteConfigEntry = + RemoteConfigEntry( + key = key, + value = value, + source = RemoteConfigSource.OVERRIDE, + ) diff --git a/sdk/remote-config/src/test/kotlin/io/devconsole/remoteconfig/RemoteConfigOverridesTest.kt b/sdk/remote-config/src/test/kotlin/io/devconsole/remoteconfig/RemoteConfigOverridesTest.kt new file mode 100644 index 0000000..3bd3391 --- /dev/null +++ b/sdk/remote-config/src/test/kotlin/io/devconsole/remoteconfig/RemoteConfigOverridesTest.kt @@ -0,0 +1,358 @@ +/** + * @author Shakib + * @since 04/11/26 + */ +package io.devconsole.remoteconfig + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class RemoteConfigOverridesTest { + @Test + fun `an override replaces the value and keeps the provider value and source`() { + val registry = RemoteConfigRegistry() + registry.register(provider("firebase", entry("checkout_v2", "false", RemoteConfigSource.REMOTE))) + + registry.overrides.setOverride("firebase", "checkout_v2", "true") + + val stored = registry.snapshot("firebase")!!.entries.single() + assertEquals("true", stored.value) + assertEquals(RemoteConfigSource.OVERRIDE, stored.source) + assertEquals("false", stored.providerValue) + assertEquals(RemoteConfigSource.REMOTE, stored.providerSource) + } + + @Test + fun `clearing an override restores the provider value`() { + val registry = RemoteConfigRegistry() + registry.register(provider("firebase", entry("checkout_v2", "false", RemoteConfigSource.REMOTE))) + registry.overrides.setOverride("firebase", "checkout_v2", "true") + + registry.overrides.clearOverride("firebase", "checkout_v2") + + val restored = registry.snapshot("firebase")!!.entries.single() + assertEquals("false", restored.value) + assertEquals(RemoteConfigSource.REMOTE, restored.source) + assertNull(restored.providerValue) + assertNull(restored.providerSource) + } + + @Test + fun `an override for an unreported key is appended after the provider entries in key order`() { + val registry = RemoteConfigRegistry() + registry.register( + provider( + "firebase", + entry("zeta", "1", RemoteConfigSource.REMOTE), + entry("alpha", "2", RemoteConfigSource.REMOTE), + ), + ) + registry.overrides.setOverride("firebase", "unreported-b", "b") + registry.overrides.setOverride("firebase", "unreported-a", "a") + + val entries = registry.snapshot("firebase")!!.entries + + assertEquals( + listOf("zeta", "alpha", "unreported-a", "unreported-b"), + entries.map { it.key }, + ) + val added = entries.last() + assertEquals("b", added.value) + assertEquals(RemoteConfigSource.OVERRIDE, added.source) + assertNull(added.providerValue) + assertNull(added.providerSource) + } + + @Test + fun `an unavailable provider keeps an empty entry list even when overrides name it`() { + val registry = RemoteConfigRegistry() + registry.register( + object : RemoteConfigProvider { + override val id: String = "broken" + + override fun snapshot(): RemoteConfigSnapshot = error("boom") + }, + ) + registry.overrides.setOverride("broken", "key", "override") + + val snapshot = registry.snapshot("broken")!! + + assertTrue(snapshot.entries.isEmpty()) + assertEquals("boom", snapshot.unavailableReason) + } + + @Test + fun `a snapshot that reports itself unavailable does not gain override entries`() { + val registry = RemoteConfigRegistry() + registry.register( + object : RemoteConfigProvider { + override val id: String = "firebase" + + override fun snapshot(): RemoteConfigSnapshot = + RemoteConfigSnapshot( + providerId = id, + entries = emptyList(), + fetchInfo = unknownFetch(), + unavailableReason = "unreadable", + ) + }, + ) + registry.overrides.setOverride("firebase", "key", "override") + + val snapshot = registry.snapshot("firebase")!! + + assertTrue(snapshot.entries.isEmpty()) + assertEquals("unreadable", snapshot.unavailableReason) + } + + @Test + fun `overrideValue answers from the store even when the provider never reported the key`() { + val registry = RemoteConfigRegistry() + registry.overrides.setOverride("firebase", "checkout_v2", "true") + + assertEquals("true", registry.overrideValue("firebase", "checkout_v2")) + assertNull(registry.overrideValue("firebase", "missing")) + assertNull(registry.overrideValue("configcat", "checkout_v2")) + } + + @Test + fun `clear keeps overrides because they are user intent rather than session state`() { + val registry = RemoteConfigRegistry() + registry.register(provider("firebase", entry("key", "remote", RemoteConfigSource.REMOTE))) + registry.overrides.setOverride("firebase", "key", "override") + + registry.clear() + + assertEquals("override", registry.overrideValue("firebase", "key")) + assertTrue(registry.providerIds().isEmpty()) + registry.register(provider("firebase", entry("key", "remote", RemoteConfigSource.REMOTE))) + assertEquals( + "override", + registry + .snapshot("firebase")!! + .entries + .single() + .value, + ) + } + + @Test + fun `an override is applied under the id the provider was registered with`() { + val registry = RemoteConfigRegistry() + registry.register( + object : RemoteConfigProvider { + override val id: String = "firebase" + + override fun snapshot(): RemoteConfigSnapshot = + RemoteConfigSnapshot( + providerId = "reported-differently", + entries = listOf(entry("key", "remote", RemoteConfigSource.REMOTE)), + fetchInfo = unknownFetch(), + ) + }, + ) + registry.overrides.setOverride("firebase", "key", "override") + registry.overrides.setOverride("reported-differently", "key", "ignored") + + val snapshot = registry.snapshot("firebase")!! + + assertEquals("firebase", snapshot.providerId) + assertEquals("override", snapshot.entries.single().value) + } + + @Test + fun `an override applies only to its own provider`() { + val registry = RemoteConfigRegistry() + registry.register(provider("firebase", entry("key", "remote", RemoteConfigSource.REMOTE))) + registry.register(provider("configcat", entry("key", "remote", RemoteConfigSource.REMOTE))) + registry.overrides.setOverride("firebase", "key", "override") + + val (firebase, configcat) = registry.snapshots() + + assertEquals("override", firebase.entries.single().value) + assertEquals("remote", configcat.entries.single().value) + assertNull(configcat.entries.single().providerValue) + } + + @Test + fun `the provider value is captured after the registry cap`() { + val registry = RemoteConfigRegistry() + val oversized = "x".repeat(RemoteConfigRegistry.MAX_VALUE_LENGTH + 10) + registry.register(provider("firebase", entry("blob", oversized, RemoteConfigSource.REMOTE))) + registry.overrides.setOverride("firebase", "blob", "short") + + val stored = registry.snapshot("firebase")!!.entries.single() + + assertEquals(RemoteConfigRegistry.MAX_VALUE_LENGTH, stored.providerValue!!.length) + assertTrue(stored.truncated) + } +} + +class InMemoryRemoteConfigOverrideStoreTest { + @Test + fun `overrides keep insertion order for providers and keys`() { + val initial: Map> = + linkedMapOf( + "second" to linkedMapOf("z" to "1", "a" to "2"), + "first" to linkedMapOf("key" to "value"), + ) + + val store = InMemoryRemoteConfigOverrideStore(initial) + + assertEquals(listOf("second", "first"), store.overrides().keys.toList()) + assertEquals(listOf("z", "a"), store.overrides()["second"]!!.keys.toList()) + } + + @Test + fun `overrides returns a copy that cannot mutate the store`() { + val store = InMemoryRemoteConfigOverrideStore() + store.setOverride("firebase", "key", "value") + + @Suppress("UNCHECKED_CAST") + val copy = store.overrides() as MutableMap<*, *> + copy.clear() + + assertEquals(mapOf("firebase" to mapOf("key" to "value")), store.overrides()) + } + + @Test + fun `initial overrides are applied and validated`() { + val store = InMemoryRemoteConfigOverrideStore(mapOf("firebase" to mapOf("key" to "value"))) + + assertEquals("value", store.overrides()["firebase"]?.get("key")) + assertIllegalArgument { + InMemoryRemoteConfigOverrideStore(mapOf(" " to mapOf("key" to "value"))) + } + } + + @Test + fun `setting an override again replaces the previous value`() { + val store = InMemoryRemoteConfigOverrideStore() + + store.setOverride("firebase", "key", "one") + store.setOverride("firebase", "key", "two") + + assertEquals(mapOf("key" to "two"), store.overrides()["firebase"]) + } + + @Test + fun `clearing removes only the requested pair and drops the empty provider`() { + val store = InMemoryRemoteConfigOverrideStore() + store.setOverride("firebase", "first", "1") + store.setOverride("firebase", "second", "2") + + store.clearOverride("firebase", "first") + + assertEquals(mapOf("second" to "2"), store.overrides()["firebase"]) + store.clearOverride("firebase", "second") + assertTrue(store.overrides().isEmpty()) + } + + @Test + fun `a listener fires on set, clear and clearAll`() { + val store = InMemoryRemoteConfigOverrideStore() + var fired = 0 + store.addListener { fired++ } + + store.setOverride("firebase", "key", "value") + store.clearOverride("firebase", "key") + store.setOverride("firebase", "key", "value") + store.clearAll() + + assertEquals(4, fired) + } + + @Test + fun `a removed listener stops receiving notifications`() { + val store = InMemoryRemoteConfigOverrideStore() + var fired = 0 + val listener = RemoteConfigOverrideListener { fired++ } + store.addListener(listener) + store.removeListener(listener) + + store.setOverride("firebase", "key", "value") + + assertEquals(0, fired) + } + + @Test + fun `a throwing listener is contained and does not stop the others`() { + val store = InMemoryRemoteConfigOverrideStore() + val healthyCalls = mutableListOf() + store.addListener { error("listener exploded") } + store.addListener { healthyCalls.add(Unit) } + + store.setOverride("firebase", "key", "value") + + assertEquals(1, healthyCalls.size) + assertEquals("value", store.overrides()["firebase"]?.get("key")) + } + + @Test + fun `blank provider ids and keys are rejected`() { + val store = InMemoryRemoteConfigOverrideStore() + + assertIllegalArgument { store.setOverride(" ", "key", "value") } + assertIllegalArgument { store.clearOverride(" ", "key") } + assertIllegalArgument { store.setOverride("firebase", " ", "value") } + assertIllegalArgument { store.clearOverride("firebase", " ") } + } + + @Test + fun `a key at the cap is accepted and one character more is rejected`() { + val store = InMemoryRemoteConfigOverrideStore() + val atCap = "k".repeat(InMemoryRemoteConfigOverrideStore.MAX_KEY_LENGTH) + + store.setOverride("firebase", atCap, "value") + + assertEquals("value", store.overrides()["firebase"]?.get(atCap)) + assertIllegalArgument { store.setOverride("firebase", "${atCap}k", "value") } + } + + @Test + fun `a value at the cap is accepted and one character more is rejected`() { + val store = InMemoryRemoteConfigOverrideStore() + val atCap = "v".repeat(RemoteConfigRegistry.MAX_VALUE_LENGTH) + + store.setOverride("firebase", "key", atCap) + + assertEquals(atCap, store.overrides()["firebase"]?.get("key")) + assertIllegalArgument { store.setOverride("firebase", "key", "${atCap}v") } + } +} + +private fun assertIllegalArgument(block: () -> Unit) { + val failure = runCatching(block).exceptionOrNull() + + assertTrue("expected IllegalArgumentException but was $failure", failure is IllegalArgumentException) +} + +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(), + ) + } + +private fun unknownFetch() = + RemoteConfigFetchInfo( + lastFetchEpochMs = null, + status = RemoteConfigFetchStatus.UNKNOWN, + minimumFetchIntervalSeconds = null, + ) diff --git a/sdk/security/src/main/kotlin/io/devconsole/security/RedactionEngine.kt b/sdk/security/src/main/kotlin/io/devconsole/security/RedactionEngine.kt index 8a54150..6d9f489 100644 --- a/sdk/security/src/main/kotlin/io/devconsole/security/RedactionEngine.kt +++ b/sdk/security/src/main/kotlin/io/devconsole/security/RedactionEngine.kt @@ -159,7 +159,7 @@ class RedactionEngine( if (policy.normalizedFieldNames.isEmpty()) return Regex("(?!)") val sensitiveNamePattern = policy.normalizedFieldNames.joinToString("|") { Regex.escape(it) } return Regex( - "(\\\"(?:$sensitiveNamePattern)\\\"\\s*:\\s*)(?:\\\"(?:\\\\.|[^\\\"])*\\\"|[^,}\\s]+)", + "(\\\"(?:$sensitiveNamePattern)\\\"\\s*:\\s*)(?:\\\"(?:[^\\\"\\\\]++|\\\\.)*+\\\"|[^,}\\s]++)", RegexOption.IGNORE_CASE, ) } diff --git a/sdk/security/src/test/kotlin/io/devconsole/security/RedactionEngineTest.kt b/sdk/security/src/test/kotlin/io/devconsole/security/RedactionEngineTest.kt index 3f44ce0..fa0311f 100644 --- a/sdk/security/src/test/kotlin/io/devconsole/security/RedactionEngineTest.kt +++ b/sdk/security/src/test/kotlin/io/devconsole/security/RedactionEngineTest.kt @@ -127,4 +127,15 @@ class RedactionEngineTest { assertEquals("", engine.redactText("a".repeat(32_768) + "!", maxLength = 4_096)) } + + @Test(timeout = 1_000) + fun `pathological unclosed JSON secret string remains bounded`() { + val input = "{\"token\":\"" + "\\".repeat(100_000) + + val redacted = engine.redactText(input) + + // Completes (no catastrophic backtracking / stack overflow) and the secret-looking value is masked. + assertTrue(redacted.length <= RedactionEngine.DEFAULT_TEXT_LIMIT) + assertFalse(redacted.contains("\\".repeat(10))) + } } diff --git a/sdk/server-ktor/api/server-ktor.api b/sdk/server-ktor/api/server-ktor.api index be17186..90a5ed1 100644 --- a/sdk/server-ktor/api/server-ktor.api +++ b/sdk/server-ktor/api/server-ktor.api @@ -1,3 +1,26 @@ +public abstract interface class io/devconsole/server/ktor/CaptureControl { + public abstract fun isPaused ()Z + public abstract fun purge (Lkotlin/coroutines/Continuation;)Ljava/lang/Object; + public abstract fun setPaused (Z)Z +} + +public final class io/devconsole/server/ktor/CapturePurgeSummary { + public fun (IIII)V + public final fun component1 ()I + public final fun component2 ()I + public final fun component3 ()I + public final fun component4 ()I + public final fun copy (IIII)Lio/devconsole/server/ktor/CapturePurgeSummary; + public static synthetic fun copy$default (Lio/devconsole/server/ktor/CapturePurgeSummary;IIIIILjava/lang/Object;)Lio/devconsole/server/ktor/CapturePurgeSummary; + public fun equals (Ljava/lang/Object;)Z + public final fun getNetworkTransactions ()I + public final fun getPushEvents ()I + public final fun getRetainedRunsDeleted ()I + public final fun getSocketConnections ()I + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + public final class io/devconsole/server/ktor/DevConsoleKtorModuleKt { public static final fun devConsoleModule (Lio/ktor/server/application/Application;Lio/devconsole/server/api/SessionAuthority;Lio/devconsole/server/api/SessionCodeAuthority;Lkotlin/jvm/functions/Function1;)V public static synthetic fun devConsoleModule$default (Lio/ktor/server/application/Application;Lio/devconsole/server/api/SessionAuthority;Lio/devconsole/server/api/SessionCodeAuthority;Lkotlin/jvm/functions/Function1;ILjava/lang/Object;)V @@ -11,6 +34,7 @@ public final class io/devconsole/server/ktor/DevConsoleModuleConfig { public final fun getAttachmentReader ()Lkotlin/jvm/functions/Function2; public final fun getBoundEndpoint ()Lkotlin/jvm/functions/Function0; public final fun getBrowserSecurity ()Lio/devconsole/api/BrowserSecurity; + public final fun getCaptureControl ()Lio/devconsole/server/ktor/CaptureControl; public final fun getCaptureRules ()Lio/devconsole/api/CaptureRuleEngine; public final fun getCaptureRulesEditable ()Z public final fun getCommandAuditLog ()Lio/devconsole/server/api/CommandAuditLog; @@ -22,6 +46,7 @@ public final class io/devconsole/server/ktor/DevConsoleModuleConfig { public final fun getCurrentSessionId ()Lkotlin/jvm/functions/Function0; public final fun getDatabaseEditable ()Z public final fun getDatabaseInspector ()Lio/devconsole/server/api/DatabaseInspector; + public final fun getDeleteRun ()Lkotlin/jvm/functions/Function2; public final fun getEvidenceStore ()Lio/devconsole/storage/api/EvidenceStore; public final fun getExportDirectory ()Ljava/io/File; public final fun getFeatureFlags ()Lio/devconsole/state/SessionFeatureFlags; @@ -33,17 +58,21 @@ public final class io/devconsole/server/ktor/DevConsoleModuleConfig { public final fun getMocksEditable ()Z public final fun getNetworkProtection ()Lio/devconsole/api/NetworkProtection; public final fun getNetworkTransactions ()Lio/devconsole/network/NetworkTransactionStore; + public final fun getPinRun ()Lkotlin/jvm/functions/Function3; public final fun getPreferencesEditable ()Z public final fun getPreferencesInspector ()Lio/devconsole/server/api/PreferencesInspector; 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 getRemoteConfigOverrides ()Lio/devconsole/remoteconfig/RemoteConfigOverrideStore; public final fun getRemoteConfigSnapshots ()Lkotlin/jvm/functions/Function0; public final fun getRetainedCaptures ()Lio/devconsole/storage/api/RetainedCaptureQuery; + public final fun getRetainedNetworkTransactions ()Lkotlin/jvm/functions/Function2; public final fun getScreenshotCapture ()Lkotlin/jvm/functions/Function1; public final fun getSdkHealth ()Lkotlin/jvm/functions/Function0; public final fun getSessionSnapshotProvider ()Lkotlin/jvm/functions/Function1; public final fun getSessionsProvider ()Lkotlin/jvm/functions/Function1; + public final fun getSocketSenders ()Lio/devconsole/socket/SocketSenderRegistry; public final fun getSocketStore ()Lio/devconsole/socket/SocketStore; public final fun getStateMutationsEnabled ()Z public final fun getStateRegistry ()Lio/devconsole/state/StateRegistry; @@ -55,6 +84,7 @@ public final class io/devconsole/server/ktor/DevConsoleModuleConfig { public final fun setAttachmentReader (Lkotlin/jvm/functions/Function2;)V public final fun setBoundEndpoint (Lkotlin/jvm/functions/Function0;)V public final fun setBrowserSecurity (Lio/devconsole/api/BrowserSecurity;)V + public final fun setCaptureControl (Lio/devconsole/server/ktor/CaptureControl;)V public final fun setCaptureRules (Lio/devconsole/api/CaptureRuleEngine;)V public final fun setCaptureRulesEditable (Z)V public final fun setCommandAuditLog (Lio/devconsole/server/api/CommandAuditLog;)V @@ -66,6 +96,7 @@ public final class io/devconsole/server/ktor/DevConsoleModuleConfig { public final fun setCurrentSessionId (Lkotlin/jvm/functions/Function0;)V public final fun setDatabaseEditable (Z)V public final fun setDatabaseInspector (Lio/devconsole/server/api/DatabaseInspector;)V + public final fun setDeleteRun (Lkotlin/jvm/functions/Function2;)V public final fun setEvidenceStore (Lio/devconsole/storage/api/EvidenceStore;)V public final fun setExportDirectory (Ljava/io/File;)V public final fun setFeatureFlags (Lio/devconsole/state/SessionFeatureFlags;)V @@ -77,17 +108,21 @@ public final class io/devconsole/server/ktor/DevConsoleModuleConfig { public final fun setMocksEditable (Z)V public final fun setNetworkProtection (Lio/devconsole/api/NetworkProtection;)V public final fun setNetworkTransactions (Lio/devconsole/network/NetworkTransactionStore;)V + public final fun setPinRun (Lkotlin/jvm/functions/Function3;)V public final fun setPreferencesEditable (Z)V public final fun setPreferencesInspector (Lio/devconsole/server/api/PreferencesInspector;)V 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 setRemoteConfigOverrides (Lio/devconsole/remoteconfig/RemoteConfigOverrideStore;)V public final fun setRemoteConfigSnapshots (Lkotlin/jvm/functions/Function0;)V public final fun setRetainedCaptures (Lio/devconsole/storage/api/RetainedCaptureQuery;)V + public final fun setRetainedNetworkTransactions (Lkotlin/jvm/functions/Function2;)V public final fun setScreenshotCapture (Lkotlin/jvm/functions/Function1;)V public final fun setSdkHealth (Lkotlin/jvm/functions/Function0;)V public final fun setSessionSnapshotProvider (Lkotlin/jvm/functions/Function1;)V public final fun setSessionsProvider (Lkotlin/jvm/functions/Function1;)V + public final fun setSocketSenders (Lio/devconsole/socket/SocketSenderRegistry;)V public final fun setSocketStore (Lio/devconsole/socket/SocketStore;)V public final fun setStateMutationsEnabled (Z)V public final fun setStateRegistry (Lio/devconsole/state/StateRegistry;)V @@ -111,8 +146,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;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;ZZLio/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;ZZLio/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/server/ktor/CaptureControl;Lio/devconsole/socket/SocketSenderRegistry;Lio/devconsole/remoteconfig/RemoteConfigOverrideStore;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;ZZLio/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/server/ktor/CaptureControl;Lio/devconsole/socket/SocketSenderRegistry;Lio/devconsole/remoteconfig/RemoteConfigOverrideStore;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;ZZLio/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 permitsComposerHost (Ljava/lang/String;)Z @@ -125,5 +160,7 @@ public final class io/devconsole/server/ktor/KtorLocalServerEngine : io/devconso public final fun withBrowserSecurity (Lio/devconsole/api/BrowserSecurity;)Lio/devconsole/server/ktor/KtorLocalServerEngine; public final fun withNetworkProtection (Lio/devconsole/api/NetworkProtection;)Lio/devconsole/server/ktor/KtorLocalServerEngine; public final fun withRetainedCaptures (Lio/devconsole/storage/api/RetainedCaptureQuery;)Lio/devconsole/server/ktor/KtorLocalServerEngine; + public final fun withRetainedNetworkTransactions (Lkotlin/jvm/functions/Function2;)Lio/devconsole/server/ktor/KtorLocalServerEngine; + public final fun withRunControls (Lkotlin/jvm/functions/Function2;Lkotlin/jvm/functions/Function3;)Lio/devconsole/server/ktor/KtorLocalServerEngine; } diff --git a/sdk/server-ktor/src/main/kotlin/io/devconsole/server/ktor/CaptureControl.kt b/sdk/server-ktor/src/main/kotlin/io/devconsole/server/ktor/CaptureControl.kt new file mode 100644 index 0000000..a27d8cf --- /dev/null +++ b/sdk/server-ktor/src/main/kotlin/io/devconsole/server/ktor/CaptureControl.kt @@ -0,0 +1,28 @@ +/** + * @author Shakib + * @since 04/11/26 + */ +package io.devconsole.server.ktor + +/** + * Host-side capture pause/resume and purge, exposed by the HTTP module without depending on the + * facade. `:sdk:full` wires its `PlatformFacadeProvider` implementation in at engine construction; + * keeping the contract this small means the server never has to know what a capture buffer is. + */ +interface CaptureControl { + fun isPaused(): Boolean + + /** Applies [paused]; false means this build/session cannot honour the change right now. */ + fun setPaused(paused: Boolean): Boolean + + /** Discards this run's buffered captures plus old, unpinned retained runs. */ + suspend fun purge(): CapturePurgeSummary +} + +/** What one [CaptureControl.purge] removed, as counts so the dashboard can report it honestly. */ +data class CapturePurgeSummary( + val networkTransactions: Int, + val socketConnections: Int, + val pushEvents: Int, + val retainedRunsDeleted: Int, +) 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 3c647a7..96af1a5 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 @@ -22,10 +22,10 @@ import io.devconsole.export.DEFAULT_EXPORT_LIMIT_BYTES import io.devconsole.export.EventExportWriter import io.devconsole.export.EvidenceBundleAttachment import io.devconsole.export.EvidenceBundleContent +import io.devconsole.export.ExportAttachmentSource import io.devconsole.export.ExportRequest import io.devconsole.export.ExportResult import io.devconsole.export.ExportScope -import io.devconsole.mocks.MockAction import io.devconsole.mocks.MockEngine import io.devconsole.mocks.MockRule import io.devconsole.mocks.MockRuleStats @@ -55,6 +55,7 @@ import io.devconsole.push.PushInput import io.devconsole.push.PushSimulator import io.devconsole.push.PushStore import io.devconsole.remoteconfig.RemoteConfigEntry +import io.devconsole.remoteconfig.RemoteConfigOverrideStore import io.devconsole.remoteconfig.RemoteConfigSnapshot import io.devconsole.security.RedactionEngine import io.devconsole.security.RedactionPolicy @@ -93,7 +94,10 @@ import io.devconsole.socket.SocketMessage import io.devconsole.socket.SocketMessageQuery import io.devconsole.socket.SocketPayload import io.devconsole.socket.SocketProtocol +import io.devconsole.socket.SocketSendResult +import io.devconsole.socket.SocketSenderRegistry import io.devconsole.socket.SocketStore +import io.devconsole.state.FeatureFlagType import io.devconsole.state.SessionFeatureFlags import io.devconsole.state.StateMutationResult import io.devconsole.state.StateMutator @@ -129,16 +133,17 @@ import io.ktor.server.application.Application import io.ktor.server.application.ApplicationCallPipeline import io.ktor.server.application.call import io.ktor.server.application.install +import io.ktor.server.application.serverConfig import io.ktor.server.cio.CIO import io.ktor.server.engine.EmbeddedServer +import io.ktor.server.engine.connector import io.ktor.server.engine.embeddedServer import io.ktor.server.plugins.BadRequestException import io.ktor.server.plugins.ContentTransformationException import io.ktor.server.plugins.UnsupportedMediaTypeException import io.ktor.server.plugins.origin import io.ktor.server.request.httpMethod -import io.ktor.server.request.receiveParameters -import io.ktor.server.request.receiveText +import io.ktor.server.request.receiveChannel import io.ktor.server.request.uri import io.ktor.server.response.respondBytes import io.ktor.server.response.respondOutputStream @@ -153,20 +158,25 @@ import io.ktor.server.websocket.pingPeriod import io.ktor.server.websocket.timeout import io.ktor.server.websocket.webSocket import io.ktor.util.decodeBase64Bytes +import io.ktor.utils.io.readRemaining import io.ktor.websocket.CloseReason import io.ktor.websocket.Frame import io.ktor.websocket.close import io.ktor.websocket.readText import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CoroutineExceptionHandler import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.delay import kotlinx.coroutines.flow.collect +import kotlinx.coroutines.flow.onSubscription import kotlinx.coroutines.isActive import kotlinx.coroutines.launch import kotlinx.coroutines.withContext +import kotlinx.io.readByteArray +import java.io.ByteArrayInputStream import java.io.File import java.net.Inet4Address import java.net.InetSocketAddress @@ -226,6 +236,9 @@ class DevConsoleModuleConfig { * while this is false. */ var featureFlagsEditable: Boolean = true + + /** Store backing Remote Config overrides; null leaves override routes reporting unavailable. */ + var remoteConfigOverrides: RemoteConfigOverrideStore? = null var stateRegistry: StateRegistry = StateRegistry() var stateMutationsEnabled: Boolean = true @@ -236,6 +249,21 @@ class DevConsoleModuleConfig { */ var remoteConfigSnapshots: () -> List = { emptyList() } + /** + * Host-side capture pause/resume and purge, backing `/api/v1/capture`. Null (the default) makes + * those routes report the control as unavailable instead of toggling a buffer this module cannot + * reach; `:sdk:full` wires its `PlatformFacadeProvider` in at engine construction. + */ + var captureControl: CaptureControl? = null + + /** + * Writes one host-originated frame onto a live WebSocket/MQTT connection, backing + * `POST /api/v1/websockets/connections/{id}/send`. Null (the default) makes that route answer + * `SEND_UNSUPPORTED` instead of pretending a connection it cannot reach is writable; `:sdk:full` + * wires the same registry its socket adapters register into. + */ + var socketSenders: SocketSenderRegistry? = null + /** Reads (file/entry listing) always work; [preferencesEditable] mirrors `EditingCapabilities.preferences`. */ var preferencesInspector: PreferencesInspector? = null var preferencesEditable: Boolean = true @@ -272,6 +300,13 @@ class DevConsoleModuleConfig { var attachmentMetadataReader: suspend (String) -> StoredAttachment? = { null } var retainedCaptures: RetainedCaptureQuery? = null + /** + * Read-only transaction store rebuilt from a completed run's persisted captures, so the network + * list, detail, cURL and HAR/Postman routes can serve `?sessionId=`. Null (the + * default, or an unknown session) answers `SESSION_NOT_FOUND`. + */ + var retainedNetworkTransactions: suspend (sessionId: String) -> NetworkTransactionStore? = { null } + /** * Durable QA evidence tray. Null (the default) makes every `/api/v1/evidence` route answer * `EVIDENCE_UNAVAILABLE`. @@ -293,6 +328,12 @@ class DevConsoleModuleConfig { */ var sessionsProvider: suspend () -> List = { emptyList() } + /** Deletes a finished run and its captures (`DELETE /api/v1/runs/{id}`); false refuses it. */ + var deleteRun: suspend (sessionId: String) -> Boolean = { false } + + /** Pins or unpins a finished run against retention (`POST /api/v1/runs/{id}/pin`). */ + var pinRun: suspend (sessionId: String, pinned: Boolean) -> Boolean = { _, _ -> false } + /** * Delegates to `DevConsoleFacadeProvider.captureScreenshot()`. Defaults to always reporting the * SDK as disabled for this build, mirroring `ScreenshotResult.DisabledForBuild`'s own meaning. @@ -343,8 +384,11 @@ fun Application.devConsoleModule( val captureRulesEditable = config.captureRulesEditable val featureFlags = config.featureFlags val featureFlagsEditable = config.featureFlagsEditable + val remoteConfigOverrides = config.remoteConfigOverrides val stateRegistry = config.stateRegistry val remoteConfigSnapshots = config.remoteConfigSnapshots + val captureControl = config.captureControl + val socketSenders = config.socketSenders val stateMutationsEnabled = config.stateMutationsEnabled val preferencesInspector = config.preferencesInspector val preferencesEditable = config.preferencesEditable @@ -362,10 +406,13 @@ fun Application.devConsoleModule( val attachmentReader = config.attachmentReader val attachmentMetadataReader = config.attachmentMetadataReader val retainedCaptures = config.retainedCaptures + val retainedNetworkTransactions = config.retainedNetworkTransactions val evidenceStore = config.evidenceStore val currentSessionId = config.currentSessionId val sessionSnapshotProvider = config.sessionSnapshotProvider val sessionsProvider = config.sessionsProvider + val deleteRun = config.deleteRun + val pinRun = config.pinRun val screenshotCapture = config.screenshotCapture val metadata = config.metadata val sdkHealth = config.sdkHealth @@ -574,6 +621,12 @@ fun Application.devConsoleModule( call.respondClientError(HttpStatusCode.BadRequest, "VALIDATION_FAILED", malformed) } catch (badRequest: BadRequestException) { call.respondClientError(HttpStatusCode.BadRequest, "VALIDATION_FAILED", badRequest) + } catch (_: RequestBodyTooLargeException) { + call.respondText( + "{\"code\":\"PAYLOAD_TOO_LARGE\"}", + status = HttpStatusCode.PayloadTooLarge, + contentType = io.ktor.http.ContentType.Application.Json, + ) } catch (throwable: Throwable) { call.application.environment.log.error( "Unhandled exception handling ${call.request.httpMethod.value} ${call.request.uri}", @@ -605,6 +658,25 @@ fun Application.devConsoleModule( contentType = io.ktor.http.ContentType.Application.Json, ) } + + /** + * The live store unless `sessionId` names a past run, in which case that run's retained store. + * Responds `SESSION_NOT_FOUND` and returns null when the past run cannot be served. + */ + suspend fun io.ktor.server.application.ApplicationCall.networkStoreForRequestedSession(): NetworkTransactionStore? { + val requested = request.queryParameters["sessionId"]?.takeIf(String::isNotBlank) + val store = + if (requested == null || requested == currentSessionId()) { + networkTransactions + } else { + runCatching { retainedNetworkTransactions(requested) }.getOrNull() + } + if (store == null) { + respondText("{\"code\":\"SESSION_NOT_FOUND\"}", status = HttpStatusCode.NotFound) + } + return store + } + routing { get("/") { call.response.headers.append(HttpHeaders.CacheControl, "no-store") @@ -699,7 +771,7 @@ fun Application.devConsoleModule( call.respondText("{\"code\":\"RATE_LIMITED\"}", status = HttpStatusCode.TooManyRequests) return@post } - val parameters = call.receiveParameters() + val parameters = call.receiveParametersWithin(MAX_DEFAULT_REQUEST_BODY_BYTES) val code = parameters["code"].orEmpty() if (code.isBlank()) { call.respondText("{\"code\":\"VALIDATION_FAILED\"}", status = HttpStatusCode.BadRequest) @@ -855,10 +927,40 @@ fun Application.devConsoleModule( sessionsProvider() .sortedWith(compareByDescending { it.startedAtMs }.thenByDescending { it.id }) call.respondText( - "{\"data\":[${runs.joinToString(",") { it.json() }}]}", + "{\"data\":[${runs.joinToString(",") { it.json(current = it.id == currentSessionId()) }}]}", contentType = io.ktor.http.ContentType.Application.Json, ) } + // Same gate as the network clear route: bearer session plus Origin+CSRF, audited both ways. + delete("/api/v1/runs/{id}") { + val runId = call.parameters["id"].orEmpty() + val session = + call.captureControlSession(sessionAuthority, commandAuditLog, "runs.delete", runId) + ?: return@delete + val deleted = runId != currentSessionId() && runCatching { deleteRun(runId) }.getOrDefault(false) + if (!deleted) { + commandAuditLog.recordControlFailure(session.id, "runs.delete", runId) + call.respondText("{\"code\":\"RUN_NOT_DELETABLE\"}", status = HttpStatusCode.Conflict) + return@delete + } + commandAuditLog.recordControlSuccess(session.id, "runs.delete", runId) + call.respondText("{\"status\":\"deleted\"}", contentType = io.ktor.http.ContentType.Application.Json) + } + post("/api/v1/runs/{id}/pin") { + val runId = call.parameters["id"].orEmpty() + val session = + call.captureControlSession(sessionAuthority, commandAuditLog, "runs.pin", runId) + ?: return@post + val pinned = call.receiveParametersWithin(MAX_DEFAULT_REQUEST_BODY_BYTES)["pinned"] != "false" + val changed = runCatching { pinRun(runId, pinned) }.getOrDefault(false) + if (!changed) { + commandAuditLog.recordControlFailure(session.id, "runs.pin", runId) + call.respondText("{\"code\":\"RUN_NOT_PINNABLE\"}", status = HttpStatusCode.Conflict) + return@post + } + commandAuditLog.recordControlSuccess(session.id, "runs.pin", runId) + call.respondText("{\"pinned\":$pinned}", contentType = io.ktor.http.ContentType.Application.Json) + } get("/api/v1/report") { val session = sessionAuthority.bearerSession(call.request.headers[HttpHeaders.Authorization]) @@ -913,7 +1015,7 @@ fun Application.devConsoleModule( call.respondText("{\"code\":\"CSRF_INVALID\"}", status = HttpStatusCode.Forbidden) return@post } - val receivedParameters = call.receiveParameters() + val receivedParameters = call.receiveParametersWithin(MAX_DEFAULT_REQUEST_BODY_BYTES) if ((receivedParameters["scope"] ?: "").uppercase() == "EVIDENCE") { val maxBytes = receivedParameters.resolveMaxBytes() if (maxBytes == null) { @@ -980,13 +1082,22 @@ fun Application.devConsoleModule( return@post } val prepared = - prepareExport(receivedParameters, timeline, retainedCaptures, attachmentReader) + prepareExport( + receivedParameters, + timeline, + retainedCaptures, + ExportSources(attachmentReader, attachmentMetadataReader, currentSessionId), + ) if (prepared == null) { commandAuditLog.recordExport(session.id, CommandAuditResult.REJECTED, "validation") call.respondText("{\"code\":\"VALIDATION_FAILED\"}", status = HttpStatusCode.BadRequest) return@post } pruneStaleExports(exportDirectory) + val annotationSnapshots = + withContext(Dispatchers.IO) { + prepared.scopedEvents.associate { it.id to annotations.get(it.id) } + } val request = ExportRequest( sessionId = prepared.exportSessionId, @@ -995,8 +1106,8 @@ fun Application.devConsoleModule( maxBytes = prepared.maxBytes, ).withScope(prepared.scope) .withMetadataOnly(prepared.metadataOnly) - .withAnnotations(prepared.scopedEvents.associate { it.id to annotations.get(it.id) }) - .withAttachments(prepared.attachments) + .withAnnotations(annotationSnapshots) + .withAttachmentSources(prepared.attachments) val writer = EventExportWriter(redaction) when (val result = writer.writeAsync(request)) { is ExportResult.Success -> { @@ -1095,11 +1206,20 @@ fun Application.devConsoleModule( return@get } val prepared = - prepareExport(call.request.queryParameters, timeline, retainedCaptures, attachmentReader) + prepareExport( + call.request.queryParameters, + timeline, + retainedCaptures, + ExportSources(attachmentReader, attachmentMetadataReader, currentSessionId), + ) if (prepared == null) { call.respondText("{\"code\":\"VALIDATION_FAILED\"}", status = HttpStatusCode.BadRequest) return@get } + val annotationSnapshots = + withContext(Dispatchers.IO) { + prepared.scopedEvents.associate { it.id to annotations.get(it.id) } + } val request = ExportRequest( sessionId = prepared.exportSessionId, @@ -1108,8 +1228,8 @@ fun Application.devConsoleModule( maxBytes = prepared.maxBytes, ).withScope(prepared.scope) .withMetadataOnly(prepared.metadataOnly) - .withAnnotations(prepared.scopedEvents.associate { it.id to annotations.get(it.id) }) - .withAttachments(prepared.attachments) + .withAnnotations(annotationSnapshots) + .withAttachmentSources(prepared.attachments) val estimatedBytes = EventExportWriter(redaction).estimateBytes(request) call.respondText( "{\"estimatedBytes\":$estimatedBytes}", @@ -1251,8 +1371,10 @@ fun Application.devConsoleModule( call.respondText("{\"code\":\"VALIDATION_FAILED\"}", status = HttpStatusCode.BadRequest) return@get } - call.respondNetworkTransactionPage(networkTransactions.page(query)) + val store = call.networkStoreForRequestedSession() ?: return@get + call.respondNetworkTransactionPage(store.page(query)) } + networkEndpointStatsRoutes(sessionAuthority, ::categoryEnabled) { it.networkStoreForRequestedSession() } /** * Discards every captured transaction -- the dashboard's "Clear" action beside the HAR and * Postman exports, and the counterpart of the in-app inspector's own clear. @@ -1372,8 +1494,7 @@ fun Application.devConsoleModule( return@post } val enabled = - call - .receiveText() + (call.receiveTextWithin(MAX_DEFAULT_REQUEST_BODY_BYTES) ?: return@post) .trim() .trim('"') .toBooleanStrictOrNull() @@ -1439,22 +1560,40 @@ fun Application.devConsoleModule( call.respondCategoryDisabled("mocks") return@post } - val parameters = call.receiveParameters() + val parameters = call.receiveParametersWithin(MAX_DEFAULT_REQUEST_BODY_BYTES) val id = parameters["id"].orEmpty() val priority = parameters["priority"]?.toIntOrNull() - val status = parameters["status"]?.toIntOrNull() val scope = parameters["scope"]?.let { runCatching { MockScope.valueOf(it) }.getOrNull() } ?: MockScope.SESSION - val delayMs = parameters["delayMs"]?.toLongOrNull() val headers = runCatching { parameters["headers"].parseMockRuleHeaders() }.getOrNull() - val basicFieldsValid = id.matches(MOCK_RULE_ID) && priority != null && status in 100..599 - val delayValid = delayMs == null || delayMs in 0..MOCK_RULE_MAX_DELAY_MS - if (!basicFieldsValid || !delayValid || headers == null) { + val existingRule = mockEngine.rules().firstOrNull { it.id == id } + val rawQueryPredicates = parameters.getAll("queryPredicate") + val rawHeaderPredicates = parameters.getAll("headerPredicate") + val queryPredicates = runCatching { parseMockPredicates(rawQueryPredicates) }.getOrNull() + val headerPredicates = runCatching { parseMockPredicates(rawHeaderPredicates) }.getOrNull() + val requestedEnabled = parameters["enabled"]?.toBooleanStrictOrNull() + val predicatesValid = + (rawQueryPredicates == null || queryPredicates != null) && + (rawHeaderPredicates == null || headerPredicates != null) + val enabledValid = parameters["enabled"] == null || requestedEnabled != null + val action = runCatching { parseMockAction(parameters, headers.orEmpty()) }.getOrNull() + val idValid = id.matches(MOCK_RULE_ID) + if (!idValid || priority == null) { + commandAuditLog.recordControlFailure(session.id, "mock.rule.upsert", id.ifBlank { "rule" }) + call.respondText("{\"code\":\"VALIDATION_FAILED\"}", status = HttpStatusCode.BadRequest) + return@post + } + if (headers == null || !predicatesValid || !enabledValid) { + commandAuditLog.recordControlFailure(session.id, "mock.rule.upsert", id.ifBlank { "rule" }) + call.respondText("{\"code\":\"VALIDATION_FAILED\"}", status = HttpStatusCode.BadRequest) + return@post + } + if (action == null) { commandAuditLog.recordControlFailure(session.id, "mock.rule.upsert", id.ifBlank { "rule" }) call.respondText("{\"code\":\"VALIDATION_FAILED\"}", status = HttpStatusCode.BadRequest) return@post } - val staticResponse = MockAction.StaticResponse(status!!, parameters["body"].orEmpty(), headers) + val statusCode = action.statusCodeOrNull val rule = MockRule( id = id, @@ -1463,8 +1602,11 @@ fun Application.devConsoleModule( scheme = parameters["scheme"]?.lowercase()?.takeIf { it.isNotBlank() }, host = parameters["host"]?.takeIf { it.isNotBlank() }, path = parameters["path"]?.takeIf { it.isNotBlank() } ?: ".*", + queryPredicates = queryPredicates ?: existingRule?.queryPredicates.orEmpty(), + headerPredicates = headerPredicates ?: existingRule?.headerPredicates.orEmpty(), + bodyPredicate = parameters["bodyPredicate"] ?: existingRule?.bodyPredicate, scope = scope, - action = if (delayMs != null) MockAction.Delay(delayMs, staticResponse) else staticResponse, + action = action, // Set only by the mock-from-transaction flows; hand-authored rules never send this // field, and it is never written to disk (MockEngine strips it before persisting). // The dashboard omits this param when editing a rule whose snapshot was reported @@ -1477,7 +1619,13 @@ fun Application.devConsoleModule( // defaults to null. sourceBodySnapshot = parameters["sourceBodySnapshot"]?.takeIf { it.isNotBlank() } - ?: mockEngine.rules().firstOrNull { it.id == id }?.sourceBodySnapshot, + ?: existingRule?.sourceBodySnapshot, + ).withPersistence( + existingRule?.persistence?.let { persistence -> + persistence.copy(enabled = requestedEnabled ?: persistence.enabled) + } ?: io.devconsole.mocks.MockRulePersistence( + enabled = requestedEnabled ?: true, + ), ) runCatching { mockEngine.upsert(rule) }.onFailure { commandAuditLog.recordControlFailure(session.id, "mock.rule.upsert", id) @@ -1490,11 +1638,11 @@ fun Application.devConsoleModule( id, mapOf( "scope" to scope.name, - "status" to status.toString(), + "status" to (statusCode?.toString() ?: "-"), ), ) call.respondText( - "{\"id\":\"${id.escapeJson()}\",\"statusCode\":$status}", + "{\"id\":\"${id.escapeJson()}\",\"statusCode\":${statusCode ?: "null"}}", contentType = io.ktor.http.ContentType.Application.Json, status = HttpStatusCode.Created, ) @@ -1515,8 +1663,7 @@ fun Application.devConsoleModule( return@post } val enabled = - call - .receiveText() + (call.receiveTextWithin(MAX_DEFAULT_REQUEST_BODY_BYTES) ?: return@post) .trim() .trim('"') .toBooleanStrictOrNull() @@ -1598,7 +1745,189 @@ fun Application.devConsoleModule( return@get } val providers = remoteConfigSnapshots().joinToString(",") { it.json() } - call.respondText("{\"data\":[$providers]}", contentType = io.ktor.http.ContentType.Application.Json) + val overridesEditable = remoteConfigOverrides != null && featureFlagsEditable + call.respondText( + "{\"data\":[$providers],\"overridesEditable\":$overridesEditable}", + contentType = io.ktor.http.ContentType.Application.Json, + ) + } + delete("/api/v1/remote-config/overrides") { + val session = sessionAuthority.bearerSession(call.request.headers[HttpHeaders.Authorization]) + if (session == null) { + call.respondText("{\"code\":\"AUTH_REQUIRED\"}", status = HttpStatusCode.Unauthorized) + return@delete + } + if (!call.isOriginAndCsrfAuthorized(sessionAuthority)) { + commandAuditLog.recordControlFailure(session.id, "remoteConfig.clearAllOverrides", "remoteConfig") + call.respondText("{\"code\":\"CSRF_INVALID\"}", status = HttpStatusCode.Forbidden) + return@delete + } + if (!categoryEnabled("state")) { + commandAuditLog.recordControlFailure(session.id, "remoteConfig.clearAllOverrides", "remoteConfig") + call.respondCategoryDisabled("state") + return@delete + } + if (!featureFlagsEditable) { + commandAuditLog.recordControlFailure(session.id, "remoteConfig.clearAllOverrides", "remoteConfig") + call.respondText( + "{\"code\":\"REMOTE_CONFIG_OVERRIDES_DISABLED\"}", + status = HttpStatusCode.Forbidden, + ) + return@delete + } + val store = remoteConfigOverrides + if (store == null) { + commandAuditLog.recordControlFailure(session.id, "remoteConfig.clearAllOverrides", "remoteConfig") + call.respondText( + "{\"code\":\"REMOTE_CONFIG_OVERRIDES_UNAVAILABLE\"}", + status = HttpStatusCode.ServiceUnavailable, + ) + return@delete + } + store.clearAll() + commandAuditLog.record( + CommandAuditEvent( + timestampEpochMs = System.currentTimeMillis(), + browserSessionId = session.id, + commandType = "remoteConfig.clearAllOverrides", + target = "remoteConfig", + result = CommandAuditResult.SUCCESS, + ), + ) + call.respondText("{\"status\":\"cleared\"}", contentType = io.ktor.http.ContentType.Application.Json) + } + put("/api/v1/remote-config/{provider}/overrides/{key}") { + val session = sessionAuthority.bearerSession(call.request.headers[HttpHeaders.Authorization]) + val provider = call.parameters["provider"].orEmpty() + val key = call.parameters["key"].orEmpty() + val target = "$provider/$key" + if (session == null) { + call.respondText("{\"code\":\"AUTH_REQUIRED\"}", status = HttpStatusCode.Unauthorized) + return@put + } + if (!call.isOriginAndCsrfAuthorized(sessionAuthority)) { + commandAuditLog.recordControlFailure(session.id, "remoteConfig.override", target) + call.respondText("{\"code\":\"CSRF_INVALID\"}", status = HttpStatusCode.Forbidden) + return@put + } + if (!categoryEnabled("state")) { + commandAuditLog.recordControlFailure(session.id, "remoteConfig.override", target) + call.respondCategoryDisabled("state") + return@put + } + if (!featureFlagsEditable) { + commandAuditLog.recordControlFailure(session.id, "remoteConfig.override", target) + call.respondText( + "{\"code\":\"REMOTE_CONFIG_OVERRIDES_DISABLED\"}", + status = HttpStatusCode.Forbidden, + ) + return@put + } + val store = remoteConfigOverrides + if (store == null) { + commandAuditLog.recordControlFailure(session.id, "remoteConfig.override", target) + call.respondText( + "{\"code\":\"REMOTE_CONFIG_OVERRIDES_UNAVAILABLE\"}", + status = HttpStatusCode.ServiceUnavailable, + ) + return@put + } + val knownProviders = remoteConfigSnapshots().map { it.providerId } + if (provider !in knownProviders) { + commandAuditLog.recordControlFailure(session.id, "remoteConfig.override", target) + call.respondText( + "{\"code\":\"REMOTE_CONFIG_PROVIDER_NOT_FOUND\"}", + status = HttpStatusCode.NotFound, + ) + return@put + } + val rawValue = call.receiveParametersWithin(MAX_DEFAULT_REQUEST_BODY_BYTES)["value"] + if (rawValue == null) { + commandAuditLog.recordControlFailure(session.id, "remoteConfig.override", target) + call.respondText("{\"code\":\"VALIDATION_FAILED\"}", status = HttpStatusCode.BadRequest) + return@put + } + val replaced = store.overrides()[provider]?.containsKey(key) == true + val setSuccess = runCatching { store.setOverride(provider, key, rawValue) }.isSuccess + if (!setSuccess) { + commandAuditLog.recordControlFailure(session.id, "remoteConfig.override", target) + call.respondText("{\"code\":\"VALIDATION_FAILED\"}", status = HttpStatusCode.BadRequest) + return@put + } + // Values are never audited: config keys are snake_case, which header-shaped redaction + // lists miss, so a secret override would land in the log. Size and replace-vs-new suffice. + commandAuditLog.record( + CommandAuditEvent( + timestampEpochMs = System.currentTimeMillis(), + browserSessionId = session.id, + commandType = "remoteConfig.override", + target = target, + result = CommandAuditResult.SUCCESS, + parameters = + mapOf( + "valueLength" to rawValue.length.toString(), + "replaced" to replaced.toString(), + ), + ), + ) + call.respondText("{\"status\":\"updated\"}", contentType = io.ktor.http.ContentType.Application.Json) + } + delete("/api/v1/remote-config/{provider}/overrides/{key}") { + val session = sessionAuthority.bearerSession(call.request.headers[HttpHeaders.Authorization]) + val provider = call.parameters["provider"].orEmpty() + val key = call.parameters["key"].orEmpty() + val target = "$provider/$key" + if (session == null) { + call.respondText("{\"code\":\"AUTH_REQUIRED\"}", status = HttpStatusCode.Unauthorized) + return@delete + } + if (!call.isOriginAndCsrfAuthorized(sessionAuthority)) { + commandAuditLog.recordControlFailure(session.id, "remoteConfig.clearOverride", target) + call.respondText("{\"code\":\"CSRF_INVALID\"}", status = HttpStatusCode.Forbidden) + return@delete + } + if (!categoryEnabled("state")) { + commandAuditLog.recordControlFailure(session.id, "remoteConfig.clearOverride", target) + call.respondCategoryDisabled("state") + return@delete + } + if (!featureFlagsEditable) { + commandAuditLog.recordControlFailure(session.id, "remoteConfig.clearOverride", target) + call.respondText( + "{\"code\":\"REMOTE_CONFIG_OVERRIDES_DISABLED\"}", + status = HttpStatusCode.Forbidden, + ) + return@delete + } + val store = remoteConfigOverrides + if (store == null) { + commandAuditLog.recordControlFailure(session.id, "remoteConfig.clearOverride", target) + call.respondText( + "{\"code\":\"REMOTE_CONFIG_OVERRIDES_UNAVAILABLE\"}", + status = HttpStatusCode.ServiceUnavailable, + ) + return@delete + } + val knownProviders = remoteConfigSnapshots().map { it.providerId } + if (provider !in knownProviders) { + commandAuditLog.recordControlFailure(session.id, "remoteConfig.clearOverride", target) + call.respondText( + "{\"code\":\"REMOTE_CONFIG_PROVIDER_NOT_FOUND\"}", + status = HttpStatusCode.NotFound, + ) + return@delete + } + store.clearOverride(provider, key) + commandAuditLog.record( + CommandAuditEvent( + timestampEpochMs = System.currentTimeMillis(), + browserSessionId = session.id, + commandType = "remoteConfig.clearOverride", + target = target, + result = CommandAuditResult.SUCCESS, + ), + ) + call.respondText("{\"status\":\"cleared\"}", contentType = io.ktor.http.ContentType.Application.Json) } post("/api/v1/flags/{key}") { val session = sessionAuthority.bearerSession(call.request.headers[HttpHeaders.Authorization]) @@ -1627,7 +1956,7 @@ fun Application.devConsoleModule( } // Accepts a bare value, so "true" still works and "staging" now does too. Quotes are // tolerated because a browser posting JSON is the common case. - val value = call.receiveText().trim().trim('"') + val value = (call.receiveTextWithin(MAX_DEFAULT_REQUEST_BODY_BYTES) ?: return@post).trim().trim('"') val previousValue = featureFlags.value(key) val changed = runCatching { featureFlags.override(key, value) }.isSuccess if (!changed) { @@ -1657,6 +1986,122 @@ fun Application.devConsoleModule( timeline.appendFlagOverride(session.id, key, redactedBefore, redactedAfter) call.respondText("{\"status\":\"updated\"}", contentType = io.ktor.http.ContentType.Application.Json) } + get("/api/v1/capture") { + if (sessionAuthority.bearerSession(call.request.headers[HttpHeaders.Authorization]) == + null + ) { + call.respondText("{\"code\":\"AUTH_REQUIRED\"}", status = HttpStatusCode.Unauthorized) + return@get + } + val control = captureControl + call.respondText( + "{\"paused\":${control?.isPaused() ?: false},\"available\":${control != null}}", + contentType = io.ktor.http.ContentType.Application.Json, + ) + } + post("/api/v1/capture/paused") { + val session = sessionAuthority.bearerSession(call.request.headers[HttpHeaders.Authorization]) + if (session == null) { + call.respondText("{\"code\":\"AUTH_REQUIRED\"}", status = HttpStatusCode.Unauthorized) + return@post + } + if (!call.isOriginAndCsrfAuthorized(sessionAuthority)) { + commandAuditLog.recordControlFailure(session.id, "capture.pause", "capture") + call.respondText("{\"code\":\"CSRF_INVALID\"}", status = HttpStatusCode.Forbidden) + return@post + } + val control = captureControl + if (control == null) { + commandAuditLog.recordControlFailure(session.id, "capture.pause", "capture") + call.respondText( + "{\"code\":\"CAPTURE_CONTROL_UNAVAILABLE\"}", + status = HttpStatusCode.ServiceUnavailable, + ) + return@post + } + // Accepts plain or quoted booleans, since a browser posting JSON is the common case. + val requested = + (call.receiveTextWithin(MAX_DEFAULT_REQUEST_BODY_BYTES) ?: return@post).trim().trim('"') + val paused = + when (requested) { + "true" -> true + "false" -> false + else -> null + } + if (paused == null) { + commandAuditLog.recordControlFailure(session.id, "capture.pause", "capture") + call.respondText("{\"code\":\"VALIDATION_FAILED\"}", status = HttpStatusCode.BadRequest) + return@post + } + val commandType = if (paused) "capture.pause" else "capture.resume" + if (!control.setPaused(paused)) { + commandAuditLog.recordControlFailure(session.id, commandType, "capture") + call.respondText( + "{\"code\":\"CAPTURE_CONTROL_UNAVAILABLE\"}", + status = HttpStatusCode.ServiceUnavailable, + ) + return@post + } + commandAuditLog.record( + CommandAuditEvent( + timestampEpochMs = System.currentTimeMillis(), + browserSessionId = session.id, + commandType = commandType, + target = "capture", + result = CommandAuditResult.SUCCESS, + parameters = mapOf("paused" to paused.toString()), + ), + ) + call.respondText( + "{\"paused\":${control.isPaused()}}", + contentType = io.ktor.http.ContentType.Application.Json, + ) + } + post("/api/v1/capture/purge") { + val session = sessionAuthority.bearerSession(call.request.headers[HttpHeaders.Authorization]) + if (session == null) { + call.respondText("{\"code\":\"AUTH_REQUIRED\"}", status = HttpStatusCode.Unauthorized) + return@post + } + if (!call.isOriginAndCsrfAuthorized(sessionAuthority)) { + commandAuditLog.recordControlFailure(session.id, "capture.purge", "capture") + call.respondText("{\"code\":\"CSRF_INVALID\"}", status = HttpStatusCode.Forbidden) + return@post + } + val control = captureControl + if (control == null) { + commandAuditLog.recordControlFailure(session.id, "capture.purge", "capture") + call.respondText( + "{\"code\":\"CAPTURE_CONTROL_UNAVAILABLE\"}", + status = HttpStatusCode.ServiceUnavailable, + ) + return@post + } + val summary = control.purge() + commandAuditLog.record( + CommandAuditEvent( + timestampEpochMs = System.currentTimeMillis(), + browserSessionId = session.id, + commandType = "capture.purge", + target = "capture", + result = CommandAuditResult.SUCCESS, + parameters = + mapOf( + "networkTransactions" to summary.networkTransactions.toString(), + "socketConnections" to summary.socketConnections.toString(), + "pushEvents" to summary.pushEvents.toString(), + "retainedRunsDeleted" to summary.retainedRunsDeleted.toString(), + ), + ), + ) + call.respondText( + "{\"networkTransactions\":${summary.networkTransactions}," + + "\"socketConnections\":${summary.socketConnections}," + + "\"pushEvents\":${summary.pushEvents}," + + "\"retainedRunsDeleted\":${summary.retainedRunsDeleted}}", + contentType = io.ktor.http.ContentType.Application.Json, + ) + } get("/api/v1/capture-rules") { if (sessionAuthority.bearerSession(call.request.headers[HttpHeaders.Authorization]) == null @@ -1689,7 +2134,7 @@ fun Application.devConsoleModule( call.respondCategoryDisabled("mocks") return@post } - val parameters = call.receiveParameters() + val parameters = call.receiveParametersWithin(MAX_DEFAULT_REQUEST_BODY_BYTES) val id = parameters["id"].orEmpty() val rule = runCatching { @@ -1734,8 +2179,7 @@ fun Application.devConsoleModule( return@post } val enabled = - call - .receiveText() + (call.receiveTextWithin(MAX_DEFAULT_REQUEST_BODY_BYTES) ?: return@post) .trim() .trim('"') .toBooleanStrictOrNull() @@ -1792,7 +2236,10 @@ fun Application.devConsoleModule( call.respondText("{\"code\":\"EVIDENCE_UNAVAILABLE\"}", status = HttpStatusCode.ServiceUnavailable) return@get } - val sessionId = currentSessionId() + // Read-only `?sessionId=` reaches a previous run's tray, kept in Room across restarts; + // every mutation route below stays scoped to the current run. + val sessionId = + call.request.queryParameters["sessionId"]?.takeIf(String::isNotBlank) ?: currentSessionId() val items = store.items(sessionId) val report = store.report(sessionId) // Bounded independently of the store's own quota (see MAX_EVIDENCE_ITEMS_PER_RESPONSE): @@ -1832,7 +2279,7 @@ fun Application.devConsoleModule( call.respondText("{\"code\":\"EVIDENCE_UNAVAILABLE\"}", status = HttpStatusCode.ServiceUnavailable) return@post } - val parameters = call.receiveParameters() + val parameters = call.receiveParametersWithin(MAX_DEFAULT_REQUEST_BODY_BYTES) val kind = parameters["kind"]?.let { raw -> runCatching { EvidenceKind.valueOf(raw.uppercase()) }.getOrNull() } val subjectId = parameters["id"].orEmpty() @@ -1954,7 +2401,7 @@ fun Application.devConsoleModule( call.respondText("{\"code\":\"EVIDENCE_UNAVAILABLE\"}", status = HttpStatusCode.ServiceUnavailable) return@put } - val parameters = call.receiveParameters() + val parameters = call.receiveParametersWithin(MAX_DEFAULT_REQUEST_BODY_BYTES) val severityRaw = parameters["severity"] val severity = if (severityRaw == null) { @@ -2074,7 +2521,7 @@ fun Application.devConsoleModule( call.respondText("{\"code\":\"UNAVAILABLE\"}", status = HttpStatusCode.ServiceUnavailable) return@post } - val parameters = call.receiveParameters() + val parameters = call.receiveParametersWithin(MAX_DEFAULT_REQUEST_BODY_BYTES) val key = parameters["key"].orEmpty() val value = parameters["value"].orEmpty() val type = parameters["type"].orEmpty() @@ -2223,7 +2670,7 @@ fun Application.devConsoleModule( return@post } val inspector = databaseInspector - val sql = call.receiveParameters()["sql"].orEmpty() + val sql = call.receiveParametersWithin(MAX_DEFAULT_REQUEST_BODY_BYTES)["sql"].orEmpty() if (inspector == null || sql.isBlank() || sql.length > MAX_SQL_INPUT_BYTES) { commandAuditLog.recordControlFailure(session.id, "database.sql.execute", database) call.respondText("{\"code\":\"VALIDATION_FAILED\"}", status = HttpStatusCode.BadRequest) @@ -2382,7 +2829,7 @@ fun Application.devConsoleModule( call.respondCategoryDisabled("inspection") return@put } - val parameters = call.receiveParameters() + val parameters = call.receiveParametersWithin(MAX_DEFAULT_REQUEST_BODY_BYTES) val relativePath = parameters["path"].orEmpty() val content = parameters["content"].orEmpty() val inspector = fileInspector @@ -2415,7 +2862,7 @@ fun Application.devConsoleModule( call.respondCategoryDisabled("inspection") return@post } - val parameters = call.receiveParameters() + val parameters = call.receiveParametersWithin(MAX_DEFAULT_REQUEST_BODY_BYTES) val relativePath = parameters["path"].orEmpty() val newRelativePath = parameters["newPath"].orEmpty() val inspector = fileInspector @@ -2448,7 +2895,7 @@ fun Application.devConsoleModule( call.respondCategoryDisabled("inspection") return@post } - val parameters = call.receiveParameters() + val parameters = call.receiveParametersWithin(MAX_DEFAULT_REQUEST_BODY_BYTES) val relativePath = parameters["path"].orEmpty() val content = parameters["content"].orEmpty() val inspector = fileInspector @@ -2572,11 +3019,11 @@ fun Application.devConsoleModule( commandType = "composer.execute", target = "request", ) ?: return@post - val parameters = call.receiveParameters() + val parameters = call.receiveParametersWithin(MAX_COMPOSER_BODY_BYTES) val request = parameters.toComposerRequestOrNull() val method = request?.method.orEmpty() val url = request?.url.orEmpty() - if (request == null || method !in COMPOSER_METHODS || !url.isHttpUrl()) { + if (request == null || method !in COMPOSER_METHODS) { commandAuditLog.recordControlFailure( session.id, "composer.execute", @@ -2585,11 +3032,6 @@ fun Application.devConsoleModule( call.respondText("{\"code\":\"VALIDATION_FAILED\"}", status = HttpStatusCode.BadRequest) return@post } - if (!composerHosts.permitsHostOf(url)) { - commandAuditLog.recordControlFailure(session.id, "composer.execute", url.hostOrEmpty()) - call.respondText("{\"code\":\"COMPOSER_HOST_REJECTED\"}", status = HttpStatusCode.Forbidden) - return@post - } val executor = parameters["executor"].orEmpty().ifBlank { COMPOSER_EXECUTOR_DEVICE } val agent = composerAgents.findByExecutor(executor) if (executor != COMPOSER_EXECUTOR_DEVICE && agent == null) { @@ -2610,6 +3052,16 @@ fun Application.devConsoleModule( call.respondText("{\"code\":\"VALIDATION_FAILED\"}", status = HttpStatusCode.BadRequest) return@post } + if (!resolvedRequest.url.isHttpUrl()) { + commandAuditLog.recordControlFailure(session.id, "composer.execute", "request") + call.respondText("{\"code\":\"VALIDATION_FAILED\"}", status = HttpStatusCode.BadRequest) + return@post + } + if (!composerHosts.permitsHostOf(resolvedRequest.url)) { + commandAuditLog.recordControlFailure(session.id, "composer.execute", resolvedRequest.url.hostOrEmpty()) + call.respondText("{\"code\":\"COMPOSER_HOST_REJECTED\"}", status = HttpStatusCode.Forbidden) + return@post + } val execution = try { val selectedExecutor = @@ -2772,7 +3224,7 @@ fun Application.devConsoleModule( call.respondText("{\"code\":\"COMPOSER_HOSTS_READ_ONLY\"}", status = HttpStatusCode.Forbidden) return@post } - val requested = call.receiveParameters()["host"].orEmpty() + val requested = call.receiveParametersWithin(MAX_DEFAULT_REQUEST_BODY_BYTES)["host"].orEmpty() when (val result = composerHosts.add(requested)) { is ComposerHostAllowlist.AddResult.Added -> { commandAuditLog.recordControlSuccess(session.id, "composer.host.add", result.host) @@ -2919,7 +3371,7 @@ fun Application.devConsoleModule( call.respondText("{\"code\":\"CSRF_INVALID\"}", status = HttpStatusCode.Forbidden) return@post } - val command = call.receiveText() + val command = call.receiveTextWithin(MAX_DEFAULT_REQUEST_BODY_BYTES) ?: return@post val request = ComposerCurlImporter.import(command).getOrNull() if (request == null) { commandAuditLog.recordControlFailure(session.id, "composer.import", "curl") @@ -2951,7 +3403,7 @@ fun Application.devConsoleModule( call.respondText("{\"code\":\"CSRF_INVALID\"}", status = HttpStatusCode.Forbidden) return@post } - val parameters = call.receiveParameters() + val parameters = call.receiveParametersWithin(MAX_DEFAULT_REQUEST_BODY_BYTES) val request = ComposerCurlImporter.import(parameters["curl"].orEmpty()).getOrNull() val name = parameters["name"].orEmpty() if (request == null || name.isBlank()) { @@ -3059,7 +3511,7 @@ fun Application.devConsoleModule( call.respondText("{\"code\":\"PUSH_SIMULATION_UNAVAILABLE\"}", status = HttpStatusCode.Conflict) return@post } - val parameters = call.receiveParameters() + val parameters = call.receiveParametersWithin(MAX_DEFAULT_REQUEST_BODY_BYTES) val data = parameters.names().filter { it.startsWith("data.") }.associate { name -> name.removePrefix("data.") to @@ -3164,16 +3616,7 @@ fun Application.devConsoleModule( call.respondCategoryDisabled("state") return@post } - val input = call.receiveText() - if (input.length > MAX_STATE_MUTATION_INPUT_BYTES) { - commandAuditLog.recordControlFailure( - session.id, - "state.mutation", - "${call.parameters["id"]}.${call.parameters["command"]}", - ) - call.respondText("{\"code\":\"VALIDATION_FAILED\"}", status = HttpStatusCode.BadRequest) - return@post - } + val input = call.receiveTextWithin(MAX_STATE_MUTATION_INPUT_BYTES) ?: return@post val providerId = call.parameters["id"].orEmpty() val commandId = call.parameters["command"].orEmpty() when (val result = stateRegistry.mutate(providerId, commandId, input)) { @@ -3208,7 +3651,7 @@ fun Application.devConsoleModule( socketStore .connections() .filter { protocolFilter == null || it.protocol == protocolFilter } - .joinToString(",") { it.summaryJson() } + .joinToString(",") { it.summaryJson(socketSenders) } call.respondText( "{\"schemaVersion\":1,\"data\":[$connections]}", contentType = io.ktor.http.ContentType.Application.Json, @@ -3229,10 +3672,88 @@ fun Application.devConsoleModule( return@get } call.respondText( - "{\"schemaVersion\":1,\"data\":${connection.detailJson()}}", + "{\"schemaVersion\":1,\"data\":${connection.detailJson(socketSenders)}}", contentType = io.ktor.http.ContentType.Application.Json, ) } + // Sends one host-originated frame over a live connection. Gated like every other command + // route: bearer session, origin/CSRF, the socket/mqtt capture categories, and the same + // request-execution capability Composer and Network resend share -- a browser may not make + // the device write on a socket it can otherwise only observe when the host disabled that. + post("/api/v1/websockets/connections/{id}/send") { + val session = sessionAuthority.bearerSession(call.request.headers[HttpHeaders.Authorization]) + val connectionId = call.parameters["id"].orEmpty() + val auditTarget = connectionId.ifBlank { "connection" } + if (session == null) { + call.respondText("{\"code\":\"AUTH_REQUIRED\"}", status = HttpStatusCode.Unauthorized) + return@post + } + if (!call.isOriginAndCsrfAuthorized(sessionAuthority)) { + commandAuditLog.recordControlFailure(session.id, SOCKET_SEND_COMMAND, auditTarget) + call.respondText("{\"code\":\"CSRF_INVALID\"}", status = HttpStatusCode.Forbidden) + return@post + } + if (!categoryEnabled("socket") && !categoryEnabled("mqtt")) { + commandAuditLog.recordControlFailure(session.id, SOCKET_SEND_COMMAND, auditTarget) + call.respondCategoryDisabled("socket") + return@post + } + if (!composerEnabled) { + commandAuditLog.recordControlFailure(session.id, SOCKET_SEND_COMMAND, auditTarget) + call.respondText("{\"code\":\"SOCKET_SEND_DISABLED\"}", status = HttpStatusCode.Forbidden) + return@post + } + val senders = socketSenders + if (senders == null) { + commandAuditLog.recordControlFailure(session.id, SOCKET_SEND_COMMAND, auditTarget) + call.respondText("{\"code\":\"SEND_UNSUPPORTED\"}", status = HttpStatusCode.ServiceUnavailable) + return@post + } + // Form-encoded like the other command routes: text, and for MQTT topic/qos/retained. + val form = call.receiveParametersWithin(MAX_DEFAULT_REQUEST_BODY_BYTES) + val request = form.toSocketSendRequest() + if (request == null) { + commandAuditLog.recordControlFailure(session.id, SOCKET_SEND_COMMAND, auditTarget) + call.respondText("{\"code\":\"VALIDATION_FAILED\"}", status = HttpStatusCode.BadRequest) + return@post + } + val text = request.text + when (val result = senders.send(connectionId, request)) { + SocketSendResult.Sent -> { + // Only the frame's size and topic are audited; the frame text itself never is. + commandAuditLog.record( + CommandAuditEvent( + timestampEpochMs = System.currentTimeMillis(), + browserSessionId = session.id, + commandType = SOCKET_SEND_COMMAND, + target = auditTarget, + result = CommandAuditResult.SUCCESS, + parameters = + mapOf( + "bytes" to text.encodeToByteArray().size.toString(), + "topic" to request.topic.orEmpty(), + ), + ), + ) + call.respondText("{\"status\":\"sent\"}", contentType = io.ktor.http.ContentType.Application.Json) + } + SocketSendResult.NotConnected -> { + commandAuditLog.recordControlFailure(session.id, SOCKET_SEND_COMMAND, auditTarget) + call.respondText("{\"code\":\"NOT_CONNECTED\"}", status = HttpStatusCode.Conflict) + } + is SocketSendResult.Rejected -> { + commandAuditLog.recordControlFailure(session.id, SOCKET_SEND_COMMAND, auditTarget) + call.respondText( + "{\"code\":\"SEND_REJECTED\",\"message\":\"${result.reason.escapeJson()}\"}", + status = HttpStatusCode.BadRequest, + ) + } + SocketSendResult.Unsupported -> { + commandAuditLog.recordControlFailure(session.id, SOCKET_SEND_COMMAND, auditTarget) + call.respondText("{\"code\":\"SEND_UNSUPPORTED\"}", status = HttpStatusCode.ServiceUnavailable) + } + } + } get("/api/v1/websockets/messages") { if (sessionAuthority.bearerSession(call.request.headers[HttpHeaders.Authorization]) == null) { call.respondText("{\"code\":\"AUTH_REQUIRED\"}", status = HttpStatusCode.Unauthorized) @@ -3269,7 +3790,8 @@ fun Application.devConsoleModule( call.respondCategoryDisabled("network") return@get } - val transaction = networkTransactions.find(call.parameters["id"].orEmpty()) + val store = call.networkStoreForRequestedSession() ?: return@get + val transaction = store.find(call.parameters["id"].orEmpty()) if (transaction == null) { call.respondText("{\"code\":\"NOT_FOUND\"}", status = HttpStatusCode.NotFound) return@get @@ -3357,7 +3879,8 @@ fun Application.devConsoleModule( call.respondCategoryDisabled("network") return@get } - val transaction = networkTransactions.find(call.parameters["id"].orEmpty()) + val store = call.networkStoreForRequestedSession() ?: return@get + val transaction = store.find(call.parameters["id"].orEmpty()) if (transaction == null) { call.respondText("{\"code\":\"NOT_FOUND\"}", status = HttpStatusCode.NotFound) return@get @@ -3427,10 +3950,9 @@ fun Application.devConsoleModule( } val execution = try { - composerExecutor.execute( - request, - composerHosts::permitsHostOf, - ) + withContext(Dispatchers.IO) { + composerExecutor.execute(request, composerHosts::permitsHostOf) + } } catch (rejected: io.devconsole.composer.ComposerDestinationRejectedException) { recordComposerCapture( request = resolvedRequest, @@ -3504,7 +4026,8 @@ fun Application.devConsoleModule( call.respondCategoryDisabled("network") return@get } - val resolution = call.resolveNetworkExportTransactions(networkTransactions) ?: return@get + val store = call.networkStoreForRequestedSession() ?: return@get + val resolution = call.resolveNetworkExportTransactions(store) ?: return@get call.applyExportTruncationHeaders(resolution) call.respondText( NetworkExport.toHarTransactions(resolution.transactions, redaction), @@ -3522,7 +4045,8 @@ fun Application.devConsoleModule( call.respondCategoryDisabled("network") return@get } - val resolution = call.resolveNetworkExportTransactions(networkTransactions) ?: return@get + val store = call.networkStoreForRequestedSession() ?: return@get + val resolution = call.resolveNetworkExportTransactions(store) ?: return@get call.applyExportTruncationHeaders(resolution) call.respondText( NetworkExport.toPostman(resolution.transactions, redaction), @@ -3540,8 +4064,9 @@ fun Application.devConsoleModule( // POST is what a same-origin-restricted browser would otherwise auto-CSRF. post("/api/v1/network/har") { val resolution = - call.authorizeNetworkExportPost(networkTransactions, sessionAuthority, commandAuditLog) - ?: return@post + call.authorizeNetworkExportPost(sessionAuthority, commandAuditLog) { + networkStoreForRequestedSession() + } ?: return@post if (!categoryEnabled("network")) { call.respondCategoryDisabled("network") return@post @@ -3554,8 +4079,9 @@ fun Application.devConsoleModule( } post("/api/v1/network/postman") { val resolution = - call.authorizeNetworkExportPost(networkTransactions, sessionAuthority, commandAuditLog) - ?: return@post + call.authorizeNetworkExportPost(sessionAuthority, commandAuditLog) { + networkStoreForRequestedSession() + } ?: return@post if (!categoryEnabled("network")) { call.respondCategoryDisabled("network") return@post @@ -3602,7 +4128,7 @@ fun Application.devConsoleModule( ) return@put } - val note = call.receiveText() + val note = call.receiveTextWithin(MAX_STATE_MUTATION_INPUT_BYTES) ?: return@put val stored = runCatching { annotations.setNote(id, note) }.isSuccess if (!stored) { call.respondText("{\"code\":\"VALIDATION_FAILED\"}", status = HttpStatusCode.BadRequest) @@ -3672,15 +4198,28 @@ fun Application.devConsoleModule( close(CloseReason(CloseReason.Codes.CANNOT_ACCEPT.code, "HELLO_REQUIRED")) return@webSocket } + // Subscribe BEFORE the welcome: the hub has no replay, so an event published between the + // welcome and a later subscription was lost for good (and its sequence was already + // covered by currentSequence, so the client never backfilled it). Frames are held until + // the welcome is out, which keeps the welcome first; the hub buffers meanwhile. + val subscribed = CompletableDeferred() + val welcomeSent = CompletableDeferred() + val streamJob = + launch { + streamHub.events + .onSubscription { subscribed.complete(Unit) } + .collect { event -> + welcomeSent.await() + send(Frame.Text(event.toStreamMessage())) + } + } + subscribed.await() send( Frame.Text( "{\"type\":\"server.welcome\",\"protocolVersion\":1,\"currentSequence\":${streamHub.currentSequence},\"heartbeatSeconds\":20}", ), ) - val streamJob = - launch { - streamHub.events.collect { event -> send(Frame.Text(event.toStreamMessage())) } - } + welcomeSent.complete(Unit) try { while (isActive) { delay(STREAM_AUTH_RECHECK_MS) @@ -3720,6 +4259,11 @@ class KtorLocalServerEngine( private val stateRegistry: StateRegistry = StateRegistry(), /** Already-redacted Remote Config snapshots; see [DevConsoleModuleConfig.remoteConfigSnapshots]. */ private val remoteConfigSnapshots: () -> List = { emptyList() }, + /** Host-side capture pause/resume and purge; see [DevConsoleModuleConfig.captureControl]. */ + private val captureControl: CaptureControl? = null, + /** Host-side socket senders; see [DevConsoleModuleConfig.socketSenders]. */ + private val socketSenders: SocketSenderRegistry? = null, + private val remoteConfigOverrides: RemoteConfigOverrideStore? = null, featureFlags: SessionFeatureFlags = SessionFeatureFlags(emptyList()), featureFlagsEditable: Boolean = true, private val mockEngine: MockEngine = MockEngine(emptyList()), @@ -3799,6 +4343,33 @@ class KtorLocalServerEngine( retainedCaptures = query } + @Volatile + private var retainedNetworkTransactions: suspend (sessionId: String) -> NetworkTransactionStore? = { null } + + @Volatile + private var deleteRun: suspend (sessionId: String) -> Boolean = { false } + + @Volatile + private var pinRun: suspend (sessionId: String, pinned: Boolean) -> Boolean = { _, _ -> false } + + /** Backs `DELETE /api/v1/runs/{id}` and `POST /api/v1/runs/{id}/pin`. */ + fun withRunControls( + delete: suspend (sessionId: String) -> Boolean, + pin: suspend (sessionId: String, pinned: Boolean) -> Boolean, + ): KtorLocalServerEngine = + apply { + deleteRun = delete + pinRun = pin + } + + /** Serves `?sessionId=` on the network list, detail, cURL and HAR/Postman routes. */ + fun withRetainedNetworkTransactions( + provider: suspend (sessionId: String) -> NetworkTransactionStore?, + ): KtorLocalServerEngine = + apply { + retainedNetworkTransactions = provider + } + /** Sets the browser authentication policy used by the next server start. */ fun withBrowserSecurity(value: BrowserSecurity): KtorLocalServerEngine = apply { @@ -3923,60 +4494,80 @@ class KtorLocalServerEngine( val security = browserSecurity val candidate = runCatching { - serverScope - .embeddedServer( - CIO, - host = endpoint.host, - port = endpoint.port, - parentCoroutineContext = asyncBindFailureHandler, - ) { - devConsoleModule(sessionAuthority, sessionCodeAuthority) { - allowedHosts = setOf("localhost", endpoint.host) - browserSecurity = security - this.networkTransactions = this@KtorLocalServerEngine.networkTransactions - 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 - this.mocksEditable = configuration.mocksEditable - this.captureRules = this@KtorLocalServerEngine.captureRules - this.captureRulesEditable = configuration.captureRulesEditable - this.preferencesInspector = this@KtorLocalServerEngine.preferencesInspector - this.preferencesEditable = configuration.preferencesEditable - this.databaseInspector = this@KtorLocalServerEngine.databaseInspector - this.databaseEditable = configuration.databaseEditable - this.fileInspector = this@KtorLocalServerEngine.fileInspector - this.filesEditable = configuration.filesEditable - this.timeline = this@KtorLocalServerEngine.timeline - this.metadata = this@KtorLocalServerEngine.metadata() - this.sdkHealth = this@KtorLocalServerEngine.sdkHealth - this.streamHub = this@KtorLocalServerEngine.streamHub - this.annotations = this@KtorLocalServerEngine.annotations - this.stateMutationsEnabled = configuration.stateMutationsEnabled - this.composerEnabled = configuration.composerEnabled - this.composerAllowedHosts = configuration.composerAllowedHosts - this.composerHostsEditable = configuration.composerHostsEditable - this.sharedComposerHosts = composerHosts - this.composerExecutor = this@KtorLocalServerEngine.composerExecutor - this.composerCollections = this@KtorLocalServerEngine.composerCollections - this.pushSimulator = this@KtorLocalServerEngine.pushSimulator - this.commandAuditLog = this@KtorLocalServerEngine.commandAuditLog - this.redactionPolicy = configuration.redactionPolicy - this.networkProtection = this@KtorLocalServerEngine.networkProtection - this.attachmentReader = this@KtorLocalServerEngine.attachmentReader - this.attachmentMetadataReader = this@KtorLocalServerEngine.attachmentMetadataReader - this.retainedCaptures = this@KtorLocalServerEngine.retainedCaptures - this.evidenceStore = this@KtorLocalServerEngine.evidenceStore - this.currentSessionId = this@KtorLocalServerEngine.currentSessionId - this.sessionSnapshotProvider = this@KtorLocalServerEngine.sessionSnapshotProvider - this.sessionsProvider = this@KtorLocalServerEngine.sessionsProvider - this.screenshotCapture = this@KtorLocalServerEngine.screenshotCapture - boundEndpoint = { currentEndpoint } + embeddedServer( + CIO, + serverConfig { + // Same parent the CoroutineScope overload builds; that overload has no + // engine `configure`, which reuseAddress below needs. + parentCoroutineContext = serverScope.coroutineContext + asyncBindFailureHandler + module { + devConsoleModule(sessionAuthority, sessionCodeAuthority) { + allowedHosts = setOf("localhost", endpoint.host) + browserSecurity = security + this.networkTransactions = this@KtorLocalServerEngine.networkTransactions + this.socketStore = this@KtorLocalServerEngine.socketStore + this.pushStore = this@KtorLocalServerEngine.pushStore + this.stateRegistry = this@KtorLocalServerEngine.stateRegistry + this.remoteConfigSnapshots = this@KtorLocalServerEngine.remoteConfigSnapshots + this.captureControl = this@KtorLocalServerEngine.captureControl + this.socketSenders = this@KtorLocalServerEngine.socketSenders + this.remoteConfigOverrides = this@KtorLocalServerEngine.remoteConfigOverrides + this.featureFlags = configuration.featureFlags + this.featureFlagsEditable = configuration.featureFlagsEditable + this.mockEngine = this@KtorLocalServerEngine.mockEngine + this.mocksEditable = configuration.mocksEditable + this.captureRules = this@KtorLocalServerEngine.captureRules + this.captureRulesEditable = configuration.captureRulesEditable + this.preferencesInspector = this@KtorLocalServerEngine.preferencesInspector + this.preferencesEditable = configuration.preferencesEditable + this.databaseInspector = this@KtorLocalServerEngine.databaseInspector + this.databaseEditable = configuration.databaseEditable + this.fileInspector = this@KtorLocalServerEngine.fileInspector + this.filesEditable = configuration.filesEditable + this.timeline = this@KtorLocalServerEngine.timeline + this.metadata = this@KtorLocalServerEngine.metadata() + this.sdkHealth = this@KtorLocalServerEngine.sdkHealth + this.streamHub = this@KtorLocalServerEngine.streamHub + this.annotations = this@KtorLocalServerEngine.annotations + this.stateMutationsEnabled = configuration.stateMutationsEnabled + this.composerEnabled = configuration.composerEnabled + this.composerAllowedHosts = configuration.composerAllowedHosts + this.composerHostsEditable = configuration.composerHostsEditable + this.sharedComposerHosts = composerHosts + this.composerExecutor = this@KtorLocalServerEngine.composerExecutor + this.composerCollections = this@KtorLocalServerEngine.composerCollections + this.pushSimulator = this@KtorLocalServerEngine.pushSimulator + this.commandAuditLog = this@KtorLocalServerEngine.commandAuditLog + this.redactionPolicy = configuration.redactionPolicy + this.networkProtection = this@KtorLocalServerEngine.networkProtection + this.attachmentReader = this@KtorLocalServerEngine.attachmentReader + this.attachmentMetadataReader = + this@KtorLocalServerEngine.attachmentMetadataReader + this.retainedCaptures = this@KtorLocalServerEngine.retainedCaptures + this.retainedNetworkTransactions = + this@KtorLocalServerEngine.retainedNetworkTransactions + this.evidenceStore = this@KtorLocalServerEngine.evidenceStore + this.currentSessionId = this@KtorLocalServerEngine.currentSessionId + this.sessionSnapshotProvider = + this@KtorLocalServerEngine.sessionSnapshotProvider + this.sessionsProvider = this@KtorLocalServerEngine.sessionsProvider + this.deleteRun = this@KtorLocalServerEngine.deleteRun + this.pinRun = this@KtorLocalServerEngine.pinRun + this.screenshotCapture = this@KtorLocalServerEngine.screenshotCapture + boundEndpoint = { currentEndpoint } + } } - }.start(wait = false) + }, + ) { + connector { + this.host = endpoint.host + this.port = endpoint.port + } + // Lets a restarted app rebind its usual port while the previous process's + // dashboard connections linger in TIME_WAIT, instead of drifting to the next + // port and stranding every open tab. A live listener still blocks the bind. + reuseAddress = true + }.start(wait = false) }.getOrNull() ?: return@forEach if (!isServerBound(endpoint.host, endpoint.port)) { @@ -4062,7 +4653,6 @@ private const val DEFAULT_RELATED_EVENT_WINDOW_MS = 1_000L private const val MAX_RELATED_EVENT_WINDOW_MS = 60_000L private val COMPOSER_METHODS = setOf("GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS") private val MOCK_RULE_ID = Regex("[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}") -private const val MOCK_RULE_MAX_DELAY_MS = 30_000L private const val MAX_MOCK_RULE_HEADERS = 50 /** @@ -4089,6 +4679,9 @@ private fun String?.parseMockRuleHeaders(): Map = .associate { it.splitComposerPair(':') } .onEach { (name, value) -> require(validMockHeader(name, value)) } +private fun parseMockPredicates(values: List?): Map? = + values?.map { it.splitComposerPair('=') }?.toMap() + private fun io.ktor.server.application.ApplicationCall.setStreamSessionCookie(token: String) { response.headers.append( HttpHeaders.SetCookie, @@ -4171,14 +4764,35 @@ private val asyncBindFailureHandler = CoroutineExceptionHandler { _, _ -> } private fun isPortAvailable( host: String, port: Int, +): Boolean = isPortBindable(host, port) && !acceptsConnections(host, port) + +/** + * Binds with SO_REUSEADDR, like the engine itself, so the previous process's TIME_WAIT leftovers do + * not count as "in use". That alone is not enough: BSD lets a specific-address bind sit beside a + * wildcard listener, hence the connect probe in [isPortAvailable]. + */ +private fun isPortBindable( + host: String, + port: Int, ): Boolean = runCatching { ServerSocket().use { socket -> - socket.reuseAddress = false + socket.reuseAddress = true socket.bind(InetSocketAddress(host, port)) } }.isSuccess +/** True when something is already accepting connections on [host]:[port]. */ +private fun acceptsConnections( + host: String, + port: Int, +): Boolean = + runCatching { + Socket().use { socket -> socket.connect(InetSocketAddress(host, port), PORT_PROBE_CONNECT_TIMEOUT_MS) } + }.isSuccess + +private const val PORT_PROBE_CONNECT_TIMEOUT_MS = 200 + /** Verifies that the asynchronous CIO engine bound successfully by probing the target port. */ private fun isServerBound( host: String, @@ -4267,7 +4881,13 @@ private data class ExportPreparation( val maxBytes: Long, val exportSessionId: String, val scopedEvents: List, - val attachments: Map, + val attachments: Map, +) + +private data class ExportSources( + val attachmentReader: suspend (String) -> ByteArray?, + val attachmentMetadataReader: suspend (String) -> StoredAttachment?, + val currentSessionId: () -> String, ) /** Shared by [prepareExport] and the `scope=EVIDENCE` branch of both export routes. */ @@ -4290,7 +4910,7 @@ private suspend fun prepareExport( parameters: Parameters, timeline: Timeline, retainedCaptures: RetainedCaptureQuery?, - attachmentReader: suspend (String) -> ByteArray?, + sources: ExportSources, ): ExportPreparation? { val scope = runCatching { @@ -4334,7 +4954,12 @@ private suspend fun prepareExport( .distinctBy(StoredEvent::id) .sortedWith(compareBy(StoredEvent::wallTimeMs).thenBy(StoredEvent::sequence)) .toList() - val exportSessionId = requestedSessionId ?: events.lastOrNull()?.sessionId ?: "current" + // Explicitly picked events name their own run; whole-session/time-range exports use the active + // run, never "whichever session the newest event happens to belong to" (Composer events). + val exportSessionId = + requestedSessionId + ?: (scope as? ExportScope.EventIds)?.let { picked -> events.firstOrNull { it.id in picked.ids }?.sessionId } + ?: sources.currentSessionId() val scopedEvents = when (scope) { ExportScope.WholeSession -> events @@ -4348,13 +4973,20 @@ private suspend fun prepareExport( if (metadataOnly) { emptyMap() } else { - buildMap { + buildMap { scopedEvents .mapNotNull(StoredEvent::attachmentId) .distinct() .forEach { attachmentId -> try { - attachmentReader(attachmentId)?.let { put(attachmentId, it) } + sources.attachmentMetadataReader(attachmentId)?.let { metadata -> + put( + attachmentId, + ExportAttachmentSource(metadata.storedLength, metadata.mimeType) { + attachmentId.readSafely(sources.attachmentReader)?.let(::ByteArrayInputStream) + }, + ) + } } catch (cancelled: kotlinx.coroutines.CancellationException) { throw cancelled } catch (_: Exception) { @@ -4457,6 +5089,37 @@ private fun String.commandAuditIdentity(method: String): Pair? = private const val MAX_SESSION_CODE_TTL_MS = 24L * 60 * 60 * 1000 private const val MAX_STATE_MUTATION_INPUT_BYTES = 64 * 1024 +private const val MAX_DEFAULT_REQUEST_BODY_BYTES = 1024 * 1024 +private const val SOCKET_SEND_COMMAND = "socket.send" + +private class RequestBodyTooLargeException : RuntimeException() + +/** Reads at most [maxBytes] plus one sentinel byte, so an untrusted body is never fully buffered. */ +private suspend fun io.ktor.server.application.ApplicationCall.receiveTextWithin(maxBytes: Int): String? { + val declaredLength = request.headers[HttpHeaders.ContentLength]?.toLongOrNull() + if (declaredLength != null && declaredLength > maxBytes) throw RequestBodyTooLargeException() + val packet = receiveChannel().readRemaining(maxBytes.toLong() + 1) + val bytes = packet.readByteArray() + if (bytes.size > maxBytes) throw RequestBodyTooLargeException() + return bytes.decodeToString() +} + +private suspend fun io.ktor.server.application.ApplicationCall.receiveParametersWithin(maxBytes: Int): Parameters { + // Same contract as receiveParameters(): a non-form body is the caller's mistake (400), not a 500. + val contentType = + request.headers[HttpHeaders.ContentType]?.let { + runCatching { + ContentType.parse( + it, + ) + }.getOrNull() + } + if (contentType != null && !contentType.match(ContentType.Application.FormUrlEncoded)) { + throw BadRequestException("Expected an application/x-www-form-urlencoded body") + } + return parseQueryString(receiveTextWithin(maxBytes) ?: throw RequestBodyTooLargeException()) +} + private const val MAX_SQL_INPUT_BYTES = 8 * 1024 private const val MAX_EXPORT_EVENTS = 50_000 private const val MAX_EXPORT_SESSION_ID_LENGTH = 256 @@ -4484,7 +5147,7 @@ private const val MAX_TIMELINE_SCAN_PAGES = 200 // an unbounded response at 120 req/min (see readQueryLimiter). private val MAX_EVIDENCE_ITEMS_PER_RESPONSE = EvidenceStore.MAX_ITEMS_PER_SESSION -private fun SessionAuthority.bearerSession(authorization: String?) = +internal fun SessionAuthority.bearerSession(authorization: String?) = if (!isBrowserAuthenticationRequired()) { openAccessSession() } else { @@ -4856,9 +5519,13 @@ private fun RemoteConfigSnapshot.json(): String { "\"entries\":[$rows]}" } -private fun RemoteConfigEntry.json(): String = - "{\"key\":\"${key.escapeJson()}\",\"value\":\"${value.escapeJson()}\"," + - "\"source\":\"${source.wireName}\",\"redacted\":$redacted,\"truncated\":$truncated}" +private fun RemoteConfigEntry.json(): String { + val providerValueJson = providerValue?.let { "\"${it.escapeJson()}\"" } ?: "null" + val providerSourceJson = providerSource?.wireName?.let { "\"${it.escapeJson()}\"" } ?: "null" + return "{\"key\":\"${key.escapeJson()}\",\"value\":\"${value.escapeJson()}\"," + + "\"source\":\"${source.wireName}\",\"redacted\":$redacted,\"truncated\":$truncated," + + "\"providerValue\":$providerValueJson,\"providerSource\":$providerSourceJson}" +} /** * Rule ids, hosts, and paths are user-supplied, so every string field is escaped. [stats] comes @@ -4867,8 +5534,7 @@ private fun RemoteConfigEntry.json(): String = * status/body/headers plus its own `delayMs`, so the edit dialog can round-trip a delayed rule too. */ private fun MockRule.json(stats: MockRuleStats): String { - val delay = action as? MockAction.Delay - val staticResponse = (delay?.next ?: action) as? MockAction.StaticResponse + val staticResponse = action.previewStatic val (body, bodyTruncated) = staticResponse?.body.orEmpty().truncateForMockRuleJson() val headers = staticResponse?.headers.orEmpty().entries.joinToString(",") { (name, value) -> @@ -4876,24 +5542,36 @@ private fun MockRule.json(stats: MockRuleStats): String { } val (sourceSnapshot, sourceSnapshotTruncated) = sourceBodySnapshot?.truncateForMockRuleJson() ?: (null to false) + val queryPredicatesJson = + queryPredicates.entries.joinToString(",") { (key, value) -> + "\"${key.escapeJson()}\":\"${value.escapeJson()}\"" + } + val headerPredicatesJson = + headerPredicates.entries.joinToString(",") { (key, value) -> + "\"${key.escapeJson()}\":\"${value.escapeJson()}\"" + } return "{\"id\":\"${id.escapeJson()}\",\"priority\":$priority," + - "\"method\":${method?.let { "\"${it.escapeJson()}\"" } ?: "null"}," + - "\"scheme\":${scheme?.let { "\"${it.escapeJson()}\"" } ?: "null"}," + - "\"host\":${host?.let { "\"${it.escapeJson()}\"" } ?: "null"}," + + "\"method\":${method.orNullJson()}," + + "\"scheme\":${scheme.orNullJson()}," + + "\"host\":${host.orNullJson()}," + "\"path\":\"${path.escapeJson()}\",\"scope\":\"${scope.name}\"," + "\"action\":\"${action::class.simpleName}\"," + - "\"statusCode\":${staticResponse?.statusCode ?: "null"}," + + "\"statusCode\":${action.previewStatusCodeJson}," + "\"body\":\"${body.escapeJson()}\",\"bodyTruncated\":$bodyTruncated," + "\"headers\":{$headers}," + - "\"delayMs\":${delay?.durationMs ?: "null"}," + + "\"delayMs\":${action.previewDelayMsJson}," + "\"hitCount\":${stats.hitCount},\"lastHitEpochMs\":${stats.lastHitEpochMs ?: "null"}," + "\"enabled\":${persistence.enabled}," + - "\"sourceBodySnapshot\":${sourceSnapshot?.let { "\"${it.escapeJson()}\"" } ?: "null"}," + + "\"queryPredicates\":{$queryPredicatesJson}," + + "\"headerPredicates\":{$headerPredicatesJson}," + + "\"bodyPredicate\":${bodyPredicate.orNullJson()}," + + "\"actionDetail\":${action.actionDetailJson()}," + + "\"sourceBodySnapshot\":${sourceSnapshot.orNullJson()}," + "\"sourceBodySnapshotTruncated\":$sourceSnapshotTruncated}" } /** Caps a mock rule's serialized response body rather than omitting it outright when oversized. */ -private fun String.truncateForMockRuleJson(maxBytes: Int = MOCK_RULE_BODY_JSON_CAP_BYTES): Pair { +internal fun String.truncateForMockRuleJson(maxBytes: Int = MOCK_RULE_BODY_JSON_CAP_BYTES): Pair { val bytes = toByteArray(Charsets.UTF_8) if (bytes.size <= maxBytes) return this to false val decoder = @@ -4904,7 +5582,7 @@ private fun String.truncateForMockRuleJson(maxBytes: Int = MOCK_RULE_BODY_JSON_C return decoder.decode(java.nio.ByteBuffer.wrap(bytes, 0, maxBytes)).toString() to true } -private const val MOCK_RULE_BODY_JSON_CAP_BYTES = 64 * 1024 +internal const val MOCK_RULE_BODY_JSON_CAP_BYTES = 64 * 1024 private fun pruneStaleExports( directory: File, @@ -4922,7 +5600,7 @@ private fun pruneStaleExports( private const val STALE_EXPORT_MAX_AGE_MS = 60L * 60L * 1000L -private fun String.escapeJson(): String = +internal fun String.escapeJson(): String = buildString(length + 16) { for (char in this@escapeJson) { when (char) { @@ -5017,7 +5695,12 @@ private fun sessionIntegrityJson( val stateMutations = auditLog.events().count { it.commandType.startsWith("state.") } val pristine = activeMocks.isEmpty() && flagOverrides.isEmpty() && stateMutations == 0 val mocksJson = activeMocks.joinToString(",") { "\"${it.escapeJson()}\"" } - val flagsJson = flagOverrides.entries.joinToString(",") { (key, value) -> "\"${key.escapeJson()}\":$value" } + val flagsJson = + flagOverrides.entries.joinToString(",") { (key, value) -> + val isBooleanFlag = featureFlags.flags().any { it.key == key && it.type == FeatureFlagType.BOOLEAN } + val booleanValue = if (isBooleanFlag) value.toBooleanStrictOrNull()?.toString() else null + "\"${key.escapeJson()}\":" + (booleanValue ?: "\"${value.escapeJson()}\"") + } return "{\"pristine\":$pristine,\"activeMockRuleIds\":[$mocksJson]," + "\"featureFlagOverrides\":{$flagsJson},\"stateMutationCount\":$stateMutations}" } @@ -5454,9 +6137,9 @@ private fun io.ktor.server.application.ApplicationCall.applyExportTruncationHead */ @Suppress("ReturnCount") // One early-exit per gate stage (auth, CSRF) reads clearest. private suspend fun io.ktor.server.application.ApplicationCall.authorizeNetworkExportPost( - networkTransactions: NetworkTransactionStore, sessionAuthority: SessionAuthority, commandAuditLog: CommandAuditLog, + networkTransactions: suspend io.ktor.server.application.ApplicationCall.() -> NetworkTransactionStore?, ): NetworkExportResolution? { val session = sessionAuthority.bearerSession(request.headers[HttpHeaders.Authorization]) if (session == null) { @@ -5469,8 +6152,10 @@ private suspend fun io.ktor.server.application.ApplicationCall.authorizeNetworkE respondText("{\"code\":\"CSRF_INVALID\"}", status = HttpStatusCode.Forbidden) return null } - val ids = receiveParameters().getAll("id").orEmpty() - return resolveNetworkExportTransactions(networkTransactions, bodyIds = ids) + // Resolved only after auth+CSRF so an unauthenticated caller cannot probe which past runs exist. + val store = networkTransactions() ?: return null + val ids = receiveParametersWithin(MAX_DEFAULT_REQUEST_BODY_BYTES).getAll("id").orEmpty() + return resolveNetworkExportTransactions(store, bodyIds = ids) } /** Answers a malformed request with the JSON envelope at a 4xx. Debug-logged: rejections are routine. */ @@ -5532,6 +6217,9 @@ private fun io.ktor.server.application.ApplicationCall.networkTransactionQuery( if (separator <= 0 || separator == encoded.lastIndex) return null encoded.substring(0, separator) to encoded.substring(separator + 1) }.toMap() + val rawBody = request.queryParameters["body"] + if (rawBody != null && rawBody.length > NetworkTransactionQuery.MAX_BODY_QUERY_LENGTH) return null + val bodyQuery = rawBody?.takeIf(String::isNotBlank) return NetworkTransactionQuery( limit = limit, cursor = request.queryParameters["cursor"], @@ -5547,6 +6235,7 @@ private fun io.ktor.server.application.ApplicationCall.networkTransactionQuery( .orEmpty(), statuses = statuses.filterNotNull().toSet(), correlationId = request.queryParameters["correlationId"], + bodyQuery = bodyQuery, ).withFilters( NetworkTransactionFilters( fromEpochMs = fromEpochMs, @@ -5658,7 +6347,8 @@ private fun NetworkTransaction.summaryJson(): String { "\"host\":\"${capture.request.url.host.escapeJson()}\"," + "\"path\":\"${capture.request.url.path.escapeJson()}\"," + "\"query\":\"${capture.request.url.queryString.escapeJson()}\"," + - "\"status\":${capture.response?.statusCode ?: "null"}," + + // Adapters record "no response" as status 0; the dashboard shows a null status as failed/ERR. + "\"status\":${capture.response?.statusCode?.takeIf { it > 0 } ?: "null"}," + "\"contentType\":\"$contentType\"," + "\"error\":$error,\"tags\":$tags,\"correlationId\":$correlationId}" } @@ -5758,7 +6448,8 @@ private fun Map.jsonObject(): String = private fun PushEvent.json(): String = buildString { - append("{\"provider\":\"").append(provider.escapeJson()).append("\"") + append("{\"id\":\"").append(stableEvidenceId().escapeJson()).append("\"") + append(",\"provider\":\"").append(provider.escapeJson()).append("\"") append(",\"messageId\":").append(messageId?.let { "\"${it.escapeJson()}\"" } ?: "null") append(",\"source\":").append(source?.let { "\"${it.escapeJson()}\"" } ?: "null") append(",\"sentAtEpochMs\":").append(sentAtEpochMs ?: "null") @@ -5782,16 +6473,24 @@ private fun PushEvent.json(): String = append('}') } -private fun SocketConnection.summaryJson(): String { +/** + * [socketSenders] decides the two write-capability fields: a connection with no registered sender + * reports `canSend:false` and `sendProtocol:null`, so the dashboard never offers a composer that + * would only fail on submit. + */ +private fun SocketConnection.summaryJson(socketSenders: SocketSenderRegistry? = null): String { val errorJson = error?.let { "\"${it.escapeJson()}\"" } ?: "null" + val canSend = socketSenders?.canSend(id) == true + val sendProtocol = socketSenders?.protocol(id)?.wireName?.let { "\"${it.escapeJson()}\"" } ?: "null" return "{\"id\":\"${id.escapeJson()}\",\"url\":\"${url.escapeJson()}\",\"state\":\"${state.name}\"," + "\"openedAtEpochMs\":$openedAtEpochMs,\"closedAtEpochMs\":${closedAtEpochMs ?: "null"}," + "\"sentCount\":$sentCount,\"receivedCount\":$receivedCount,\"error\":$errorJson," + - "\"protocol\":\"${protocol.wireName.escapeJson()}\"}" + "\"protocol\":\"${protocol.wireName.escapeJson()}\"," + + "\"canSend\":$canSend,\"sendProtocol\":$sendProtocol}" } -private fun SocketConnection.detailJson(): String = - summaryJson().dropLast(1) + +private fun SocketConnection.detailJson(socketSenders: SocketSenderRegistry? = null): String = + summaryJson(socketSenders).dropLast(1) + ",\"reconnectAttempt\":$reconnectAttempt," + "\"lifecycle\":[${lifecycleEvents.joinToString(",") { it.json() }}]," + "\"messages\":[${messages.joinToString(",") { it.json() }}]}" @@ -5940,10 +6639,7 @@ private fun materializeEvidenceSubject( ) } EvidenceKind.PUSH -> - // Mirrors dashboard.js's own convention (socketFlagId's push sibling): PushEvent has no - // durable id of its own, so the subject is the event's position in pushStore.events() -- - // the same ordering GET /api/v1/push/events already returns. - subjectId.toIntOrNull()?.let(pushStore.events()::getOrNull)?.let { push -> + pushStore.events().firstOrNull { it.stableEvidenceId() == subjectId }?.let { push -> MaterializedEvidenceSubject("${push.provider} · ${push.lifecycle.name}", push.json(), null) } } @@ -5967,6 +6663,9 @@ private fun Timeline.findEvent(id: String): StoredEvent? { return null } +private fun PushEvent.stableEvidenceId(): String = + "$provider:$receivedAtEpochMs:${messageId.orEmpty()}:${source.orEmpty()}" + /** * Resolves dashboard.js's `socketFlagId` convention (`connectionId@timestampEpochMs`) back to the * connection and message it named -- [SocketMessage] carries no id of its own. A shared timestamp @@ -6248,7 +6947,7 @@ private suspend fun String.readSafely(attachmentReader: suspend (String) -> Byte } /** GET /api/v1/runs row: enough for the previous-run-crashed banner and a future Session & Security view. */ -private fun StoredSession.json(): String = +private fun StoredSession.json(current: Boolean = false): String = "{\"id\":\"${id.escapeJson()}\",\"status\":\"${status.name}\"," + "\"startedAtEpochMs\":$startedAtMs,\"endedAtEpochMs\":${endedAtMs ?: "null"}," + "\"applicationId\":${applicationId?.let { "\"${it.escapeJson()}\"" } ?: "null"}," + @@ -6258,7 +6957,8 @@ private fun StoredSession.json(): String = "\"deviceModel\":${deviceModel?.let { "\"${it.escapeJson()}\"" } ?: "null"}," + "\"deviceApiLevel\":${deviceApiLevel ?: "null"}," + "\"deviceOsVersion\":${deviceOsVersion?.let { "\"${it.escapeJson()}\"" } ?: "null"}," + - "\"recordCount\":$recordCount,\"estimatedBytes\":$estimatedBytes}" + "\"recordCount\":$recordCount,\"estimatedBytes\":$estimatedBytes,\"pinned\":$pinned," + + "\"current\":$current}" private fun evidenceSessionJson( metadata: ServerMetadata, diff --git a/sdk/server-ktor/src/main/kotlin/io/devconsole/server/ktor/EventStreamHub.kt b/sdk/server-ktor/src/main/kotlin/io/devconsole/server/ktor/EventStreamHub.kt index 7fb1d91..e0558c3 100644 --- a/sdk/server-ktor/src/main/kotlin/io/devconsole/server/ktor/EventStreamHub.kt +++ b/sdk/server-ktor/src/main/kotlin/io/devconsole/server/ktor/EventStreamHub.kt @@ -21,6 +21,9 @@ class EventStreamHub( val events = mutableEvents.asSharedFlow() val currentSequence: Long get() = sequence.get() + /** Live stream connections currently collecting [events]; lets tests pin subscribe-before-welcome. */ + internal val subscriberCount: Int get() = mutableEvents.subscriptionCount.value + init { require(capacity > 0) { "capacity must be positive" } } @@ -53,25 +56,3 @@ private fun Map.toStreamJson(): String = .joinToString(prefix = "{", postfix = "}") { (name, value) -> "\"${name.escapeJson()}\":\"${value.escapeJson()}\"" } - -private fun String.escapeJson(): String = - buildString(length + 16) { - for (char in this@escapeJson) { - when (char) { - '"' -> append("\\\"") - '\\' -> append("\\\\") - '\b' -> append("\\b") - '\u000C' -> append("\\f") - '\n' -> append("\\n") - '\r' -> append("\\r") - '\t' -> append("\\t") - else -> { - if (char.code < 0x20) { - append("\\u").append(char.code.toString(16).padStart(4, '0')) - } else { - append(char) - } - } - } - } - } diff --git a/sdk/server-ktor/src/main/kotlin/io/devconsole/server/ktor/MockActionForm.kt b/sdk/server-ktor/src/main/kotlin/io/devconsole/server/ktor/MockActionForm.kt new file mode 100644 index 0000000..f62b137 --- /dev/null +++ b/sdk/server-ktor/src/main/kotlin/io/devconsole/server/ktor/MockActionForm.kt @@ -0,0 +1,204 @@ +/** + * @author Shakib + * @since 03/11/26 + */ +package io.devconsole.server.ktor + +import io.devconsole.mocks.MockAction +import io.ktor.http.Parameters + +private const val ACTION_TYPE_PARAM = "actionType" +private const val STATUS_PARAM = "status" +private const val BODY_PARAM = "body" +private const val DELAY_PARAM = "delayMs" +private const val FAILURE_MESSAGE_PARAM = "failureMessage" +private const val TIMEOUT_PARAM = "timeoutMs" +private const val BYTES_PER_SECOND_PARAM = "bytesPerSecond" +private const val LATENCY_PARAM = "latencyMs" +private const val REMOTE_SCHEME_PARAM = "remoteScheme" +private const val REMOTE_HOST_PARAM = "remoteHost" +private const val REMOTE_PORT_PARAM = "remotePort" +private const val REMOTE_PATH_PARAM = "remotePath" +private const val STEP_TYPE_PARAM = "stepType" +private const val STEP_STATUS_PARAM = "stepStatus" +private const val STEP_BODY_PARAM = "stepBody" +private const val STEP_DELAY_PARAM = "stepDelayMs" +private const val STEP_TIMEOUT_PARAM = "stepTimeoutMs" +private const val STEP_LOOP_PARAM = "loop" + +private const val ACTION_STATIC = "static" +private const val ACTION_TEMPLATE = "template" +private const val ACTION_STATUS_OVERRIDE = "status_override" +private const val ACTION_BODY_REPLACEMENT = "body_replacement" +private const val ACTION_CONNECTION_FAILURE = "connection_failure" +private const val ACTION_TIMEOUT = "timeout" +private const val ACTION_MAP_REMOTE = "map_remote" +private const val ACTION_THROTTLE = "throttle" +private const val ACTION_SEQUENCE = "sequence" +private const val ACTION_PASSTHROUGH = "passthrough" + +private const val STEP_STATIC = "static" +private const val STEP_CONNECTION_FAILURE = "connection_failure" +private const val STEP_TIMEOUT = "timeout" +private const val STEP_PASSTHROUGH = "passthrough" + +private const val MIN_STATUS = 100 +private const val MAX_STATUS = 599 +private const val DEFAULT_THROTTLE_LATENCY_MS = 0L + +/** Builds the full [MockAction] tree a mock-rule form describes. Invalid input throws. */ +internal fun parseMockAction( + parameters: Parameters, + headers: Map, +): MockAction { + val type = + parameters[ACTION_TYPE_PARAM] + ?.trim() + ?.lowercase() + .orEmpty() + .ifEmpty { ACTION_STATIC } + return when (type) { + ACTION_STATIC -> parseResponseAction(parameters, headers, template = false) + ACTION_TEMPLATE -> parseResponseAction(parameters, headers, template = true) + ACTION_STATUS_OVERRIDE -> MockAction.StatusOverride(parameters.statusCode()) + ACTION_BODY_REPLACEMENT -> MockAction.BodyReplacement(parameters[BODY_PARAM].orEmpty()) + ACTION_CONNECTION_FAILURE -> connectionFailure(parameters[FAILURE_MESSAGE_PARAM]) + ACTION_TIMEOUT -> + MockAction.Timeout( + requireNotNull(parameters.longOrNull(TIMEOUT_PARAM)) { "$TIMEOUT_PARAM is required" }, + ) + ACTION_MAP_REMOTE -> parseMapRemote(parameters) + ACTION_THROTTLE -> + MockAction.Throttle( + bytesPerSecond = + requireNotNull(parameters.longOrNull(BYTES_PER_SECOND_PARAM)) { + "$BYTES_PER_SECOND_PARAM is required" + }, + latencyMs = parameters.longOrNull(LATENCY_PARAM) ?: DEFAULT_THROTTLE_LATENCY_MS, + ) + ACTION_SEQUENCE -> parseSequence(parameters) + ACTION_PASSTHROUGH -> MockAction.Passthrough + else -> throw IllegalArgumentException("Unknown mock action type: $type") + } +} + +/** The status a rule's action carries, when it has exactly one (a sequence reports null). */ +internal val MockAction.statusCodeOrNull: Int? + get() = + when (this) { + is MockAction.StaticResponse -> statusCode + is MockAction.TemplateResponse -> statusCode + is MockAction.StatusOverride -> statusCode + is MockAction.Delay -> next.statusCodeOrNull + else -> null + } + +private fun parseResponseAction( + parameters: Parameters, + headers: Map, + template: Boolean, +): MockAction { + val status = parameters.statusCode() + val body = parameters[BODY_PARAM].orEmpty() + val response = + if (template) { + MockAction.TemplateResponse(status, body, headers) + } else { + MockAction.StaticResponse(status, body, headers) + } + val delay = parameters.longOrNull(DELAY_PARAM) ?: return response + return MockAction.Delay(delay, response) +} + +private fun connectionFailure(message: String?): MockAction.ConnectionFailure { + val trimmed = message?.takeIf(String::isNotBlank) ?: return MockAction.ConnectionFailure() + return MockAction.ConnectionFailure(trimmed) +} + +private fun parseMapRemote(parameters: Parameters): MockAction.MapRemote = + MockAction.MapRemote( + scheme = parameters[REMOTE_SCHEME_PARAM]?.trim()?.takeIf(String::isNotEmpty), + host = parameters[REMOTE_HOST_PARAM]?.trim()?.takeIf(String::isNotEmpty), + port = parameters.intOrNull(REMOTE_PORT_PARAM), + path = parameters[REMOTE_PATH_PARAM]?.trim()?.takeIf(String::isNotEmpty), + ) + +private fun parseSequence(parameters: Parameters): MockAction.Sequence { + val types = parameters.getAll(STEP_TYPE_PARAM).orEmpty() + require(types.isNotEmpty()) { "A sequence needs at least one step" } + val statuses = parameters.getAll(STEP_STATUS_PARAM).orEmpty() + val bodies = parameters.getAll(STEP_BODY_PARAM).orEmpty() + val delays = parameters.getAll(STEP_DELAY_PARAM).orEmpty() + val timeouts = parameters.getAll(STEP_TIMEOUT_PARAM).orEmpty() + listOf(statuses, bodies, delays, timeouts).forEach { values -> + require(values.isEmpty() || values.size == types.size) { "Sequence step lists must match in length" } + } + val steps = + types.indices.map { index -> + parseSequenceStep( + type = types[index], + status = statuses.getOrNull(index), + body = bodies.getOrNull(index), + delayMs = delays.getOrNull(index), + timeoutMs = timeouts.getOrNull(index), + ) + } + val loop = parameters[STEP_LOOP_PARAM]?.toBooleanStrictOrNull() ?: false + return MockAction.Sequence(steps, loop) +} + +private fun parseSequenceStep( + type: String, + status: String?, + body: String?, + delayMs: String?, + timeoutMs: String?, +): MockAction { + val step = + when (type.trim().lowercase()) { + STEP_STATIC -> { + val code = + requireNotNull(status?.trim()?.toIntOrNull()) { "A static sequence step needs a status" } + require(code in MIN_STATUS..MAX_STATUS) { "status must be between $MIN_STATUS and $MAX_STATUS" } + MockAction.StaticResponse(code, body.orEmpty()) + } + STEP_CONNECTION_FAILURE -> connectionFailure(body) + STEP_TIMEOUT -> + MockAction.Timeout( + requireNotNull(timeoutMs.toStepLongOrNull(STEP_TIMEOUT_PARAM)) { + "$STEP_TIMEOUT_PARAM is required for a timeout step" + }, + ) + STEP_PASSTHROUGH -> MockAction.Passthrough + else -> throw IllegalArgumentException("Unknown sequence step type: $type") + } + val delay = delayMs.toStepLongOrNull(STEP_DELAY_PARAM) ?: return step + require(step is MockAction.StaticResponse) { "Only static sequence steps can be delayed" } + return MockAction.Delay(delay, step) +} + +private fun Parameters.statusCode(): Int { + val status = + this[STATUS_PARAM]?.trim()?.toIntOrNull() + ?: throw IllegalArgumentException("$STATUS_PARAM is required") + require(status in MIN_STATUS..MAX_STATUS) { "status must be between $MIN_STATUS and $MAX_STATUS" } + return status +} + +private fun Parameters.longOrNull(name: String): Long? { + val raw = this[name]?.trim().orEmpty() + if (raw.isEmpty()) return null + return raw.toLongOrNull() ?: throw IllegalArgumentException("$name must be a number") +} + +private fun Parameters.intOrNull(name: String): Int? { + val raw = this[name]?.trim().orEmpty() + if (raw.isEmpty()) return null + return raw.toIntOrNull() ?: throw IllegalArgumentException("$name must be a number") +} + +private fun String?.toStepLongOrNull(name: String): Long? { + val raw = this?.trim().orEmpty() + if (raw.isEmpty()) return null + return raw.toLongOrNull() ?: throw IllegalArgumentException("$name must be a number") +} diff --git a/sdk/server-ktor/src/main/kotlin/io/devconsole/server/ktor/MockActionJson.kt b/sdk/server-ktor/src/main/kotlin/io/devconsole/server/ktor/MockActionJson.kt new file mode 100644 index 0000000..5f9f9fb --- /dev/null +++ b/sdk/server-ktor/src/main/kotlin/io/devconsole/server/ktor/MockActionJson.kt @@ -0,0 +1,78 @@ +/** + * @author Shakib + * @since 03/11/26 + */ +package io.devconsole.server.ktor + +import io.devconsole.mocks.MockAction + +/** Serializes the whole [MockAction] tree for `MockRule.json`'s `actionDetail` field. */ +internal fun MockAction.actionDetailJson(): String = + when (this) { + is MockAction.StaticResponse -> responseJson("static", statusCode, body, headers) + is MockAction.TemplateResponse -> templateJson() + is MockAction.Delay -> delayJson() + is MockAction.ConnectionFailure -> + "{\"type\":\"connection_failure\",\"message\":\"${message.escapeJson()}\"}" + is MockAction.Timeout -> "{\"type\":\"timeout\",\"durationMs\":$durationMs}" + is MockAction.StatusOverride -> "{\"type\":\"status_override\",\"statusCode\":$statusCode}" + is MockAction.BodyReplacement -> { + val (body, truncated) = body.truncateForMockRuleJson() + "{\"type\":\"body_replacement\",\"body\":\"${body.escapeJson()}\",\"bodyTruncated\":$truncated}" + } + is MockAction.Sequence -> sequenceJson() + is MockAction.MapRemote -> mapRemoteJson() + is MockAction.Throttle -> throttleJson() + is MockAction.Passthrough -> "{\"type\":\"passthrough\"}" + } + +private fun responseJson( + type: String, + statusCode: Int, + bodyText: String, + headers: Map, +): String { + val (body, truncated) = bodyText.truncateForMockRuleJson() + return "{\"type\":\"$type\",\"statusCode\":$statusCode,\"body\":\"${body.escapeJson()}\"," + + "\"bodyTruncated\":$truncated,\"headers\":${headersJson(headers)}}" +} + +private fun MockAction.TemplateResponse.templateJson(): String { + val (template, truncated) = template.truncateForMockRuleJson() + return "{\"type\":\"template\",\"statusCode\":$statusCode,\"template\":\"${template.escapeJson()}\"," + + "\"templateTruncated\":$truncated,\"headers\":${headersJson(headers)}}" +} + +private fun MockAction.Delay.delayJson(): String = + "{\"type\":\"delay\",\"durationMs\":$durationMs,\"next\":${next.actionDetailJson()}}" + +private fun MockAction.Sequence.sequenceJson(): String = + "{\"type\":\"sequence\",\"loop\":$loop,\"steps\":[" + + steps.joinToString(",") { it.actionDetailJson() } + "]}" + +private fun MockAction.MapRemote.mapRemoteJson(): String = + "{\"type\":\"map_remote\",\"scheme\":${scheme.orNullJson()},\"host\":${host.orNullJson()}," + + "\"port\":${port?.toString() ?: "null"},\"path\":${path.orNullJson()}}" + +private fun MockAction.Throttle.throttleJson(): String = + "{\"type\":\"throttle\",\"bytesPerSecond\":$bytesPerSecond,\"latencyMs\":$latencyMs," + + "\"next\":${next.actionDetailJson()}}" + +private fun headersJson(headers: Map): String = + headers.entries.joinToString(",", "{", "}") { (name, value) -> + "\"${name.escapeJson()}\":\"${value.escapeJson()}\"" + } + +internal fun String?.orNullJson(): String = this?.let { "\"${it.escapeJson()}\"" } ?: "null" + +/** The static response a rule list entry previews; a `Delay(StaticResponse)` reports the wrapped one. */ +internal val MockAction.previewStatic: MockAction.StaticResponse? + get() = ((this as? MockAction.Delay)?.next ?: this) as? MockAction.StaticResponse + +/** Rendered as JSON so `MockRule.json` never branches for an action that carries no status. */ +internal val MockAction.previewStatusCodeJson: String + get() = statusCodeOrNull?.toString() ?: "null" + +/** Rendered as JSON: `null` unless the action delays its response. */ +internal val MockAction.previewDelayMsJson: String + get() = (this as? MockAction.Delay)?.durationMs?.toString() ?: "null" diff --git a/sdk/server-ktor/src/main/kotlin/io/devconsole/server/ktor/NetworkEndpointStatsRoutes.kt b/sdk/server-ktor/src/main/kotlin/io/devconsole/server/ktor/NetworkEndpointStatsRoutes.kt new file mode 100644 index 0000000..d3002ca --- /dev/null +++ b/sdk/server-ktor/src/main/kotlin/io/devconsole/server/ktor/NetworkEndpointStatsRoutes.kt @@ -0,0 +1,81 @@ +/** + * @author Shakib + * @since 03/11/26 + */ +package io.devconsole.server.ktor + +import io.devconsole.network.EndpointLatency +import io.devconsole.network.EndpointLatencyStats +import io.devconsole.network.NetworkTransaction +import io.devconsole.network.NetworkTransactionQuery +import io.devconsole.network.NetworkTransactionStore +import io.devconsole.server.api.SessionAuthority +import io.ktor.http.ContentType +import io.ktor.http.HttpHeaders +import io.ktor.http.HttpStatusCode +import io.ktor.server.application.ApplicationCall +import io.ktor.server.response.respondText +import io.ktor.server.routing.Route +import io.ktor.server.routing.get + +private const val MAX_ENDPOINT_STATS_ROWS = 5_000 + +internal fun Route.networkEndpointStatsRoutes( + sessionAuthority: SessionAuthority, + categoryEnabled: (String) -> Boolean, + storeForSession: suspend (ApplicationCall) -> NetworkTransactionStore?, +) { + get("/api/v1/network/endpoints") { + if (sessionAuthority.bearerSession(call.request.headers[HttpHeaders.Authorization]) == null) { + call.respondText("{\"code\":\"AUTH_REQUIRED\"}", status = HttpStatusCode.Unauthorized) + return@get + } + if (!categoryEnabled("network")) { + call.respondEndpointCategoryDisabled("network") + return@get + } + val store = storeForSession(call) ?: return@get + val sampled = collectSampledTransactions(store) + val completedCount = sampled.count { it.completedAtEpochMs != null } + val stats = EndpointLatencyStats.from(sampled) + val dataJson = stats.joinToString(",") { it.json() } + call.respondText( + "{\"data\":[$dataJson],\"sampleSize\":$completedCount}", + contentType = ContentType.Application.Json, + ) + } +} + +private suspend fun ApplicationCall.respondEndpointCategoryDisabled(name: String) { + respondText( + "{\"error\":{\"code\":\"CATEGORY_DISABLED\"," + + "\"message\":\"The '${name.escapeJson()}' capture category is disabled for this app run\"}}", + status = HttpStatusCode.Forbidden, + contentType = ContentType.Application.Json, + ) +} + +private fun collectSampledTransactions(store: NetworkTransactionStore): List { + val collected = ArrayList() + var cursor: String? = null + var exhausted = false + while (!exhausted && collected.size < MAX_ENDPOINT_STATS_ROWS) { + val pageLimit = minOf(NetworkTransactionQuery.MAX_PAGE_LIMIT, MAX_ENDPOINT_STATS_ROWS - collected.size) + val page = store.page(NetworkTransactionQuery(limit = pageLimit, cursor = cursor)) + if (!page.invalidCursor) collected.addAll(page.transactions) + cursor = page.nextCursor + exhausted = page.invalidCursor || page.transactions.isEmpty() || !page.hasMore || cursor == null + } + return collected +} + +private fun EndpointLatency.json(): String = + "{\"method\":\"${method.escapeJson()}\"," + + "\"host\":\"${host.escapeJson()}\"," + + "\"pathTemplate\":\"${pathTemplate.escapeJson()}\"," + + "\"count\":$count," + + "\"errorCount\":$errorCount," + + "\"p50Ms\":$p50Ms," + + "\"p95Ms\":$p95Ms," + + "\"p99Ms\":$p99Ms," + + "\"maxMs\":$maxMs}" diff --git a/sdk/server-ktor/src/main/kotlin/io/devconsole/server/ktor/SocketSendForm.kt b/sdk/server-ktor/src/main/kotlin/io/devconsole/server/ktor/SocketSendForm.kt new file mode 100644 index 0000000..ed0bd15 --- /dev/null +++ b/sdk/server-ktor/src/main/kotlin/io/devconsole/server/ktor/SocketSendForm.kt @@ -0,0 +1,26 @@ +/** + * @author Shakib + * @since 04/11/26 + */ +package io.devconsole.server.ktor + +import io.devconsole.socket.SocketSendRequest +import io.ktor.http.Parameters + +/** + * Reads the send route's form (`text`, plus MQTT `topic`/`qos`/`retained`); null when `text` is + * missing or `qos`/`retained` is malformed. Range checks stay with `SocketSenderRegistry`. + */ +internal fun Parameters.toSocketSendRequest(): SocketSendRequest? { + val text = this["text"]?.takeIf(String::isNotEmpty) + val qos = this["qos"]?.takeIf(String::isNotBlank)?.let { it.toIntOrNull() ?: INVALID_QOS } ?: 0 + val retained = this["retained"]?.takeIf(String::isNotBlank)?.toBooleanStrictOrNull() + val retainedValid = retained != null || this["retained"].isNullOrBlank() + return if (text == null || qos == INVALID_QOS || !retainedValid) { + null + } else { + SocketSendRequest(text, this["topic"]?.takeIf(String::isNotBlank), qos, retained ?: false) + } +} + +private const val INVALID_QOS = -1 diff --git a/sdk/server-ktor/src/main/resources/devconsole-web/dashboard.css b/sdk/server-ktor/src/main/resources/devconsole-web/dashboard.css index 6638cfd..2f41ca5 100644 --- a/sdk/server-ktor/src/main/resources/devconsole-web/dashboard.css +++ b/sdk/server-ktor/src/main/resources/devconsole-web/dashboard.css @@ -84,6 +84,9 @@ } * { box-sizing: border-box; } +.composer-collection-row { display: flex; align-items: stretch; border-bottom: 1px solid var(--line); } +.composer-collection-load { flex: 1; min-width: 0; } +.composer-collection-delete { align-self: center; margin: 0 8px; } /* The `hidden` attribute only sets `display: none` in the UA stylesheet, so any author rule that sets `display` beats it and the element stays on screen. Several components here declare `display: flex` or `grid` and are toggled by setting `.hidden` from JS -- the empty selection bar @@ -644,7 +647,7 @@ button.ghost { background: transparent; } } /* Card section shell — scaffolding for card-grid views. */ -.card-shell { display: flex; flex-direction: column; border: 0; border-radius: 0; background: transparent; overflow: visible; } +.card-shell { display: flex; flex-direction: column; min-width: 0; border: 0; border-radius: 0; background: transparent; overflow: visible; } .card-shell-head { display: flex; align-items: center; gap: 8px; min-height: 36px; padding: 0 0 8px; border-bottom: 1px solid var(--line); } .card-shell-head .ic { width: 14px; height: 14px; } .card-shell-title { margin: 0; font-size: 14px; text-transform: none; letter-spacing: 0; font-weight: 700; flex: 1; } @@ -671,7 +674,7 @@ button.is-refreshing .ic { animation: composerSpin 0.8s linear infinite; } .field.field-highlight select { border-color: var(--signal); animation: composerFieldPulse 0.9s ease-in-out 3; } #mocksRulesBadge:empty { display: none; } .card-shell-badge { font-family: var(--font-mono); font-size: 10.5px; padding: 2px 8px; border-radius: 99px; border: 1px solid var(--line); color: var(--text-3); } -.card-shell-body { flex: 1; display: flex; flex-direction: column; padding: 14px 0 0; } +.card-shell-body { flex: 1; display: flex; flex-direction: column; min-width: 0; padding: 14px 0 0; } /* --d-card-pad, not a literal 16px: this is the consumer that token was declared for, and until now it had none -- so Simple mode grew every row and the body font while leaving cards exactly as tight as Advanced. */ @@ -753,7 +756,7 @@ body.detail-zoom .split-shell.collapse-detail { grid-template-columns: 1fr; } desktop width doesn't carry that grid-template-columns override into stacked mode. */ .split-shell, .split-shell.collapse-list, - .split-shell.collapse-detail { grid-template-columns: 1fr; grid-template-rows: none; flex: 0 0 auto; min-height: 0; } + .split-shell.collapse-detail { grid-template-columns: minmax(0, 1fr); grid-template-rows: none; flex: 0 0 auto; min-height: 0; } .split-shell > .splitter { display: none; } /* height (not just min-height) so the stacked panes are a bounded box, not an unbounded one that only ever grows to fit its content -- .list-body's flex:1;min-height:0;overflow-y:auto (below) @@ -796,7 +799,13 @@ body.detail-zoom .split-shell.collapse-detail { grid-template-columns: 1fr; } .col-duration { flex: 0 0 74px; text-align: right; } .col-status { flex: 0 0 62px; text-align: right; } .col-flag { flex: 0 0 24px; text-align: right; } -@media (max-width: 620px) { .col-duration { display: none; } } +@media (max-width: 620px) { + /* The row cell goes with its header: hiding only the header left Crashes/Push/Timeline rows a + 74px column the head no longer labels, which squeezed the summary to ~10px at 390px. Network's + duration sits inside .row-metrics, so the direct-child selector leaves it alone. */ + .col-duration, .row > .row-duration { display: none; } + #crashesView .col-badge, #crashesView .row-badge { flex-basis: 56px; } +} /* The stacked pair keeps both values at every width — it costs one column, not two, and Network's list head is sr-only anyway, so there is no header to drift out of step with it. */ @@ -1201,7 +1210,9 @@ body.detail-zoom .split-shell.collapse-detail { grid-template-columns: 1fr; } .card-metric-label { font-size: 10.5px; font-weight: 600; color: var(--text-3); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .card-metric-val { font-family: var(--font-mono); font-size: 17px; margin-top: 4px; font-variant-numeric: tabular-nums; white-space: nowrap; } -.card-toggles { display: grid; gap: 1px; margin-bottom: 12px; } +/* minmax(0, 1fr), not the implicit auto column: a long rule id would otherwise set the grid's + min-content width and push the row's toggle off a phone-width screen. */ +.card-toggles { display: grid; grid-template-columns: minmax(0, 1fr); gap: 1px; margin-bottom: 12px; min-width: 0; } .card-toggle-row { display: flex; align-items: center; gap: 12px; padding: 8px 0; border-bottom: 1px solid var(--line); } .card-toggle-row:last-child { border-bottom: none; } .card-toggle-text { flex: 1; min-width: 0; } @@ -1356,6 +1367,14 @@ body.detail-zoom .split-shell.collapse-detail { grid-template-columns: 1fr; } without the path/headers/body rows wrapping too tightly. */ .modal.modal-wide { max-width: 640px; } .mock-body-toolbar { display: flex; align-items: center; gap: 12px; margin-top: -4px; } +/* The action editor only renders the fields the selected action type needs. The attribute-driven + hide must beat `.field`'s own display rule. */ +#mockRuleModal [data-mock-fields][hidden] { display: none !important; } +.mock-step-row { display: flex; flex-wrap: wrap; gap: 8px; align-items: flex-end; padding: 8px 0; } +.mock-step-row .field { flex: 1 1 140px; min-width: 120px; margin: 0; } +.mock-step-row .field-full { flex-basis: 100%; } +.mock-step-remove { align-self: center; } +.mock-step-loop { display: inline-flex; align-items: center; gap: 6px; font-size: 12.5px; } /* The JSON status is the one thing on its row that can run long (a parse error carries the engine's own message), so it takes the slack and ellipses rather than widening the dialog. The full-window toggle lives on the find bar below and parks on that row's right edge. */ @@ -1823,7 +1842,7 @@ label.field.export-metadata { display: flex; flex-direction: row; align-items: c .row-check { flex-basis: 24px; } } @media (max-width: 960px) { - .split-shell { grid-template-columns: 1fr; gap: 16px; } + .split-shell { grid-template-columns: minmax(0, 1fr); gap: 16px; } .host-line { display: none; } } @media (max-width: 780px) { @@ -1882,10 +1901,11 @@ label.field.export-metadata { display: flex; flex-direction: row; align-items: c margin: 4px 0; } .toolbar .topbar-overflow > button { - height: 32px; + /* Matches the redesigned `.toolbar > button` (40px / 13px) so Export sits level with its neighbours. */ + height: 40px; border-radius: 8px; padding: 0 12px; - font-size: 12.5px; + font-size: 13px; } .topbar-menu-item.danger { color: var(--error); @@ -1940,6 +1960,11 @@ label.field.export-metadata { display: flex; flex-direction: row; align-items: c /* Timeline and WebSockets rows carry four columns, so their list starts at half the width (the splitter still overrides it per view). */ #timelineView .split-shell, #socketView .split-shell { grid-template-columns: minmax(360px, var(--list-w, 50%)) 5px minmax(360px, 1fr); } +/* The id selector above outranks the generic stacked-mode rule, so restate the single column here; + without it Timeline and Sockets kept two 360px columns on a phone and ran off the screen. */ +@media (max-width: 960px) { + #timelineView .split-shell, #socketView .split-shell { grid-template-columns: minmax(0, 1fr); } +} #networkView .split-shell { position: relative; grid-template-columns: minmax(300px, var(--list-w, 44%)) 5px minmax(0, 1fr); } #networkView .list-pane, #networkDetailPane { border-radius: 0; min-width: 0; } #networkView .list-head { position: relative; padding: 0 12px; height: 36px; flex-basis: 36px; gap: 8px; } @@ -1960,6 +1985,15 @@ label.field.export-metadata { display: flex; flex-direction: row; align-items: c /* Full endpoint: the host takes a small first line so the path keeps its full width (rows stay 44px). */ #transactions .row-main-host { display: block; font-size: 11px; line-height: 14px; overflow: hidden; text-overflow: ellipsis; } #transactions .row-metrics-inline { font-family: var(--font-mono); font-size: 12px; } +/* Phone width: the path is the one column worth reading, so the method column narrows, the duration + and the Full-endpoint toggle drop out, and the status keeps only its own width -- before this the + path was squeezed to "/…" and the toggle overlapped the "Status · time" heading. */ +@media (max-width: 480px) { + #networkView .col-badge, #transactions .row-badge { flex-basis: 44px; } + #networkView .col-network-metrics, #transactions .row-metrics-inline { min-width: 0; } + #transactions .row-time, #networkFullEndpoint, #networkView .col-network-time { display: none; } + #transactions .row { gap: 8px; } +} #transactions .row.selected { background: var(--surface-2); box-shadow: inset 2px 0 var(--signal); } #transactions .row-check, #transactions .row-flag, #networkSelectAllVisible { opacity: 0; } #transactions .row:hover .row-check, #transactions .row:hover .row-flag, @@ -1967,6 +2001,10 @@ label.field.export-metadata { display: flex; flex-direction: row; align-items: c #transactions .row.row-picked .row-check, #transactions .row.row-picked .row-flag, #networkView .list-head:hover #networkSelectAllVisible, #networkSelectAllVisible:focus-visible, #networkSelectAllVisible[aria-checked="true"], #networkSelectAllVisible[aria-checked="mixed"] { opacity: 1; } +/* Touch screens have no hover: never hide row controls behind it. */ +@media (hover: none) { + #transactions .row-check, #transactions .row-flag, #networkSelectAllVisible { opacity: 1; } +} #networkDetailPane .network-detail-head { padding: 12px 16px 0; } #networkDetailPane .detail-head-row { flex-wrap: nowrap; gap: 8px; } #networkDetailPane .network-method { font: 12px var(--font-mono); color: var(--muted); } @@ -2014,3 +2052,174 @@ body.mode-simple #networkDetailPane [data-detail-tab] { display: inline-flex; } #networkDetailPane .network-head-actions { gap: 0; } #networkDetailPane .network-icon-action, #networkDetailPane .detail-menu-btn { width: 24px; } } + +/* Pin/delete controls in the Session view run-history table. */ +.card-table td.run-actions { white-space: nowrap; text-align: right; } +.run-actions-row { display: inline-flex; gap: 4px; vertical-align: middle; } + +/* Network endpoint latency panel & clickable rows. */ +.network-endpoints-panel { margin-bottom: 12px; } +.network-endpoints-panel .card-lede { margin-bottom: 10px; } +.endpoint-row { cursor: pointer; } +.endpoint-row:hover { background: var(--surface-2); } +.endpoint-row:focus-visible { outline: 2px solid var(--signal); outline-offset: -2px; background: var(--surface-2); } +@media (max-width: 620px) { + .network-endpoints-panel .card-shell-head { flex-wrap: wrap; } + .network-endpoints-panel .card-table th, + .network-endpoints-panel .card-table td { padding: 10px 12px; font-size: 12px; } +} + +/* Endpoint latency: path over host in one cell keeps the numeric columns on screen. */ +.network-endpoints-panel .endpoint-cell { max-width: 260px; } +.network-endpoints-panel .endpoint-cell > span { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.network-endpoints-panel .endpoint-host { font-size: 11px; margin-top: 2px; } + +/* ---- HAR offline viewer banner ---------------------------------------- */ +/* Wraps rather than scrolls: the file name is the one unbounded string here, and at 390px it + must break inside the banner instead of widening the page. */ +.har-banner { + display: flex; align-items: center; flex-wrap: wrap; gap: 8px 12px; + margin-bottom: 12px; padding: 8px 12px; min-width: 0; + border: 1px solid var(--put); border-radius: 8px; + background: var(--put-soft); color: var(--ink); font-size: 12.5px; +} +.har-banner-text { display: flex; align-items: center; gap: 8px; flex: 1 1 220px; min-width: 0; } +.har-banner-text .ic { color: var(--put); flex: 0 0 auto; } +.har-banner-file { font-family: var(--font-mono); font-weight: 700; overflow-wrap: anywhere; } +.har-banner-close { flex: 0 0 auto; height: 28px; padding: 0 10px; border-radius: 6px; font-size: 12px; } + +/* ---- Structured decoders (JWT / GraphQL) in the network detail -------- */ +.decoded-sections { display: grid; gap: 4px; margin-top: 12px; min-width: 0; } +.decoded-group { border-top: 1px solid var(--line); padding-top: 12px; } +.decoded-source { display: flex; align-items: center; gap: 6px; margin-bottom: 8px; color: var(--muted); font-family: var(--font-mono); font-size: 11.5px; overflow-wrap: anywhere; } +.decoded-source .ic { flex: 0 0 auto; } +.decoded-note { display: flex; align-items: flex-start; gap: 6px; margin-top: 8px; color: var(--muted); font-size: 11.5px; } +.decoded-note .ic { flex: 0 0 auto; margin-top: 2px; } +.decoded-sections .code-block { min-width: 0; overflow-x: auto; } + +/* ---- Crash grouping ---------------------------------------------------- */ +/* A pressed toolbar toggle reads as an active filter, matching the segmented controls it sits + beside without turning into a second selected-state language. */ +/* A group's "×N" is its identity; let the exception name ellipsise first. */ +#crashesView .row-tag { flex-shrink: 0; } +#crashesGroupToggle[aria-pressed="true"] { border-color: var(--signal); color: var(--signal); background: var(--signal-soft); } +.crash-occurrences { display: grid; gap: 2px; margin-bottom: 16px; min-width: 0; } +.crash-occurrence { + display: flex; align-items: baseline; gap: 12px; width: 100%; min-width: 0; + padding: 6px 8px; text-align: left; border: 1px solid transparent; border-radius: 6px; + background: transparent; font-size: 12px; +} +.crash-occurrence:hover, .crash-occurrence:focus-visible { border-color: var(--line); background: var(--surface-2); } +.crash-occurrence-time { flex: 0 0 auto; font-family: var(--font-mono); color: var(--ink); } +.crash-occurrence-run { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 11.5px; } +@media (max-width: 480px) { + .har-banner { align-items: flex-start; flex-direction: column; } + /* In a column the 220px basis becomes a height, which ballooned the banner on phones. */ + .har-banner-text { flex: 0 0 auto; } + .har-banner-close { align-self: flex-end; } +} + +/* ---- Socket send composer ---- */ +.socket-composer { + margin-top: 16px; + padding: 12px; + border: 1px solid var(--line); + border-radius: 8px; + background: var(--surface-2); + display: flex; + flex-direction: column; + gap: 10px; +} +.socket-composer-head { + display: flex; + align-items: center; + gap: 8px; + font-size: 11px; + font-weight: 700; + color: var(--muted); + text-transform: uppercase; + letter-spacing: 0.05em; +} +.socket-composer-head .ic { + color: var(--signal); +} +.socket-composer textarea { + width: 100%; + box-sizing: border-box; + resize: vertical; + font-family: var(--font-mono); + font-size: 12px; +} +.socket-composer-mqtt { + display: flex; + flex-wrap: wrap; + align-items: flex-end; + gap: 10px; +} +.socket-composer-mqtt .field { + flex: 1 1 140px; +} +.socket-composer-mqtt .field-qos { + flex: 0 0 80px; +} +.socket-composer-checkbox { + display: inline-flex; + align-items: center; + gap: 6px; + font-size: 12px; + cursor: pointer; + color: var(--ink); + padding-bottom: 8px; + user-select: none; +} +.socket-composer-checkbox input { + cursor: pointer; +} +.socket-composer-foot { + display: flex; + align-items: center; + justify-content: flex-end; + gap: 8px; +} + +/* ---- Remote Config override editor ---- */ +.rc-override-section { + margin-top: 16px; + padding-top: 14px; + border-top: 1px solid var(--line); + display: flex; + flex-direction: column; + gap: 10px; +} +.rc-provider-fallback { + font-size: 12px; + color: var(--muted); + background: var(--code-bg); + border: 1px solid var(--line); + border-radius: 6px; + padding: 8px 10px; + word-break: break-all; + font-family: var(--font-mono); +} +.rc-override-section textarea { + width: 100%; + box-sizing: border-box; + font-family: var(--font-mono); + font-size: 12px; + resize: vertical; +} +.rc-override-actions { + display: flex; + align-items: center; + gap: 8px; + flex-wrap: wrap; +} +@media (max-width: 480px) { + .socket-composer-mqtt { + flex-direction: column; + align-items: stretch; + } + .socket-composer-mqtt .field-qos { + flex: 1 1 auto; + } +} 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 43584d6..33f5ca1 100644 --- a/sdk/server-ktor/src/main/resources/devconsole-web/dashboard.js +++ b/sdk/server-ktor/src/main/resources/devconsole-web/dashboard.js @@ -12,6 +12,13 @@ // and shares one request between identical concurrent GETs, so a burst of view switches does not // trip the limiter. It delegates to window.fetch, which adds the 401 session tracking below. const inFlightGets = new Map(); + const requestGenerations = new Map(); + function nextGen(key) { + const gen = (requestGenerations.get(key) || 0) + 1; + requestGenerations.set(key, gen); + return gen; + } + const isLatest = (key, gen) => requestGenerations.get(key) === gen; function getAuthHeader(headers) { if (!headers) return ''; @@ -169,6 +176,21 @@ } let openAccess = false; let currentView = 'overview'; + // Deep link: `#view=` restores the view after reload/sharing. Read once at startup, since + // pairing strips the hash; never carries tokens (the `code=` pairing param is handled separately). + const DEEP_LINK_VIEWS = new Set(['overview', 'timeline', 'network', 'socket', 'state', 'remoteConfig', 'preferences', + 'database', 'files', 'push', 'crashes', 'composer', 'mocks', 'captureRules', 'sdkHealth', 'evidence', 'session']); + const viewFromHash = () => { + const view = new URLSearchParams(location.hash.slice(1)).get('view'); + return view && DEEP_LINK_VIEWS.has(view) ? view : null; + }; + let pendingDeepLinkView = viewFromHash(); + // `#view=network&tx=` opens one capture, so a link can point a teammate at a specific request. + const DEEP_LINK_TX_RE = /^[A-Za-z0-9._:-]{1,128}$/; + let pendingDeepLinkTx = (() => { + const id = new URLSearchParams(location.hash.slice(1)).get('tx'); + return id && DEEP_LINK_TX_RE.test(id) ? id : null; + })(); let sessionRetryTimer = 0; let csrf = ''; let paused = true; @@ -181,6 +203,7 @@ let selectedTransactionId = ''; let selectedTransactionDetail = null; let selectedEventId = ''; + let eventNotesById = new Map(); let eventDetailQuery = ''; let selectedPushIndex = -1; let pushDetailQuery = ''; @@ -194,6 +217,10 @@ // draft came from "Mock this response" (or an edit of a rule that already had one), reset on // every dialog open, and included in the save payload as-is (never re-derived from edited fields). let mockRuleDraftSourceBodySnapshot = null; + // The sequence editor's in-memory steps; re-rendered from the DOM before every add/remove so + // half-typed values survive the re-render. + let mockRuleSteps = []; + let mockRuleDraftUnsupported = false; // Full-window mode for the mock rule dialog. Deliberately outside openMockRuleDialog so it // sticks for the rest of the page session: someone hand-writing JSON bodies wants the big // editor on every rule, not one dialog at a time. @@ -212,6 +239,11 @@ let selectedFilePath = ''; let stream = null; let streamRetry = null; + let streamRetryDelay = 1500; + let overviewRefreshAt = 0; + let overviewRefreshTimer = null; + let lastSocketFetchAt = 0; + let lastRenderedSocketMode = ''; // Highest Timeline event.sequence this browser has taken delivery of, whether via a live WS // frame or a full /api/v1/events refetch -- compared against server.welcome's currentSequence on // every (re)connect so a reconnect that missed events while the socket was down can tell that @@ -283,6 +315,11 @@ } } let networkHostDropOpen = false; + // HAR 1.2 opened entirely in this tab: { name, entries, total, truncated }. Non-null means the + // Network view is an offline viewer over that file — no request in it may reach the server, + // whose ids would not resolve to these imported rows. + const HAR_MAX_ENTRIES = 5000; + let harOffline = null; // WebSockets: `socketConnections` from /connections; `socketMessages_` from /messages for the // active connection/frame-type/direction filters (fetched broad, connection multi-select and @@ -344,7 +381,14 @@ evidenceFlags.delete(key); updateEvidenceUi(); if (!hasSession()) return; - const r = await fetch('/api/v1/evidence/' + encodeURIComponent(kind) + '/' + encodeURIComponent(id), { method: 'DELETE', headers: controlHeaders() }); + let r; + try { r = await fetch('/api/v1/evidence/' + encodeURIComponent(kind) + '/' + encodeURIComponent(id), { method: 'DELETE', headers: controlHeaders() }); } + catch (err) { + evidenceFlags.set(key, prev); + updateEvidenceUi(); + toast('Could not remove evidence: ' + (err?.message || 'network error'), 'error'); + return; + } if (r.ok) { toast('Removed from evidence.'); if (currentView === 'evidence') loadEvidence(); @@ -358,11 +402,17 @@ evidenceFlags.set(key, { kind: String(kind).toLowerCase(), id, label, flaggedAtMs: Date.now() }); updateEvidenceUi(); if (!hasSession()) return; - const r = await fetch('/api/v1/evidence', { + let r; + try { r = await fetch('/api/v1/evidence', { method: 'POST', headers: { ...controlHeaders(), 'Content-Type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams({ kind, id }), - }); + }); } catch (err) { + evidenceFlags.delete(key); + updateEvidenceUi(); + toast('Could not flag evidence: ' + (err?.message || 'network error'), 'error'); + return; + } if (r.ok) { const item = await r.json(); evidenceFlags.set(key, { @@ -435,6 +485,8 @@ if (h < 24) return h + 'h ago'; return Math.floor(h / 24) + 'd ago'; } + /** "1 file" / "3 files": a count with its noun in the right number. */ + const countLabel = (n, one, many = one + 's') => n + ' ' + (Number(n) === 1 ? one : many); const escapeRegExp = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); /** Shared byte formatter — used anywhere the server reports a raw byte count (database size, * export size estimate) so the same value always reads the same way across views. */ @@ -893,15 +945,33 @@ /** `chipsLabel` (e.g. "N of M shown ·") is optional — callers only pass it when * they already track a distinct shown/total pair; never invented for views that don't. */ + /** Live batches re-render toolbars many times a second; rewriting identical markup would drop + * keyboard focus mid-Tab. Skip unchanged markup, and when it did change, put focus back on the + * control with the same data-value / data-chip-index / data-chip-reset, if it still exists. */ + function setHtmlPreservingFocus(el, html) { + if (!el || el.dataset.renderedHtml === html) return; + const focused = el.contains(document.activeElement) ? document.activeElement : null; + const focusKey = focused + ? ['value', 'chipIndex', 'chipReset'].map((k) => (focused.dataset[k] !== undefined ? k + ':' + focused.dataset[k] : '')).join('|') + : null; + el.innerHTML = html; + el.dataset.renderedHtml = html; + if (focusKey == null) return; + const match = [...el.querySelectorAll('button')].find( + (b) => ['value', 'chipIndex', 'chipReset'].map((k) => (b.dataset[k] !== undefined ? k + ':' + b.dataset[k] : '')).join('|') === focusKey, + ); + match?.focus({ preventScroll: true }); + } function appliedFiltersHtml(containerId, chips, resetFn, chipsLabel) { const wrap = $(containerId); if (!chips.length) { wrap.hidden = true; wrap.innerHTML = ''; + delete wrap.dataset.renderedHtml; return; } wrap.hidden = false; - wrap.innerHTML = + setHtmlPreservingFocus(wrap, (chipsLabel ? `${esc(chipsLabel)}` : '') + chips .map( @@ -910,7 +980,7 @@ c.label, )}×`, ) - .join('') + ``; + .join('') + ``); wrap.onclick = (e) => { const resetBtn = e.target.closest('[data-chip-reset]'); if (resetBtn) { @@ -1083,10 +1153,20 @@ .map((r) => { const inner = `${esc(r.k)}${esc(r.v)}${ r.tag ? `${esc(r.tag)}` : '' - }`; - return r.click + }${r.sub ? `${esc(r.sub)}` : ''}`; + const row = r.click ? `` : `
${inner}
`; + if (!r.actions?.length && !r.editorHtml) return row; + // Actions are real `) + .join('')}` + : ''; + return `
${row}${actions}${r.editorHtml ? `
${r.editorHtml}
` : ''}
`; }) .join('')}`; } @@ -1228,7 +1308,12 @@ if (wiredCardGrids.has(containerId)) return; wiredCardGrids.add(containerId); $(containerId).addEventListener('click', (e) => { - const { onToggle, onButton, onTree, onDelete, onEdit, onRow } = cardGridHandlers[containerId]; + const { onToggle, onButton, onTree, onDelete, onEdit, onRow, onRowAction } = cardGridHandlers[containerId]; + const ra = e.target.closest('[data-card-row-action]'); + if (ra && onRowAction) { + onRowAction(ra.dataset.cardRowAction); + return; + } const ed = e.target.closest('[data-card-edit]'); if (ed && onEdit) { onEdit(ed.dataset.cardEdit); @@ -1599,7 +1684,7 @@ // ================================================================ function openConfirm(title, message, confirmLabel) { const overlay = $('confirmModal'); - if (!overlay) return Promise.resolve(window.confirm(message)); + if (!overlay) return Promise.resolve(false); $('confirmTitle').textContent = title; $('confirmMessage').textContent = message; $('confirmSubmit').textContent = confirmLabel || 'Confirm'; @@ -1785,8 +1870,77 @@ id: $('mockRuleId'), method: $('mockRuleMethod'), scheme: $('mockRuleScheme'), host: $('mockRuleHost'), path: $('mockRulePath'), status: $('mockRuleStatus'), delay: $('mockRuleDelay'), headers: $('mockRuleHeaders'), body: $('mockRuleBody'), priority: $('mockRulePriority'), scope: $('mockRuleScope'), + actionType: $('mockRuleActionType'), failureMessage: $('mockRuleFailureMessage'), timeoutMs: $('mockRuleTimeoutMs'), + remoteScheme: $('mockRuleRemoteScheme'), remoteHost: $('mockRuleRemoteHost'), remotePort: $('mockRuleRemotePort'), + remotePath: $('mockRuleRemotePath'), bytesPerSecond: $('mockRuleBytesPerSecond'), + throttleLatency: $('mockRuleThrottleLatency'), queryPredicates: $('mockRuleQueryPredicates'), + headerPredicates: $('mockRuleHeaderPredicates'), bodyPredicate: $('mockRuleBodyPredicate'), }; } + /** Shows only the fields the selected action type needs. */ + function syncMockRuleActionFields() { + const type = $('mockRuleActionType').value; + document.querySelectorAll('#mockRuleModal [data-mock-fields]').forEach((el) => { + el.hidden = !el.dataset.mockFields.split(' ').includes(type); + }); + } + /** Maps an `actionDetail` tree onto the editor's flat form values, or null when the shape is + * richer than this form can express (e.g. a Delay wrapping a sequence, a nested throttle). */ + function mockActionForm(detail) { + if (!detail || !detail.type) return null; + switch (detail.type) { + case 'passthrough': return { type: 'passthrough' }; + case 'static': + return detail.bodyTruncated ? null : { type: 'static', status: detail.statusCode, body: detail.body, headers: detail.headers || {} }; + case 'template': + return detail.templateTruncated ? null : { type: 'template', status: detail.statusCode, body: detail.template, headers: detail.headers || {} }; + case 'delay': { + const inner = mockActionForm(detail.next); + if (!inner || (inner.type !== 'static' && inner.type !== 'template') || inner.delayMs != null) return null; + return { ...inner, delayMs: detail.durationMs }; + } + case 'status_override': return { type: 'status_override', status: detail.statusCode }; + case 'body_replacement': return detail.bodyTruncated ? null : { type: 'body_replacement', body: detail.body }; + case 'connection_failure': return { type: 'connection_failure', message: detail.message || '' }; + case 'timeout': return { type: 'timeout', timeoutMs: detail.durationMs }; + case 'map_remote': return { type: 'map_remote', scheme: detail.scheme, host: detail.host, port: detail.port, path: detail.path }; + case 'throttle': + return detail.next && detail.next.type !== 'passthrough' + ? null + : { type: 'throttle', bytesPerSecond: detail.bytesPerSecond, latencyMs: detail.latencyMs }; + case 'sequence': return mockSequenceForm(detail); + default: return null; + } + } + function mockSequenceForm(detail) { + const steps = []; + for (const step of detail.steps || []) { + const form = mockActionForm(step); + if (!form || !['static', 'connection_failure', 'timeout', 'passthrough'].includes(form.type)) return null; + // Sequence steps can't carry headers in the form; reject those rather than dropping them. + if (form.headers && Object.keys(form.headers).length) return null; + steps.push({ type: form.type, status: form.status, body: form.body, delayMs: form.delayMs, timeoutMs: form.timeoutMs, message: form.message }); + } + return { type: 'sequence', steps, loop: detail.loop === true }; + } + /** Readable one-line summary of a rule's action for the rule list. */ + function mockActionLabel(rule) { + const d = rule.actionDetail; + if (!d) return rule.action || 'Passthrough'; + switch (d.type) { + case 'static': return 'Static'; + case 'template': return 'Template'; + case 'delay': return 'Delay ' + d.durationMs + ' ms'; + case 'sequence': return 'Sequence · ' + countLabel((d.steps || []).length, 'step'); + case 'throttle': return 'Throttle ' + formatBytes(d.bytesPerSecond) + '/s'; + case 'map_remote': return 'Map remote → ' + (d.host || d.path || (d.scheme || '') + (d.port != null ? ':' + d.port : '')); + case 'connection_failure': return 'Connection failure'; + case 'timeout': return 'Timeout ' + d.durationMs + ' ms'; + case 'status_override': return 'Status override'; + case 'body_replacement': return 'Body replacement'; + default: return rule.action || d.type; + } + } function setMockDialogError(msg) { const el = $('mockRuleFormError'); el.textContent = msg || ''; @@ -1804,9 +1958,11 @@ } function syncMockRuleDialogGate() { const btn = $('mockRuleSave'); - const ok = canEditMocks(); + const ok = canEditMocks() && !mockRuleDraftUnsupported; btn.disabled = !ok; - btn.title = ok ? 'Save rule' : hasSession() ? 'The mocks capability is off for this build' : 'Sign in and enable the mocks capability'; + btn.title = mockRuleDraftUnsupported + ? 'This rule’s action cannot be expressed by this editor' + : ok ? 'Save rule' : hasSession() ? 'The mocks capability is off for this build' : 'Sign in and enable the mocks capability'; } /** Same rule server's `validMockHeader` (DevConsoleKtorModule.kt) enforces at the POST boundary * — validated here too so a typo surfaces as an inline dialog error instead of a round trip. */ @@ -1984,18 +2140,20 @@ el.focus({ preventScroll: true }); el.closest('.field')?.scrollIntoView({ block: 'start' }); } - /** Only a plain (optionally delayed) static response with an untruncated body survives a round - * trip through this dialog -- richer actions (ConnectionFailure/Timeout/TemplateResponse/etc.) - * and truncated bodies have no representation in the form, so saving one back would silently - * collapse it into StaticResponse(200, ""). Shared by the mock-rule-list edit-button gate, the - * open guard, and the save-time id-collision guard below so all three agree on the same rule. */ + /** Every rule can be opened: unsupported shapes land in the dialog read-only with an inline + * explanation instead of being silently rewritten as a static response. */ function isMockRuleEditable(rule) { - return Boolean(rule) && (rule.action === 'StaticResponse' || rule.action === 'Delay') && rule.bodyTruncated !== true; + return Boolean(rule); + } + /** True only for actions this editor can round-trip without losing fields. */ + function isMockRuleRoundTrippable(rule) { + return Boolean(rule) && Boolean(mockActionForm(rule.actionDetail)); } function openMockRuleDialog(rule, { editing = false } = {}) { const overlay = $('mockRuleModal'); if (!overlay) return; mockRuleDraftSourceBodySnapshot = rule?.sourceBodySnapshot || null; + mockRuleDraftUnsupported = rule?.unsupported === true; const f = mockRuleFieldEls(); f.id.value = rule?.id || ''; f.id.disabled = editing; @@ -2003,16 +2161,34 @@ f.scheme.value = rule?.scheme || ''; f.host.value = rule?.host || ''; f.path.value = rule?.path || ''; + f.actionType.value = rule?.actionType || 'static'; f.status.value = rule?.status ?? 200; f.delay.value = rule?.delayMs ?? ''; f.headers.value = rule?.headers || ''; f.body.value = rule?.body || ''; + f.failureMessage.value = rule?.failureMessage || ''; + f.timeoutMs.value = rule?.timeoutMs ?? 1000; + f.remoteScheme.value = rule?.remoteScheme || ''; + f.remoteHost.value = rule?.remoteHost || ''; + f.remotePort.value = rule?.remotePort ?? ''; + f.remotePath.value = rule?.remotePath || ''; + f.bytesPerSecond.value = rule?.bytesPerSecond ?? 50000; + f.throttleLatency.value = rule?.latencyMs ?? 0; + f.queryPredicates.value = rule?.queryPredicates || ''; + f.headerPredicates.value = rule?.headerPredicates || ''; + f.bodyPredicate.value = rule?.bodyPredicate || ''; f.priority.value = rule?.priority ?? 0; f.scope.value = rule?.scope || 'SESSION'; + mockRuleSteps = (rule?.steps || []).map((step) => ({ ...step })); + $('mockRuleSequenceLoop').checked = rule?.loop === true; + renderMockRuleSteps(); + syncMockRuleActionFields(); setFieldError(f.id, false, 'mockRuleIdHelp'); setFieldError(f.status, false); setFieldError(f.headers, false); - setMockDialogError(''); + setMockDialogError(mockRuleDraftUnsupported + ? 'This rule uses ' + (rule?.actionLabel || rule?.action || 'an action') + ' that this editor cannot express — saving here would overwrite it. Delete and recreate it instead.' + : ''); $('mockRuleModalTitleText').textContent = editing ? 'Edit mock rule' : 'New mock rule'; setMockBodyExpanded(mockBodyExpanded); $('mockRuleBodyFind').value = ''; @@ -2049,19 +2225,27 @@ function editMockRule(id) { const rule = mockRulesCache.find((r) => r.id === id); if (!rule) return; - // Defense in depth alongside the pencil button's own `editable` gate (cardTogglesHtml/ - // loadMockRules) -- this is the only function that actually opens the dialog for an existing - // rule, so it refuses on its own rather than trusting the button was never reachable. - if (!isMockRuleEditable(rule)) { - toast('This rule uses ' + rule.action + ' and can’t be edited here — saving would replace it with a plain 200 response. Delete and recreate it instead.', 'error'); - return; - } + const form = mockActionForm(rule.actionDetail); openMockRuleDialog( { id: rule.id, method: rule.method || '', scheme: rule.scheme || '', host: rule.host || '', - path: rule.path, status: rule.statusCode, delayMs: rule.delayMs, - headers: Object.entries(rule.headers || {}).map(([k, v]) => k + ': ' + v).join('\n'), - body: rule.body || '', priority: rule.priority, scope: rule.scope, + path: rule.path, priority: rule.priority, scope: rule.scope, + actionType: form?.type, + status: form?.status ?? rule.statusCode, + delayMs: form?.delayMs, + headers: Object.entries(form?.headers || {}).map(([k, v]) => k + ': ' + v).join('\n'), + body: form?.body || '', + failureMessage: form?.message || '', + timeoutMs: form?.timeoutMs, + remoteScheme: form?.scheme || '', remoteHost: form?.host || '', + remotePort: form?.port ?? '', remotePath: form?.path || '', + bytesPerSecond: form?.bytesPerSecond, latencyMs: form?.latencyMs, + steps: form?.steps || [], loop: form?.loop === true, + queryPredicates: Object.entries(rule.queryPredicates || {}).map(([k, v]) => k + '=' + v).join('\n'), + headerPredicates: Object.entries(rule.headerPredicates || {}).map(([k, v]) => k + '=' + v).join('\n'), + bodyPredicate: rule.bodyPredicate || '', + unsupported: !form, + actionLabel: mockActionLabel(rule), // `sourceBodySnapshotTruncated` (see MockRule.json()) means the 64KB-capped value below is // an unparseable prefix of the real snapshot, not the snapshot itself — carrying it into // the draft (and back out to the server on save) would permanently clobber the engine's @@ -2072,43 +2256,197 @@ { editing: true }, ); } + const MOCK_STEP_TYPES = ['static', 'connection_failure', 'timeout', 'passthrough']; + function mockStepDefaults() { + return { type: 'static', status: '200', body: '', delayMs: '', timeoutMs: '1000', message: '' }; + } + function readMockRuleSteps() { + const rows = [...document.querySelectorAll('#mockRuleSteps [data-step-row]')]; + if (!rows.length) return; + mockRuleSteps = rows.map((row) => ({ + type: row.querySelector('[data-step-type]').value, + status: row.querySelector('[data-step-status]')?.value ?? '', + body: row.querySelector('[data-step-body]')?.value ?? '', + delayMs: row.querySelector('[data-step-delay]')?.value ?? '', + timeoutMs: row.querySelector('[data-step-timeout]')?.value ?? '', + message: row.querySelector('[data-step-message]')?.value ?? '', + })); + } + const MOCK_STEP_LABELS = { + static: 'Static response', + connection_failure: 'Connection failure', + timeout: 'Timeout', + passthrough: 'Passthrough (real network)', + }; + function mockStepHtml(step, index) { + const options = MOCK_STEP_TYPES + .map((type) => ``) + .join(''); + let fields = ''; + if (step.type === 'static') { + fields = ` + + `; + } else if (step.type === 'connection_failure') { + fields = ``; + } else if (step.type === 'timeout') { + fields = ``; + } + return `
+ + ${fields} + +
`; + } + function renderMockRuleSteps() { + $('mockRuleSteps').innerHTML = mockRuleSteps.map(mockStepHtml).join(''); + } + function addMockRuleStep() { + readMockRuleSteps(); + mockRuleSteps.push(mockStepDefaults()); + renderMockRuleSteps(); + } + function removeMockRuleStep(index) { + readMockRuleSteps(); + mockRuleSteps.splice(index, 1); + renderMockRuleSteps(); + } + function changeMockRuleStepType(index, type) { + readMockRuleSteps(); + mockRuleSteps[index].type = type; + renderMockRuleSteps(); + } + function mockPredicateLines(text, label) { + const lines = text.split('\n').map((line) => line.trim()).filter(Boolean); + const bad = lines.find((line) => line.indexOf('=') <= 0); + if (bad) throw new Error(label + ' line "' + bad + '" must be key=value.'); + return lines; + } + function mockFormFromDialog() { + const f = mockRuleFieldEls(); + return { + type: f.actionType.value, status: Number(f.status.value), body: f.body.value, + headersText: f.headers.value, delayMs: f.delay.value.trim(), message: f.failureMessage.value.trim(), + timeoutMs: f.timeoutMs.value.trim(), scheme: f.remoteScheme.value.trim(), host: f.remoteHost.value.trim(), + port: f.remotePort.value.trim(), path: f.remotePath.value.trim(), + bytesPerSecond: f.bytesPerSecond.value.trim(), latencyMs: f.throttleLatency.value.trim(), + steps: mockRuleSteps, loop: $('mockRuleSequenceLoop').checked, + }; + } + function validateMockActionForm(form) { + const number = (value) => Number(value); + if (['static', 'template', 'status_override'].includes(form.type) && !(Number.isInteger(form.status) && form.status >= 100 && form.status <= 599)) { + return 'Status must be an integer between 100 and 599.'; + } + if (form.type === 'timeout') { + const ms = number(form.timeoutMs); + if (!(Number.isInteger(ms) && ms >= 0 && ms <= 30000)) return 'Timeout must be between 0 and 30000 ms.'; + } + if (form.type === 'map_remote') { + if (!form.scheme && !form.host && !form.port && !form.path) return 'Map remote needs at least one of scheme, host, port, or path.'; + if (form.scheme && !['http', 'https'].includes(form.scheme)) return 'Remote scheme must be http or https.'; + if (form.path && !form.path.startsWith('/')) return "Remote path must start with '/'."; + if (form.port && !(Number.isInteger(number(form.port)) && number(form.port) >= 1 && number(form.port) <= 65535)) return 'Remote port must be between 1 and 65535.'; + } + if (form.type === 'throttle') { + const bps = number(form.bytesPerSecond), latency = number(form.latencyMs || 0); + if (!(Number.isInteger(bps) && bps >= 1 && bps <= 104857600)) return 'Bytes per second must be between 1 and 104857600.'; + if (!(Number.isInteger(latency) && latency >= 0 && latency <= 30000)) return 'Throttle latency must be between 0 and 30000 ms.'; + } + if (form.type === 'sequence') { + if (!form.steps.length) return 'A sequence needs at least one step.'; + if (form.steps.length > 20) return 'A sequence may contain at most 20 steps.'; + for (const step of form.steps) { + if (step.type === 'static' && !(Number.isInteger(number(step.status)) && number(step.status) >= 100 && number(step.status) <= 599)) return 'Every static step needs a status between 100 and 599.'; + if (step.type === 'timeout' && !(Number.isInteger(number(step.timeoutMs)) && number(step.timeoutMs) >= 0 && number(step.timeoutMs) <= 30000)) return 'Every timeout step needs a value between 0 and 30000 ms.'; + if (step.type === 'static' && step.delayMs !== '' && !(Number.isInteger(number(step.delayMs)) && number(step.delayMs) >= 0 && number(step.delayMs) <= 30000)) return 'Step delays must be between 0 and 30000 ms.'; + } + } + return null; + } + function applyMockActionParams(params, form) { + // Imported rules build `form` from JSON, where an absent value is undefined/null rather than the + // editor's ''; without this guard String(undefined) went out as "undefined" and every imported + // static/template rule without a delay failed validation. + const has = (v) => v != null && v !== ''; + params.set('actionType', form.type); + if (['static', 'template', 'status_override'].includes(form.type)) params.set('status', String(form.status)); + if (['static', 'template', 'body_replacement'].includes(form.type)) params.set('body', form.body || ''); + if (form.type === 'static' || form.type === 'template') { + if ((form.headersText || '').trim()) params.set('headers', form.headersText); + if (has(form.delayMs)) params.set('delayMs', String(form.delayMs)); + } else if (form.type === 'connection_failure') { + if (form.message) params.set('failureMessage', form.message); + } else if (form.type === 'timeout') { + if (has(form.timeoutMs)) params.set('timeoutMs', String(form.timeoutMs)); + } else if (form.type === 'map_remote') { + if (form.scheme) params.set('remoteScheme', form.scheme); + if (form.host) params.set('remoteHost', form.host); + if (form.port) params.set('remotePort', form.port); + if (form.path) params.set('remotePath', form.path); + } else if (form.type === 'throttle') { + if (has(form.bytesPerSecond)) params.set('bytesPerSecond', String(form.bytesPerSecond)); + params.set('latencyMs', form.latencyMs || '0'); + } else if (form.type === 'sequence') { + form.steps.forEach((step) => { + params.append('stepType', step.type); + params.append('stepStatus', step.type === 'static' ? String(step.status ?? '') : ''); + params.append('stepBody', step.type === 'connection_failure' ? (step.message || '') : (step.body || '')); + params.append('stepDelayMs', step.type === 'static' ? String(step.delayMs ?? '') : ''); + params.append('stepTimeoutMs', step.type === 'timeout' ? String(step.timeoutMs ?? '') : ''); + }); + params.set('loop', form.loop ? 'true' : 'false'); + } + } async function saveMockRuleDialog() { - if (!canEditMocks()) return; + if (!canEditMocks() || mockRuleDraftUnsupported) return; const f = mockRuleFieldEls(); const id = f.id.value.trim(); - const status = Number(f.status.value); const idValid = MOCK_RULE_ID_RE.test(id); - const statusValid = Number.isInteger(status) && status >= 100 && status <= 599; setFieldError(f.id, !idValid, 'mockRuleIdHelp'); - setFieldError(f.status, !statusValid); - if (!idValid || !statusValid) { - setMockDialogError(!idValid ? 'Rule id must start with a letter or digit and contain only letters, digits, dot, underscore, or hyphen.' : 'Status must be an integer between 100 and 599.'); - (!idValid ? f.id : f.status).focus(); + if (!idValid) { + setMockDialogError('Rule id must start with a letter or digit and contain only letters, digits, dot, underscore, or hyphen.'); + f.id.focus(); return; } // POST /api/v1/mocks/rules upserts by id, so a "new rule" save whose id happens to collide - // with an existing non-editable rule (a fault-injection/template action, or a truncated body) - // would silently replace it with this form's plain StaticResponse -- exactly the destructive - // save the pencil-button gate exists to prevent, just reached from the New-rule dialog instead. + // with an existing rule this editor cannot round-trip would silently replace it. const collision = mockRulesCache.find((r) => r.id === id); - if (collision && !isMockRuleEditable(collision)) { - const msg = 'A rule named "' + id + '" already exists as ' + collision.action + ' — saving here would replace it with a plain 200 response. Delete it first or choose a different id.'; + if (collision && !isMockRuleRoundTrippable(collision)) { + const msg = 'A rule named "' + id + '" already exists as ' + mockActionLabel(collision) + ' — saving here would replace it. Delete it first or choose a different id.'; setMockDialogError(msg); toast(msg, 'error'); return; } - const headerErr = f.headers.value.trim() ? validateMockRuleHeaders(f.headers.value) : null; + readMockRuleSteps(); + const form = mockFormFromDialog(); + const headerErr = + (form.type === 'static' || form.type === 'template') && form.headersText.trim() + ? validateMockRuleHeaders(form.headersText) + : null; setFieldError(f.headers, Boolean(headerErr)); if (headerErr) { setMockDialogError(headerErr); f.headers.focus(); return; } + const actionErr = validateMockActionForm(form); + if (actionErr) { setMockDialogError(actionErr); toast(actionErr, 'error'); return; } + let queryPredicateLines = [], headerPredicateLines = []; + try { + queryPredicateLines = mockPredicateLines(f.queryPredicates.value, 'Query predicate'); + headerPredicateLines = mockPredicateLines(f.headerPredicates.value, 'Header predicate'); + } catch (err) { setMockDialogError(err.message); return; } + setMockDialogError(''); const params = new URLSearchParams({ - id, status: String(status), path: f.path.value.trim() || '.*', - priority: String(Number(f.priority.value) || 0), scope: f.scope.value || 'SESSION', body: f.body.value, + id, path: f.path.value.trim() || '.*', + priority: String(Number(f.priority.value) || 0), scope: f.scope.value || 'SESSION', }); if (f.method.value) params.set('method', f.method.value); if (f.scheme.value.trim()) params.set('scheme', f.scheme.value.trim()); if (f.host.value.trim()) params.set('host', f.host.value.trim()); - if (f.delay.value.trim()) params.set('delayMs', f.delay.value.trim()); - if (f.headers.value.trim()) params.set('headers', f.headers.value); + applyMockActionParams(params, form); + queryPredicateLines.forEach((line) => params.append('queryPredicate', line)); + headerPredicateLines.forEach((line) => params.append('headerPredicate', line)); + if (f.bodyPredicate.value.trim()) params.set('bodyPredicate', f.bodyPredicate.value.trim()); + const editingRule = mockRulesCache.find((rule) => rule.id === id); + if (editingRule) params.set('enabled', String(editingRule.enabled === true)); // Carries through as captured at dialog-open time — never re-derived from the (possibly // user-edited) body field, since the whole point is a diff against the untouched original. if (mockRuleDraftSourceBodySnapshot) params.set('sourceBodySnapshot', mockRuleDraftSourceBodySnapshot); @@ -2814,7 +3152,7 @@ if (spanSec > 0) cells.push(metricHtml('Rate', (events.length / spanSec).toFixed(1), '/s', 'ink')); } $('timelineMetrics').innerHTML = cells.join(''); - $('timelineBadge').textContent = events.length + ' events'; + $('timelineBadge').textContent = countLabel(events.length, 'event'); } function timelineChips(shownCount) { @@ -2848,6 +3186,13 @@ const TIMELINE_EMPTY_HTML = '
' + spot('search') + '
No events match
Clear a filter to see the other captured events.
'; const render = () => { + const noteInput = $('eventNoteInput'); + const noteEventId = $('eventDetail').dataset.noteEventId; + const noteSavedValue = eventNotesById.get(selectedEventId) ?? events.find((event) => event.id === selectedEventId)?.note; + const noteDirty = noteInput && noteEventId === selectedEventId && (noteSavedValue == null || noteInput.value !== noteSavedValue); + const noteEditing = noteInput && document.activeElement === noteInput; + const noteDraft = noteDirty ? noteInput.value : null; + const noteSelection = noteEditing ? [noteInput.selectionStart, noteInput.selectionEnd, noteInput.selectionDirection] : null; const q = $('search').value.toLowerCase(); const rows = events.filter( (e) => @@ -2888,7 +3233,18 @@ $('timelineFootRight').textContent = paused ? 'paused' : 'tailing'; timelineMetrics(rows); timelineChips(rows.length); - renderEventDetail(); + if (noteDirty && selectedEventId === $('eventDetail').dataset.noteEventId) { + const event = events.find((entry) => entry.id === selectedEventId); + const previous = event?.note; + if (event) event.note = noteDraft; + renderEventDetail(); + if (event) event.note = previous; + const restored = $('eventNoteInput'); + if (noteEditing && restored) { + restored.focus({ preventScroll: true }); + restored.setSelectionRange(noteSelection[0], noteSelection[1], noteSelection[2]); + } + } else if (!noteEditing) renderEventDetail(); }; viewControllers.timeline = { @@ -2904,9 +3260,9 @@ if (!sources.includes(timelineSourceFilter)) timelineSourceFilter = ''; const counts = {}; events.forEach((e) => { counts[e.pluginId] = (counts[e.pluginId] || 0) + 1; }); - $('timelineSourceSeg').innerHTML = + setHtmlPreservingFocus($('timelineSourceSeg'), `` + - sources.map((s) => ``).join(''); + sources.map((s) => ``).join('')); } const refreshSources = renderTimelineSourceSeg; @@ -2930,6 +3286,11 @@ // for any row with an attachmentId ("APPLIED"/"NOT_APPLICABLE"/omitted-as-null when unknown) — // never inferred from pluginId here. Only meaningful when eventAttachmentIdsById also has the id. const eventRedactionApplicabilityById = new Map(); + function boundedSet(map, key, value, cap = 200) { + map.delete(key); + map.set(key, value); + while (map.size > cap) map.delete(map.keys().next().value); + } // Negative cache: event ids renderEventDetail() has already scheduled exactly one // ensureEventPayloadsLoaded().then(rerender) for. Without this, an event whose payload is // permanently absent (host never wired retention, or it aged out of the retained store — both @@ -2968,10 +3329,10 @@ const rows = body?.data || []; if (rows.length) retainedStoreConfirmedWired = true; rows.forEach((e) => { - if (e.payloadJson) eventPayloadsById.set(e.id, e.payloadJson); + if (e.payloadJson) boundedSet(eventPayloadsById, e.id, e.payloadJson); if (e.attachmentId) { - eventAttachmentIdsById.set(e.id, e.attachmentId); - eventRedactionApplicabilityById.set(e.id, e.redactionApplicability ?? null); + boundedSet(eventAttachmentIdsById, e.id, e.attachmentId); + boundedSet(eventRedactionApplicabilityById, e.id, e.redactionApplicability ?? null); } }); }) @@ -2985,6 +3346,7 @@ function renderEventDetail() { const pane = $('eventDetail'); const event = events.find((e) => e.id === selectedEventId); + if (event) pane.dataset.noteEventId = event.id; if (!event) { renderEmpty(pane, 'activity', 'No event selected', 'Select a timeline event from the list to inspect it.'); return; @@ -3068,7 +3430,7 @@ ${screenshotHtml} ${kvGridHtml(kvs, true)} ${stackTraceHtml} -
${icon('chevron', 'ic-sm fold-chevron')}Add note
+
${icon('chevron', 'ic-sm fold-chevron')}Add note
`; restoreFocus(focusSnap, pane); @@ -3111,7 +3473,7 @@ // active) — yanking them back to page 1 loses selection and place. Fresh page = safe refresh. // Scroll is preserved around the reload for all three list bodies. const LIVE_TAIL_LOADERS = { - network: () => { if (!networkCursorActive()) liveTailPreservingScroll('transactions', loadNetwork); }, + network: () => { if (!harOffline && !networkCursorActive() && !networkRunId) liveTailPreservingScroll('transactions', loadNetwork); }, socket: () => liveTailPreservingScroll('sockets', liveTailRefreshSockets), push: () => liveTailPreservingScroll('pushEvents', loadPush), }; @@ -3135,7 +3497,17 @@ * plain loadSockets() would silently reselect whatever now sits at the old index once a live * frame prepends. Re-locates the previously selected frame by its (connection, direction, * timestamp) identity after reloading so it stays selected instead of swapping under the user. */ + // Live tail only (never a user-driven filter change): at most one frame refetch per + // SOCKET_LIVE_TAIL_MIN_MS, and none while the tab is hidden -- the trailing timer catches up. + const SOCKET_LIVE_TAIL_MIN_MS = 2000; + let socketLiveTailTimer = null; async function liveTailRefreshSockets() { + const wait = document.hidden ? SOCKET_LIVE_TAIL_MIN_MS : SOCKET_LIVE_TAIL_MIN_MS - (Date.now() - lastSocketFetchAt); + if (wait > 0) { + clearTimeout(socketLiveTailTimer); + socketLiveTailTimer = setTimeout(() => { if (currentView === 'socket') LIVE_TAIL_LOADERS.socket(); }, wait); + return; + } const prev = socketSelectedIndex >= 0 ? socketMessages_[socketSelectedIndex] : null; await loadSockets(); if (!prev) return; @@ -3274,7 +3646,9 @@ return; } if (value.type === 'server.welcome') { + streamRetryDelay = 1500; $('lamp').classList.remove('expired'); + $('lamp').classList.remove('reconnecting'); $('lamp').classList.add('live'); $('status').textContent = paused ? 'Paused' : 'Live'; // lastKnownSequence starts at -1, so this only fires on a genuine reconnect (one that @@ -3306,10 +3680,19 @@ scheduleTimelineMerge(); } const liveTailKind = LIVE_TAIL_KIND_BY_PLUGIN[value.event.pluginId]; + if (currentView === 'overview') { + const wait = Math.max(0, 3000 - (Date.now() - overviewRefreshAt)); + clearTimeout(overviewRefreshTimer); + overviewRefreshTimer = setTimeout(() => { + overviewRefreshAt = Date.now(); + if (currentView === 'overview' && !paused) loadOverview(); + }, wait); + } if (liveTailKind) scheduleLiveTailRefresh(liveTailKind); }; stream.onclose = (event) => { $('lamp').classList.remove('live'); + $('lamp').classList.add('reconnecting'); // A queued merge flush must not fire after the socket that queued it is gone -- but the // frames it buffered were already delivered by that socket, so flush them synchronously now // instead of discarding: reconnect never re-fetches, and the buffered batch is exactly the @@ -3327,11 +3710,27 @@ return; } if (token) { - $('status').textContent = 'RECONNECTING LIVE STREAM'; - streamRetry = setTimeout(connectStream, 1500); + setStatus(navigator.onLine === false ? 'Offline — reconnecting when online' : 'Reconnecting…'); + if (navigator.onLine !== false) { + const delay = Math.min(30000, streamRetryDelay) * (0.8 + Math.random() * 0.4); + streamRetryDelay = Math.min(30000, streamRetryDelay * 2); + streamRetry = setTimeout(connectStream, delay); + } } }; } + window.addEventListener('hashchange', () => { + const view = viewFromHash(); + if (view && view !== currentView && hasSession()) show(view); + }); + window.addEventListener('online', () => { if (token && !streamRetry) connectStream(); }); + window.addEventListener('offline', () => { + clearTimeout(streamRetry); streamRetry = null; + if (token) setStatus('Offline — reconnecting when online'); + }); + document.addEventListener('visibilitychange', () => { + if (document.visibilityState === 'visible' && token && stream?.readyState !== WebSocket.OPEN && stream?.readyState !== WebSocket.CONNECTING) connectStream(); + }); // ================================================================ // Session expiry @@ -3353,6 +3752,7 @@ token = ''; invalidateSessionCache(); csrf = ''; + try { sessionStorage.removeItem('devconsole.browserSession'); } catch { /* storage unavailable */ } stream?.close(); stream = null; $('lamp').classList.remove('live'); @@ -3469,7 +3869,8 @@ const runs = runsRes.ok ? (await runsRes.json()).data || [] : []; const previousRun = runs.find((run) => run.status !== 'ACTIVE') || null; const crashSample = crashesRes.ok ? ((await crashesRes.json()).data || []).map(decorateCrashRow) : []; - renderOverview(await overviewRes.json(), meta, netSample, eventSample, previousRun, crashSample); + const currentRunId = (runs.find((run) => run.current) || {}).id || null; + renderOverview(await overviewRes.json(), meta, netSample, eventSample, previousRun, crashSample, currentRunId); } /** Keeps the session-pill's visible label and its hover tooltip (the full text, for when the * pill has ellipsised at a narrow width — see the topbar breakpoint ladder in dashboard.css) in @@ -3485,6 +3886,11 @@ openAccess = isOpen; token = isOpen ? 'open' : accessToken; csrf = isOpen ? '' : csrfToken; + if (!isOpen) { + try { sessionStorage.setItem('devconsole.browserSession', JSON.stringify({ token: accessToken, csrf: csrfToken })); } catch { /* storage unavailable */ } + } else { + try { sessionStorage.removeItem('devconsole.browserSession'); } catch { /* storage unavailable */ } + } sessionExpired = false; consecutiveAuthFailures = 0; Object.values(viewContainers).forEach((id) => { @@ -3503,6 +3909,8 @@ // history still re-pauses (see the cursor check in the timeline load). setPaused(false); loadOverview(); + if (pendingDeepLinkView && pendingDeepLinkView !== 'overview') show(pendingDeepLinkView); + pendingDeepLinkView = null; // Prime the mocks/composer capability flags so "Mock this response"/"Resend" aren't dead // until Mocks/Composer are visited. loadMockRules(); @@ -3522,15 +3930,13 @@ body: 'code=' + encodeURIComponent(code) + '&browserLabel=' + encodeURIComponent(navigator.userAgent.slice(0, 96)), }); if (!r.ok) { - setStatus( - r.status === 401 ? 'Code expired or invalid' : 'Code rejected', - (r.status === 401 ? 'Code expired or invalid' : 'Code rejected') + " — get a fresh one from the device's More screen (codes are single-use and expire after five minutes)", - ); - if (source === 'manual') toast('Session code rejected.', 'error'); + const message = r.status === 401 ? 'Code expired or invalid' : 'Code rejected'; + setStatus(message + ' — ' + unavailableReason(r.status), message + " — get a fresh one from the device's More screen (codes are single-use and expire after five minutes)"); + toast(message + ': ' + unavailableReason(r.status), 'error'); // Codes are single-use, so a code that just failed exchange is burned either way — strip it // from the URL on the auto-connect path same as the success branch below does, or a refresh // just resubmits the same dead code and repeats this failure forever. - if (source !== 'manual') history.replaceState(null, '', location.pathname); + history.replaceState(null, '', location.pathname); return; } const b = await r.json(); @@ -3561,8 +3967,8 @@ ${esc(t.status || 'Failed')}${esc(t.durationMs != null ? t.durationMs + ' ms' : '—')} `; } - function renderOverview(body, meta, netSample, eventSample, previousRun, crashSample = []) { - $('overviewCrashBanner').hidden = true; + function renderOverview(body, meta, netSample, eventSample, previousRun, crashSample = [], currentRunId = null) { + renderOverviewCrashBanner(previousRun); $('overviewMetrics').innerHTML = ''; $('overviewCards').classList.remove('cards-grid'); const latest = netSample.slice().sort((a, b) => (b.startedAtEpochMs || 0) - (a.startedAtEpochMs || 0)); @@ -3570,10 +3976,15 @@ const p95 = percentile(durations, 0.95); const requestCount = body ? Object.values(body.networkStatusDistribution || {}).reduce((sum, count) => sum + Number(count), 0) : 0; $('overviewSubtitle').textContent = body - ? (requestCount || netSample.length) + ' requests in this session' + (p95 != null ? ' · p95 ' + p95 + ' ms' : '') + ? countLabel(requestCount || netSample.length, 'request') + ' in this session' + (p95 != null ? ' · p95 ' + p95 + ' ms' : '') : 'Connect this browser to see session activity.'; const failures = latest.filter(failing).map((t) => ({ time: t.startedAtEpochMs || 0, html: overviewNetworkRow(t) })); - const crashes = crashSample.map((e) => ({ time: e.wallTimeMs || 0, html: `` })); + // Retained crashes span every run; one from an earlier run is labelled as such (with its date) + // so it does not read as something that just happened in the session this page is about. + const crashWhen = (e) => (currentRunId && e.sessionId && e.sessionId !== currentRunId + ? 'earlier run · ' + new Date(e.wallTimeMs || 0).toLocaleString([], { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' }) + : time(e.wallTimeMs)); + const crashes = crashSample.map((e) => ({ time: e.wallTimeMs || 0, html: `` })); const attention = failures.concat(crashes).sort((a, b) => b.time - a.time).slice(0, 5); const connect = body ? '' : `
`; $('overviewCards').innerHTML = `${connect} @@ -3734,6 +4145,19 @@ /** Shared by loadNetwork and loadMoreNetworkIfPossible so a scroll-triggered "load more" * request always respects exactly the filters the operator has applied — never a subtly * different set. */ + /** "Yesterday 23:03 · completed · 1 record" -- a bare time read as today for a run from last week. */ + function networkRunLabel(run) { + const started = new Date(run.startedAtEpochMs); + const today = new Date(); + const yesterday = new Date(today.getFullYear(), today.getMonth(), today.getDate() - 1); + const sameDay = (a, b) => a.toDateString() === b.toDateString(); + const day = sameDay(started, today) ? '' : sameDay(started, yesterday) ? 'Yesterday ' : + started.toLocaleDateString(undefined, { month: 'short', day: 'numeric' }) + ' '; + const parts = [day + time(run.startedAtEpochMs), run.status.toLowerCase()]; + if (run.pinned) parts.push('pinned'); + if (run.recordCount != null) parts.push(run.recordCount + (run.recordCount === 1 ? ' record' : ' records')); + return parts.join(' · '); + } function networkFilterEntries() { return [ ['query', 'networkSearch'], @@ -3750,37 +4174,96 @@ ['error', 'networkError'], ['correlationId', 'networkCorrelation'], ['tag', 'networkTag'], + ['body', 'networkBody'], ] .map(([name, id]) => [name, $(id).value.trim()]) .filter(([, value]) => value); } + // '' is the live run; otherwise a completed run's id, read back from its durable captures + // (server: `?sessionId=` on the list, detail, cURL and HAR/Postman routes). Past runs never live-tail. + let networkRunId = ''; + function networkRunParam() { + return networkRunId ? 'sessionId=' + encodeURIComponent(networkRunId) : ''; + } + function withNetworkRun(url) { + const param = networkRunParam(); + if (!param) return url; + return url + (url.includes('?') ? '&' : '?') + param; + } + /** Fills the Run picker from GET /api/v1/runs; hidden until there is a past run to pick. */ + async function refreshNetworkRunPicker() { + const res = await cachedJson('/api/v1/runs', 30000).catch(() => null); + if (!res?.ok) return; + const runs = ((await res.json()).data || []).filter((run) => !run.current); + if (networkRunId && !runs.some((run) => run.id === networkRunId)) { + networkRunId = ''; + toast('That run is no longer retained — showing the live run.', 'error'); + } + const select = $('networkRun'); + select.innerHTML = '' + runs + .map((run) => ``) + .join(''); + select.value = networkRunId; + $('networkRunGroup').hidden = runs.length === 0 && !networkRunId; + } + function selectNetworkRun(id) { + if (id === networkRunId) return; + networkRunId = id; + networkSelectedIds.clear(); + networkDetailCache.clear(); + selectedTransactionId = ''; + selectedTransactionDetail = null; + $('networkBadge').textContent = id ? 'Past run' : ''; + loadNetwork(); + } async function loadNetwork(cursor = null) { + // An open HAR is the whole data source: never fetch, and never let the 5s view cache or a + // live-tail refresh replace the imported rows with the live ones. + if (harOffline) return loadHarOffline(); if (!hasSession()) return loadNetworkImpl(cursor); return runViewLoader('network', () => loadNetworkImpl(cursor)); } + function loadHarOffline() { + networkPage = harOffline.entries; + networkCursor = null; + networkPagedIntoHistory = false; + setNavCount('navCountNetwork', networkPage.length); + applyNetworkFilters(); + } async function loadNetworkImpl(cursor = null) { if (!token) return; - networkPagedIntoHistory = Boolean(cursor); + const gen = nextGen('network'); + if (!cursor) networkPagedIntoHistory = false; const params = new URLSearchParams({ limit: String(NETWORK_FETCH_LIMIT) }); if (cursor) params.set('cursor', cursor); networkFilterEntries().forEach(([name, value]) => params.append(name, value)); + if (networkRunId) params.set('sessionId', networkRunId); + if (!cursor) refreshNetworkRunPicker(); const r = await fetch('/api/v1/network/transactions?' + params, { headers: auth() }); + if (r.status === 404 && networkRunId) { + selectNetworkRun(''); + return; + } requireLoad(r); const body = await r.json(); + if (!isLatest('network', gen)) return; networkPage = body.data || []; networkCursor = body.page?.nextCursor || null; $('networkOlder').disabled = !body.page?.hasMore; - if (networkHostFilter.size) { + if (!cursor && networkHostFilter.size) { // Drop hosts from the selection that no longer appear on this page. [...networkHostFilter].forEach((h) => { if (!networkPage.some((t) => t.host === h)) networkHostFilter.delete(h); }); } - if (networkSelectedIds.size) { + if (!cursor && networkSelectedIds.size) { // Same pruning rule as networkHostFilter above: an exported-selection checkbox can only ever // refer to a row the operator can currently see evidence of. [...networkSelectedIds].forEach((id) => { if (!networkPage.some((t) => t.id === id)) networkSelectedIds.delete(id); }); } setNavCount('navCountNetwork', networkPage.length); applyNetworkFilters(); + // Keep an open latency panel in step with the list: new captures, a reconnect to a restarted + // app, or a run switch all land here, and the panel otherwise kept the previous numbers. + if (!cursor && networkEndpointsOpen) loadNetworkEndpoints(); } /** Infinite-scroll companion to the Older/Newest pager: fired by the Network virtualizer when @@ -3797,6 +4280,7 @@ try { const params = new URLSearchParams({ limit: String(NETWORK_FETCH_LIMIT), cursor: networkCursor }); networkFilterEntries().forEach(([name, value]) => params.append(name, value)); + if (networkRunId) params.set('sessionId', networkRunId); const r = await fetch('/api/v1/network/transactions?' + params, { headers: auth() }); if (!r.ok) return; const body = await r.json(); @@ -3820,7 +4304,14 @@ /** Applies Status/Method/Service/Failures-only client-side over the broad `networkPage`, * recomputing `transactions` (the visible subset), then re-renders everything downstream. */ function applyNetworkFilters() { + // The live list's search is a server query; an imported HAR has no server, so the same box + // filters the mapped rows client-side over the fields the row/detail actually show. + const offlineQuery = harOffline ? $('networkSearch').value.trim().toLowerCase() : ''; transactions = networkPage.filter((t) => { + if (offlineQuery) { + const haystack = [t.method, t.host, t.path, t.query, t.status, t.request?.url].join(' ').toLowerCase(); + if (!haystack.includes(offlineQuery)) return false; + } if (networkFailOnly && !failing(t)) return false; if (networkMethodFilter && t.method !== networkMethodFilter) return false; if (networkHostFilter.size && !networkHostFilter.has(t.host)) return false; @@ -3871,7 +4362,253 @@ let networkOrder = []; const NETWORK_EMPTY_HTML = '
' + spot('search') + '
No transactions match
Clear a filter or widen the status/method selection to see the other captures.
'; + // With nothing narrowing the list, an empty page means no traffic yet -- "clear a filter" would mislead. + const NETWORK_IDLE_HTML = '
' + spot('search') + '
No requests captured yet
Requests the app makes appear here as they happen.
'; + const NETWORK_RUN_IDLE_HTML = '
' + spot('search') + '
No requests in this run
This run finished without capturing any network traffic.
'; + const NETWORK_HAR_EMPTY_HTML = '
' + spot('search') + '
No requests match
Clear the search or the status/method filter to see the rest of this HAR file.
'; + const NETWORK_HAR_NONE_HTML = '
' + spot('search') + '
This HAR file has no entries
A HAR 1.2 export records its requests under log.entries.
'; + function networkEmptyHtml() { + if (harOffline) return networkPage.length ? NETWORK_HAR_EMPTY_HTML : NETWORK_HAR_NONE_HTML; + if (networkFilterEntries().length || networkHostFilter.size) return NETWORK_EMPTY_HTML; + return networkRunId ? NETWORK_RUN_IDLE_HTML : NETWORK_IDLE_HTML; + } + + // ---------------------------------------------------------------- + // HAR 1.2 import — read, parsed, and rendered entirely in this tab. The file is never uploaded: + // a HAR often carries auth headers and bodies, so it must not leave the browser. + // ---------------------------------------------------------------- + function renderHarBanner() { + const banner = $('networkHarBanner'); + if (!banner) return; + if (!harOffline) { banner.hidden = true; banner.innerHTML = ''; return; } + const truncated = harOffline.truncated + ? ` · first ${HAR_MAX_ENTRIES.toLocaleString()} of ${harOffline.total.toLocaleString()} requests` + : ''; + banner.hidden = false; + banner.innerHTML = `${icon('folder', 'ic-sm')}Viewing ${esc(harOffline.name)} · ${countLabel(harOffline.entries.length, 'request')} (offline)${esc(truncated)}`; + $('networkHarClose').onclick = closeHarOffline; + } + + /** Hides or restores every control whose action would either fetch the live capture store or + * address a transaction id that only exists on the device. Client-side controls (search, the + * status/method segments, host dropdown, Full endpoint) stay live. */ + function applyHarOfflineChrome() { + const off = Boolean(harOffline); + const setHidden = (id, hidden) => { const el = $(id); if (el) el.hidden = hidden; }; + ['networkAdvFilters', 'networkEndpointsBtn', 'networkSelectAllVisible', 'networkNewest', 'networkOlder', 'networkRefresh'] + .forEach((id) => setHidden(id, off)); + if (off) setHidden('networkRunGroup', true); + const har = $('networkHarDownload'); + const postman = $('networkPostmanDownload'); + if (har) { har.disabled = off; har.title = off ? 'Not available while viewing a HAR file' : 'Export every captured transaction (up to 500)'; } + if (postman) { postman.disabled = off; postman.title = off ? 'Not available while viewing a HAR file' : 'Export every captured transaction (up to 500)'; } + const clear = $('networkClear'); + if (clear) { + clear.disabled = off || !hasSession(); + clear.title = off ? 'Not available while viewing a HAR file' : hasSession() ? 'Discard every captured request on the device' : 'Connect this browser first'; + } + if (off) { + const bar = $('networkSelectionBar'); + if (bar) { bar.hidden = true; bar.innerHTML = ''; } + } + } + + function readLocalFileText(file) { + if (typeof file.text === 'function') return file.text(); + return new Promise((resolve, reject) => { + const reader = new FileReader(); + reader.onload = () => resolve(String(reader.result || '')); + reader.onerror = () => reject(reader.error || new Error('Could not read the file')); + reader.readAsText(file); + }); + } + + /** Whether a MIME type is worth base64-decoding to text. Everything else keeps an honest + * "binary body (N bytes)" placeholder instead of mojibake. */ + function harIsTextualMime(mimeType) { + const mime = String(mimeType || '').toLowerCase(); + return mime.startsWith('text/') + || /(json|xml|javascript|ecmascript|x-www-form-urlencoded|graphql|yaml|csv|xhtml|svg)/.test(mime); + } + + function harBase64ByteLength(text) { + const clean = String(text || '').replace(/\s/g, ''); + const padding = (clean.match(/=+$/) || [''])[0].length; + return Math.max(0, Math.floor((clean.length * 3) / 4) - padding); + } + + function harDecodeBase64(text) { + try { + const binary = atob(String(text || '').replace(/\s/g, '')); + if (typeof TextDecoder === 'function') { + const bytes = new Uint8Array(binary.length); + for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i); + return new TextDecoder('utf-8').decode(bytes); + } + return binary; + } catch { + return null; + } + } + + /** HAR `content`/`postData` → the BodyPreview shape the detail pane already renders. */ + function harBodyPreview(content) { + if (!content) return null; + const text = content.text; + if (typeof text !== 'string' || !text) { + const size = Number(content.size); + return Number.isFinite(size) && size > 0 ? { type: 'binary', length: size } : null; + } + if (String(content.encoding || '').toLowerCase() === 'base64') { + if (!harIsTextualMime(content.mimeType)) { + return { type: 'binary', length: harBase64ByteLength(text) || Number(content.size) || text.length }; + } + const decoded = harDecodeBase64(text); + if (decoded == null) return { type: 'binary', length: harBase64ByteLength(text) }; + return { type: 'text', value: decoded }; + } + return { type: 'text', value: text }; + } + + function harHeaderRows(headers) { + return (Array.isArray(headers) ? headers : []) + .map((header) => ({ name: String(header?.name ?? ''), value: String(header?.value ?? '') })) + .filter((header) => header.name); + } + + function harContentTypeOf(headers) { + return (headers.find((header) => header.name.toLowerCase() === 'content-type') || {}).value || ''; + } + + /** One HAR entry → the same transaction shape the Network list and detail already render. */ + function harEntryToTransaction(entry, index) { + const request = entry?.request || {}; + const response = entry?.response || {}; + const url = String(request.url || ''); + let host = ''; + let path = '/'; + let query = ''; + try { + const parsed = new URL(url); + host = parsed.host; + path = parsed.pathname || '/'; + query = parsed.search.replace(/^\?/, ''); + } catch { + const noHash = url.split('#')[0]; + const question = noHash.indexOf('?'); + query = question >= 0 ? noHash.slice(question + 1) : ''; + const pathPart = question >= 0 ? noHash.slice(0, question) : noHash; + const slash = pathPart.indexOf('/'); + host = slash >= 0 ? pathPart.slice(0, slash) : pathPart; + path = slash >= 0 ? pathPart.slice(slash) : '/'; + } + const requestHeaders = harHeaderRows(request.headers); + const responseHeaders = harHeaderRows(response.headers); + const postData = request.postData || null; + const requestBody = postData && typeof postData.text === 'string' && postData.text + ? { type: 'text', value: postData.text } + : null; + const statusValue = Number(response.status); + const status = Number.isFinite(statusValue) && statusValue > 0 ? statusValue : undefined; + const duration = Number(entry?.time); + const started = Date.parse(entry?.startedDateTime || ''); + return { + id: 'har:' + index, + method: String(request.method || 'GET').toUpperCase(), + host, + path, + query, + status, + durationMs: Number.isFinite(duration) && duration >= 0 ? Math.round(duration) : null, + startedAtEpochMs: Number.isFinite(started) ? started : 0, + error: entry?._error || response._error || undefined, + request: { + url, + headers: requestHeaders, + contentType: String(postData?.mimeType || harContentTypeOf(requestHeaders)), + body: requestBody, + }, + response: { + headers: responseHeaders, + contentType: String(response.content?.mimeType || harContentTypeOf(responseHeaders)), + body: harBodyPreview(response.content), + }, + correlationId: '', + tags: {}, + }; + } + + function openHarFilePicker() { + $('networkHarFile')?.click(); + } + + async function handleHarFileSelected(event) { + const input = event.target; + const file = input.files && input.files[0]; + // Reset first so picking the same file again still fires `change`. + input.value = ''; + if (!file) return; + let text; + try { + text = await readLocalFileText(file); + } catch { + toast('Not a HAR file', 'error'); + return; + } + const parsed = parseJsonText(text); + const entries = parsed?.log?.entries; + if (!Array.isArray(entries)) { + // Nothing about the current view changes when the file is rejected. + toast('Not a HAR file', 'error'); + return; + } + const total = entries.length; + const mapped = entries.slice(0, HAR_MAX_ENTRIES).map(harEntryToTransaction); + enterHarOffline({ name: file.name || 'HAR file', entries: mapped, total, truncated: total > HAR_MAX_ENTRIES }); + } + + function enterHarOffline(har) { + harOffline = har; + networkSelectedIds.clear(); + networkHostFilter.clear(); + selectedTransactionId = ''; + selectedTransactionDetail = null; + networkPinnedId = ''; + networkActionsMenuOpen = false; + if (networkTab === 'diff' || networkTab === 'related') networkTab = 'response'; + networkPage = har.entries; + transactions = []; + toggleNetworkEndpoints(false); + if (currentView !== 'network') show('network'); + // Render explicitly even when show()'s 5s view cache short-circuits its loader. + loadHarOffline(); + if (!har.entries.length) renderNetworkEmpty(); + } + + function closeHarOffline() { + if (!harOffline) return; + harOffline = null; + networkSelectedIds.clear(); + networkHostFilter.clear(); + networkPage = []; + transactions = []; + selectedTransactionId = ''; + selectedTransactionDetail = null; + networkTab = networkTab === 'diff' || networkTab === 'related' ? 'response' : networkTab; + renderHarBanner(); + applyHarOfflineChrome(); + if (hasSession() || openAccess) { + loadNetwork(); + } else { + setNavCount('navCountNetwork', 0); + renderNetwork(); + renderNetworkEmpty(); + } + } + function renderNetwork() { + renderHarBanner(); + applyHarOfflineChrome(); $('networkMainColLabel').textContent = 'Path'; $('networkFullEndpoint').setAttribute('aria-pressed', String(networkFullEndpoint)); // Normalize the selection BEFORE painting, like the other four list views: rows gate tabindex @@ -3885,7 +4622,9 @@ const t = transactions[i]; return rowHtml({ id: t.id, selected: selectedTransactionId === t.id, - checkbox: true, checked: networkSelectedIds.has(t.id), + // Export selection and evidence flagging both resolve ids on the server; neither can + // point at an imported row, so both affordances disappear in offline mode. + checkbox: !harOffline, checked: !harOffline && networkSelectedIds.has(t.id), badgeText: t.method, badgeTone: methodTone(t.method), mainText: t.path, mainPrefix: networkFullEndpoint ? t.host : '', @@ -3893,27 +4632,44 @@ // dimmed and after the path, which stays the part that survives the ellipsis. mainSub: t.query ? '?' + t.query : '', // Single row-tag slot: a pinned diff baseline always wins over the mocked marker. - tagText: false, + tagText: networkPinnedId === t.id ? 'PINNED' : (t.tags?.mocked === 'true' || t.mocked === true) ? 'MOCKED' : false, tagTone: 'put', duration: t.durationMs != null ? t.durationMs + ' ms' : t.error ? 'failed' : '—', statusText: t.status != null ? String(t.status) : t.error ? 'ERR' : '—', sTone: t.status != null ? statusTone(t.status) : t.error ? 'error' : 'muted', metricsInline: true, - flagKind: 'network', flagLabel: t.method + ' ' + t.path, + flagKind: harOffline ? null : 'network', flagLabel: t.method + ' ' + t.path, posinset: i + 1, setsize: total, }); }, - NETWORK_EMPTY_HTML, + networkEmptyHtml(), ); networkOrder = transactions.map((t) => t.id); - $('networkFootLeft').textContent = transactions.length + ' of ' + networkPage.length + ' · newest first'; - $('networkFootRight').textContent = networkHostFilter.size ? networkHostFilter.size + ' service' + (networkHostFilter.size === 1 ? '' : 's') + ' selected' : 'all services'; - $('networkBadge').textContent = networkPage.length + ' captured'; + $('networkFootLeft').textContent = harOffline + ? transactions.length + ' of ' + networkPage.length + ' · offline' + : transactions.length + ' of ' + networkPage.length + ' · newest first'; + $('networkFootRight').textContent = harOffline + ? 'client-side view' + : networkHostFilter.size ? networkHostFilter.size + ' service' + (networkHostFilter.size === 1 ? '' : 's') + ' selected' : 'all services'; + $('networkBadge').textContent = harOffline ? countLabel(networkPage.length, 'request') + ' offline' : networkPage.length + ' captured'; updateNetworkFacetCounts(); renderNetworkMetrics(); renderNetworkChips(); renderNetworkHostDrop(); renderNetworkSelectionBar(); - if (networkSelectionStale) { + if (harOffline) { + // The `tx=` deep link points at live-row ids; never chase one in offline mode. + if (networkSelectionStale) { + if (transactions.length) showTransaction(selectedTransactionId); + else renderNetworkEmpty(); + } + return; + } + if (pendingDeepLinkTx) { + // Fetched by id, so the linked capture opens even when the current filters or page hide its row. + const id = pendingDeepLinkTx; + pendingDeepLinkTx = null; + showTransaction(id); + } else if (networkSelectionStale) { if (transactions.length) showTransaction(selectedTransactionId); else renderNetworkEmpty(); } @@ -3962,24 +4718,14 @@ return; } const params = new URLSearchParams({ limit: String(500) }); - [ - ['query', 'networkSearch'], - ['from', 'networkFrom'], - ['to', 'networkTo'], - ['path', 'networkPath'], - ['contentType', 'networkContentType'], - ['minDurationMs', 'networkMinDuration'], - ['maxDurationMs', 'networkMaxDuration'], - ['error', 'networkError'], - ['correlationId', 'networkCorrelation'], - ['tag', 'networkTag'], - ].forEach(([name, id]) => { - const value = $(id).value.trim(); - if (value) params.append(name, value); - }); + // Same advanced filters the visible list was loaded with (networkFilterEntries), plus the + // quick method/host/status controls layered on top of them. + const advanced = networkFilterEntries(); + advanced.forEach(([name, value]) => params.append(name, value)); if (networkMethodFilter) params.append('method', networkMethodFilter); networkHostFilter.forEach((h) => params.append('host', h)); - if (networkStatusFilter) { + const hasStatusRange = advanced.some(([name]) => name === 'statusFrom' || name === 'statusTo'); + if (networkStatusFilter && !hasStatusRange) { const from = Number(networkStatusFilter[0]) * 100; params.append('statusFrom', String(from)); params.append('statusTo', String(from + 99)); @@ -3990,7 +4736,7 @@ (body.data || []).forEach((t) => networkSelectedIds.add(t.id)); renderNetwork(); toast( - 'Selected ' + (body.data || []).length + ' matching transaction(s)' + + 'Selected ' + countLabel((body.data || []).length, 'matching transaction') + (body.page?.hasMore ? ' — more than 500 matched; only the first 500 were selected.' : '.'), ); } @@ -4007,9 +4753,9 @@ } const toolbarHar = $('networkHarDownload'); const toolbarPostman = $('networkPostmanDownload'); - const scopeTitle = count ? `Export the ${count} selected transaction(s)` : 'Export every captured transaction (up to 500)'; - if (toolbarHar) toolbarHar.title = scopeTitle; - if (toolbarPostman) toolbarPostman.title = scopeTitle; + const scopeTitle = count ? `Export the ${countLabel(count, 'selected transaction')}` : 'Export every captured transaction (up to 500)'; + if (toolbarHar && !harOffline) toolbarHar.title = scopeTitle; + if (toolbarPostman && !harOffline) toolbarPostman.title = scopeTitle; bar.hidden = count === 0; if (count === 0) return; bar.innerHTML = `${count} selected @@ -4041,10 +4787,13 @@ if (networkMethodFilter) chips.push({ label: 'method ' + networkMethodFilter, title: 'Clear the method filter', on: () => { networkMethodFilter = ''; $('networkMethodSeg').querySelectorAll('button').forEach((b) => b.classList.toggle('active', b.dataset.value === '')); applyNetworkFilters(); } }); networkHostFilter.forEach((h) => chips.push({ label: h, title: 'Remove ' + h, on: () => { networkHostFilter.delete(h); applyNetworkFilters(); } })); if (networkFailOnly) chips.push({ label: 'failures only', title: 'Show all statuses again', on: () => { networkFailOnly = false; applyNetworkFilters(); } }); + const advanced = [['from','networkFrom'],['to','networkTo'],['method','networkMethod'],['host','networkHost'],['path','networkPath'],['type','networkContentType'],['min ms','networkMinDuration'],['max ms','networkMaxDuration'],['error','networkError'],['correlation','networkCorrelation'],['tag','networkTag'],['body','networkBody'],['status ≥','networkStatusFrom'],['status ≤','networkStatusTo']]; + advanced.forEach(([label,id]) => { const input = $(id); if (input?.value.trim()) chips.push({ label: label + ' ' + input.value.trim(), title: 'Clear ' + label, on: () => { input.value = ''; loadNetwork(); } }); }); appliedFiltersHtml( 'networkChips', chips, () => { $('networkSearch').value = ''; + ['networkFrom','networkTo','networkMethod','networkHost','networkPath','networkContentType','networkMinDuration','networkMaxDuration','networkError','networkCorrelation','networkTag','networkBody','networkStatusFrom','networkStatusTo'].forEach((id) => { if ($(id)) $(id).value = ''; }); networkStatusFilter = ''; networkMethodFilter = ''; networkHostFilter.clear(); networkFailOnly = false; $('networkStatusSeg').querySelectorAll('button').forEach((b) => b.classList.toggle('active', b.dataset.value === '')); $('networkMethodSeg').querySelectorAll('button').forEach((b) => b.classList.toggle('active', b.dataset.value === '')); @@ -4054,13 +4803,107 @@ ); } + let networkEndpointsOpen = false; + function endpointLiteralPrefix(pathTemplate) { + const template = String(pathTemplate || ''); + const idx = template.indexOf('{id}'); + const raw = idx >= 0 ? template.slice(0, idx) : template; + return raw.length > 1 && raw.endsWith('/') ? raw.slice(0, -1) : raw; + } + async function loadNetworkEndpoints() { + if (!token) { + $('networkEndpointsBadge').textContent = ''; + $('networkEndpointsBody').innerHTML = '

Connect this browser to inspect endpoint latency.

'; + return; + } + const gen = nextGen('network-endpoints'); + const r = await fetch(withNetworkRun('/api/v1/network/endpoints'), { headers: auth() }); + if (!isLatest('network-endpoints', gen)) return; + if (!r.ok) { + $('networkEndpointsBadge').textContent = ''; + renderLoadFailure($('networkEndpointsBody'), 'Could not load endpoint statistics', r.status, loadNetworkEndpoints); + return; + } + const body = await r.json(); + const rows = body.data || []; + const sampleSize = body.sampleSize ?? 0; + $('networkEndpointsBadge').textContent = sampleSize + ' sampled'; + if (!rows.length) { + $('networkEndpointsBody').innerHTML = '

No completed requests captured yet.

'; + return; + } + // Host rides under the path instead of in its own column: a full hostname is the widest cell and, + // in a narrow window, pushed the count/error/latency columns -- the point of the panel -- off-screen. + const cols = ['Method', 'Endpoint', 'Count', 'Errors', 'p50', 'p95', 'p99', 'Max']; + const tbody = rows + .map((row) => { + const prefix = endpointLiteralPrefix(row.pathTemplate); + const errTone = row.errorCount > 0 ? 'error' : 'muted'; + return ` + ${esc(row.method)} + ${esc(row.pathTemplate)}${esc(row.host)} + ${esc(String(row.count))} + ${esc(String(row.errorCount))} + ${esc(row.p50Ms + ' ms')} + ${esc(row.p95Ms + ' ms')} + ${esc(row.p99Ms + ' ms')} + ${esc(row.maxMs + ' ms')} + `; + }) + .join(''); + $('networkEndpointsBody').innerHTML = `
${cols.map((c) => ``).join('')}${tbody}
${esc(c)}
`; + } + function toggleNetworkEndpoints(force) { + const panel = $('networkEndpointsPanel'); + const btn = $('networkEndpointsBtn'); + if (!panel || !btn) return; + networkEndpointsOpen = force !== undefined ? force : panel.hidden; + panel.hidden = !networkEndpointsOpen; + btn.classList.toggle('active', networkEndpointsOpen); + btn.setAttribute('aria-expanded', String(networkEndpointsOpen)); + if (networkEndpointsOpen) loadNetworkEndpoints(); + } + function wireNetworkEndpointsPanel() { + const panel = $('networkEndpointsPanel'); + const btn = $('networkEndpointsBtn'); + if (!panel || !btn) return; + btn.onclick = () => toggleNetworkEndpoints(); + $('networkEndpointsRefresh').onclick = () => loadNetworkEndpoints(); + $('networkEndpointsClose').onclick = () => { toggleNetworkEndpoints(false); btn.focus(); }; + const activateRow = (row) => { + const prefix = row.dataset.endpointPrefix || ''; + $('networkSearch').value = prefix; + loadNetwork(); + }; + panel.addEventListener('click', (e) => { + const row = e.target.closest('[data-endpoint-prefix]'); + if (row) activateRow(row); + }); + panel.addEventListener('keydown', (e) => { + if (e.key === 'Escape') { + e.preventDefault(); + toggleNetworkEndpoints(false); + btn.focus(); + return; + } + if (e.key === 'Enter' || e.key === ' ') { + const row = e.target.closest('[data-endpoint-prefix]'); + if (row) { + e.preventDefault(); + activateRow(row); + } + } + }); + } + viewControllers.network = { containerId: 'transactions', order: () => networkOrder, getSelected: () => selectedTransactionId, select: (id) => showTransaction(id), - flagCurrent: () => { const t = transactions.find((x) => x.id === selectedTransactionId); if (t) toggleEvidenceFlag('network', t.id, t.method + ' ' + t.host + t.path); }, - pinCurrent: () => pinNetworkBaseline(selectedTransactionId), + // Imported HAR ids do not exist server-side, so Enter must not attempt to flag one. + flagCurrent: () => { if (harOffline) return; const t = transactions.find((x) => x.id === selectedTransactionId); if (t) toggleEvidenceFlag('network', t.id, t.method + ' ' + t.host + t.path); }, + pinCurrent: () => { if (!harOffline) pinNetworkBaseline(selectedTransactionId); }, }; /** Generic labeled multi-select dropdown (the `.drop*` classes): a button @@ -4213,6 +5056,7 @@ } async function loadSocketMessagesImpl() { if (!token) return; + const gen = nextGen('socket-messages'); const params = new URLSearchParams(); socketSelectedConnIds.forEach((id) => params.append('connectionId', id)); if (socketDirectionFilter) params.append('direction', socketDirectionFilter); @@ -4224,11 +5068,14 @@ }); const r = await fetch('/api/v1/websockets/messages?' + params, { headers: auth() }); if (!r.ok) { + if (!isLatest('socket-messages', gen)) return; renderLoadFailure($('sockets'), 'Could not load messages', r.status, loadSocketMessages); viewLoadedAt.delete('socket'); return false; } + if (!isLatest('socket-messages', gen)) return; socketMessages_ = formatSocketMessages((await r.json()).data || []); + lastSocketFetchAt = Date.now(); if (socketSelectedIndex >= socketMessages_.length) socketSelectedIndex = -1; renderSockets(); } @@ -4247,6 +5094,7 @@ // height var it reads switches with the mode (--d-trace-h vs --d-row-h, both scaled by // body.mode-simple/advanced), so a List↔Timeline toggle just changes what `update()` supplies. const socketsVirt = virtualList('sockets', { rowHeightVar: () => (socketMode === 'timeline' ? '--d-trace-h' : '--d-row-h') }); + if (lastRenderedSocketMode !== socketMode) { socketsVirt.remeasure(); lastRenderedSocketMode = socketMode; } if (timelineMode) { const chrono = socketMessages_.map((m, i) => ({ m, i })).sort((a, b) => a.m.timestampEpochMs - b.m.timestampEpochMs); const maxBytes = Math.max(1, ...chrono.map((x) => frameSizeValue(x.m))); @@ -4312,13 +5160,13 @@ : socketConnections; const socketTotalFrames = socketConnScope.reduce((sum, s) => sum + s.sentCount + s.receivedCount, 0); $('socketFootLeft').textContent = timelineMode - ? socketMessages_.length + ' frames · oldest first' - : socketMessages_.length + ' of ' + socketTotalFrames + ' frames'; + ? countLabel(socketMessages_.length, 'frame') + ' · oldest first' + : socketMessages_.length + ' of ' + countLabel(socketTotalFrames, 'frame'); $('socketFootRight').textContent = timelineMode ? 'bar width ∝ payload size' : socketSelectedConnIds.size === 1 ? (() => { const s = socketConnections.find((x) => socketSelectedConnIds.has(x.id)); return s ? s.state + ' · ' + s.sentCount + '↑ ' + s.receivedCount + '↓' : ''; })() - : socketSelectedConnIds.size ? socketSelectedConnIds.size + ' connections' : socketConnections.length + ' connections'; + : socketSelectedConnIds.size ? countLabel(socketSelectedConnIds.size, 'connection') : countLabel(socketConnections.length, 'connection'); renderSocketMetrics(); renderSocketChips(); renderSocketConnDrop(); @@ -4363,7 +5211,7 @@ order: () => socketOrder, getSelected: () => String(socketSelectedIndex), select: (id) => { socketSelectedIndex = Number(id); renderSockets(); }, - flagCurrent: () => { const m = socketMessages_[socketSelectedIndex]; if (m) toggleEvidenceFlag('socket', socketSelectedIndex + '@' + m.timestampEpochMs, m.direction + ' ' + m.frameType); }, + flagCurrent: () => { const m = socketMessages_[socketSelectedIndex]; if (m) toggleEvidenceFlag('socket', socketFlagId(socketSelectedIndex, m), m.direction + ' ' + m.frameType); }, }; function renderSocketConnDrop() { @@ -4391,6 +5239,128 @@ }); } + // ================================================================ + // Socket send composer + // ================================================================ + const socketSendDrafts = new Map(); // connId -> { text: '', topic: '', qos: 0, retained: false } + + function getSocketDraft(conn, m) { + if (!conn) return { text: '', topic: '', qos: 0, retained: false }; + if (!socketSendDrafts.has(conn.id)) { + socketSendDrafts.set(conn.id, { + text: '', + topic: conn.sendProtocol === 'mqtt' ? (m?.topic ?? '') : '', + qos: conn.sendProtocol === 'mqtt' ? (m?.qos ?? 0) : 0, + retained: false, + }); + } + return socketSendDrafts.get(conn.id); + } + + function socketSendErrorMessage(code, message) { + if (code === 'NOT_CONNECTED') return 'Connection is not open'; + if (code === 'SEND_REJECTED') return message || 'Send rejected'; + if (code === 'VALIDATION_FAILED') return message || 'Validation failed'; + if (code === 'SOCKET_SEND_DISABLED') return 'Sending is disabled by the host (request execution capability)'; + if (code === 'SEND_UNSUPPORTED') return "This connection's adapter can't send"; + if (code === 'CSRF_INVALID') return 'Security check failed (invalid CSRF token)'; + return (message || 'Failed to send frame') + (code ? ': ' + code : ''); + } + + async function sendSocketFrame(connId) { + const conn = socketConnections.find((s) => s.id === connId); + if (!conn) return; + const draft = socketSendDrafts.get(connId) || { text: '', topic: '', qos: 0, retained: false }; + if (!draft.text.trim()) return; + if (conn.sendProtocol === 'mqtt' && !draft.topic.trim()) return; + + const btn = $('socketComposerSend'); + if (btn) btn.disabled = true; + + try { + const params = new URLSearchParams(); + params.set('text', draft.text); + if (conn.sendProtocol === 'mqtt') { + params.set('topic', draft.topic); + params.set('qos', String(draft.qos ?? 0)); + params.set('retained', String(Boolean(draft.retained))); + } + + const r = await fetch(`/api/v1/websockets/connections/${encodeURIComponent(connId)}/send`, { + method: 'POST', + headers: { ...controlHeaders(), 'Content-Type': 'application/x-www-form-urlencoded' }, + body: params, + }); + + if (!r.ok) { + let errData = {}; + try { errData = await r.json(); } catch {} + toast(socketSendErrorMessage(errData.code, errData.message), 'error'); + return; + } + + toast('Frame sent'); + draft.text = ''; + const textEl = $('socketComposerText'); + if (textEl) textEl.value = ''; + loadSocketMessages(); + } catch { + toast('Failed to send frame', 'error'); + } finally { + syncSocketComposerSendButton(connId); + } + } + + function syncSocketComposerSendButton(connId) { + const btn = $('socketComposerSend'); + if (!btn) return; + const conn = socketConnections.find((s) => s.id === connId); + if (!conn || !conn.canSend) { + btn.disabled = true; + return; + } + const draft = socketSendDrafts.get(connId) || { text: '', topic: '', qos: 0, retained: false }; + const textEmpty = !draft.text.trim(); + const mqttTopicEmpty = conn.sendProtocol === 'mqtt' && !draft.topic.trim(); + btn.disabled = textEmpty || mqttTopicEmpty; + } + + function socketComposerHtml(conn, m) { + if (!conn || !conn.canSend) return ''; + const draft = getSocketDraft(conn, m); + const isMqtt = conn.sendProtocol === 'mqtt'; + return `
+
${icon('send', 'ic-sm')}Send frame
+ ${isMqtt ? `
+ + + +
` : ''} + +
+ +
+
`; + } + // Keyed on connection+timestamp, never the list index: live-tail prepends frames and would // silently re-point an index-keyed evidence flag at a different frame. function socketFlagId(index, m) { return (m.connectionId || 'conn') + '@' + m.timestampEpochMs; } @@ -4436,14 +5406,20 @@ } const findBar = findBarHtml(query, lines ? countPaneHits([{ groups: [{ code: lines }] }]) : 0, 'socketDetailFindInput'); if (redactionShown()) body += `
${icon('lock', 'ic-sm')}Frame payloads are redacted on device.
`; + const composer = socketComposerHtml(conn, m); const focusSnap = captureFocus(pane); - pane.innerHTML = head + findBar + `
${body}
`; + pane.innerHTML = head + findBar + `
${body}${composer}
`; mountBodyViewers(pane); restoreFocus(focusSnap, pane); } function wireSocketDetailPane() { $('socketMessages').addEventListener('click', (e) => { if (e.target.closest('[data-action="toggle-zoom"]')) { toggleDetailZoom(); return; } + if (e.target.closest('#socketComposerSend')) { + const wrap = e.target.closest('.socket-composer'); + if (wrap?.dataset.connId) sendSocketFrame(wrap.dataset.connId); + return; + } const actionBtn = e.target.closest('[data-detail-action]'); if (!actionBtn) return; const m = socketMessages_[socketSelectedIndex]; @@ -4453,7 +5429,29 @@ else if (id === 'copy-frame') copyToClipboard(m.payload?.kind === 'binary' ? '[binary frame]' : (m.payload?.preview ?? ''), 'Frame payload'); else if (id === 'copy-all-frames') copyToClipboard(JSON.stringify(socketMessages_, null, 2), 'All frames'); }); - $('socketMessages').addEventListener('input', (e) => { if (e.target.id === 'socketDetailFindInput') { socketDetailQuery = e.target.value; renderSocketDetail(); } }); + $('socketMessages').addEventListener('input', (e) => { + if (e.target.id === 'socketDetailFindInput') { socketDetailQuery = e.target.value; renderSocketDetail(); return; } + const wrap = e.target.closest('.socket-composer'); + if (wrap && wrap.dataset.connId) { + const connId = wrap.dataset.connId; + const conn = socketConnections.find((s) => s.id === connId); + const draft = getSocketDraft(conn, socketMessages_[socketSelectedIndex]); + if (e.target.id === 'socketComposerText') draft.text = e.target.value; + else if (e.target.id === 'socketComposerTopic') draft.topic = e.target.value; + syncSocketComposerSendButton(connId); + } + }); + $('socketMessages').addEventListener('change', (e) => { + const wrap = e.target.closest('.socket-composer'); + if (wrap && wrap.dataset.connId) { + const connId = wrap.dataset.connId; + const conn = socketConnections.find((s) => s.id === connId); + const draft = getSocketDraft(conn, socketMessages_[socketSelectedIndex]); + if (e.target.id === 'socketComposerQos') draft.qos = Number(e.target.value) || 0; + else if (e.target.id === 'socketComposerRetained') draft.retained = Boolean(e.target.checked); + syncSocketComposerSendButton(connId); + } + }); } // ================================================================ @@ -4471,6 +5469,7 @@ (!pushProviderFilter || p.provider === pushProviderFilter) && (!q || `${p.messageId || ''} ${p.source || ''} ${p.lifecycle || ''} ${p.notification?.title || ''}`.toLowerCase().includes(q)), ); + rows.reverse(); pushOrder = rows.map(({ i }) => String(i)); if (!pushOrder.includes(String(selectedPushIndex))) selectedPushIndex = rows.length ? rows[0].i : -1; virtualList('pushEvents').update( @@ -4483,7 +5482,7 @@ mainText: p.notification?.title || p.messageId || '(untitled)', tagText: p.simulated ? 'SIMULATED' : false, tagTone: 'warn', duration: p.lifecycle, statusText: time(p.receivedAtEpochMs), sTone: 'muted', - flagKind: 'push', flagLabel: p.provider + ' · ' + p.lifecycle, + flagKind: 'push', flagId: pushFlagId(p, i), flagLabel: p.provider + ' · ' + p.lifecycle, posinset: n + 1, setsize: total, }); }, @@ -4491,7 +5490,7 @@ ); $('pushFootLeft').textContent = rows.length + ' of ' + pushes.length; $('pushFootRight').textContent = redactionShown() ? 'push tokens are redacted' : ''; - $('pushBadge').textContent = pushes.length + ' events'; + $('pushBadge').textContent = countLabel(pushes.length, 'event'); renderPushMetrics(); renderPushDetail(); } @@ -4513,14 +5512,16 @@ order: () => pushOrder, getSelected: () => String(selectedPushIndex), select: (id) => { selectedPushIndex = Number(id); renderPush(); }, - flagCurrent: () => { const p = pushes[selectedPushIndex]; if (p) toggleEvidenceFlag('push', String(selectedPushIndex), p.provider + ' · ' + p.lifecycle); }, + flagCurrent: () => { const p = pushes[selectedPushIndex]; if (p) toggleEvidenceFlag('push', pushFlagId(p, selectedPushIndex), p.provider + ' · ' + p.lifecycle); }, }; + // The server keys push evidence by a stable id (list positions shift when the bounded store evicts). + const pushFlagId = (p, index) => (p && p.id ? String(p.id) : String(index)); function renderPushDetail() { const pane = $('pushDetail'); const p = pushes[selectedPushIndex]; if (!p) { renderEmpty(pane, 'push', 'No push notification selected', 'Select a push event from the list to inspect its payload.'); return; } - const flagged = isFlagged('push', String(selectedPushIndex)); + const flagged = isFlagged('push', pushFlagId(p, selectedPushIndex)); const head = detailHeadHtml({ badgeText: p.provider.toUpperCase(), badgeTone: p.simulated ? 'warn' : 'signal', title: p.notification?.title || p.messageId || '(untitled)', statusText: p.lifecycle, sTone: 'muted', @@ -4552,7 +5553,7 @@ const p = pushes[selectedPushIndex]; if (!p) return; const id = actionBtn.dataset.detailAction; - if (id === 'flag') { toggleEvidenceFlag('push', String(selectedPushIndex), p.provider + ' · ' + p.lifecycle); renderPushDetail(); } + if (id === 'flag') { toggleEvidenceFlag('push', pushFlagId(p, selectedPushIndex), p.provider + ' · ' + p.lifecycle); renderPushDetail(); } else if (id === 'replay') replayPush(p); else if (id === 'copy-payload') copyToClipboard(JSON.stringify(p, null, 2), 'Payload'); }); @@ -4648,8 +5649,14 @@ // ================================================================ let crashEvents = []; let selectedCrashId = ''; + let selectedCrashGroup = ''; + let currentCrashGroups = []; let crashOrder = []; let crashKindFilter = ''; + // Per-viewer convenience only, never server state: remembering the grouping toggle across reloads + // must not make a failed localStorage access break the Crashes view. + let crashGroupMode = false; + try { crashGroupMode = localStorage.getItem('devconsole.crashes.group') === 'true'; } catch { /* storage unavailable */ } let crashRunsById = new Map(); // sessionId -> row from GET /api/v1/runs, refreshed by loadCrashes() const CRASHES_EMPTY_HTML = listEmptyHtml('bug', 'No crashes or ANRs match', 'Clear the kind filter or search to see the other captured events.'); const CRASHES_NONE_HTML = listEmptyHtml('bug', 'No crashes yet', 'Crashes and ANRs from this session appear here.'); @@ -4699,6 +5706,103 @@ if (!e?.payloadJson) return null; try { return JSON.parse(e.payloadJson); } catch { return null; } } + + // ================================================================ + // Crash grouping — a direct port of InspectorCrashGrouping.kt so the same crashes fingerprint + // identically on the Android inspector and here (same normalization, same framework skips). + // A group answers "is this the same bug again?" by keeping only the exception class and the + // first non-framework frame's `Class.method`, without `(File.kt:123)` — a moved line must not + // split a group. + // ================================================================ + const CRASH_FRAMEWORK_PACKAGE_PREFIXES = [ + 'java.', 'javax.', 'kotlin.', 'kotlinx.', 'android.', 'androidx.', + 'com.android.', 'dalvik.', 'libcore.', 'sun.', + ]; + + function crashSummaryHead(summary) { + return String(summary || '').split(':')[0].trim(); + } + + /** A summary like "java.io.IOException boom" names its class first; otherwise keep the head. */ + function exceptionClassFromSummary(summaryHead) { + const leadingToken = summaryHead.split(' ')[0].trim(); + const looksLikeClass = leadingToken.includes('.') + || leadingToken.endsWith('Exception') + || leadingToken.endsWith('Error'); + return looksLikeClass ? leadingToken : summaryHead; + } + + function extractExceptionClass(lines, summary) { + const candidate = lines.find((line) => !line.startsWith('at ') && !line.startsWith('"') && !line.startsWith('...')); + const candidateFromStack = candidate ? candidate.split(':')[0].trim() : ''; + const summaryHead = crashSummaryHead(summary); + if (candidateFromStack) return candidateFromStack; + if (summaryHead) return exceptionClassFromSummary(summaryHead); + return lines.length ? lines[0].split(':')[0].trim() : ''; + } + + function extractFrameClassMethod(frameLine) { + const afterAt = frameLine.replace(/^at /, '').trim(); + if (!afterAt) return null; + const withoutSource = afterAt.split('(')[0].trim(); + const withoutModule = withoutSource.split('/').pop(); + return withoutModule || null; + } + + function isFrameworkFrame(classMethod) { + return CRASH_FRAMEWORK_PACKAGE_PREFIXES.some((prefix) => classMethod.startsWith(prefix)); + } + + function crashFingerprint(e) { + const payload = crashPayloadOf(e); + const lines = String(payload?.stackTrace || '') + .split('\n') + .map((line) => line.trim()) + .filter(Boolean); + const exceptionClass = extractExceptionClass(lines, e.summary); + const frameMethods = lines.filter((line) => line.startsWith('at ')).map(extractFrameClassMethod).filter(Boolean); + const primaryFrame = frameMethods.find((frame) => !isFrameworkFrame(frame)) || frameMethods[0]; + return primaryFrame ? exceptionClass + '|' + primaryFrame : exceptionClass; + } + + /** `java.lang.IllegalStateException` -> `IllegalStateException`. */ + function simpleClassName(qualified) { + return String(qualified).split('.').pop() || String(qualified); + } + /** `io.example.MainActivity.onCreate` -> `MainActivity.onCreate`: the package rarely tells two groups apart. */ + function shortFrameName(classMethod) { + const parts = String(classMethod).split('.'); + return parts.length > 2 ? parts.slice(-2).join('.') : String(classMethod); + } + + /** Groups by fingerprint, newest crash of each group first, groups newest-first. */ + function groupCrashes(crashes) { + if (!crashes.length) return []; + const sortedNewestFirst = crashes.slice().sort((a, b) => (b.wallTimeMs || 0) - (a.wallTimeMs || 0)); + const byFingerprint = new Map(); + sortedNewestFirst.forEach((crash) => { + const fingerprint = crashFingerprint(crash); + if (!byFingerprint.has(fingerprint)) byFingerprint.set(fingerprint, []); + byFingerprint.get(fingerprint).push(crash); + }); + return [...byFingerprint.entries()] + .map(([fingerprint, members]) => ({ + fingerprint, + newest: members[0], + count: members.length, + lastSeenEpochMs: members[0].wallTimeMs || 0, + crashes: members, + })) + .sort((a, b) => b.lastSeenEpochMs - a.lastSeenEpochMs); + } + + function syncCrashGroupToggle() { + const btn = $('crashesGroupToggle'); + if (!btn) return; + btn.setAttribute('aria-pressed', String(crashGroupMode)); + btn.classList.toggle('active', crashGroupMode); + } + /** Cross-session by design (see the module doc above): pluginId=crash with no sessionId reads * every retained run, not just the live one — the entire point, since a crash's process is gone * by the time anyone reopens the app to look for it. GET /api/v1/runs is fetched alongside it so @@ -4738,13 +5842,62 @@ metricHtml('Flagged', String([...evidenceFlags.values()].filter((v) => v.kind === 'crash').length), 'as evidence', 'signal'), ].join(''); } - function renderCrashes() { + function crashRowsForFilters() { const q = $('crashesSearch').value.toLowerCase(); - const rows = crashEvents.filter( + return crashEvents.filter( (e) => (!crashKindFilter || crashKindOf(e) === crashKindFilter) && (!q || (e.summary + ' ' + crashThreadOf(e)).toLowerCase().includes(q)), ); + } + function renderCrashes() { + syncCrashGroupToggle(); + const rows = crashRowsForFilters(); + const emptyHtml = crashEvents.length ? CRASHES_EMPTY_HTML : CRASHES_NONE_HTML; + if (crashGroupMode) { + const groups = groupCrashes(rows); + currentCrashGroups = groups; + crashOrder = groups.map((group) => group.fingerprint); + if (!crashOrder.includes(selectedCrashGroup)) selectedCrashGroup = crashOrder[0] || ''; + const selected = groups.find((group) => group.fingerprint === selectedCrashGroup); + // Keep an explicitly opened older occurrence selected; only fall back to the newest crash + // when the current selection isn't part of this group anymore (a filter change, new load). + if (!selected) selectedCrashId = ''; + else if (!selected.crashes.some((crash) => crash.id === selectedCrashId)) selectedCrashId = selected.newest.id; + virtualList('crashesList').update( + groups.length, + (n, total) => { + const group = groups[n]; + const kind = crashKindOf(group.newest); + const split = group.fingerprint.indexOf('|'); + const exceptionType = split >= 0 ? group.fingerprint.slice(0, split) : group.fingerprint; + const topFrame = split >= 0 ? group.fingerprint.slice(split + 1) : ''; + return rowHtml({ + id: group.fingerprint, selected: selectedCrashGroup === group.fingerprint, + badgeText: kind === 'ANR' ? 'ANR' : 'CRASH', badgeTone: 'error', + // Simple names: the Summary column is narrow, and a fully-qualified `java.lang.…` plus + // a package-qualified frame ellipsised to nothing. The detail pane keeps the full text. + mainText: simpleClassName(exceptionType), mainSub: topFrame ? shortFrameName(topFrame) : undefined, + // The count lives in the tag slot rather than the duration column: the duration column + // is hidden below 620px, and the count is the whole point of grouping. "×N" stays + // legible where "N crashes" was squeezed to "2.". + tagText: '×' + group.count, tagTone: group.count > 1 ? 'error' : 'muted', + duration: '', + statusText: time(group.lastSeenEpochMs), sTone: 'muted', + flagKind: 'crash', flagId: group.newest.id, flagLabel: group.newest.summary, + posinset: n + 1, setsize: total, + }); + }, + emptyHtml, + ); + $('crashesFootLeft').textContent = countLabel(groups.length, 'group') + ' · ' + countLabel(rows.length, 'crash'); + $('crashesFootRight').textContent = 'grouped by exception + top frame'; + $('crashesBadge').textContent = countLabel(rows.length, 'crash') + ' in ' + countLabel(groups.length, 'group'); + renderCrashesMetrics(); + renderCrashDetail(); + return; + } + currentCrashGroups = []; crashOrder = rows.map((e) => e.id); if (!crashOrder.includes(selectedCrashId)) selectedCrashId = rows[0]?.id || ''; // No onNearEnd — see the module doc above; retained-events has no cursor and loadCrashes() @@ -4765,7 +5918,7 @@ posinset: n + 1, setsize: total, }); }, - crashEvents.length ? CRASHES_EMPTY_HTML : CRASHES_NONE_HTML, + emptyHtml, ); $('crashesFootLeft').textContent = rows.length + ' of ' + crashEvents.length; $('crashesFootRight').textContent = 'auto-flagged as evidence'; @@ -4773,11 +5926,29 @@ renderCrashesMetrics(); renderCrashDetail(); } + /** One select path for both modes: a group id focuses its newest crash, a crash id selected from + * a group's occurrence list keeps that exact crash in the detail pane. */ + function selectCrashRow(id) { + if (!crashGroupMode) { selectedCrashId = id; renderCrashes(); return; } + const group = currentCrashGroups.find((item) => item.fingerprint === id) + || currentCrashGroups.find((item) => item.crashes.some((crash) => crash.id === id)); + if (group) { + selectedCrashGroup = group.fingerprint; + selectedCrashId = group.fingerprint === id ? group.newest.id : id; + } + renderCrashes(); + } + function setCrashGroupMode(on) { + crashGroupMode = Boolean(on); + try { localStorage.setItem('devconsole.crashes.group', String(crashGroupMode)); } catch { /* storage unavailable */ } + syncCrashGroupToggle(); + renderCrashes(); + } viewControllers.crashes = { containerId: 'crashesList', order: () => crashOrder, - getSelected: () => selectedCrashId, - select: (id) => { selectedCrashId = id; renderCrashes(); }, + getSelected: () => (crashGroupMode ? selectedCrashGroup : selectedCrashId), + select: selectCrashRow, flagCurrent: () => { const e = crashEvents.find((x) => x.id === selectedCrashId); if (e) toggleEvidenceFlag('crash', e.id, e.summary); }, }; /** Target of the Overview "previous run crashed" banner (renderOverviewCrashBanner) — landing on @@ -4802,12 +5973,32 @@ } if ($('crashesSearch').value) $('crashesSearch').value = ''; await viewControllers.crashes.select(target.id); - focusSelectedRow('crashesList', crashOrder.indexOf(target.id)); + focusSelectedRow('crashesList', crashOrder.indexOf(viewControllers.crashes.getSelected())); } const crashGroupOpen = {}; + /** The group the detail pane is currently showing, or null when grouping is off (and for the + * fallback where the selected crash is no longer inside the filtered group list). */ + function selectedCrashGroupEntry() { + if (!crashGroupMode) return null; + return currentCrashGroups.find((group) => group.crashes.some((crash) => crash.id === selectedCrashId)) || null; + } + function crashOccurrencesHtml(group) { + if (!group) return ''; + const others = group.crashes.filter((crash) => crash.id !== selectedCrashId); + const rows = others.map((crash) => { + const run = crashRunInfo(crash); + return ``; + }).join(''); + return `
Other occurrences · ${countLabel(group.count - 1, 'crash')}
+
${rows || 'This is the only recorded occurrence.'}
`; + } function renderCrashDetail() { const pane = $('crashDetail'); - const e = crashEvents.find((x) => x.id === selectedCrashId); + const group = selectedCrashGroupEntry(); + const e = (group && group.crashes.find((x) => x.id === selectedCrashId)) || crashEvents.find((x) => x.id === selectedCrashId); if (!e) { renderEmpty(pane, 'bug', 'No crash selected', 'Select a crash or ANR from the list to inspect its breadcrumbs and all-thread dump.'); return; } const kind = crashKindOf(e); const flagged = isFlagged('crash', e.id); @@ -4819,6 +6010,7 @@ extraBadge: run?.current ? { text: 'CURRENT RUN', tone: 'signal' } : null, facts: [{ k: 'thread', v: crashThreadOf(e) || '—' }, { k: 'type', v: e.type }] .concat(run ? [{ k: 'run', v: run.text }] : []) + .concat(group ? [{ k: 'group', v: countLabel(group.count, 'crash') + ' · same exception + frame' }] : []) .concat(payload?.breadcrumbs ? [{ k: 'breadcrumbs', v: String(payload.breadcrumbs.length) }] : []), actions: [ { id: 'flag', label: flagged ? 'Flagged as evidence' : 'Flag as evidence', icon: 'flag', on: flagged, title: 'Attach this crash to the evidence tray (Enter) — crashes auto-flag at capture time, so this is usually already on' }, @@ -4837,11 +6029,12 @@ })(); const dumpGroup = detailGroupHtml( 'crash/dump', - { label: 'All-thread dump', code: payload?.stackTrace ? plainCodeLines(payload.stackTrace) : null, empty: payload?.stackTrace ? undefined : (payload ? 'No stack trace recorded.' : crashPayloadMissingMessage('Stack trace')), meta: payload?.stackTrace ? payload.stackTrace.split('\n').length + ' lines' : '' }, + { label: 'All-thread dump', code: payload?.stackTrace ? plainCodeLines(payload.stackTrace) : null, empty: payload?.stackTrace ? undefined : (payload ? 'No stack trace recorded.' : crashPayloadMissingMessage('Stack trace')), meta: payload?.stackTrace ? countLabel(payload.stackTrace.split('\n').length, 'line') : '' }, crashGroupOpen, ); const focusSnap = captureFocus(pane); pane.innerHTML = head + `
+ ${crashOccurrencesHtml(group)}
Breadcrumbs
${breadcrumbsHtml} ${dumpGroup} @@ -4854,6 +6047,8 @@ if (e.target.closest('[data-action="toggle-zoom"]')) { toggleDetailZoom(); return; } const groupToggle = e.target.closest('[data-group-toggle]'); if (groupToggle) { crashGroupOpen[groupToggle.dataset.groupToggle] = groupToggle.getAttribute('aria-expanded') !== 'true'; renderCrashDetail(); return; } + const occurrence = e.target.closest('[data-crash-occurrence]'); + if (occurrence) { selectedCrashId = occurrence.dataset.crashOccurrence; renderCrashDetail(); renderCrashes(); return; } const actionBtn = e.target.closest('[data-detail-action]'); if (!actionBtn) return; const ev = crashEvents.find((x) => x.id === selectedCrashId); @@ -4882,6 +6077,7 @@ let selectedStateProviderId = ''; let selectedStateValue; // undefined = not loaded yet let selectedStateMutators = []; + let stateReadError = ''; let cachedFlags = []; async function loadState() { if (!hasSession()) return loadStateImpl(); @@ -4889,9 +6085,11 @@ } async function loadStateImpl() { if (!token) return; + const gen = nextGen('state-providers'); const [statesRes, flagsRes] = await Promise.all([fetch('/api/v1/state', { headers: auth() }), fetch('/api/v1/flags', { headers: auth() })]); requireLoad(statesRes); requireLoad(flagsRes); + if (!isLatest('state-providers', gen)) return; stateProviderIds = statesRes.ok ? ((await statesRes.json()).data || []).map((s) => s.id) : []; if (!stateProviderIds.includes(selectedStateProviderId)) { selectedStateProviderId = stateProviderIds[0] || ''; @@ -4903,12 +6101,22 @@ } async function showState(id) { if (!token || !id) return; + const gen = nextGen('state-provider'); selectedStateProviderId = id; selectedStateValue = undefined; selectedStateMutators = []; renderStateCards(); const r = await fetch('/api/v1/state/' + encodeURIComponent(id), { headers: auth() }); - const body = r.ok ? await r.json() : null; + if (!isLatest('state-provider', gen) || selectedStateProviderId !== id) return; + if (!r.ok) { + selectedStateValue = null; + selectedStateMutators = []; + stateReadError = unavailableReason(r.status); + renderStateCards(); + return; + } + const body = await r.json(); + stateReadError = ''; selectedStateValue = body ? body.values : null; selectedStateMutators = body?.mutators || []; renderStateCards(); @@ -5015,7 +6223,7 @@ }, { icon: 'grid', iconTone: 'signal', title: selectedStateProviderId ? 'App state · ' + selectedStateProviderId : 'App state', span: 2, - lede: selectedStateProviderId ? (selectedStateValue === undefined ? 'Loading…' : false) : 'Choose a provider to inspect its typed snapshot.', + lede: stateReadError ? 'State unavailable. ' + stateReadError : selectedStateProviderId ? (selectedStateValue === undefined ? 'Loading…' : false) : 'Choose a provider to inspect its typed snapshot.', code: selectedStateValue !== undefined && selectedStateValue !== null ? formatJsonLines(selectedStateValue, '') : false, bodyHtml: stateMutatorsFieldsHtml(selectedStateProviderId, selectedStateMutators), buttons: (selectedStateValue != null ? [{ id: 'copy-state', label: 'Copy JSON', icon: 'copy' }] : []).concat( @@ -5032,9 +6240,21 @@ // Remote Config // ================================================================ let remoteConfigProviders = []; + let remoteConfigOverridesEditable = false; let remoteConfigQuery = ''; let remoteConfigSourceFilter = 'all'; const REMOTE_CONFIG_SOURCE_TONE = { remote: 'signal', override: 'warn', default: 'muted', static: 'muted', unknown: 'muted' }; + + function remoteConfigErrorMessage(code, defaultMsg) { + if (code === 'REMOTE_CONFIG_OVERRIDES_DISABLED') return 'Remote config overrides are disabled by the host.'; + if (code === 'REMOTE_CONFIG_OVERRIDES_UNAVAILABLE') return 'Remote config overrides are unavailable.'; + if (code === 'REMOTE_CONFIG_PROVIDER_NOT_FOUND') return 'Remote config provider not found.'; + if (code === 'VALIDATION_FAILED') return 'Validation failed for remote config override.'; + if (code === 'CSRF_INVALID') return 'Security check failed (invalid CSRF token).'; + if (code === 'AUTH_REQUIRED') return 'Connect this browser first.'; + return (defaultMsg || 'Remote config action failed') + (code ? ': ' + code : ''); + } + async function loadRemoteConfig() { if (!hasSession()) return loadRemoteConfigImpl(); return runViewLoader('remoteConfig', () => loadRemoteConfigImpl()); @@ -5043,7 +6263,9 @@ if (!token) return; const r = await fetch('/api/v1/remote-config', { headers: auth() }); requireLoad(r); - remoteConfigProviders = (await r.json()).data || []; + const body = await r.json(); + remoteConfigProviders = body.data || []; + remoteConfigOverridesEditable = body.overridesEditable === true; renderRemoteConfigCards(); } /** Never-fetched is spelled out; rendering epoch 0 (or a sentinel) as a date would read as a real fetch. */ @@ -5060,6 +6282,13 @@ $('remoteConfigBadge').textContent = remoteConfigProviders.length ? total + ' key' + (total === 1 ? '' : 's') + ' · ' + remoteConfigProviders.length + ' provider' + (remoteConfigProviders.length === 1 ? '' : 's') : 'no providers'; + + const hasAnyOverride = remoteConfigProviders.some((p) => (p.entries || []).some((e) => e.providerSource != null)); + const clearAllBtn = $('remoteConfigClearOverrides'); + if (clearAllBtn) { + clearAllBtn.hidden = !(remoteConfigOverridesEditable && hasAnyOverride); + } + if (!remoteConfigProviders.length) { cardsGridHtml('remoteConfigCards', [{ icon: 'cloud', iconTone: 'signal', title: 'Remote Config', span: 2, @@ -5085,18 +6314,28 @@ 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, - // 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', - })), + rows: shown.map((e) => { + const rowObj = { + k: e.key, + v: e.redacted ? '' : e.value, + 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', + }; + if (e.source === 'override' && e.providerValue != null) { + rowObj.sub = 'Provider value: ' + e.providerValue + (e.providerSource ? ' (' + e.providerSource + ')' : ''); + } + if (remoteConfigOverridesEditable) { + rowObj.actions = [{ + id: 'override:' + JSON.stringify([provider.id, e.key]), + label: 'Override', + title: 'Override ' + e.key, + }]; + } + return rowObj; + }), }; })); } @@ -5162,6 +6401,106 @@ $('remoteConfigValueBody').innerHTML = remoteConfigValueMode === 'json' && view.jsonOk ? codeLinesHtml(formatJsonLines(view.parsed, ''), true) : `
${esc(view.text)}
`; + + const overrideSection = $('remoteConfigOverrideSection'); + if (overrideSection) { + overrideSection.hidden = !remoteConfigOverridesEditable; + if (remoteConfigOverridesEditable) { + const fallback = $('remoteConfigProviderFallback'); + if (fallback) { + if (entry && entry.providerValue != null) { + fallback.hidden = false; + fallback.textContent = 'Provider value: ' + entry.providerValue + (entry.providerSource ? ' (' + entry.providerSource + ')' : ''); + } else { + fallback.hidden = true; + fallback.textContent = ''; + } + } + const input = $('remoteConfigOverrideInput'); + if (input) { + // A redacted value is a placeholder, not the real string: never offer it for re-saving. + input.value = entry && !entry.redacted ? (entry.value ?? '') : ''; + } + const clearBtn = $('remoteConfigClearOverride'); + if (clearBtn) { + // providerSource is set only while a DevConsole override is active; a provider's own + // `override` source is not ours to clear. + clearBtn.hidden = entry?.providerSource == null; + } + } + } + } + + async function saveRemoteConfigOverride() { + if (!remoteConfigValueTarget) return; + const { providerId, key } = remoteConfigValueTarget; + const input = $('remoteConfigOverrideInput'); + const val = input ? input.value : ''; + try { + const r = await fetch(`/api/v1/remote-config/${encodeURIComponent(providerId)}/overrides/${encodeURIComponent(key)}`, { + method: 'PUT', + headers: { ...controlHeaders(), 'Content-Type': 'application/x-www-form-urlencoded' }, + body: new URLSearchParams({ value: val }), + }); + if (!r.ok) { + let errData = {}; + try { errData = await r.json(); } catch {} + toast(remoteConfigErrorMessage(errData.code, 'Failed to save override'), 'error'); + return; + } + toast('Override saved'); + closeRemoteConfigValue(); + loadRemoteConfig(); + } catch { + toast('Failed to save override', 'error'); + } + } + + async function clearRemoteConfigOverride() { + if (!remoteConfigValueTarget) return; + const { providerId, key } = remoteConfigValueTarget; + try { + const r = await fetch(`/api/v1/remote-config/${encodeURIComponent(providerId)}/overrides/${encodeURIComponent(key)}`, { + method: 'DELETE', + headers: controlHeaders(), + }); + if (!r.ok) { + let errData = {}; + try { errData = await r.json(); } catch {} + toast(remoteConfigErrorMessage(errData.code, 'Failed to clear override'), 'error'); + return; + } + toast('Override cleared'); + closeRemoteConfigValue(); + loadRemoteConfig(); + } catch { + toast('Failed to clear override', 'error'); + } + } + + async function clearAllRemoteConfigOverrides() { + const ok = await openConfirm( + 'Clear all Remote Config overrides?', + 'Removes every active override so each key falls back to its provider value. This cannot be undone.', + 'Clear all', + ); + if (!ok) return; + try { + const r = await fetch('/api/v1/remote-config/overrides', { + method: 'DELETE', + headers: controlHeaders(), + }); + if (!r.ok) { + let errData = {}; + try { errData = await r.json(); } catch {} + toast(remoteConfigErrorMessage(errData.code, 'Failed to clear overrides'), 'error'); + return; + } + toast('All overrides cleared'); + loadRemoteConfig(); + } catch { + toast('Failed to clear overrides', 'error'); + } } function openRemoteConfigValue(rowId) { let providerId, key; @@ -5252,7 +6591,7 @@ }, file ? { - icon: 'sliders', iconTone: 'signal', title: name, span: 2, editFold: 'Add or change a key', badge: entries.length + ' entries', badgeTone: 'muted', + icon: 'sliders', iconTone: 'signal', title: name, span: 2, editFold: 'Add or change a key', badge: countLabel(entries.length, 'entry', 'entries'), badgeTone: 'muted', lede: entries.length ? false : 'This file has no entries.', table: entries.length ? { @@ -5356,8 +6695,10 @@ const name = $('dbName').value; if (!name || !table) return; dbSelectedTable = table; + const gen = nextGen('table-rows'); const r = await fetch('/api/v1/database/' + encodeURIComponent(name) + '/tables/' + encodeURIComponent(table), { headers: auth() }); - dbLastRows = r.ok ? await r.json() : null; + if (!isLatest('table-rows', gen) || $('dbName').value !== name || dbSelectedTable !== table) return; + dbLastRows = r.ok ? await r.json() : { error: unavailableReason(r.status) }; renderDbCards(); } function renderDbCards() { @@ -5388,8 +6729,8 @@ }, { icon: 'grid', iconTone: 'signal', title: table ? table.name : 'Table rows', span: 2, - badge: table ? (rows ? rows.length : 0) + ' of ' + table.rowCount.toLocaleString() + ' rows' : false, badgeTone: 'muted', - lede: !table + badge: table ? (rows ? rows.length : 0) + ' of ' + countLabel(table.rowCount.toLocaleString(), 'row') : false, badgeTone: 'muted', + lede: dbLastRows?.error ? 'Rows unavailable. ' + dbLastRows.error : !table ? 'Choose a table to inspect its rows.' : rows && !rows.length ? 'This table is empty — nothing has been written to it in this session.' @@ -5531,6 +6872,13 @@ let fileEntries = []; let filePreviewStatus = 'Choose a file to preview its contents.'; let filePreviewContent = null; // raw text, only when preview.kind === 'TEXT' + let filePreviewEditable = false; + const clearFileSelection = () => { + selectedFilePath = ''; + filePreviewContent = null; + filePreviewEditable = false; + filePreviewStatus = 'Choose a file to preview its contents.'; + }; async function loadFileRoots() { if (!hasSession()) return loadFileRootsImpl(); return runViewLoader('files', () => loadFileRootsImpl()); @@ -5550,20 +6898,27 @@ const root = fileRoots.includes(selected) ? selected : (fileRoots.includes('files') ? 'files' : fileRoots[0] || ''); $('fileRoot').value = root; $('filePath').value = ''; - selectedFilePath = ''; - filePreviewContent = null; - filePreviewStatus = 'Choose a file to preview its contents.'; + clearFileSelection(); if (root) loadFileListing(root, ''); else renderFilesCards(); } async function loadFileListing(root, path) { if (!token || !root) return; + if ($('fileRoot').value !== root) { + $('fileRoot').value = root; + $('fileRoot').dataset.listingRoot = ''; + clearFileSelection(); + } + const previousRoot = $('fileRoot').dataset.listingRoot || ''; + const previousPath = $('filePath').value || ''; + if (root !== previousRoot || (path || '') !== previousPath) clearFileSelection(); const r = await fetch('/api/v1/files/' + encodeURIComponent(root) + '?path=' + encodeURIComponent(path || ''), { headers: auth() }); if (!r.ok) { cardsGridHtml('filesCards', [{ icon: 'folder', iconTone: 'signal', title: 'Tree', lede: 'Listing unavailable. ' + unavailableReason(r.status) }]); return; } const listing = await r.json(); + $('fileRoot').dataset.listingRoot = root; $('filePath').value = listing.relativePath || ''; fileEntries = listing.entries || []; $('filesBadge').textContent = '/' + (listing.relativePath || ''); @@ -5577,6 +6932,7 @@ return; } selectedFilePath = relativePath; + filePreviewEditable = false; filePreviewContent = null; filePreviewStatus = 'Loading…'; renderFilesCards(); @@ -5587,25 +6943,46 @@ return; } const preview = await r.json(); + // A slower response for a file the user already navigated away from must not overwrite it. + if (selectedFilePath !== relativePath) return; if (preview.kind === 'TEXT') { - filePreviewContent = preview.content + (preview.truncated ? '\n…(truncated)' : ''); - filePreviewStatus = false; + // Previews are always redacted (FileInspector contract), so they are never saved back. An + // untruncated text file is edited from its raw bytes (the same download route) instead. + filePreviewEditable = false; + filePreviewContent = preview.content; + filePreviewStatus = preview.truncated + ? 'Preview is truncated — editing disabled to protect the file' + : false; + if (!preview.truncated && canEditFiles()) { + const requestedPath = relativePath; + try { + const raw = await fetch('/api/v1/files/' + encodeURIComponent(root) + '/download?path=' + encodeURIComponent(requestedPath), { headers: auth() }); + if (raw.ok && selectedFilePath === requestedPath) { + filePreviewContent = new TextDecoder('utf-8', { fatal: true }).decode(await raw.arrayBuffer()); + filePreviewEditable = true; + } + } catch { /* not UTF-8 or unavailable: keep the read-only redacted preview */ } + if (!filePreviewEditable) filePreviewStatus = 'Showing a redacted preview — editing disabled to protect the file'; + } } else { + filePreviewEditable = false; filePreviewContent = null; filePreviewStatus = preview.kind === 'BINARY' ? `[binary, ${preview.sizeBytes} bytes]` : 'Unavailable: ' + preview.reason; } renderFilesCards(); } async function deleteSelectedFile() { - if (!canEditFiles() || !selectedFilePath) return; + const displayedPath = $('filesCards').querySelector('[data-tree-id].selected')?.dataset.treeId || ''; + if (!canEditFiles() || !selectedFilePath || selectedFilePath !== displayedPath || $('fileRoot').value !== $('fileRoot').dataset.listingRoot) return; const root = $('fileRoot').value; if (!root) return; - if (!(await openConfirm('Delete file', 'Delete ' + selectedFilePath + '?', 'Delete'))) return; const path = selectedFilePath; + if (!(await openConfirm('Delete file', 'Delete ' + path + '?', 'Delete'))) return; const r = await fetch('/api/v1/files/' + encodeURIComponent(root) + '?path=' + encodeURIComponent(path), { method: 'DELETE', headers: controlHeaders() }); if (r.ok) { selectedFilePath = ''; filePreviewContent = null; + filePreviewEditable = false; filePreviewStatus = 'File deleted.'; toast('File deleted.'); loadFileListing(root, $('filePath').value); @@ -5634,9 +7011,10 @@ } } async function saveFileContent() { - if (!canEditFiles() || !selectedFilePath) return; + if (!canEditFiles() || !selectedFilePath || !filePreviewEditable) return; const root = $('fileRoot').value; - if (!root) return; + if (!root || root !== $('fileRoot').dataset.listingRoot + || $('filesCards').querySelector('#fileEditor')?.dataset.filePath !== selectedFilePath) return; const body = new URLSearchParams({ path: selectedFilePath, content: $('fileEditor')?.value || '' }); const r = await fetch('/api/v1/files/' + encodeURIComponent(root), { method: 'POST', @@ -5648,6 +7026,8 @@ async function renameSelectedFile() { if (!canEditFiles() || !selectedFilePath) return; const root = $('fileRoot').value; + if (root !== $('fileRoot').dataset.listingRoot + || $('filesCards').querySelector('[data-tree-id].selected')?.dataset.treeId !== selectedFilePath) return; const newPath = $('fileTargetPath')?.value.trim(); if (!root || !newPath) return; const body = new URLSearchParams({ path: selectedFilePath, newPath }); @@ -5675,19 +7055,14 @@ return; } const blob = await r.blob(); - const url = URL.createObjectURL(blob); - const a = document.createElement('a'); - a.href = url; - a.download = selectedFilePath.split('/').pop() || 'download'; - a.click(); - URL.revokeObjectURL(url); + downloadBlob(blob, selectedFilePath.split('/').pop() || 'download'); } function renderFilesCards() { const base = $('filePath').value || ''; const indent = 8 + (base ? base.split('/').filter(Boolean).length : 0) * 16; cardsGridHtml('filesCards', [ { - icon: 'folder', iconTone: 'signal', title: 'Tree', badge: fileEntries.length + ' entries', badgeTone: 'muted', + icon: 'folder', iconTone: 'signal', title: 'Tree', badge: countLabel(fileEntries.length, 'entry', 'entries'), badgeTone: 'muted', lede: fileEntries.length ? false : 'This directory is empty.', tree: fileEntries.map((e) => ({ id: e.relativePath, label: e.name + (e.isDirectory ? '/' : ''), icon: e.isDirectory ? 'folder' : 'file', @@ -5701,12 +7076,13 @@ lede: filePreviewStatus || false, code: filePreviewContent != null ? filePreviewContent.split('\n').map((line) => ({ pad: '', k: '', v: line, cls: 'tone-text-ink' })) : false, fieldsHtml: `
- + ${selectedFilePath && !filePreviewEditable ? '

Preview is truncated/redacted — editing disabled to protect the file

' : ''} +
`, buttons: [ { id: 'rename', label: 'Rename', icon: 'pencil', disabled: !canEditFiles() || !selectedFilePath, title: canEditFiles() ? 'Rename to the target path above' : 'Sign in and enable the files capability' }, - { id: 'save', label: 'Save changes', icon: 'check', kind: canEditFiles() ? 'primary' : 'default', disabled: !canEditFiles() || !selectedFilePath, title: canEditFiles() ? 'Save changes' : 'Sign in and enable the files capability' }, + { id: 'save', label: 'Save changes', icon: 'check', kind: canEditFiles() ? 'primary' : 'default', disabled: !canEditFiles() || !selectedFilePath || !filePreviewEditable, title: !filePreviewEditable && selectedFilePath ? 'Editing disabled for truncated or redacted previews' : canEditFiles() ? 'Save changes' : 'Sign in and enable the files capability' }, { id: 'download', label: 'Download', icon: 'download', disabled: !canEditFiles() || !selectedFilePath, title: canEditFiles() ? 'Download' : 'Sign in and enable the files capability' }, { id: 'delete', label: 'Delete', icon: 'trash', kind: 'danger', disabled: !canEditFiles() || !selectedFilePath, title: canEditFiles() ? 'Delete' : 'Sign in and enable the files capability' }, ], @@ -5880,9 +7256,26 @@ loadSession(); } } + /** Signs only this browser out (revokes its own bearer session); other browsers and the server stay up. */ + async function endBrowserSession() { + if (!hasSession() || openAccess) return; + if (!(await openConfirm('Sign out this browser?', 'You will need a fresh connect code from the device to reconnect.', 'Sign out'))) return; + try { await fetch('/api/v1/auth/logout', { method: 'POST', headers: controlHeaders() }); } catch { /* signing out locally regardless */ } + clearTimeout(streamRetry); streamRetry = null; + token = ''; + csrf = ''; + invalidateSessionCache(); + try { sessionStorage.removeItem('devconsole.browserSession'); } catch { /* storage unavailable */ } + stream?.close(); + stream = null; + $('lamp').classList.remove('live', 'reconnecting'); + setStatus('Signed out', "Signed out — get a fresh connect code from the device's More screen"); + toast('Signed out of this browser session.'); + updateControlUi(); + } async function stopServer() { if (!hasSession()) return; - if (!(await openConfirm('Stop the DevConsole server?', 'All connected browsers will be disconnected.', 'Stop server'))) return; + if (!(await openConfirm('Stop the DevConsole server?', 'Stops the DevConsole server for every connected browser.', 'Stop server'))) return; await fetch('/api/v1/session/stop', { method: 'POST', headers: controlHeaders() }); toast('Server stop requested.'); } @@ -5904,16 +7297,49 @@ * crashed, and roughly how much each is holding. Read-only, newest-first (server-sorted). */ const RUN_STATUS_TONE = { CRASHED: 'error', ACTIVE: 'signal', DELETING: 'warn', COMPLETED: 'muted' }; function retainedRunsTableHtml(runs) { - return cardTableHtml({ - cols: ['Status', 'Started', 'App', 'Device', 'Records'], - rows: runs.map((r) => [ - { v: r.status, tone: RUN_STATUS_TONE[r.status] || 'muted' }, - { v: time(r.startedAtEpochMs), tone: 'muted' }, - { v: [r.applicationId, r.appVersionName].filter(Boolean).join(' ') || '—', tone: 'ink' }, - { v: [r.deviceModel, r.deviceOsVersion].filter(Boolean).join(' · ') || '—', tone: 'muted' }, - { v: r.recordCount != null ? String(r.recordCount) : '—', tone: 'ink' }, - ]), + const cells = (r) => [ + { v: r.current ? 'LIVE' : (r.pinned ? r.status + ' · pinned' : r.status), tone: RUN_STATUS_TONE[r.status] || 'muted' }, + { v: time(r.startedAtEpochMs), tone: 'muted' }, + { v: [r.applicationId, r.appVersionName].filter(Boolean).join(' ') || '—', tone: 'ink' }, + { v: [r.deviceModel, r.deviceOsVersion].filter(Boolean).join(' · ') || '—', tone: 'muted' }, + { v: r.recordCount != null ? String(r.recordCount) : '—', tone: 'ink' }, + ]; + // Finished runs only: the live run can be neither pinned nor deleted. + const actions = (r) => (!hasSession() || r.current || !['COMPLETED', 'CRASHED'].includes(r.status) ? '' : ` + + `); + const head = ['Status', 'Started', 'App', 'Device', 'Records', ''].map((h) => `${esc(h)}`).join(''); + const body = runs + .map((r) => `${cells(r).map((c) => `${esc(c.v)}`).join('')}${actions(r)}`) + .join(''); + return `
${head}${body}
`; + } + /** Drops every cached copy of [url] so the next cachedJson() read refetches it. */ + function forgetCachedJson(url) { + [...jsonCache.keys()].filter((key) => key.endsWith(':' + url)).forEach((key) => jsonCache.delete(key)); + } + async function setRunPinned(id, pinned) { + if (!hasSession()) return; + const r = await fetch('/api/v1/runs/' + encodeURIComponent(id) + '/pin', { + method: 'POST', + headers: { ...controlHeaders(), 'Content-Type': 'application/x-www-form-urlencoded' }, + body: new URLSearchParams({ pinned: String(pinned) }), }); + if (!r.ok) { toast('Could not ' + (pinned ? 'pin' : 'unpin') + ' that run: ' + r.status, 'error'); return; } + toast(pinned ? 'Run pinned — retention will keep it.' : 'Run unpinned.'); + forgetCachedJson('/api/v1/runs'); + loadSession(); + } + async function deleteRun(id) { + if (!hasSession()) return; + const ok = await openConfirm('Delete this run?', 'Its captures, logs, crashes and attachments are removed from the device. This cannot be undone.', 'Delete run'); + if (!ok) return; + const r = await fetch('/api/v1/runs/' + encodeURIComponent(id), { method: 'DELETE', headers: controlHeaders() }); + if (!r.ok) { toast('Could not delete that run: ' + r.status, 'error'); return; } + toast('Run deleted.'); + forgetCachedJson('/api/v1/runs'); + if (networkRunId === id) selectNetworkRun(''); + loadSession(); } function renderSessionCards(meta, capabilities) { const endpoint = meta?.endpoint; @@ -5964,7 +7390,8 @@ : [], ), buttons: [ - { id: 'end-session', label: openAccess ? 'Stop server' : 'End session', icon: 'trash', kind: 'danger', disabled: !hasSession(), title: hasSession() ? (openAccess ? 'Stop the DevConsole server' : 'End this browser session') : 'Connect this browser first' }, + ...(openAccess ? [] : [{ id: 'end-session', label: 'Sign out this browser', icon: 'close', disabled: !hasSession(), title: hasSession() ? 'End this browser session only; the server keeps running' : 'Connect this browser first' }]), + { id: 'stop-server', label: 'Stop server', icon: 'trash', kind: 'danger', disabled: !hasSession(), title: hasSession() ? 'Stop the DevConsole server for every connected browser' : 'Connect this browser first' }, { id: 'rotate-code', label: 'Rotate code now', icon: 'refresh', disabled: !hasSession() || openAccess, title: openAccess ? 'Session codes are disabled in open mode' : hasSession() ? 'Invalidate the current session code and mint a new one' : 'Connect this browser first' }, ], }, @@ -5975,7 +7402,7 @@ }, { icon: 'database', iconTone: retainedRuns.some((r) => r.status === 'CRASHED') ? 'error' : 'signal', title: 'Run history', span: 2, - bodyFold: 'Retained runs', foldCount: retainedRuns.length + ' runs', + bodyFold: 'Retained runs', foldCount: countLabel(retainedRuns.length, 'run'), emptyText: 'No retained runs on this device yet.', bodyHtml: retainedRuns.length ? retainedRunsTableHtml(retainedRuns) : '', }, @@ -6014,7 +7441,8 @@ updateExportScope(); wireCardGrid('sessionCards', { onButton: (id) => { - if (id === 'end-session') stopServer(); + if (id === 'end-session') endBrowserSession(); + else if (id === 'stop-server') stopServer(); else if (id === 'rotate-code') rotateSessionCode(); else if (id === 'export-estimate') estimateExportSize(); else if (id === 'export-create') createExport(); @@ -6023,6 +7451,8 @@ }, }); $('sessionCards').querySelectorAll('[data-revoke-principal]').forEach((btn) => { btn.onclick = () => revokePrincipal(btn.dataset.revokePrincipal); }); + $('sessionCards').querySelectorAll('[data-run-pin]').forEach((btn) => { btn.onclick = () => setRunPinned(btn.dataset.runPin, btn.dataset.pinned !== 'true'); }); + $('sessionCards').querySelectorAll('[data-run-delete]').forEach((btn) => { btn.onclick = () => deleteRun(btn.dataset.runDelete); }); } function updateExportScope() { const scope = $('exportScope').value; @@ -6099,12 +7529,7 @@ return; } const blob = await r.blob(); - const url = URL.createObjectURL(blob); - const a = document.createElement('a'); - a.href = url; - a.download = 'devconsole-export.zip'; - a.click(); - URL.revokeObjectURL(url); + downloadBlob(blob, 'devconsole-export.zip'); if (status) { delete status.dataset.busy; status.textContent = 'Export ready. Verify manifest.json before sharing.'; } toast('Export downloaded.'); if (btn) btn.disabled = false; @@ -6214,6 +7639,20 @@ updateEvidenceUi(); return { items: [...evidenceFlags.values()], report: evidenceReport }; } + /** The tray is per app run (Room keeps every run's); this saves the newest finished run's as JSON. */ + async function downloadPreviousRunEvidence() { + if (!hasSession()) return; + const runsRes = await cachedJson('/api/v1/runs', 30000).catch(() => null); + const runs = runsRes?.ok ? (await runsRes.json()).data || [] : []; + const previous = runs.find((run) => !run.current); + if (!previous) { toast('No previous run is retained on this device.', 'error'); return; } + const r = await fetch('/api/v1/evidence?sessionId=' + encodeURIComponent(previous.id), { headers: auth() }); + if (!r.ok) { toast('Evidence unavailable: ' + r.status, 'error'); return; } + const body = await r.json(); + if (!(body.data || []).length) { toast('The previous run has no flagged evidence.'); return; } + const blob = new Blob([JSON.stringify({ run: previous, ...body }, null, 2)], { type: 'application/json' }); + downloadBlob(blob, 'devconsole-evidence-' + previous.id + '.json'); + } async function loadEvidence() { if (!hasSession()) return loadEvidenceImpl(); return runViewLoader('evidence', () => loadEvidenceImpl()); @@ -6323,17 +7762,24 @@ ); const text = results.filter(Boolean).join('\n\n'); if (!text) { toast('cURL unavailable for the flagged transactions', 'error'); return; } - await copyToClipboard(text, results.filter(Boolean).length + ' capture(s) as cURL'); + await copyToClipboard(text, countLabel(results.filter(Boolean).length, 'capture') + ' as cURL'); } - async function downloadBlobResponse(r, filename) { - if (!r.ok) return false; - const blob = await r.blob(); + /** Revoking the object URL right after click() can cancel the download in some browsers, so it + * is released a while later instead. */ + function downloadBlob(blob, filename) { const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = filename; + document.body.appendChild(a); a.click(); - URL.revokeObjectURL(url); + a.remove(); + setTimeout(() => URL.revokeObjectURL(url), 30000); + } + async function downloadBlobResponse(r, filename) { + if (!r.ok) return false; + const blob = await r.blob(); + downloadBlob(blob, filename); return true; } function flaggedNetworkIds(items) { @@ -6461,6 +7907,108 @@ // ---- Screenshot capture (B): POST /api/v1/screenshots, then flag the resulting event as // SCREENSHOT-kind evidence so a capture is immediately visible in the tray with a thumbnail -- // the capture flow *is* the flag flow here, matching "capture button ... in the evidence tray". + function captureControlErrorMessage(code, defaultMsg) { + if (code === 'CAPTURE_CONTROL_UNAVAILABLE') return 'Capture control is unavailable on this device.'; + if (code === 'VALIDATION_FAILED') return 'Validation failed for capture request.'; + if (code === 'CSRF_INVALID') return 'Security check failed (invalid CSRF token).'; + if (code === 'AUTH_REQUIRED') return 'Connect this browser first.'; + return (defaultMsg || 'Capture action failed') + (code ? ': ' + code : ''); + } + + let captureStateAvailable = false; + let capturePausedState = false; + + function updateCaptureControlsUi(available, paused) { + captureStateAvailable = Boolean(available); + capturePausedState = Boolean(paused); + + const toggleBtn = $('capturePausedToggle'); + const purgeBtn = $('capturePurge'); + const pill = $('capturePausedPill'); + + if (toggleBtn) { + toggleBtn.hidden = !captureStateAvailable; + const labelText = capturePausedState ? 'Resume capture' : 'Pause capture'; + const labelSpan = toggleBtn.querySelector('span'); + if (labelSpan) labelSpan.textContent = labelText; + toggleBtn.setAttribute('aria-label', labelText); + const useEl = toggleBtn.querySelector('svg use'); + if (useEl) { + useEl.setAttribute('href', capturePausedState ? '#dc-record' : '#dc-pause'); + } + } + if (purgeBtn) { + purgeBtn.hidden = !captureStateAvailable; + } + if (pill) { + pill.hidden = !capturePausedState; + } + } + + async function loadCaptureState() { + if (!token) return; + try { + const r = await fetch('/api/v1/capture', { headers: auth() }); + if (!r.ok) return; + const data = await r.json(); + updateCaptureControlsUi(data.available, data.paused); + } catch { + /* ignore transient failure */ + } + } + + async function setCapturePaused(nextPaused) { + if (!hasSession()) { toast('Connect this browser first.', 'error'); return; } + try { + const r = await fetch('/api/v1/capture/paused', { + method: 'POST', + headers: { ...controlHeaders(), 'Content-Type': 'application/x-www-form-urlencoded' }, + body: String(Boolean(nextPaused)), + }); + if (!r.ok) { + let code; try { code = (await r.json()).code; } catch { code = undefined; } + toast(captureControlErrorMessage(code, 'Failed to update capture state'), 'error'); + return; + } + const data = await r.json(); + updateCaptureControlsUi(true, data.paused); + toast(data.paused ? 'Capture paused' : 'Capture resumed'); + } catch { + toast('Failed to update capture state', 'error'); + } + } + + async function purgeCaptureData() { + if (!hasSession()) { toast('Connect this browser first.', 'error'); return; } + const ok = await openConfirm( + 'Purge captured data?', + "Removes this run's captured network, socket and push data from the device, and deletes old unpinned runs. This cannot be undone.", + 'Purge', + ); + if (!ok) return; + try { + const r = await fetch('/api/v1/capture/purge', { method: 'POST', headers: controlHeaders() }); + if (!r.ok) { + let code; try { code = (await r.json()).code; } catch { code = undefined; } + toast(captureControlErrorMessage(code, 'Failed to purge captured data'), 'error'); + return; + } + const data = await r.json(); + // Same wording as the in-app inspector: name only what was removed, never a row of zeros. + const parts = [ + [data.networkTransactions ?? 0, 'request'], + [data.socketConnections ?? 0, 'connection'], + [data.pushEvents ?? 0, 'push event'], + [data.retainedRunsDeleted ?? 0, 'old run'], + ].filter(([n]) => n > 0).map(([n, noun]) => `${n} ${noun}${n === 1 ? '' : 's'}`); + toast(parts.length === 0 ? 'Nothing to purge' + : 'Removed ' + (parts.length === 1 ? parts[0] : parts.slice(0, -1).join(', ') + ' and ' + parts[parts.length - 1])); + reloadActiveView(); + } catch { + toast('Failed to purge captured data', 'error'); + } + } + function screenshotErrorMessage(code) { if (code === 'SCREENSHOT_DISABLED') return 'Screenshot capture is off by default — the host must set screenshotPolicy.enabled = true (DevConsoleConfig.withScreenshotPolicy(...)) to turn it on.'; if (code === 'NO_FOREGROUND_ACTIVITY') return 'Nothing to capture — no foreground Activity on the device right now.'; @@ -6540,11 +8088,16 @@ bodyHtml: foldHtml('How the tray works', '

' + esc("Flag a transaction, frame, push event, timeline event or crash with the flag button at the end of its row — or from its detail header — and it lands here with the full redacted detail the server captured at flag time, not just a label. Draft the report while the session is still live; once it ends the proof is gone. A browser refresh keeps everything: flagged items and any typed report text are saved server-side.") + '

'), buttons: [ { id: 'go-network', label: 'Go to Network', icon: 'network', kind: 'primary' }, + { id: 'previous-run-evidence', label: "Previous run's evidence", icon: 'download', disabled: !hasSession(), title: 'The tray is per app run; download what was flagged before the last restart' }, { id: 'capture-screenshot', label: 'Capture screenshot', icon: 'camera', disabled: !hasSession(), title: hasSession() ? 'Capture the device\'s foreground screen — off by default; set screenshotPolicy.enabled to allow it' : 'Connect this browser first' }, ], }, ]); - wireCardGrid('evidenceList', { onButton: (id) => { if (id === 'go-network') show('network'); else if (id === 'capture-screenshot') captureScreenshot(); } }); + wireCardGrid('evidenceList', { onButton: (id) => { + if (id === 'go-network') show('network'); + else if (id === 'capture-screenshot') captureScreenshot(); + else if (id === 'previous-run-evidence') downloadPreviousRunEvidence(); + } }); return; } $('evidenceMetrics').innerHTML = metricsStripHtml([ @@ -6604,7 +8157,7 @@ buttons: [{ id: 'capture-screenshot', label: 'Capture screenshot', icon: 'camera', disabled: !hasSession(), title: hasSession() ? 'Capture the device\'s foreground screen — off by default; set screenshotPolicy.enabled to allow it' : 'Connect this browser first' }], }, { - icon: 'flag', iconTone: 'signal', title: 'Attachments', span: 3, badge: items.length + ' items', badgeTone: 'muted', + icon: 'flag', iconTone: 'signal', title: 'Attachments', span: 3, badge: countLabel(items.length, 'item'), badgeTone: 'muted', // Bespoke table, not cardTableHtml: the last column needs real download/unflag buttons per // row, which a plain escaped-text cell can't hold. bodyHtml: evidenceAttachmentsTableHtml(items), @@ -6646,6 +8199,7 @@ * (and the still-persisted report draft, if any) render from the real post-clear server state * rather than an assumed-empty local one. */ async function clearEvidenceTray() { + if (!(await openConfirm('Clear evidence tray?', 'Remove all persisted evidence items from this session? This cannot be undone.', 'Clear tray'))) return; if (!hasSession()) { evidenceFlags.clear(); updateEvidenceUi(); loadEvidence(); return; } const r = await fetch('/api/v1/evidence', { method: 'DELETE', headers: controlHeaders() }); if (r.ok) { toast('Evidence tray cleared.'); clearAttachmentInfoCache(); } @@ -6707,6 +8261,7 @@ // ever gated on "is a session connected", exactly like Export; SCREENSHOT_DISABLED is // surfaced as a toast naming the config property once a capture is actually attempted. $('captureScreenshot').disabled = !token; + if (token) loadCaptureState(); syncConnectPrompts(enabled); }; @@ -6755,21 +8310,29 @@ return false; } const collections = (await r.json()).data || []; + composerCollectionsCache = collections; $('composerCollectionList').innerHTML = collections.length - ? cardRowsHtml( - collections.map((c) => ({ - k: c.name, v: (c.request?.method || 'GET') + ' ' + (c.request?.url || ''), tone: 'ink', - tag: hasSession() ? 'DELETE' : false, tagTone: 'error', - })), - ) + ? `
${collections.map((c) => `
+ ${hasSession() ? `` : ''} +
`).join('')}
` : 'Collections contain no persisted secret variable values.'; - if (hasSession()) { - $('composerCollectionList').querySelectorAll('.card-row').forEach((row, i) => { - row.style.cursor = 'pointer'; - row.title = 'Delete this collection'; - row.onclick = () => deleteComposerCollection(collections[i].id); - }); - } + } + let composerCollectionsCache = []; + function loadComposerCollection(collection) { + const request = collection.request || {}; + $('composerMethod').value = request.method || 'GET'; + $('composerUrl').value = request.url || ''; + $('composerBodyType').value = request.bodyType || 'NONE'; + $('composerTimeout').value = request.timeoutMs || 15000; + $('composerRedirects').value = String(request.followRedirects ?? true); + $('composerBody').value = ''; + $('composerHeaders').value = ''; + $('composerQuery').value = ''; + $('composerForm').value = ''; + $('composerMultipart').value = ''; + toast('Loaded "' + collection.name + '" into Composer.'); } const COMPOSER_DEVICE_EXECUTOR = 'device'; const COMPOSER_AGENT_PREFIX = 'agent:'; @@ -7321,8 +8884,9 @@ toast(r.ok ? 'Collection saved without secret values.' : 'Save failed: ' + r.status, r.ok ? undefined : 'error'); if (r.ok) loadComposerCollections(); } - async function deleteComposerCollection(id) { + async function deleteComposerCollection(id, name = 'this saved Composer collection') { if (!hasSession()) return; + if (!(await openConfirm('Delete collection?', 'Delete "' + name + '"?', 'Delete'))) return; const r = await fetch('/api/v1/composer/collections/' + encodeURIComponent(id), { method: 'DELETE', headers: controlHeaders() }); toast(r.ok ? 'Collection deleted.' : 'Delete failed: ' + r.status, r.ok ? undefined : 'error'); if (r.ok) loadComposerCollections(); @@ -7332,7 +8896,8 @@ // Mocks // ================================================================ const canEditMocks = () => hasSession() && mocksEditable; - const canResend = () => hasSession() && composerCapabilityEnabled; + // A past run's capture can still be copied as cURL or cloned into Composer, but not re-sent. + const canResend = () => hasSession() && composerCapabilityEnabled && !networkRunId; let mockConflictCount = 0; let mockPendingHighlightId = ''; async function loadMockRules() { @@ -7353,13 +8918,12 @@ $('mockRuleList').innerHTML = rules.length ? cardTogglesHtml( rules.map((rule) => ({ - // Only StaticResponse (± Delay) rules survive a dialog round-trip; editing a - // fault-injection/template rule here would silently rewrite it as a static 200, - // and a truncated body would save the truncation as content. + // Every action type is welcome in the editor; shapes it cannot express open + // read-only with an inline note instead of being silently rewritten. id: rule.id, checked: rule.enabled, disabled: !canEditMocks(), deletable: canEditMocks(), editable: isMockRuleEditable(rule), k: rule.id, - sub: (rule.method || '*') + ' ' + rule.path + ' → ' + rule.action + (rule.statusCode != null ? ' ' + rule.statusCode : '') + ' · ' + rule.scope + sub: (rule.method || '*') + ' ' + rule.path + ' → ' + mockActionLabel(rule) + (rule.statusCode != null ? ' ' + rule.statusCode : '') + ' · ' + rule.scope + (rule.hitCount ? ' · ' + rule.hitCount + ' hit' + (rule.hitCount === 1 ? '' : 's') + (rule.lastHitEpochMs ? ' · ' + relativeTime(rule.lastHitEpochMs) : '') : ''), })), ) @@ -7468,6 +9032,75 @@ toast(r.ok ? 'Mock rule ' + (enabled ? 'enabled.' : 'disabled.') : 'Update failed: ' + r.status, r.ok ? undefined : 'error'); if (r.ok) loadMockRules(); } + /** True when any response body inside the action tree was capped by MockRule.json(). */ + function mockActionHasTruncatedBody(detail) { + if (!detail) return false; + if (detail.bodyTruncated === true || detail.templateTruncated === true) return true; + if (detail.next && mockActionHasTruncatedBody(detail.next)) return true; + return Array.isArray(detail.steps) && detail.steps.some(mockActionHasTruncatedBody); + } + async function exportMockRules() { + if (!hasSession()) return; + const r = await fetch('/api/v1/mocks/rules', { headers: auth() }); + if (!r.ok) { toast('Export failed: ' + r.status, 'error'); return; } + const rules = (await r.json()).data || []; + const exportable = rules.filter((rule) => !mockActionHasTruncatedBody(rule.actionDetail)); + const payload = { + format: 'devconsole-mock-rules', version: 1, + rules: exportable.map((rule) => ({ + id: rule.id, priority: rule.priority, method: rule.method, scheme: rule.scheme, host: rule.host, + path: rule.path, scope: rule.scope, enabled: rule.enabled, + queryPredicates: rule.queryPredicates || {}, headerPredicates: rule.headerPredicates || {}, + bodyPredicate: rule.bodyPredicate, action: rule.actionDetail, + })), + }; + downloadBlob(new Blob([JSON.stringify(payload, null, 2)], { type: 'application/json' }), 'devconsole-mock-rules.json'); + const skipped = rules.length - exportable.length; + toast( + 'Exported ' + exportable.length + ' rule' + (exportable.length === 1 ? '' : 's') + + (skipped ? '; skipped ' + skipped + ' with truncated bodies.' : '.'), + skipped ? 'error' : undefined, + ); + } + async function importMockRules(file) { + if (!file || !canEditMocks()) return; + let payload; + try { payload = JSON.parse(await file.text()); } catch { toast('Import failed: not valid JSON.', 'error'); return; } + if (!payload || payload.format !== 'devconsole-mock-rules' || payload.version !== 1 || !Array.isArray(payload.rules)) { + toast('Import failed: expected format devconsole-mock-rules, version 1.', 'error'); + return; + } + let created = 0, failed = 0; + for (const rule of payload.rules) { + const form = mockActionForm(rule.action); + if (!form || typeof rule.id !== 'string' || !MOCK_RULE_ID_RE.test(rule.id)) { failed++; continue; } + const params = new URLSearchParams({ + id: rule.id, path: rule.path || '.*', priority: String(Number(rule.priority) || 0), scope: rule.scope || 'SESSION', + }); + if (rule.method) params.set('method', rule.method); + if (rule.scheme) params.set('scheme', rule.scheme); + if (rule.host) params.set('host', rule.host); + params.set('enabled', String(rule.enabled !== false)); + applyMockActionParams(params, { + ...form, + headersText: Object.entries(form.headers || {}).map(([k, v]) => k + ': ' + v).join('\n'), + }); + Object.entries(rule.queryPredicates || {}).forEach(([k, v]) => params.append('queryPredicate', k + '=' + v)); + Object.entries(rule.headerPredicates || {}).forEach(([k, v]) => params.append('headerPredicate', k + '=' + v)); + if (rule.bodyPredicate) params.set('bodyPredicate', rule.bodyPredicate); + const r = await fetch('/api/v1/mocks/rules', { + method: 'POST', + headers: { ...controlHeaders(), 'Content-Type': 'application/x-www-form-urlencoded' }, + body: params, + }); + if (r.ok) created++; else failed++; + } + toast( + 'Imported ' + created + ' rule' + (created === 1 ? '' : 's') + (failed ? '; ' + failed + ' failed.' : '.'), + failed ? 'error' : undefined, + ); + loadMockRules(); + } // ================================================================ // Capture rules @@ -7704,19 +9337,19 @@ renderEmpty(pane, 'network', 'No transaction selected', 'Select a request to inspect it.'); pane.insertAdjacentHTML('afterbegin', `
${networkListToggleHtml()}
`); } - function networkDetailHeadHtml({ badgeText, title, actions, tabs, menuOpen, fullUrl, metaLine }) { + function networkDetailHeadHtml({ badgeText, title, actions, tabs, menuOpen, fullUrl, metaLine, offline }) { const primary = ['curl', 'clone', 'flag']; const menuActions = actions.filter((a) => !primary.includes(a.id)); return `
${networkListToggleHtml()}${esc(badgeText)} ${esc(title)} -
${primary.map((id) => { +
${offline ? '' : `${primary.map((id) => { const a = actions.find((item) => item.id === id); const label = id === 'curl' ? 'Copy cURL' : id === 'clone' ? 'Open in Composer' : 'Flag as evidence'; return ``; - }).join('')}
+ }).join('')}`}
${menuOpen ? `` : ''} -
${esc(metaLine)}
+
${esc(metaLine)}${offline ? ' · offline HAR' : ''}
${tabs.map((t) => ``).join('')}
`; } const NETWORK_STATUS_REASONS = { @@ -7727,22 +9360,345 @@ 500: 'Internal Server Error', 502: 'Bad Gateway', 503: 'Service Unavailable', 504: 'Gateway Timeout', }; + // ================================================================ + // Structured decoders — JWT and GraphQL. Mirrors the Android inspector's + // InspectorStructuredDecoders.kt so the same token or operation reads the same on both + // surfaces. Decoding only: a JWT signature is never verified here (the dashboard has no key), + // so every JWT section says so outright rather than implying the token is trustworthy. + // ================================================================ + const JWT_SEGMENT_COUNT = 3; + const JWT_TIMESTAMP_CLAIMS = ['exp', 'iat', 'nbf']; + + /** A redacted value ( / ***) must never be decoded — the marker is not a token. */ + function isRedactedValue(text) { + const value = String(text ?? ''); + return //i.test(value) || value.includes('***'); + } + + /** Base64url → UTF-8 text. JWT segments drop their `=` padding, and a length of 1 mod 4 is + * never valid base64, so both are normalized/left to throw into the null-returning catch. */ + function decodeBase64UrlUtf8(segment) { + try { + const padded = segment.replace(/-/g, '+').replace(/_/g, '/') + '='.repeat((4 - (segment.length % 4)) % 4); + const binary = atob(padded); + if (typeof TextDecoder === 'function') { + const bytes = new Uint8Array(binary.length); + for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i); + return new TextDecoder('utf-8').decode(bytes); + } + return decodeURIComponent(binary.split('').map((c) => '%' + c.charCodeAt(0).toString(16).padStart(2, '0')).join('')); + } catch { + return null; + } + } + + function parseJsonText(text) { + try { return JSON.parse(text); } catch { return undefined; } + } + + /** + * The Android decoder's coarsest-unit span: `45 s`, `15 min`, `2 h 5 min`, `3 days`, + * `about 5 months`, `about 3 years`. Partial minutes round up so a token with 30 s left never + * reads as `0 min`. + */ + function formatJwtSpan(seconds) { + const minutes = Math.ceil(seconds / 60); + const hours = Math.floor(minutes / 60); + const days = Math.floor(hours / 24); + if (seconds < 60) return seconds + ' s'; + if (minutes < 60) return minutes + ' min'; + if (hours < 24) return hours + ' h' + (minutes % 60 ? ' ' + (minutes % 60) + ' min' : ''); + if (days < 60) return days + ' day' + (days === 1 ? '' : 's'); + if (days < 365) return 'about ' + Math.floor(days / 30) + ' months'; + const years = Math.floor(days / 365); + return 'about ' + years + ' year' + (years === 1 ? '' : 's'); + } + + /** exp/iat/nbf as a local date-time plus the same relative suffix the Android inspector shows. */ + function jwtTimestamps(payload, nowMs) { + const nowSeconds = Math.floor(nowMs / 1000); + return JWT_TIMESTAMP_CLAIMS.map((claim) => { + const value = payload[claim]; + if (typeof value !== 'number' || !Number.isFinite(value)) return null; + const epochSeconds = Math.trunc(value); + const span = formatJwtSpan(Math.abs(epochSeconds - nowSeconds)); + const inPast = epochSeconds <= nowSeconds; + let relative; + if (claim === 'exp') relative = inPast ? 'expired ' + span + ' ago' : 'expires in ' + span; + else if (claim === 'nbf') relative = inPast ? 'active since ' + span + ' ago' : 'starts in ' + span; + else relative = inPast ? 'issued ' + span + ' ago' : 'issued in the future (clock skew?)'; + return { claim, at: new Date(epochSeconds * 1000).toLocaleString(), relative, expired: claim === 'exp' && inPast }; + }).filter(Boolean); + } + + /** + * Decodes one candidate token. Returns null — never throws — unless it is a bare 3-segment + * compact JWS whose header parses as a JSON object carrying `alg` and whose payload parses as a + * JSON object. That header check is what keeps a dotted package name or a random string from + * being presented as a decoded credential. + */ + function decodeJwtValue(raw, source, nowMs) { + let token = String(raw ?? '').trim().replace(/^"|"$/g, ''); + if (/^Bearer\s+/i.test(token)) token = token.replace(/^Bearer\s+/i, '').trim(); + if (!token || isRedactedValue(token)) return null; + const segments = token.split('.'); + if (segments.length !== JWT_SEGMENT_COUNT || segments.some((segment) => !segment)) return null; + const headerText = decodeBase64UrlUtf8(segments[0]); + const payloadText = decodeBase64UrlUtf8(segments[1]); + if (!headerText || !payloadText || isRedactedValue(headerText) || isRedactedValue(payloadText)) return null; + const header = parseJsonText(headerText); + const payload = parseJsonText(payloadText); + if (!header || typeof header !== 'object' || Array.isArray(header) || !header.alg) return null; + if (!payload || typeof payload !== 'object' || Array.isArray(payload)) return null; + return { source, header, payload, signatureLength: segments[2].length, timestamps: jwtTimestamps(payload, nowMs) }; + } + + /** Every string leaf under `node`, so a token nested anywhere in a JSON body is still found. */ + function collectJwtCandidatesFromJson(node, out) { + if (typeof node === 'string') { out.push(node); return; } + if (Array.isArray(node)) { node.forEach((item) => collectJwtCandidatesFromJson(item, out)); return; } + if (node && typeof node === 'object') Object.values(node).forEach((value) => collectJwtCandidatesFromJson(value, out)); + } + + /** + * JWTs in a transaction: the request `Authorization: Bearer …` header, then any header or body + * value that is itself exactly a bare compact JWS. The Android decoder also pulls + * `access_token`/`id_token`/`token` fields out of a JSON response; scanning every leaf string + * covers those and can only false-positive on a string that both has 3 segments and decodes to + * `{"alg":…}`, so it stays conservative in practice. + */ + function extractTransactionJwts(detail, nowMs) { + const found = []; + const seen = new Set(); + const add = (raw, source) => { + const decoded = decodeJwtValue(raw, source, nowMs); + if (!decoded) return; + const key = JSON.stringify([decoded.header, decoded.payload]); + if (seen.has(key)) return; + seen.add(key); + found.push(decoded); + }; + const requestHeaders = detail.request?.headers || []; + requestHeaders.forEach((header) => { + const name = String(header.name || ''); + const value = String(header.value || ''); + if (name.toLowerCase() === 'authorization' && /^Bearer\s+/i.test(value.trim())) add(value, 'request Authorization'); + }); + const scanHeaders = (headers, side) => (headers || []).forEach((header) => { + const name = String(header.name || ''); + if (name.toLowerCase() === 'authorization') return; + const value = String(header.value || '').trim(); + if (value.split('.').length === JWT_SEGMENT_COUNT) add(value, side + ' header ' + name); + }); + scanHeaders(detail.request?.headers, 'request'); + scanHeaders(detail.response?.headers, 'response'); + const scanBody = (body, side) => { + if (body?.type !== 'text' || !body.value) return; + const text = body.value.trim(); + const json = parseJsonText(text); + if (json !== undefined) { + const strings = []; + collectJwtCandidatesFromJson(json, strings); + strings.forEach((value) => add(value, side + ' body')); + } else { + add(text, side + ' body'); + } + }; + scanBody(detail.request?.body, 'request'); + scanBody(detail.response?.body, 'response'); + return found; + } + + /** Same header regex as the Android decoder: `query|mutation|subscription `. */ + function parseGraphQlOperationHeader(query) { + const stripped = String(query || '') + .split('\n') + .map((line) => line.split('#')[0].trim()) + .filter(Boolean) + .join(' ') + .trim(); + const match = /^(query|mutation|subscription)\b(?:\s+([_A-Za-z][_0-9A-Za-z]*))?/.exec(stripped); + if (!match) return { type: 'query', name: null }; + return { type: match[1].toLowerCase(), name: match[2] || null }; + } + + function graphQlOperationFromPayload(payload) { + if (!payload || typeof payload !== 'object' || Array.isArray(payload)) return null; + const query = typeof payload.query === 'string' ? payload.query.trim() : ''; + if (!query || isRedactedValue(query)) return null; + const explicitName = typeof payload.operationName === 'string' + && payload.operationName.trim() + && !isRedactedValue(payload.operationName) ? payload.operationName.trim() : null; + const parsed = parseGraphQlOperationHeader(query); + let variables = null; + if (payload.variables != null) { + if (typeof payload.variables === 'string') { + const parsedVariables = parseJsonText(payload.variables); + variables = parsedVariables !== undefined ? JSON.stringify(parsedVariables, null, 2) : payload.variables; + } else { + variables = JSON.stringify(payload.variables, null, 2); + } + } + return { operationType: parsed.type, operationName: explicitName || parsed.name, query, variables }; + } + + /** GraphQL operations in a POST JSON body (single or batched array), or in a GET's `query=`. */ + function decodeGraphQlOperations(detail) { + const operations = []; + const method = String(detail.method || '').toUpperCase(); + const body = detail.request?.body; + if (method === 'POST' && body?.type === 'text' && body.value) { + const parsed = parseJsonText(body.value.trim()); + if (parsed !== undefined) { + const payloads = Array.isArray(parsed) ? parsed : [parsed]; + payloads.forEach((payload) => { + const operation = graphQlOperationFromPayload(payload); + if (operation) operations.push(operation); + }); + } + } + if (operations.length) return operations; + if (method !== 'GET') return operations; + let queryString = String(detail.query || ''); + if (!queryString) { + try { queryString = new URL(detail.request?.url || '').search.slice(1); } catch { queryString = ''; } + } + const params = new URLSearchParams(queryString); + const query = params.get('query'); + if (query && query.trim() && !isRedactedValue(query)) { + const operation = graphQlOperationFromPayload({ query, variables: params.get('variables') || undefined }); + if (operation) operations.push(operation); + } + return operations; + } + + /** GraphQL `errors[]` from the response body, including a batched array of `{errors}` results. */ + function graphQlErrorsFromDetail(detail) { + const body = detail.response?.body; + if (body?.type !== 'text' || !body.value) return []; + const parsed = parseJsonText(body.value.trim()); + if (parsed === undefined) return []; + const errors = []; + const collect = (node) => { + if (Array.isArray(node)) { node.forEach(collect); return; } + if (!node || typeof node !== 'object') return; + if (Array.isArray(node.errors)) { + node.errors.forEach((error) => { + if (!error || typeof error !== 'object') return; + errors.push({ + message: typeof error.message === 'string' ? error.message : JSON.stringify(error), + path: Array.isArray(error.path) ? error.path.join('.') : null, + }); + }); + } + }; + collect(parsed); + return errors; + } + + /** A collapsible section inside the detail body that shares the group collapse state. */ + function structuredGroupHtml(key, label, meta, inner) { + const state = networkGroupOpen[key]; + const open = state === undefined ? true : state; + return `
+
+ + + ${esc(meta || '')} +
+ ${open ? inner : 'hidden'} +
`; + } + + function jwtSectionHtml(jwt, index, query) { + const claims = jwt.timestamps.map((stamp) => ({ + k: stamp.claim, + v: stamp.at + ' · ' + stamp.relative, + tone: stamp.expired ? 'error' : 'muted', + })); + const meta = [jwt.header.alg, jwt.header.typ].filter(Boolean).join(' · '); + return structuredGroupHtml('jwt/' + index + '/' + jwt.source, 'JWT', meta, ` +
${icon('lock', 'ic-sm')}${esc(jwt.source)}
+ + ${codeBlockHtml(formatJsonLines(jwt.header, query), false, 'JWT header')} + + ${codeBlockHtml(formatJsonLines(jwt.payload, query), false, 'JWT payload')} + ${claims.length ? `${kvGridHtml(claims, true)}` : ''} +
${icon('alert', 'ic-sm')}Signature not verified · ${esc(String(jwt.signatureLength))} base64url chars.
`); + } + + function graphQlSectionHtml(operation, index, query, errors) { + const label = operation.operationType + ' ' + (operation.operationName || 'anonymous'); + let inner = `
${icon('network', 'ic-sm')}${esc(label)}
`; + inner += `${codeBlockHtml(plainCodeLines(operation.query), false, 'GraphQL query')}`; + if (operation.variables != null) { + const parsed = parseJsonText(operation.variables); + const lines = formatJsonLines(parsed !== undefined ? parsed : operation.variables, query); + if (lines.length) inner += `${codeBlockHtml(lines, false, 'GraphQL variables')}`; + } + inner += graphQlErrorsHtml(errors); + return structuredGroupHtml('graphql/' + index, 'GraphQL', label, inner); + } + + function graphQlErrorsHtml(errors) { + if (!errors.length) return ''; + const rows = errors.map((error) => ({ + k: error.path ? 'path ' + error.path : 'error', + v: error.message, + tone: 'error', + })); + return `${kvGridHtml(rows, true)}`; + } + + /** Everything the structured decoders found for this transaction, ready to append to a pane. */ + function structuredSectionsHtml(detail, responseSide, query) { + const jwts = extractTransactionJwts(detail, Date.now()); + const operations = decodeGraphQlOperations(detail); + const errors = graphQlErrorsFromDetail(detail); + const sections = []; + jwts.forEach((jwt, index) => sections.push(jwtSectionHtml(jwt, index, query))); + if (operations.length) { + operations.forEach((operation, index) => sections.push(graphQlSectionHtml(operation, index, query, responseSide ? errors : []))); + } else if (responseSide && errors.length) { + sections.push(structuredGroupHtml('graphql/errors', 'GraphQL', 'errors', graphQlErrorsHtml(errors))); + } + return sections.length ? `
${sections.join('')}
` : ''; + } + async function fetchTransactionDetail(id) { if (networkDetailCache.has(id)) { const cached = networkDetailCache.get(id); cacheNetworkDetail(id, cached); // touch: refresh recency on hit return cached; } - const r = await fetch('/api/v1/network/transactions/' + encodeURIComponent(id), { headers: auth() }); + const r = await fetch(withNetworkRun('/api/v1/network/transactions/' + encodeURIComponent(id)), { headers: auth() }); if (!r.ok) return null; const detail = await r.json(); cacheNetworkDetail(id, detail); return detail; } async function showTransaction(id) { - if (!token || !id) return; + if (!id) return; + if (harOffline) { + // Imported rows are already complete transaction details; there is nothing to fetch and + // their ids are meaningless to the server. + const detail = harOffline.entries.find((entry) => entry.id === id) || null; + selectedTransactionId = detail ? id : ''; + selectedTransactionDetail = detail; + if (!detail) { renderNetworkEmpty(); return; } + if (networkTab === 'diff' && !networkPinnedId) networkTab = 'response'; + renderNetwork(); + renderNetworkDetail(); + return; + } + if (!token) return; + const gen = nextGen('transaction-detail'); selectedTransactionId = id; selectedTransactionDetail = await fetchTransactionDetail(id); + if (!isLatest('transaction-detail', gen) || selectedTransactionId !== id) return; + if (currentView === 'network' && !location.hash.includes('code=') && DEEP_LINK_TX_RE.test(id)) { + history.replaceState(null, '', location.pathname + '#view=network&tx=' + encodeURIComponent(id)); + } if (networkTab === 'diff' && !networkPinnedId) networkTab = 'response'; renderNetwork(); renderNetworkDetail(); @@ -8027,6 +9983,7 @@ if (!detail) { renderNetworkEmpty(); return; } normalizeNetworkTabForMode(); resetBodyViewers(); + const offline = Boolean(harOffline); const pinId = networkPinnedId; const samePin = pinId === selectedTransactionId; const hasPin = Boolean(pinId) && !samePin && networkDetailCache.has(pinId); @@ -8059,7 +10016,10 @@ // always being rebuilt from scratch — distinct whenever the rule or its snapshot differs, and // stable (so the cache actually hits) across renders where neither changed. const mockDiffSig = mockDiff ? (mockRule.id || '') + ':' + mockRule.sourceBodySnapshot : ''; - const actions = [ + // A HAR row has no server-side identity: flagging, resend, pin/diff, mock-from-response, + // cURL through the device and related-events all address the live capture store, so the + // offline pane is deliberately read-only (copy buttons in the body viewers still work). + const actions = offline ? [] : [ { id: 'flag', label: flagged ? 'Flagged as evidence' : 'Flag as evidence', icon: 'flag', on: flagged, title: 'Attach this transaction to the evidence tray (Enter)' }, // Pin stays out of Simple mode's action row (brief: Flag/Mock/cURL/Clone only) *unless* a // baseline is already pinned — once one exists, hiding Pin would strand that state (no way @@ -8082,8 +10042,8 @@ mocked: isMocked, // No facts strip: time/duration/content type/correlation/mock rule now live in the Timing // tab (see networkSummaryKvs) instead of being repeated under the title. - actions, tabs, networkHeader: { fullUrl, metaLine }, - actionsMenu: true, menuOpen: networkActionsMenuOpen, + actions, tabs, networkHeader: { fullUrl, metaLine, offline }, + actionsMenu: !offline, menuOpen: !offline && networkActionsMenuOpen, }); let findBar = ''; let bodyHtml; @@ -8100,6 +10060,7 @@ else if (lines) bodyHtml += bodyViewerHtml(bodyRawText(side?.body), side?.contentType, lines, response ? 'Response body' : 'Request body', true, 'network/' + detail.id + '/' + networkTab, response ? mockDiff : undefined, response ? mockDiffSig : undefined, true); else bodyHtml += `
${esc(response ? 'No response body.' : detail.method + ' request — no body sent.')}
`; bodyHtml += `
${icon('chevron', 'ic-sm fold-chevron')}${response ? 'Response' : 'Request'} headers · ${headers.length}
${kvGridHtml(markKvHits(headers, networkDetailQuery), true)}
`; + bodyHtml += structuredSectionsHtml(detail, response, networkDetailQuery); } else if (networkTab === 'diff') { if (!hasPin) { bodyHtml = `
${sbsPaneHtml({ @@ -8123,7 +10084,7 @@ } else { bodyHtml = barsHtml(bars); if (fallback) { - bodyHtml += `
Phase-level timing (DNS/connect/TLS/wait/receive) requires the OkHttp event listener to be installed; showing total duration only.
`; + bodyHtml += `
${offline ? 'A HAR entry carries only its total time; phase-level timing is not part of the format.' : 'Phase-level timing (DNS/connect/TLS/wait/receive) requires the OkHttp event listener to be installed; showing total duration only.'}
`; } } bodyHtml += kvGridHtml(networkSummaryKvs(detail, { mockRuleId, mockDiffTotal }), true); @@ -8140,7 +10101,7 @@ bodyHtml = `No related timeline events found for this transaction's correlation id.`; } } - if (redactionShown()) bodyHtml += `
${icon('lock', 'ic-sm')}Redacted on device.
`; + if (redactionShown() && !offline) bodyHtml += `
${icon('lock', 'ic-sm')}Redacted on device.
`; pane.innerHTML = head + findBar + `
${bodyHtml}
`; mountBodyViewers(pane); // The menu panel is position: fixed (the detail pane is overflow: hidden, so an absolutely @@ -8281,9 +10242,8 @@ const method = selectedTransactionDetail?.method || ''; if (['POST', 'PUT', 'PATCH', 'DELETE'].includes(method)) { const ok = await openConfirm( - 'Resend without body', - method + ' bodies are not retained by capture, so this replays the request with an EMPTY body ' - + 'and the redacted stored headers. Use Clone to composer to author the body first.', + 'Resend captured request', + 'This replays the captured request body (which may be redacted or truncated) and the redacted stored headers.', 'Resend anyway', ); if (!ok) return; @@ -8301,8 +10261,8 @@ } async function cloneCapturedRequest() { if (!token || !selectedTransactionId) return; - const r = await fetch('/api/v1/network/transactions/' + encodeURIComponent(selectedTransactionId) + '/curl', { headers: auth() }); - if (!r.ok) return; + const r = await fetch(withNetworkRun('/api/v1/network/transactions/' + encodeURIComponent(selectedTransactionId) + '/curl'), { headers: auth() }); + if (!r.ok) { toast('Request unavailable: ' + unavailableReason(r.status), 'error'); return; } $('composerCurl').value = await r.text(); renderEmpty( $('composerResult'), @@ -8395,8 +10355,8 @@ } async function copyNetworkCurl() { if (!token || !selectedTransactionId) return; - const r = await fetch('/api/v1/network/transactions/' + encodeURIComponent(selectedTransactionId) + '/curl', { headers: auth() }); - if (!r.ok) return; + const r = await fetch(withNetworkRun('/api/v1/network/transactions/' + encodeURIComponent(selectedTransactionId) + '/curl'), { headers: auth() }); + if (!r.ok) { toast('cURL unavailable: ' + unavailableReason(r.status), 'error'); return; } await copyToClipboard(await r.text(), 'cURL'); } function headersToObject(headers) { @@ -8438,24 +10398,19 @@ if (!token) return; const useSelection = networkSelectedIds.size > 0; const r = useSelection - ? await fetch(path, { + ? await fetch(withNetworkRun(path), { method: 'POST', headers: { ...controlHeaders(), 'Content-Type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams([...networkSelectedIds].map((id) => ['id', id])), }) - : await fetch(path + '?' + new URLSearchParams({ limit: '500' }), { headers: auth() }); + : await fetch(withNetworkRun(path + '?' + new URLSearchParams({ limit: '500' })), { headers: auth() }); if (!r.ok) { toast('Export failed: ' + r.status, 'error'); return; } if (r.headers.get('X-DevConsole-Export-Truncated') === 'true') { const count = r.headers.get('X-DevConsole-Export-Count'); toast('Export truncated to ' + (count ?? 'the first 500') + ' transactions — narrow the filter or selection to get the rest.', 'error'); } const blob = await r.blob(); - const url = URL.createObjectURL(blob); - const a = document.createElement('a'); - a.href = url; - a.download = filename; - a.click(); - URL.revokeObjectURL(url); + downloadBlob(blob, filename); } async function downloadHar() { await downloadNetworkExport('/api/v1/network/har', 'devconsole-network.har'); @@ -8522,6 +10477,7 @@ const input = $('eventNoteInput'); if (!input) return; const r = await fetch('/api/v1/events/' + encodeURIComponent(selectedEventId) + '/note', { method: 'PUT', headers: controlHeaders(), body: input.value }); + if (r.ok) eventNotesById.set(selectedEventId, input.value); toast(r.ok ? 'Note saved.' : 'Save failed: ' + r.status, r.ok ? undefined : 'error'); } @@ -8601,6 +10557,7 @@ else button.removeAttribute('aria-current'); }); currentView = view; + if (!location.hash.includes('code=')) history.replaceState(null, '', location.pathname + '#view=' + encodeURIComponent(view)); // This nav already loads the view fresh below, so any live-tail refresh queued while it was // off-screen (or paused) would just be redundant work once resumed. if (liveTailDirty[view] !== undefined) liveTailDirty[view] = false; @@ -8641,6 +10598,11 @@ return loaders[view] ? loaders[view]() : undefined; } + function reloadActiveView() { + viewLoadedAt.delete(currentView); + return show(currentView); + } + // ================================================================ // Session-code exchange // ================================================================ @@ -8665,6 +10627,14 @@ activateBrowserAccess('', '', 'open', true); return; } + try { + const saved = location.hash.includes('code=') ? null : JSON.parse(sessionStorage.getItem('devconsole.browserSession') || 'null'); + if (saved?.token && saved?.csrf) { + const response = await fetch('/api/v1/overview', { headers: { Authorization: 'Bearer ' + saved.token } }); + if (response.ok) { activateBrowserAccess(saved.token, saved.csrf, 'restore'); return; } + if (response.status === 401) sessionStorage.removeItem('devconsole.browserSession'); + } + } catch { /* storage or validation unavailable; continue normal connection flow */ } if (location.hash.includes('code=')) beginSessionCode(); else loadOverview(); } @@ -8682,6 +10652,7 @@ } try { const [overviewRes, metaRes] = await Promise.all([fetch('/api/v1/overview', { headers: auth() }), cachedJson('/api/v1/meta', 30000)]); + loadCaptureState(); const overview = overviewRes.ok ? await overviewRes.json() : null; const meta = metaRes.ok ? await metaRes.json() : null; if (currentView === 'network') renderNetworkDetail(); @@ -8801,7 +10772,7 @@ wireRowList('transactions', { onSelect: (id) => { showTransaction(id); networkListController?.close(); }, onCheck: (id) => toggleNetworkSelection(id) }); wireRowList('sockets', { onSelect: (id) => { socketSelectedIndex = Number(id); renderSockets(); }, rowSelector: '.row, .trace-row' }); wireRowList('pushEvents', { onSelect: (id) => { selectedPushIndex = Number(id); renderPush(); } }); - wireRowList('crashesList', { onSelect: (id) => { selectedCrashId = id; renderCrashes(); } }); + wireRowList('crashesList', { onSelect: selectCrashRow }); wireNetworkDetailPane(); wireSocketDetailPane(); wirePushDetailPane(); @@ -8865,15 +10836,32 @@ $('timelineBookmarkOnly').onclick = () => { timelineBookmarkedOnly = !timelineBookmarkedOnly; updateBookmarkOnlyButton(); render(); }; $('eventDetail').addEventListener('click', (e) => { if (e.target.closest('[data-action="toggle-zoom"]')) toggleDetailZoom(); }); $('eventDetail').addEventListener('input', (e) => { if (e.target.id === 'eventDetailFindInput') { eventDetailQuery = e.target.value; renderEventDetail(); } }); + $('composerCollectionList').addEventListener('click', (e) => { + const del = e.target.closest('[data-collection-delete]'); + if (del) { + const collection = composerCollectionsCache.find((item) => item.id === del.dataset.collectionDelete); + deleteComposerCollection(del.dataset.collectionDelete, collection?.name || 'saved Composer collection'); + return; + } + const load = e.target.closest('[data-collection-load]'); + if (load) { + const collection = composerCollectionsCache.find((item) => item.id === load.dataset.collectionLoad); + if (collection) loadComposerCollection(collection); + } + }); // ---- Network ----------------------------------------------------------------- wireSeg($('networkStatusSeg'), (value) => { networkStatusFilter = value; applyNetworkFilters(); }); wireSeg($('networkMethodSeg'), (value) => { networkMethodFilter = value; applyNetworkFilters(); }); wireServerSearch('networkSearch', () => loadNetwork()); + $('networkRun').addEventListener('change', (event) => selectNetworkRun(event.target.value)); $('networkRefresh').onclick = () => loadNetwork(); $('networkNewest').onclick = () => loadNetwork(); $('networkOlder').onclick = () => networkCursor && loadNetwork(networkCursor); + wireNetworkEndpointsPanel(); wireNetworkExportMenu(); + $('networkHarOpen').onclick = openHarFilePicker; + $('networkHarFile').addEventListener('change', handleHarFileSelected); $('networkHarDownload').onclick = downloadHar; $('networkPostmanDownload').onclick = downloadPostman; $('networkClear').onclick = clearNetworkCaptures; @@ -8900,6 +10888,17 @@ wireSeg($('socketProtocolSeg'), (value) => { socketProtocolFilter = value || 'all'; loadSockets(); }); wireSeg($('socketModeSeg'), (value) => { socketMode = value; renderSockets(); }); $('socketApply').onclick = () => loadSocketMessages(); + // Enter in any "More filters" field applies the group, as it would in a form -- before this the + // only way to run a typed filter was to find and click Apply. + document.querySelectorAll('details.adv-filters').forEach((group) => { + const apply = group.querySelector('.filter-actions button'); + if (!apply || apply.id === 'pushSimulate') return; + group.addEventListener('keydown', (e) => { + if (e.key !== 'Enter' || e.isComposing || !e.target.matches('input')) return; + e.preventDefault(); + apply.click(); + }); + }); $('socketClearFilters').onclick = () => { ['socketSearch', 'socketFrom', 'socketTo', 'socketError'].forEach((id) => ($(id).value = '')); socketFrameTypeFilter = ''; socketDirectionFilter = ''; socketSelectedConnIds.clear(); @@ -8943,6 +10942,8 @@ // ---- Crashes ----------------------------------------------------------------- $('crashesSearch').addEventListener('input', renderCrashes); wireSeg($('crashesKindSeg'), (value) => { crashKindFilter = value; renderCrashes(); }); + $('crashesGroupToggle').onclick = () => setCrashGroupMode(!crashGroupMode); + syncCrashGroupToggle(); $('crashesRefresh').onclick = loadCrashes; $('viewOverview').onclick = () => show('overview'); @@ -8962,9 +10963,19 @@ $('viewSession').onclick = () => show('session'); $('remoteConfigRefresh').onclick = loadRemoteConfig; + $('remoteConfigClearOverrides').onclick = clearAllRemoteConfigOverrides; + $('remoteConfigSaveOverride').onclick = saveRemoteConfigOverride; + $('remoteConfigClearOverride').onclick = clearRemoteConfigOverride; $('remoteConfigSearch').oninput = (e) => { remoteConfigQuery = e.target.value; renderRemoteConfigCards(); }; wireSeg($('remoteConfigSourceSeg'), (value) => { remoteConfigSourceFilter = value; renderRemoteConfigCards(); }); - wireCardGrid('remoteConfigCards', { onRow: openRemoteConfigValue }); + wireCardGrid('remoteConfigCards', { + onRow: openRemoteConfigValue, + onRowAction: (actionId) => { + if (actionId.startsWith('override:')) { + openRemoteConfigValue(actionId.slice('override:'.length)); + } + }, + }); $('remoteConfigValueClose').onclick = closeRemoteConfigValue; $('remoteConfigValueCopy').onclick = copyRemoteConfigValue; $('remoteConfigValueModal').addEventListener('click', (e) => { if (e.target.id === 'remoteConfigValueModal') closeRemoteConfigValue(); }); @@ -8981,7 +10992,7 @@ $('dbTableSearch').addEventListener('input', (e) => { dbTableQuery = e.target.value; renderDbCards(); }); wireSeg($('dbSortSeg'), (value) => { dbSort = value; renderDbCards(); }); - $('fileRoot').onchange = (e) => loadFileListing(e.target.value, ''); + $('fileRoot').onchange = (e) => { clearFileSelection(); $('filePath').value = ''; loadFileListing(e.target.value, ''); }; $('fileGo').onclick = () => loadFileListing($('fileRoot').value, $('filePath').value); $('fileCreate').onclick = () => createFile(); @@ -9011,6 +11022,34 @@ $('mockDisable').onclick = toggleMockEngine; $('mockNewRule').onclick = () => openMockRuleDialog(null); + $('mockExportRules').onclick = exportMockRules; + $('mockImportRules').onclick = () => $('mockImportRulesFile').click(); + $('mockImportRulesFile').addEventListener('change', async (e) => { + const file = e.target.files?.[0]; + e.target.value = ''; + await importMockRules(file); + }); + $('mockRuleActionType').addEventListener('change', () => { + // A sequence with no steps can't be saved; start it with one so the editor shows what a step is. + if ($('mockRuleActionType').value === 'sequence') { + readMockRuleSteps(); + if (!mockRuleSteps.length) { + mockRuleSteps.push(mockStepDefaults()); + renderMockRuleSteps(); + } + } + syncMockRuleActionFields(); + }); + $('mockRuleStepAdd').onclick = addMockRuleStep; + $('mockRuleSteps').addEventListener('click', (e) => { + const btn = e.target.closest('[data-step-remove]'); + if (btn) removeMockRuleStep(Number(btn.dataset.stepRemove)); + }); + $('mockRuleSteps').addEventListener('change', (e) => { + const select = e.target.closest('[data-step-type]'); + if (!select) return; + changeMockRuleStepType(Number(select.closest('[data-step-row]').dataset.stepRow), select.value); + }); $('mockRuleModalClose').onclick = closeMockRuleDialog; $('mockRuleCancel').onclick = closeMockRuleDialog; $('mockRuleSave').onclick = saveMockRuleDialog; @@ -9062,6 +11101,9 @@ $('viewEvidence').onclick = () => show('evidence'); $('viewCrashes').onclick = () => show('crashes'); $('captureScreenshot').onclick = () => captureScreenshot(); + $('capturePausedToggle').onclick = () => setCapturePaused(!capturePausedState); + $('captureResumePill').onclick = () => setCapturePaused(false); + $('capturePurge').onclick = () => purgeCaptureData(); updateEvidenceUi(); function setRailHidden(next) { @@ -9088,12 +11130,7 @@ return; } const blob = await r.blob(); - const url = URL.createObjectURL(blob); - const a = document.createElement('a'); - a.href = url; - a.download = 'devconsole-session.zip'; - a.click(); - URL.revokeObjectURL(url); + downloadBlob(blob, 'devconsole-session.zip'); toast('Session ZIP exported.'); } finally { btn.disabled = !token; 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 71c7c53..8a87984 100644 --- a/sdk/server-ktor/src/main/resources/devconsole-web/index.html +++ b/sdk/server-ktor/src/main/resources/devconsole-web/index.html @@ -96,6 +96,10 @@ Open DevConsole on device → More → scan the QR
+
@@ -107,6 +111,9 @@ @@ -258,10 +265,17 @@
+
+
+ +
More filters
@@ -287,14 +317,16 @@ +
+
- MethodPathStatus · time + MethodPathStatus · time
@@ -388,6 +420,7 @@
No socket message selected
Select a connection or apply filters to inspect frames. JSON text frames are formatted; binary previews appear only when the host opted in.
+ @@ -451,6 +484,7 @@
+
@@ -490,6 +524,7 @@
Source
+
Not connected yet
Open DevConsole on the device → More, then open the dashboard URL.
How to connect

Open DevConsole on the device → More → scan the QR or paste the code in Overview to inspect Remote Config.

@@ -628,6 +663,9 @@
+ + +
@@ -713,28 +751,59 @@ - - - -
diff --git a/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/CaptureControlRoutesTest.kt b/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/CaptureControlRoutesTest.kt new file mode 100644 index 0000000..2923a2c --- /dev/null +++ b/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/CaptureControlRoutesTest.kt @@ -0,0 +1,244 @@ +/** + * @author Shakib + * @since 04/11/26 + */ +package io.devconsole.server.ktor + +import io.devconsole.server.api.BrowserSession +import io.devconsole.server.api.InMemoryCommandAuditLog +import io.devconsole.server.api.SessionAuthority +import io.devconsole.server.api.SessionCodeAuthority +import io.ktor.client.request.HttpRequestBuilder +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 CaptureControlRoutesTest { + @Test + fun `reading capture state requires a bearer session`() = + testApplication { + val sessions = SessionAuthority() + val sessionCodes = SessionCodeAuthority(sessions) + application { protectedDevConsoleModule(sessions, sessionCodes) } + + val response = client.get("/api/v1/capture") { header(HttpHeaders.Host, "localhost") } + + assertEquals(HttpStatusCode.Unauthorized, response.status) + assertEquals("{\"code\":\"AUTH_REQUIRED\"}", response.bodyAsText()) + } + + @Test + fun `reading capture state reflects the injected control`() = + testApplication { + val sessions = SessionAuthority() + val sessionCodes = SessionCodeAuthority(sessions) + application { + protectedDevConsoleModule(sessions, sessionCodes) { + captureControl = FakeCaptureControl(paused = true) + } + } + val session = approvedSession(sessions, sessionCodes) + + val response = client.get("/api/v1/capture") { authHeaders(session) } + + assertEquals(HttpStatusCode.OK, response.status) + assertEquals("{\"paused\":true,\"available\":true}", response.bodyAsText()) + } + + @Test + fun `pausing then resuming returns the new state and audits both commands`() = + testApplication { + val sessions = SessionAuthority() + val sessionCodes = SessionCodeAuthority(sessions) + val control = FakeCaptureControl() + val audit = InMemoryCommandAuditLog() + application { + protectedDevConsoleModule(sessions, sessionCodes) { + captureControl = control + commandAuditLog = audit + } + } + val session = approvedSession(sessions, sessionCodes) + + val paused = + client.post("/api/v1/capture/paused") { + controlHeaders(session) + setBody("true") + } + assertEquals(HttpStatusCode.OK, paused.status) + assertEquals("{\"paused\":true}", paused.bodyAsText()) + assertTrue(control.isPaused()) + + val resumed = + client.post("/api/v1/capture/paused") { + controlHeaders(session) + setBody("\"false\"") + } + assertEquals(HttpStatusCode.OK, resumed.status) + assertEquals("{\"paused\":false}", resumed.bodyAsText()) + assertFalse(control.isPaused()) + + val events = audit.events() + assertEquals(listOf("capture.pause", "capture.resume"), events.map { it.commandType }) + assertTrue(events.all { it.target == "capture" }) + } + + @Test + fun `a mutation without origin and csrf headers is refused`() = + testApplication { + val sessions = SessionAuthority() + val sessionCodes = SessionCodeAuthority(sessions) + val control = FakeCaptureControl() + application { + protectedDevConsoleModule(sessions, sessionCodes) { captureControl = control } + } + val session = approvedSession(sessions, sessionCodes) + + val response = + client.post("/api/v1/capture/paused") { + authHeaders(session) + setBody("true") + } + + assertEquals(HttpStatusCode.Forbidden, response.status) + assertEquals("{\"code\":\"CSRF_INVALID\"}", response.bodyAsText()) + assertFalse("the control must stay untouched", control.isPaused()) + } + + @Test + fun `an unrecognised body is rejected without touching the control`() = + testApplication { + val sessions = SessionAuthority() + val sessionCodes = SessionCodeAuthority(sessions) + val control = FakeCaptureControl() + application { + protectedDevConsoleModule(sessions, sessionCodes) { captureControl = control } + } + val session = approvedSession(sessions, sessionCodes) + + val response = + client.post("/api/v1/capture/paused") { + controlHeaders(session) + setBody("maybe") + } + + assertEquals(HttpStatusCode.BadRequest, response.status) + assertEquals("{\"code\":\"VALIDATION_FAILED\"}", response.bodyAsText()) + assertFalse(control.isPaused()) + } + + @Test + fun `purging reports the removed counts and audits them`() = + testApplication { + val sessions = SessionAuthority() + val sessionCodes = SessionCodeAuthority(sessions) + val audit = InMemoryCommandAuditLog() + application { + protectedDevConsoleModule(sessions, sessionCodes) { + captureControl = + FakeCaptureControl(summary = CapturePurgeSummary(2, 3, 4, 5)) + commandAuditLog = audit + } + } + val session = approvedSession(sessions, sessionCodes) + + val response = client.post("/api/v1/capture/purge") { controlHeaders(session) } + + assertEquals(HttpStatusCode.OK, response.status) + assertEquals( + "{\"networkTransactions\":2,\"socketConnections\":3," + + "\"pushEvents\":4,\"retainedRunsDeleted\":5}", + response.bodyAsText(), + ) + val event = audit.events().single() + assertEquals("capture.purge", event.commandType) + assertEquals("capture", event.target) + assertEquals("2", event.parameters["networkTransactions"]) + assertEquals("3", event.parameters["socketConnections"]) + assertEquals("4", event.parameters["pushEvents"]) + assertEquals("5", event.parameters["retainedRunsDeleted"]) + } + + @Test + fun `an absent control reports unavailable and refuses mutations`() = + testApplication { + val sessions = SessionAuthority() + val sessionCodes = SessionCodeAuthority(sessions) + application { protectedDevConsoleModule(sessions, sessionCodes) } + val session = approvedSession(sessions, sessionCodes) + + val state = client.get("/api/v1/capture") { authHeaders(session) } + assertEquals(HttpStatusCode.OK, state.status) + assertEquals("{\"paused\":false,\"available\":false}", state.bodyAsText()) + + val paused = + client.post("/api/v1/capture/paused") { + controlHeaders(session) + setBody("true") + } + assertEquals(HttpStatusCode.ServiceUnavailable, paused.status) + assertEquals( + "{\"code\":\"CAPTURE_CONTROL_UNAVAILABLE\"}", + paused.bodyAsText(), + ) + + val purge = client.post("/api/v1/capture/purge") { controlHeaders(session) } + assertEquals(HttpStatusCode.ServiceUnavailable, purge.status) + assertEquals( + "{\"code\":\"CAPTURE_CONTROL_UNAVAILABLE\"}", + purge.bodyAsText(), + ) + } +} + +private class FakeCaptureControl( + private var paused: Boolean = false, + private val summary: CapturePurgeSummary = CapturePurgeSummary(0, 0, 0, 0), +) : CaptureControl { + override fun isPaused(): Boolean = paused + + override fun setPaused(paused: Boolean): Boolean { + this.paused = paused + return true + } + + override suspend fun purge(): CapturePurgeSummary = summary +} + +/** Bearer-only headers for a plain GET -- no Origin/CSRF, since a read route never needs them. */ +private fun HttpRequestBuilder.authHeaders(session: BrowserSession) { + header(HttpHeaders.Host, "localhost") + header(HttpHeaders.Authorization, "Bearer ${session.token}") +} + +private fun HttpRequestBuilder.controlHeaders(session: BrowserSession) { + header(HttpHeaders.Host, "localhost") + header(HttpHeaders.Authorization, "Bearer ${session.token}") + header(HttpHeaders.Origin, "http://localhost") + header("X-DevConsole-CSRF", session.csrfToken) +} + +private suspend fun ApplicationTestBuilder.approvedSession( + sessions: SessionAuthority, + sessionCodes: SessionCodeAuthority, +): BrowserSession { + val response = + client.post("/api/v1/auth/session-code/exchange") { + header(HttpHeaders.Host, "localhost") + header(HttpHeaders.ContentType, ContentType.Application.FormUrlEncoded) + setBody("code=${sessionCodes.issueCode().code}") + } + val token = Regex("\"accessToken\":\"([^\"]+)\"").find(response.bodyAsText())!!.groupValues[1] + return sessions.sessionForToken(token)!! +} diff --git a/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/DevConsoleKtorModuleTest.kt b/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/DevConsoleKtorModuleTest.kt index 8c8c97f..093a46a 100644 --- a/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/DevConsoleKtorModuleTest.kt +++ b/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/DevConsoleKtorModuleTest.kt @@ -106,6 +106,68 @@ import kotlin.time.Duration.Companion.seconds import io.ktor.server.websocket.WebSockets as ServerWebSockets class DevConsoleKtorModuleTest { + @Test + fun `oversized text mutation rejects from Content-Length`() = + testApplication { + val sessions = SessionAuthority() + val sessionCodes = SessionCodeAuthority(sessions) + application { protectedDevConsoleModule(sessions, sessionCodes) } + val session = client.exchangeSession(sessions, sessionCodes) + + val response = + client.post("/api/v1/network/postman") { + header(HttpHeaders.Host, "localhost") + header(HttpHeaders.Authorization, "Bearer ${session.token}") + header(HttpHeaders.Origin, "http://localhost") + header("X-DevConsole-CSRF", session.csrfToken) + header(HttpHeaders.ContentType, ContentType.Application.FormUrlEncoded.toString()) + setBody("id=" + "x".repeat(1024 * 1024 + 1)) + } + + assertEquals(HttpStatusCode.PayloadTooLarge, response.status) + assertTrue(response.bodyAsText().contains("\"code\":\"PAYLOAD_TOO_LARGE\"")) + } + + @Test + fun `editing a disabled mock rule keeps its enabled state and predicates`() = + testApplication { + val sessions = SessionAuthority() + val sessionCodes = SessionCodeAuthority(sessions) + val existing = + MockRule( + id = "orders", + priority = 1, + path = "/orders", + queryPredicates = mapOf("mode" to "safe"), + headerPredicates = mapOf("X-Mode" to "safe"), + bodyPredicate = "approved", + ).withPersistence(io.devconsole.mocks.MockRulePersistence(enabled = false)) + val mocks = MockEngine(listOf(existing)) + application { + protectedDevConsoleModule(sessions, sessionCodes) { + mockEngine = mocks + mocksEditable = true + } + } + val session = client.exchangeSession(sessions, sessionCodes) + val response = + client.post("/api/v1/mocks/rules") { + header(HttpHeaders.Host, "localhost") + header(HttpHeaders.Authorization, "Bearer ${session.token}") + header(HttpHeaders.Origin, "http://localhost") + header("X-DevConsole-CSRF", session.csrfToken) + header(HttpHeaders.ContentType, ContentType.Application.FormUrlEncoded) + setBody("id=orders&priority=2&path=%2Forders&status=201") + } + + assertEquals(HttpStatusCode.Created, response.status) + val updated = mocks.rules().single() + assertFalse(updated.persistence.enabled) + assertEquals(mapOf("mode" to "safe"), updated.queryPredicates) + assertEquals(mapOf("X-Mode" to "safe"), updated.headerPredicates) + assertEquals("approved", updated.bodyPredicate) + } + @Test fun `open browser mode exposes data and mutations without credentials`() = testApplication { @@ -642,6 +704,9 @@ class DevConsoleKtorModuleTest { val welcome = (incoming.receive() as Frame.Text).data.decodeToString() assertTrue(welcome.contains("server.welcome")) + // The hub has no replay: the stream must already be subscribed when the welcome + // arrives, or the event published below could be dropped and receive() hang. + assertEquals(1, testStreamHub.subscriberCount) testStreamHub.publish( EventEnvelope( @@ -2067,7 +2132,7 @@ class DevConsoleKtorModuleTest { header(HttpHeaders.Origin, "http://localhost") header("X-DevConsole-CSRF", session.csrfToken) header(HttpHeaders.ContentType, ContentType.Application.FormUrlEncoded) - setBody("method=GET&url=https%3A%2F%2Fapi.example.test%2Forders") + setBody("method=GET&url=https%3A%2F%2F%24%7Bhost%7D%2Forders&variable=host%3Dapi.example.test") } assertEquals(HttpStatusCode.OK, result.status) @@ -2830,7 +2895,13 @@ class DevConsoleKtorModuleTest { testApplication { val sessions = SessionAuthority() val sessionCodes = SessionCodeAuthority(sessions) - val flags = SessionFeatureFlags(listOf(FeatureFlag("checkout_v2", defaultValue = false))) + val flags = + SessionFeatureFlags( + listOf( + FeatureFlag("checkout_v2", defaultValue = false), + FeatureFlag.ofOptions("stage_name", "prod", setOf("prod", "true")), + ), + ) val mocks = MockEngine(emptyList()) application { protectedDevConsoleModule(sessions, sessionCodes) { @@ -2859,6 +2930,15 @@ class DevConsoleKtorModuleTest { assertTrue("expected a dirty session, got $dirtyBody", "\"pristine\":false" in dirtyBody) assertTrue("\"checkout_v2\":true" in dirtyBody) + flags.override("stage_name", "true") + val stringFlag = + client + .get("/api/v1/session/integrity") { + header(HttpHeaders.Host, "localhost") + header(HttpHeaders.Authorization, "Bearer ${session.token}") + }.bodyAsText() + assertTrue(stringFlag.contains("\"stage_name\":\"true\"")) + val reset = client.post("/api/v1/session/integrity/reset") { header(HttpHeaders.Host, "localhost") @@ -2946,6 +3026,15 @@ class DevConsoleKtorModuleTest { attachmentReader = { id -> if (id == "attachment-2") "token=attachment-secret".encodeToByteArray() else null } + attachmentMetadataReader = { id -> + if (id == "attachment-2") { + testAttachment("attachment-2", RedactionApplicability.APPLIED).copy( + storedLength = "token=attachment-secret".encodeToByteArray().size.toLong(), + ) + } else { + null + } + } } } val session = client.exchangeSession(sessions, sessionCodes) diff --git a/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/EvidenceAndScreenshotRoutesTest.kt b/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/EvidenceAndScreenshotRoutesTest.kt index 0884868..4001522 100644 --- a/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/EvidenceAndScreenshotRoutesTest.kt +++ b/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/EvidenceAndScreenshotRoutesTest.kt @@ -87,6 +87,30 @@ class EvidenceAndScreenshotRoutesTest { } } + @Test + fun `a previous run's tray is readable by sessionId after a restart`() = + testApplication { + val sessions = SessionAuthority() + val sessionCodes = SessionCodeAuthority(sessions) + val store = FakeEvidenceStore() + store.flag( + StoredEvidenceItem("item-1", "run-old", EvidenceKind.CRASH, "crash-1", "Crash", 1L, "{}"), + ) + application { + protectedDevConsoleModule(sessions, sessionCodes) { + evidenceStore = store + currentSessionId = { "run-new" } + } + } + val session = approvedSession(sessions, sessionCodes) + + val current = client.get("/api/v1/evidence") { authHeaders(session) }.bodyAsText() + val previous = client.get("/api/v1/evidence?sessionId=run-old") { authHeaders(session) }.bodyAsText() + + assertFalse(current.contains("crash-1")) + assertTrue(previous.contains("crash-1")) + } + @Test fun `every evidence mutation requires csrf and is audited`() = testApplication { @@ -799,7 +823,7 @@ class EvidenceAndScreenshotRoutesTest { } @Test - fun `push snapshot is materialized from the store's own index-based subject id`() = + fun `push snapshot is materialized from the push event's stable subject id`() = testApplication { val sessions = SessionAuthority() val sessionCodes = SessionCodeAuthority(sessions) @@ -817,7 +841,11 @@ class EvidenceAndScreenshotRoutesTest { val response = client.post("/api/v1/evidence") { controlHeaders(session) - setBody("kind=push&id=0") + val push = pushStore.events().single() + val stableId = + "${push.provider}:${push.receivedAtEpochMs}:" + + "${push.messageId.orEmpty()}:${push.source.orEmpty()}" + setBody("kind=push&id=" + java.net.URLEncoder.encode(stableId, "UTF-8")) } val body = response.bodyAsText() diff --git a/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/KtorLocalServerEngineTest.kt b/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/KtorLocalServerEngineTest.kt index 922d0e4..530ae2c 100644 --- a/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/KtorLocalServerEngineTest.kt +++ b/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/KtorLocalServerEngineTest.kt @@ -46,10 +46,40 @@ import org.junit.Assert.assertTrue import org.junit.Test import java.net.NetworkInterface import java.net.ServerSocket +import java.net.Socket import java.util.Collections import java.util.UUID class KtorLocalServerEngineTest { + @Test + fun `a restarted server rebinds its port while the previous listener's connections are in TIME_WAIT`() = + runBlocking { + val port = ServerSocket(0).use { it.localPort } + val first = KtorLocalServerEngine() + val firstResult = first.start(StartRequest(BindingMode.LOOPBACK, port..port)) + assertTrue(firstResult is ServerStartResult.Started) + // `Connection: close` makes the server close first, so its side of the connection -- + // bound to `port` -- is left in TIME_WAIT, exactly what a killed app leaves behind. + Socket("127.0.0.1", port).use { socket -> + socket.getOutputStream().write( + "GET /api/v1/meta HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n\r\n".toByteArray(), + ) + socket.getInputStream().readBytes() + } + first.stop() + + val second = KtorLocalServerEngine() + try { + val secondResult = second.start(StartRequest(BindingMode.LOOPBACK, port..port)) + assertTrue( + "expected a rebind of $port, got $secondResult", + secondResult is ServerStartResult.Started && secondResult.endpoint.port == port, + ) + } finally { + second.stop() + } + } + @Test fun `falls forward through a requested loopback port range`() = runBlocking { diff --git a/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/MockActionRoutesTest.kt b/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/MockActionRoutesTest.kt new file mode 100644 index 0000000..e891593 --- /dev/null +++ b/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/MockActionRoutesTest.kt @@ -0,0 +1,239 @@ +/** + * @author Shakib + * @since 03/11/26 + */ +@file:Suppress("MatchingDeclarationName") + +package io.devconsole.server.ktor + +import io.devconsole.mocks.MockAction +import io.devconsole.mocks.MockEngine +import io.devconsole.mocks.MockRule +import io.devconsole.server.api.BrowserSession +import io.devconsole.server.api.SessionAuthority +import io.devconsole.server.api.SessionCodeAuthority +import io.ktor.client.HttpClient +import io.ktor.client.request.HttpRequestBuilder +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.HttpResponse +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.assertTrue +import org.junit.Test + +class MockActionRoutesTest { + @Test + fun `every non-static action type round-trips into the engine`() = + testApplication { + val env = MockRoutes() + installMockRoutes(env) + val session = mockApprovedSession(env) + + val cases = + listOf( + Triple( + "tpl", + "id=tpl&priority=1&actionType=template&status=201&body=%7B%7Bpath%7D%7D", + MockAction.TemplateResponse(201, "{{path}}"), + ), + Triple( + "status", + "id=status&priority=1&actionType=status_override&status=204", + MockAction.StatusOverride(204), + ), + Triple( + "body", + "id=body&priority=1&actionType=body_replacement&body=patched", + MockAction.BodyReplacement("patched"), + ), + Triple( + "fail", + "id=fail&priority=1&actionType=connection_failure&failureMessage=offline", + MockAction.ConnectionFailure("offline"), + ), + Triple( + "timeout", + "id=timeout&priority=1&actionType=timeout&timeoutMs=1500", + MockAction.Timeout(1500), + ), + Triple( + "remote", + "id=remote&priority=1&actionType=map_remote&remoteHost=staging.api&remotePath=%2Fv2", + MockAction.MapRemote(host = "staging.api", path = "/v2"), + ), + Triple( + "throttle", + "id=throttle&priority=1&actionType=throttle&bytesPerSecond=50000&latencyMs=200", + MockAction.Throttle(50_000, 200), + ), + Triple("pass", "id=pass&priority=1&actionType=passthrough", MockAction.Passthrough), + ) + cases.forEach { (id, body, expected) -> + assertEquals(HttpStatusCode.Created, postMockRule(session, body).status) + assertEquals(expected, env.mocks.actionOf(id)) + } + } + + @Test + fun `a looping two-step sequence builds nested actions`() = + testApplication { + val env = MockRoutes() + installMockRoutes(env) + val session = mockApprovedSession(env) + + val created = + postMockRule( + session, + "id=seq&priority=1&actionType=sequence&loop=true" + + "&stepType=static&stepStatus=200&stepBody=first&stepDelayMs=100&stepTimeoutMs=" + + "&stepType=connection_failure&stepStatus=&stepBody=down&stepDelayMs=&stepTimeoutMs=", + ) + + assertEquals(HttpStatusCode.Created, created.status) + assertEquals( + MockAction.Sequence( + listOf( + MockAction.Delay(100, MockAction.StaticResponse(200, "first")), + MockAction.ConnectionFailure("down"), + ), + loop = true, + ), + env.mocks.actionOf("seq"), + ) + } + + @Test + fun `invalid map remote and throttle forms are rejected`() = + testApplication { + val env = MockRoutes() + installMockRoutes(env) + val session = mockApprovedSession(env) + + val remote = postMockRule(session, "id=remote&priority=1&actionType=map_remote") + val throttle = + postMockRule(session, "id=slow&priority=1&actionType=throttle&bytesPerSecond=999999999") + + assertEquals(HttpStatusCode.BadRequest, remote.status) + assertEquals(HttpStatusCode.BadRequest, throttle.status) + assertTrue(env.mocks.rules().isEmpty()) + } + + @Test + fun `rule payloads include actionDetail for a delayed static and a sequence`() = + testApplication { + val env = + MockRoutes( + mocks = + MockEngine( + listOf( + MockRule( + id = "delayed", + priority = 0, + action = MockAction.Delay(300, MockAction.StaticResponse(200, "hi")), + ), + MockRule( + id = "seq", + priority = 0, + action = + MockAction.Sequence( + listOf(MockAction.StaticResponse(200, "a"), MockAction.Passthrough), + ), + ), + ), + ), + ) + installMockRoutes(env) + val session = mockApprovedSession(env) + + val body = client.mockRulesBody(session) + + assertTrue( + body.contains( + "\"actionDetail\":{\"type\":\"delay\",\"durationMs\":300," + + "\"next\":{\"type\":\"static\",\"statusCode\":200,\"body\":\"hi\"," + + "\"bodyTruncated\":false,\"headers\":{}}}", + ), + ) + assertTrue( + body.contains( + "\"actionDetail\":{\"type\":\"sequence\",\"loop\":false,\"steps\":[" + + "{\"type\":\"static\",\"statusCode\":200,\"body\":\"a\",\"bodyTruncated\":false," + + "\"headers\":{}},{\"type\":\"passthrough\"}]}", + ), + ) + } + + @Test + fun `a request without actionType still creates a static response`() = + testApplication { + val env = MockRoutes() + installMockRoutes(env) + val session = mockApprovedSession(env) + + val created = postMockRule(session, "id=plain&priority=1&status=201&body=mocked") + + assertEquals(HttpStatusCode.Created, created.status) + assertEquals(MockAction.StaticResponse(201, "mocked"), env.mocks.actionOf("plain")) + } +} + +private class MockRoutes( + val sessions: SessionAuthority = SessionAuthority(), + val mocks: MockEngine = MockEngine(emptyList()), +) { + val codes = SessionCodeAuthority(sessions) +} + +private fun ApplicationTestBuilder.installMockRoutes(env: MockRoutes) { + application { + protectedDevConsoleModule(env.sessions, env.codes) { + mockEngine = env.mocks + mocksEditable = true + } + } +} + +private fun HttpRequestBuilder.mockControlHeaders(session: BrowserSession) { + header(HttpHeaders.Host, "localhost") + header(HttpHeaders.Authorization, "Bearer ${session.token}") + header(HttpHeaders.Origin, "http://localhost") + header("X-DevConsole-CSRF", session.csrfToken) +} + +private suspend fun ApplicationTestBuilder.postMockRule( + session: BrowserSession, + body: String, +): HttpResponse = + client.post("/api/v1/mocks/rules") { + mockControlHeaders(session) + header(HttpHeaders.ContentType, ContentType.Application.FormUrlEncoded) + setBody(body) + } + +private suspend fun HttpClient.mockRulesBody(session: BrowserSession): String = + get("/api/v1/mocks/rules") { + header(HttpHeaders.Host, "localhost") + header(HttpHeaders.Authorization, "Bearer ${session.token}") + }.bodyAsText() + +private fun MockEngine.actionOf(id: String): MockAction = rules().first { it.id == id }.action + +private suspend fun ApplicationTestBuilder.mockApprovedSession(env: MockRoutes): BrowserSession { + val code = env.codes.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 env.sessions.sessionForToken(token)!! +} diff --git a/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/NetworkEndpointStatsRoutesTest.kt b/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/NetworkEndpointStatsRoutesTest.kt new file mode 100644 index 0000000..5f7f17b --- /dev/null +++ b/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/NetworkEndpointStatsRoutesTest.kt @@ -0,0 +1,233 @@ +/** + * @author Shakib + * @since 03/11/26 + */ +package io.devconsole.server.ktor + +import io.devconsole.network.InMemoryNetworkTransactionStore +import io.devconsole.network.NetworkCaptureFactory +import io.devconsole.network.NetworkCursorCodec +import io.devconsole.network.NetworkRequestInput +import io.devconsole.network.NetworkResponseInput +import io.devconsole.network.NetworkTransaction +import io.devconsole.security.RedactionEngine +import io.devconsole.security.RedactionPolicy +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.HttpRequestBuilder +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 NetworkEndpointStatsRoutesTest { + @Test + fun `endpoints route requires an authenticated session`() = + testApplication { + val store = InMemoryNetworkTransactionStore(NetworkCursorCodec(ByteArray(16))) + application { protectedDevConsoleModule(SessionAuthority()) { networkTransactions = store } } + + val response = client.get("/api/v1/network/endpoints") { header(HttpHeaders.Host, "localhost") } + + assertEquals(HttpStatusCode.Unauthorized, response.status) + assertTrue(response.bodyAsText().contains("AUTH_REQUIRED")) + } + + @Test + fun `endpoints route returns aggregated latency statistics for two templated endpoints`() = + testApplication { + val sessions = SessionAuthority() + val sessionCodes = SessionCodeAuthority(sessions) + val store = + endpointStore( + Triple("GET", "https://api.test/v1/orders/101", 200) to (100L to 120L), + Triple("GET", "https://api.test/v1/orders/202", 500) to (200L to 280L), + Triple("POST", "https://api.test/v1/checkout", 201) to (300L to 350L), + ) + application { protectedDevConsoleModule(sessions, sessionCodes) { networkTransactions = store } } + val session = approvedSession(sessions, sessionCodes) + + val response = client.get("/api/v1/network/endpoints") { authHeaders(session) } + + assertEquals(HttpStatusCode.OK, response.status) + val body = response.bodyAsText() + assertTrue(body.contains("\"sampleSize\":3")) + assertTrue( + body.contains( + "\"method\":\"GET\",\"host\":\"api.test\",\"pathTemplate\":\"/v1/orders/{id}\"," + + "\"count\":2,\"errorCount\":1,\"p50Ms\":20,\"p95Ms\":80,\"p99Ms\":80,\"maxMs\":80", + ), + ) + assertTrue( + body.contains( + "\"method\":\"POST\",\"host\":\"api.test\",\"pathTemplate\":\"/v1/checkout\"," + + "\"count\":1,\"errorCount\":0,\"p50Ms\":50,\"p95Ms\":50,\"p99Ms\":50,\"maxMs\":50", + ), + ) + assertTrue(body.indexOf("/v1/orders/{id}") < body.indexOf("/v1/checkout")) + } + + @Test + fun `endpoints route respects categoryEnabled and sessionId query parameter`() = + testApplication { + val sessions = SessionAuthority() + val sessionCodes = SessionCodeAuthority(sessions) + val factory = NetworkCaptureFactory(RedactionEngine(RedactionPolicy.recommended())) + val liveStore = InMemoryNetworkTransactionStore(NetworkCursorCodec(ByteArray(16))) + val pastStore = + InMemoryNetworkTransactionStore(NetworkCursorCodec(ByteArray(16))).also { s -> + s.record( + NetworkTransaction( + id = "past-1", + startedAtEpochMs = 10, + completedAtEpochMs = 45, + capture = + factory.capture( + NetworkRequestInput("GET", "https://api.test/v1/past/99"), + NetworkResponseInput(200), + ), + ), + ) + } + application { + protectedDevConsoleModule(sessions, sessionCodes) { + networkTransactions = liveStore + retainedNetworkTransactions = { sessionId -> if (sessionId == "run-1") pastStore else null } + } + } + val session = approvedSession(sessions, sessionCodes) + + val okPast = client.get("/api/v1/network/endpoints?sessionId=run-1") { authHeaders(session) } + assertEquals(HttpStatusCode.OK, okPast.status) + assertTrue(okPast.bodyAsText().contains("\"/v1/past/{id}\"")) + + val missingPast = client.get("/api/v1/network/endpoints?sessionId=unknown") { authHeaders(session) } + assertEquals(HttpStatusCode.NotFound, missingPast.status) + assertTrue(missingPast.bodyAsText().contains("SESSION_NOT_FOUND")) + } + + @Test + fun `endpoints route is refused when network category is disabled`() = + testApplication { + val sessions = SessionAuthority() + val sessionCodes = SessionCodeAuthority(sessions) + application { + protectedDevConsoleModule(sessions, sessionCodes) { + metadata = ServerMetadata(captureCategories = listOf("logs")) + } + } + val session = approvedSession(sessions, sessionCodes) + + val response = client.get("/api/v1/network/endpoints") { authHeaders(session) } + + assertEquals(HttpStatusCode.Forbidden, response.status) + assertTrue(response.bodyAsText().contains("CATEGORY_DISABLED")) + } + + @Test + fun `transactions route filters by body query parameter and rejects overlong body query`() = + testApplication { + val sessions = SessionAuthority() + val sessionCodes = SessionCodeAuthority(sessions) + val factory = NetworkCaptureFactory(RedactionEngine(RedactionPolicy.recommended())) + val store = + InMemoryNetworkTransactionStore(NetworkCursorCodec(ByteArray(16))).also { s -> + s.record( + NetworkTransaction( + id = "tx-body-match", + startedAtEpochMs = 10, + completedAtEpochMs = 20, + capture = + factory.capture( + NetworkRequestInput("POST", "https://api.test/v1/items"), + NetworkResponseInput( + 200, + body = "{\"orderId\":\"ORD-7788\"}".encodeToByteArray(), + contentType = "application/json", + ), + ), + ), + ) + s.record( + NetworkTransaction( + id = "tx-body-other", + startedAtEpochMs = 30, + completedAtEpochMs = 40, + capture = + factory.capture( + NetworkRequestInput("POST", "https://api.test/v1/items"), + NetworkResponseInput( + 200, + body = "{\"orderId\":\"ORD-0000\"}".encodeToByteArray(), + contentType = "application/json", + ), + ), + ), + ) + } + application { protectedDevConsoleModule(sessions, sessionCodes) { networkTransactions = store } } + val session = approvedSession(sessions, sessionCodes) + + val filtered = client.get("/api/v1/network/transactions?body=ord-7788") { authHeaders(session) } + assertEquals(HttpStatusCode.OK, filtered.status) + val text = filtered.bodyAsText() + assertTrue(text.contains("tx-body-match")) + assertFalse(text.contains("tx-body-other")) + + val overlong = + client.get("/api/v1/network/transactions?body=${"x".repeat(257)}") { authHeaders(session) } + assertEquals(HttpStatusCode.BadRequest, overlong.status) + assertTrue(overlong.bodyAsText().contains("VALIDATION_FAILED")) + } +} + +private fun HttpRequestBuilder.authHeaders(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)!! +} + +private fun endpointStore( + vararg calls: Pair, Pair>, +): InMemoryNetworkTransactionStore { + val factory = NetworkCaptureFactory(RedactionEngine(RedactionPolicy.recommended())) + return InMemoryNetworkTransactionStore(NetworkCursorCodec(ByteArray(16))).also { store -> + calls.forEachIndexed { index, (call, timing) -> + val (method, url, status) = call + store.record( + NetworkTransaction( + id = "tx-${index + 1}", + startedAtEpochMs = timing.first, + completedAtEpochMs = timing.second, + capture = factory.capture(NetworkRequestInput(method, url), NetworkResponseInput(status)), + ), + ) + } + } +} diff --git a/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/RemoteConfigOverrideRoutesTest.kt b/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/RemoteConfigOverrideRoutesTest.kt new file mode 100644 index 0000000..cde7eb7 --- /dev/null +++ b/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/RemoteConfigOverrideRoutesTest.kt @@ -0,0 +1,459 @@ +/** + * @author Shakib + * @since 04/11/26 + */ +package io.devconsole.server.ktor + +import io.devconsole.remoteconfig.InMemoryRemoteConfigOverrideStore +import io.devconsole.remoteconfig.RemoteConfigEntry +import io.devconsole.remoteconfig.RemoteConfigFetchInfo +import io.devconsole.remoteconfig.RemoteConfigSnapshot +import io.devconsole.remoteconfig.RemoteConfigSource +import io.devconsole.server.api.BrowserSession +import io.devconsole.server.api.InMemoryCommandAuditLog +import io.devconsole.server.api.SessionAuthority +import io.devconsole.server.api.SessionCodeAuthority +import io.ktor.client.request.HttpRequestBuilder +import io.ktor.client.request.delete +import io.ktor.client.request.get +import io.ktor.client.request.header +import io.ktor.client.request.post +import io.ktor.client.request.put +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 + +private const val OVER_LONG_KEY_LENGTH = 300 + +class RemoteConfigOverrideRoutesTest { + @Test + fun `put stores the override`() = + testApplication { + val fixtures = createFixtures() + val sessions = fixtures.sessions + val sessionCodes = fixtures.sessionCodes + val audit = fixtures.audit + val store = fixtures.store + application { + protectedDevConsoleModule(sessions, sessionCodes) { + featureFlagsEditable = true + remoteConfigSnapshots = { listOf(firebaseSnapshot()) } + remoteConfigOverrides = store + commandAuditLog = audit + } + } + val session = approvedSession(sessions, sessionCodes) + + val response = + client.put("/api/v1/remote-config/firebase/overrides/welcome_message") { + controlHeaders(session) + header(HttpHeaders.ContentType, ContentType.Application.FormUrlEncoded) + setBody("value=Hello+World") + } + + assertEquals(HttpStatusCode.OK, response.status) + assertEquals("{\"status\":\"updated\"}", response.bodyAsText()) + assertEquals("Hello World", store.overrides()["firebase"]?.get("welcome_message")) + } + + @Test + fun `delete one clears it`() = + testApplication { + val fixtures = createFixtures() + val sessions = fixtures.sessions + val sessionCodes = fixtures.sessionCodes + val audit = fixtures.audit + val store = fixtures.store + store.setOverride("firebase", "welcome_message", "Hello") + application { + protectedDevConsoleModule(sessions, sessionCodes) { + featureFlagsEditable = true + remoteConfigSnapshots = { listOf(firebaseSnapshot()) } + remoteConfigOverrides = store + commandAuditLog = audit + } + } + val session = approvedSession(sessions, sessionCodes) + + val response = + client.delete("/api/v1/remote-config/firebase/overrides/welcome_message") { + controlHeaders(session) + } + + assertEquals(HttpStatusCode.OK, response.status) + assertEquals("{\"status\":\"cleared\"}", response.bodyAsText()) + assertFalse(store.overrides().getOrDefault("firebase", emptyMap()).containsKey("welcome_message")) + } + + @Test + fun `delete all clears all`() = + testApplication { + val fixtures = createFixtures() + val sessions = fixtures.sessions + val sessionCodes = fixtures.sessionCodes + val audit = fixtures.audit + val store = fixtures.store + store.setOverride("firebase", "key1", "val1") + store.setOverride("firebase", "key2", "val2") + application { + protectedDevConsoleModule(sessions, sessionCodes) { + featureFlagsEditable = true + remoteConfigSnapshots = { listOf(firebaseSnapshot()) } + remoteConfigOverrides = store + commandAuditLog = audit + } + } + val session = approvedSession(sessions, sessionCodes) + + val response = + client.delete("/api/v1/remote-config/overrides") { + controlHeaders(session) + } + + assertEquals(HttpStatusCode.OK, response.status) + assertEquals("{\"status\":\"cleared\"}", response.bodyAsText()) + assertTrue(store.overrides().isEmpty()) + } + + @Test + fun `get reports overridesEditable true and providerValue and providerSource fields`() = + testApplication { + val fixtures = createFixtures() + val sessions = fixtures.sessions + val sessionCodes = fixtures.sessionCodes + val store = fixtures.store + application { + protectedDevConsoleModule(sessions, sessionCodes) { + remoteConfigSnapshots = { listOf(firebaseSnapshot()) } + remoteConfigOverrides = store + featureFlagsEditable = true + } + } + val session = approvedSession(sessions, sessionCodes) + + val response = client.get("/api/v1/remote-config") { authHeaders(session) } + + assertEquals(HttpStatusCode.OK, response.status) + val body = response.bodyAsText() + assertTrue(body.contains("\"overridesEditable\":true")) + assertTrue(body.contains("\"providerValue\":\"Original\"")) + assertTrue(body.contains("\"providerSource\":\"remote\"")) + } + + @Test + fun `get reports overridesEditable false when store is null or featureFlagsEditable is false`() = + testApplication { + val fixtures = createFixtures() + val sessions = fixtures.sessions + val sessionCodes = fixtures.sessionCodes + application { + protectedDevConsoleModule(sessions, sessionCodes) { + remoteConfigSnapshots = { listOf(firebaseSnapshot()) } + remoteConfigOverrides = null + featureFlagsEditable = true + } + } + val session = approvedSession(sessions, sessionCodes) + + val response = client.get("/api/v1/remote-config") { authHeaders(session) } + + assertEquals(HttpStatusCode.OK, response.status) + assertTrue(response.bodyAsText().contains("\"overridesEditable\":false")) + } + + @Test + fun `returns 403 when featureFlagsEditable is false`() = + testApplication { + val fixtures = createFixtures() + val sessions = fixtures.sessions + val sessionCodes = fixtures.sessionCodes + val audit = fixtures.audit + val store = fixtures.store + application { + protectedDevConsoleModule(sessions, sessionCodes) { + remoteConfigSnapshots = { listOf(firebaseSnapshot()) } + remoteConfigOverrides = store + featureFlagsEditable = false + commandAuditLog = audit + } + } + val session = approvedSession(sessions, sessionCodes) + + val putRes = + client.put("/api/v1/remote-config/firebase/overrides/welcome_message") { + controlHeaders(session) + header(HttpHeaders.ContentType, ContentType.Application.FormUrlEncoded) + setBody("value=test") + } + val deleteOneRes = + client.delete("/api/v1/remote-config/firebase/overrides/welcome_message") { + controlHeaders(session) + } + val deleteAllRes = + client.delete("/api/v1/remote-config/overrides") { + controlHeaders(session) + } + + assertEquals(HttpStatusCode.Forbidden, putRes.status) + assertEquals("{\"code\":\"REMOTE_CONFIG_OVERRIDES_DISABLED\"}", putRes.bodyAsText()) + assertEquals(HttpStatusCode.Forbidden, deleteOneRes.status) + assertEquals("{\"code\":\"REMOTE_CONFIG_OVERRIDES_DISABLED\"}", deleteOneRes.bodyAsText()) + assertEquals(HttpStatusCode.Forbidden, deleteAllRes.status) + assertEquals("{\"code\":\"REMOTE_CONFIG_OVERRIDES_DISABLED\"}", deleteAllRes.bodyAsText()) + } + + @Test + fun `returns 503 when remoteConfigOverrides store is null`() = + testApplication { + val fixtures = createFixtures() + val sessions = fixtures.sessions + val sessionCodes = fixtures.sessionCodes + val audit = fixtures.audit + application { + protectedDevConsoleModule(sessions, sessionCodes) { + featureFlagsEditable = true + remoteConfigSnapshots = { listOf(firebaseSnapshot()) } + remoteConfigOverrides = null + commandAuditLog = audit + } + } + val session = approvedSession(sessions, sessionCodes) + + val putRes = + client.put("/api/v1/remote-config/firebase/overrides/welcome_message") { + controlHeaders(session) + header(HttpHeaders.ContentType, ContentType.Application.FormUrlEncoded) + setBody("value=test") + } + val deleteOneRes = + client.delete("/api/v1/remote-config/firebase/overrides/welcome_message") { + controlHeaders(session) + } + val deleteAllRes = + client.delete("/api/v1/remote-config/overrides") { + controlHeaders(session) + } + + assertEquals(HttpStatusCode.ServiceUnavailable, putRes.status) + assertEquals("{\"code\":\"REMOTE_CONFIG_OVERRIDES_UNAVAILABLE\"}", putRes.bodyAsText()) + assertEquals(HttpStatusCode.ServiceUnavailable, deleteOneRes.status) + assertEquals("{\"code\":\"REMOTE_CONFIG_OVERRIDES_UNAVAILABLE\"}", deleteOneRes.bodyAsText()) + assertEquals(HttpStatusCode.ServiceUnavailable, deleteAllRes.status) + assertEquals("{\"code\":\"REMOTE_CONFIG_OVERRIDES_UNAVAILABLE\"}", deleteAllRes.bodyAsText()) + } + + @Test + fun `returns 404 when provider is unknown`() = + testApplication { + val fixtures = createFixtures() + val sessions = fixtures.sessions + val sessionCodes = fixtures.sessionCodes + val audit = fixtures.audit + val store = fixtures.store + application { + protectedDevConsoleModule(sessions, sessionCodes) { + featureFlagsEditable = true + remoteConfigSnapshots = { listOf(firebaseSnapshot()) } + remoteConfigOverrides = store + commandAuditLog = audit + } + } + val session = approvedSession(sessions, sessionCodes) + + val putRes = + client.put("/api/v1/remote-config/unknown_provider/overrides/key") { + controlHeaders(session) + header(HttpHeaders.ContentType, ContentType.Application.FormUrlEncoded) + setBody("value=test") + } + val deleteRes = + client.delete("/api/v1/remote-config/unknown_provider/overrides/key") { + controlHeaders(session) + } + + assertEquals(HttpStatusCode.NotFound, putRes.status) + assertEquals("{\"code\":\"REMOTE_CONFIG_PROVIDER_NOT_FOUND\"}", putRes.bodyAsText()) + assertEquals(HttpStatusCode.NotFound, deleteRes.status) + assertEquals("{\"code\":\"REMOTE_CONFIG_PROVIDER_NOT_FOUND\"}", deleteRes.bodyAsText()) + } + + @Test + fun `returns 400 when value parameter is missing or store throws IllegalArgumentException`() = + testApplication { + val fixtures = createFixtures() + val sessions = fixtures.sessions + val sessionCodes = fixtures.sessionCodes + val audit = fixtures.audit + val store = fixtures.store + application { + protectedDevConsoleModule(sessions, sessionCodes) { + featureFlagsEditable = true + remoteConfigSnapshots = { listOf(firebaseSnapshot()) } + remoteConfigOverrides = store + commandAuditLog = audit + } + } + val session = approvedSession(sessions, sessionCodes) + + val missingValueRes = + client.put("/api/v1/remote-config/firebase/overrides/welcome_message") { + controlHeaders(session) + header(HttpHeaders.ContentType, ContentType.Application.FormUrlEncoded) + setBody("other=test") + } + + val overLongKey = "k".repeat(OVER_LONG_KEY_LENGTH) + val blankKeyRes = + client.put("/api/v1/remote-config/firebase/overrides/$overLongKey") { + controlHeaders(session) + header(HttpHeaders.ContentType, ContentType.Application.FormUrlEncoded) + setBody("value=test") + } + + assertEquals(HttpStatusCode.BadRequest, missingValueRes.status) + assertEquals("{\"code\":\"VALIDATION_FAILED\"}", missingValueRes.bodyAsText()) + assertEquals(HttpStatusCode.BadRequest, blankKeyRes.status) + assertEquals("{\"code\":\"VALIDATION_FAILED\"}", blankKeyRes.bodyAsText()) + } + + @Test + fun `returns 401 when unauthenticated`() = + testApplication { + val fixtures = createFixtures() + val sessions = fixtures.sessions + val sessionCodes = fixtures.sessionCodes + val store = fixtures.store + application { + protectedDevConsoleModule(sessions, sessionCodes) { + featureFlagsEditable = true + remoteConfigSnapshots = { listOf(firebaseSnapshot()) } + remoteConfigOverrides = store + } + } + + val putRes = + client.put("/api/v1/remote-config/firebase/overrides/key") { + header(HttpHeaders.Host, "localhost") + header(HttpHeaders.ContentType, ContentType.Application.FormUrlEncoded) + setBody("value=test") + } + val deleteOneRes = + client.delete("/api/v1/remote-config/firebase/overrides/key") { + header(HttpHeaders.Host, "localhost") + } + val deleteAllRes = + client.delete("/api/v1/remote-config/overrides") { + header(HttpHeaders.Host, "localhost") + } + + assertEquals(HttpStatusCode.Unauthorized, putRes.status) + assertEquals("{\"code\":\"AUTH_REQUIRED\"}", putRes.bodyAsText()) + assertEquals(HttpStatusCode.Unauthorized, deleteOneRes.status) + assertEquals("{\"code\":\"AUTH_REQUIRED\"}", deleteOneRes.bodyAsText()) + assertEquals(HttpStatusCode.Unauthorized, deleteAllRes.status) + assertEquals("{\"code\":\"AUTH_REQUIRED\"}", deleteAllRes.bodyAsText()) + } + + @Test + fun `audit event for PUT does not contain raw value when key is sensitive`() = + testApplication { + val fixtures = createFixtures() + val sessions = fixtures.sessions + val sessionCodes = fixtures.sessionCodes + val audit = fixtures.audit + val store = fixtures.store + application { + protectedDevConsoleModule(sessions, sessionCodes) { + featureFlagsEditable = true + remoteConfigSnapshots = { listOf(firebaseSnapshot()) } + remoteConfigOverrides = store + commandAuditLog = audit + } + } + val session = approvedSession(sessions, sessionCodes) + + val response = + client.put("/api/v1/remote-config/firebase/overrides/api_key") { + controlHeaders(session) + header(HttpHeaders.ContentType, ContentType.Application.FormUrlEncoded) + setBody("value=super_secret_token_12345") + } + + assertEquals(HttpStatusCode.OK, response.status) + val event = audit.events().last { it.commandType == "remoteConfig.override" } + assertEquals("firebase/api_key", event.target) + assertFalse( + "Audit log must not contain raw secret value", + event.parameters.values.any { it.contains("super_secret_token_12345") }, + ) + } +} + +private data class TestFixtures( + val sessions: SessionAuthority, + val sessionCodes: SessionCodeAuthority, + val audit: InMemoryCommandAuditLog, + val store: InMemoryRemoteConfigOverrideStore, +) + +private fun createFixtures(): TestFixtures { + val sessions = SessionAuthority() + return TestFixtures( + sessions = sessions, + sessionCodes = SessionCodeAuthority(sessions), + audit = InMemoryCommandAuditLog(), + store = InMemoryRemoteConfigOverrideStore(), + ) +} + +private fun firebaseSnapshot() = + RemoteConfigSnapshot( + providerId = "firebase", + entries = + listOf( + RemoteConfigEntry( + key = "welcome_message", + value = "Override", + source = RemoteConfigSource.STATIC, + redacted = false, + truncated = false, + providerValue = "Original", + providerSource = RemoteConfigSource.REMOTE, + ), + ), + fetchInfo = RemoteConfigFetchInfo.unknown(), + ) + +private fun HttpRequestBuilder.authHeaders(session: BrowserSession) { + header(HttpHeaders.Host, "localhost") + header(HttpHeaders.Authorization, "Bearer ${session.token}") +} + +private fun HttpRequestBuilder.controlHeaders(session: BrowserSession) { + header(HttpHeaders.Host, "localhost") + header(HttpHeaders.Authorization, "Bearer ${session.token}") + header(HttpHeaders.Origin, "http://localhost") + header("X-DevConsole-CSRF", session.csrfToken) +} + +private suspend fun ApplicationTestBuilder.approvedSession( + sessions: SessionAuthority, + sessionCodes: SessionCodeAuthority, +): BrowserSession { + val response = + client.post("/api/v1/auth/session-code/exchange") { + header(HttpHeaders.Host, "localhost") + header(HttpHeaders.ContentType, ContentType.Application.FormUrlEncoded) + setBody("code=${sessionCodes.issueCode().code}") + } + val token = Regex("\"accessToken\":\"([^\"]+)\"").find(response.bodyAsText())!!.groupValues[1] + return sessions.sessionForToken(token)!! +} 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 index 3545c5c..24ce602 100644 --- 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 @@ -164,7 +164,7 @@ class RemoteConfigRoutesTest { val response = client.get("/api/v1/remote-config") { authed(session) } assertEquals(HttpStatusCode.OK, response.status) - assertEquals("{\"data\":[]}", response.bodyAsText()) + assertEquals("{\"data\":[],\"overridesEditable\":false}", response.bodyAsText()) } @Test diff --git a/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/RetainedNetworkRoutesTest.kt b/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/RetainedNetworkRoutesTest.kt new file mode 100644 index 0000000..1fc5a55 --- /dev/null +++ b/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/RetainedNetworkRoutesTest.kt @@ -0,0 +1,252 @@ +/** + * @author Shakib + * @since 03/11/26 + */ +@file:Suppress("MatchingDeclarationName") + +package io.devconsole.server.ktor + +import io.devconsole.network.InMemoryNetworkTransactionStore +import io.devconsole.network.NetworkCaptureFactory +import io.devconsole.network.NetworkCursorCodec +import io.devconsole.network.NetworkRequestInput +import io.devconsole.network.NetworkResponseInput +import io.devconsole.network.NetworkTransaction +import io.devconsole.network.NetworkTransactionStore +import io.devconsole.security.RedactionEngine +import io.devconsole.security.RedactionPolicy +import io.devconsole.server.api.BrowserSession +import io.devconsole.server.api.SessionAuthority +import io.devconsole.server.api.SessionCodeAuthority +import io.ktor.client.request.HttpRequestBuilder +import io.ktor.client.request.delete +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 + +/** `?sessionId=` on the network list, detail, cURL and HAR/Postman routes. */ +class RetainedNetworkRoutesTest { + private val live = transactionStore("live-tx") + private val past = transactionStore("past-tx") + + private fun ApplicationTestBuilder.installModule( + sessions: SessionAuthority, + codes: SessionCodeAuthority, + ) { + application { + protectedDevConsoleModule(sessions, codes) { + networkTransactions = live + currentSessionId = { "run-live" } + retainedNetworkTransactions = { id -> past.takeIf { id == "run-past" } } + } + } + } + + @Test + fun `list serves the live run by default and a past run on request`() = + testApplication { + val sessions = SessionAuthority() + val codes = SessionCodeAuthority(sessions) + installModule(sessions, codes) + val session = approvedSession(sessions, codes) + + val liveBody = client.get("/api/v1/network/transactions") { authHeaders(session) }.bodyAsText() + val pastBody = + client.get("/api/v1/network/transactions?sessionId=run-past") { authHeaders(session) }.bodyAsText() + val currentBody = + client.get("/api/v1/network/transactions?sessionId=run-live") { authHeaders(session) }.bodyAsText() + + assertTrue(liveBody.contains("live-tx")) + assertFalse(liveBody.contains("past-tx")) + assertTrue(pastBody.contains("past-tx")) + assertFalse(pastBody.contains("live-tx")) + assertTrue(currentBody.contains("live-tx")) + } + + @Test + fun `detail curl and har read the requested past run`() = + testApplication { + val sessions = SessionAuthority() + val codes = SessionCodeAuthority(sessions) + installModule(sessions, codes) + val session = approvedSession(sessions, codes) + + val detail = + client.get("/api/v1/network/transactions/past-tx?sessionId=run-past") { authHeaders(session) } + val liveMiss = client.get("/api/v1/network/transactions/past-tx") { authHeaders(session) } + val curl = + client.get( + "/api/v1/network/transactions/past-tx/curl?sessionId=run-past", + ) { authHeaders(session) } + val har = client.get("/api/v1/network/har?sessionId=run-past") { authHeaders(session) } + + assertEquals(HttpStatusCode.OK, detail.status) + assertEquals(HttpStatusCode.NotFound, liveMiss.status) + assertTrue(curl.bodyAsText().contains("api.test/past-tx")) + assertTrue(har.bodyAsText().contains("api.test/past-tx")) + assertFalse(har.bodyAsText().contains("api.test/live-tx")) + } + + @Test + fun `an unknown run answers session not found`() = + testApplication { + val sessions = SessionAuthority() + val codes = SessionCodeAuthority(sessions) + installModule(sessions, codes) + val session = approvedSession(sessions, codes) + + val response = client.get("/api/v1/network/transactions?sessionId=run-gone") { authHeaders(session) } + + assertEquals(HttpStatusCode.NotFound, response.status) + assertTrue(response.bodyAsText().contains("SESSION_NOT_FOUND")) + } + + @Test + fun `post export checks auth before it looks the run up`() = + testApplication { + val sessions = SessionAuthority() + val codes = SessionCodeAuthority(sessions) + var lookups = 0 + application { + protectedDevConsoleModule(sessions, codes) { + networkTransactions = live + currentSessionId = { "run-live" } + retainedNetworkTransactions = { id -> + lookups++ + past.takeIf { id == "run-past" } + } + } + } + + val response = + client.post("/api/v1/network/har?sessionId=run-past") { + header(HttpHeaders.Host, "localhost") + header(HttpHeaders.ContentType, ContentType.Application.FormUrlEncoded) + setBody("id=past-tx") + } + + assertEquals(HttpStatusCode.Unauthorized, response.status) + assertEquals(0, lookups) + } +} + +/** `DELETE /api/v1/runs/{id}` and `POST /api/v1/runs/{id}/pin`: CSRF-gated, and never the live run. */ +class RunControlRoutesTest { + @Test + fun `deleting a finished run calls the store and the live run is refused`() = + testApplication { + val sessions = SessionAuthority() + val codes = SessionCodeAuthority(sessions) + val deleted = mutableListOf() + application { + protectedDevConsoleModule(sessions, codes) { + currentSessionId = { "run-live" } + deleteRun = { id -> + deleted += id + true + } + } + } + val session = approvedSession(sessions, codes) + + val ok = client.delete("/api/v1/runs/run-old") { controlHeaders(session) } + val live = client.delete("/api/v1/runs/run-live") { controlHeaders(session) } + val noCsrf = client.delete("/api/v1/runs/run-old") { authHeaders(session) } + + assertEquals(HttpStatusCode.OK, ok.status) + assertEquals(HttpStatusCode.Conflict, live.status) + assertEquals(HttpStatusCode.Forbidden, noCsrf.status) + assertEquals(listOf("run-old"), deleted) + } + + @Test + fun `pinning passes the requested state and reports a refusal`() = + testApplication { + val sessions = SessionAuthority() + val codes = SessionCodeAuthority(sessions) + val calls = mutableListOf>() + application { + protectedDevConsoleModule(sessions, codes) { + pinRun = { id, pinned -> + calls += id to pinned + id == "run-old" + } + } + } + val session = approvedSession(sessions, codes) + + val pin = + client.post("/api/v1/runs/run-old/pin") { + controlHeaders(session) + header(HttpHeaders.ContentType, ContentType.Application.FormUrlEncoded) + setBody("pinned=true") + } + val unpinUnknown = + client.post("/api/v1/runs/run-gone/pin") { + controlHeaders(session) + header(HttpHeaders.ContentType, ContentType.Application.FormUrlEncoded) + setBody("pinned=false") + } + + assertEquals(HttpStatusCode.OK, pin.status) + assertTrue(pin.bodyAsText().contains("\"pinned\":true")) + assertEquals(HttpStatusCode.Conflict, unpinUnknown.status) + assertEquals(listOf("run-old" to true, "run-gone" to false), calls) + } +} + +private fun HttpRequestBuilder.controlHeaders(session: BrowserSession) { + header(HttpHeaders.Host, "localhost") + header(HttpHeaders.Authorization, "Bearer ${session.token}") + header(HttpHeaders.Origin, "http://localhost") + header("X-DevConsole-CSRF", session.csrfToken) +} + +private fun transactionStore(vararg ids: String): NetworkTransactionStore = + InMemoryNetworkTransactionStore(NetworkCursorCodec(ByteArray(16))).also { store -> + ids.forEachIndexed { index, id -> + store.record( + NetworkTransaction( + id = id, + startedAtEpochMs = index.toLong() + 1, + completedAtEpochMs = index.toLong() + 2, + capture = + NetworkCaptureFactory(RedactionEngine(RedactionPolicy.recommended())).capture( + NetworkRequestInput("GET", "https://api.test/$id"), + NetworkResponseInput(200), + ), + ), + ) + } + } + +private fun HttpRequestBuilder.authHeaders(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/server-ktor/src/test/kotlin/io/devconsole/server/ktor/SocketSendRoutesTest.kt b/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/SocketSendRoutesTest.kt new file mode 100644 index 0000000..29d970e --- /dev/null +++ b/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/SocketSendRoutesTest.kt @@ -0,0 +1,275 @@ +/** + * @author Shakib + * @since 04/11/26 + */ +package io.devconsole.server.ktor + +import io.devconsole.server.api.BrowserSession +import io.devconsole.server.api.InMemoryCommandAuditLog +import io.devconsole.server.api.SessionAuthority +import io.devconsole.server.api.SessionCodeAuthority +import io.devconsole.socket.InMemorySocketStore +import io.devconsole.socket.SocketConnection +import io.devconsole.socket.SocketProtocol +import io.devconsole.socket.SocketSendRequest +import io.devconsole.socket.SocketSendResult +import io.devconsole.socket.SocketSender +import io.devconsole.socket.SocketSenderRegistry +import io.ktor.client.request.HttpRequestBuilder +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.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class SocketSendRoutesTest { + @Test + fun `sending requires a bearer session`() = + testApplication { + val sessions = SessionAuthority() + val sessionCodes = SessionCodeAuthority(sessions) + application { protectedDevConsoleModule(sessions, sessionCodes) } + + val response = + client.post("/api/v1/websockets/connections/socket-1/send") { + header(HttpHeaders.Host, "localhost") + setBody("text=hi") + } + + assertEquals(HttpStatusCode.Unauthorized, response.status) + assertEquals("{\"code\":\"AUTH_REQUIRED\"}", response.bodyAsText()) + } + + @Test + fun `connection listings report which connections can be written to`() = + testApplication { + val sessions = SessionAuthority() + val sessionCodes = SessionCodeAuthority(sessions) + val sockets = InMemorySocketStore() + sockets.open(SocketConnection("socket-1", "wss://api.test/socket", 1)) + sockets.open(SocketConnection("socket-2", "wss://api.test/other", 2)) + val senders = SocketSenderRegistry() + senders.register("socket-1", SocketProtocol.WEBSOCKET, FakeSocketSender()) + application { + protectedDevConsoleModule(sessions, sessionCodes) { + socketStore = sockets + socketSenders = senders + composerEnabled = true + } + } + val session = approvedSession(sessions, sessionCodes) + + val list = client.get("/api/v1/websockets/connections") { authHeaders(session) } + val detail = + client.get("/api/v1/websockets/connections/socket-1") { authHeaders(session) } + val sendable = client.get("/api/v1/websockets/connections/socket-2") { authHeaders(session) } + + assertEquals(HttpStatusCode.OK, list.status) + assertTrue(list.bodyAsText().contains("\"canSend\":true,\"sendProtocol\":\"websocket\"")) + assertTrue(list.bodyAsText().contains("\"canSend\":false,\"sendProtocol\":null")) + assertTrue(detail.bodyAsText().contains("\"canSend\":true,\"sendProtocol\":\"websocket\"")) + assertTrue(sendable.bodyAsText().contains("\"canSend\":false,\"sendProtocol\":null")) + } + + @Test + fun `sending passes the frame and MQTT fields to the registered sender and audits it`() = + testApplication { + val sessions = SessionAuthority() + val sessionCodes = SessionCodeAuthority(sessions) + val senders = SocketSenderRegistry() + val sender = FakeSocketSender() + senders.register("socket-1", SocketProtocol.MQTT, sender) + val audit = InMemoryCommandAuditLog() + application { + protectedDevConsoleModule(sessions, sessionCodes) { + socketSenders = senders + commandAuditLog = audit + composerEnabled = true + } + } + val session = approvedSession(sessions, sessionCodes) + + val response = + client.post("/api/v1/websockets/connections/socket-1/send") { + controlHeaders(session) + header(HttpHeaders.ContentType, ContentType.Application.FormUrlEncoded) + setBody("text=hello&topic=sensors%2F1&qos=1&retained=true") + } + + assertEquals(HttpStatusCode.OK, response.status) + assertEquals("{\"status\":\"sent\"}", response.bodyAsText()) + assertEquals(SocketSendRequest("hello", "sensors/1", 1, true), sender.lastRequest) + val event = audit.events().single() + assertEquals("socket.send", event.commandType) + assertEquals("socket-1", event.target) + assertEquals("5", event.parameters["bytes"]) + assertEquals("sensors/1", event.parameters["topic"]) + assertTrue("the frame text must never be audited", event.parameters.values.none { it.contains("hello") }) + } + + @Test + fun `a disconnected sender answers NOT_CONNECTED`() = + testApplication { + val sessions = SessionAuthority() + val sessionCodes = SessionCodeAuthority(sessions) + val senders = SocketSenderRegistry() + senders.register("socket-1", SocketProtocol.WEBSOCKET, FakeSocketSender(SocketSendResult.NotConnected)) + application { + protectedDevConsoleModule(sessions, sessionCodes) { + socketSenders = senders + composerEnabled = true + } + } + val session = approvedSession(sessions, sessionCodes) + + val response = sendFrame(session, "socket-1", "text=hi") + + assertEquals(HttpStatusCode.Conflict, response.status) + assertEquals("{\"code\":\"NOT_CONNECTED\"}", response.bodyAsText()) + } + + @Test + fun `a sender rejection answers SEND_REJECTED with its reason`() = + testApplication { + val sessions = SessionAuthority() + val sessionCodes = SessionCodeAuthority(sessions) + val senders = SocketSenderRegistry() + senders.register( + "socket-1", + SocketProtocol.WEBSOCKET, + FakeSocketSender(SocketSendResult.Rejected("queue full")), + ) + application { + protectedDevConsoleModule(sessions, sessionCodes) { + socketSenders = senders + composerEnabled = true + } + } + val session = approvedSession(sessions, sessionCodes) + + val response = sendFrame(session, "socket-1", "text=hi") + + assertEquals(HttpStatusCode.BadRequest, response.status) + assertEquals("{\"code\":\"SEND_REJECTED\",\"message\":\"queue full\"}", response.bodyAsText()) + } + + @Test + fun `a body without a text field is rejected`() = + testApplication { + val sessions = SessionAuthority() + val sessionCodes = SessionCodeAuthority(sessions) + val senders = SocketSenderRegistry() + val sender = FakeSocketSender() + senders.register("socket-1", SocketProtocol.WEBSOCKET, sender) + application { + protectedDevConsoleModule(sessions, sessionCodes) { + socketSenders = senders + composerEnabled = true + } + } + val session = approvedSession(sessions, sessionCodes) + + val response = sendFrame(session, "socket-1", "topic=sensors%2F1") + + assertEquals(HttpStatusCode.BadRequest, response.status) + assertEquals("{\"code\":\"VALIDATION_FAILED\"}", response.bodyAsText()) + assertNull(sender.lastRequest) + } + + @Test + fun `a non-numeric qos is rejected before reaching the sender`() = + testApplication { + val sessions = SessionAuthority() + val sessionCodes = SessionCodeAuthority(sessions) + val senders = SocketSenderRegistry() + val sender = FakeSocketSender() + senders.register("socket-1", SocketProtocol.MQTT, sender) + application { + protectedDevConsoleModule(sessions, sessionCodes) { + socketSenders = senders + composerEnabled = true + } + } + val session = approvedSession(sessions, sessionCodes) + + val response = sendFrame(session, "socket-1", "text=hi&topic=a&qos=high") + + assertEquals(HttpStatusCode.BadRequest, response.status) + assertEquals("{\"code\":\"VALIDATION_FAILED\"}", response.bodyAsText()) + assertNull(sender.lastRequest) + } + + @Test + fun `an unwired registry answers SEND_UNSUPPORTED`() = + testApplication { + val sessions = SessionAuthority() + val sessionCodes = SessionCodeAuthority(sessions) + application { + protectedDevConsoleModule(sessions, sessionCodes) { composerEnabled = true } + } + val session = approvedSession(sessions, sessionCodes) + + val response = sendFrame(session, "socket-1", "text=hi") + + assertEquals(HttpStatusCode.ServiceUnavailable, response.status) + assertEquals("{\"code\":\"SEND_UNSUPPORTED\"}", response.bodyAsText()) + } +} + +private class FakeSocketSender( + private val result: SocketSendResult = SocketSendResult.Sent, +) : SocketSender { + var lastRequest: SocketSendRequest? = null + private set + + override fun send(request: SocketSendRequest): SocketSendResult { + lastRequest = request + return result + } +} + +private suspend fun ApplicationTestBuilder.sendFrame( + session: BrowserSession, + connectionId: String, + body: String, +) = client.post("/api/v1/websockets/connections/$connectionId/send") { + controlHeaders(session) + header(HttpHeaders.ContentType, ContentType.Application.FormUrlEncoded) + setBody(body) +} + +/** Bearer-only headers for a plain GET -- no Origin/CSRF, since a read route never needs them. */ +private fun HttpRequestBuilder.authHeaders(session: BrowserSession) { + header(HttpHeaders.Host, "localhost") + header(HttpHeaders.Authorization, "Bearer ${session.token}") +} + +private fun HttpRequestBuilder.controlHeaders(session: BrowserSession) { + header(HttpHeaders.Host, "localhost") + header(HttpHeaders.Authorization, "Bearer ${session.token}") + header(HttpHeaders.Origin, "http://localhost") + header("X-DevConsole-CSRF", session.csrfToken) +} + +private suspend fun ApplicationTestBuilder.approvedSession( + sessions: SessionAuthority, + sessionCodes: SessionCodeAuthority, +): BrowserSession { + val response = + client.post("/api/v1/auth/session-code/exchange") { + header(HttpHeaders.Host, "localhost") + header(HttpHeaders.ContentType, ContentType.Application.FormUrlEncoded) + setBody("code=${sessionCodes.issueCode().code}") + } + val token = Regex("\"accessToken\":\"([^\"]+)\"").find(response.bodyAsText())!!.groupValues[1] + return sessions.sessionForToken(token)!! +} diff --git a/sdk/socket-okhttp/src/main/kotlin/io/devconsole/socket/okhttp/DevConsoleOkHttpWebSocketListener.kt b/sdk/socket-okhttp/src/main/kotlin/io/devconsole/socket/okhttp/DevConsoleOkHttpWebSocketListener.kt index 5fc34d7..51e36d6 100644 --- a/sdk/socket-okhttp/src/main/kotlin/io/devconsole/socket/okhttp/DevConsoleOkHttpWebSocketListener.kt +++ b/sdk/socket-okhttp/src/main/kotlin/io/devconsole/socket/okhttp/DevConsoleOkHttpWebSocketListener.kt @@ -1,12 +1,18 @@ package io.devconsole.socket.okhttp import io.devconsole.socket.SocketDirection +import io.devconsole.socket.SocketProtocol import io.devconsole.socket.SocketRecorder +import io.devconsole.socket.SocketSendResult +import io.devconsole.socket.SocketSender import okhttp3.Response import okhttp3.WebSocket import okhttp3.WebSocketListener import okio.ByteString +/** OkHttp refuses a frame for exactly one reason, and the dashboard should show OkHttp's wording. */ +private const val SEND_QUEUE_FULL_REASON = "Send queue full or socket closing" + /** * OkHttp adapter that records callbacks without altering socket control flow. * @@ -35,7 +41,36 @@ class DevConsoleOkHttpWebSocketListener /** Internal: only [onOpen] and this module's own tests need to invoke this directly. */ internal fun recordOpen(webSocket: WebSocket) { - recorder.onOpen(connectionIdProvider(webSocket), webSocket.request().url.toString()) + val connectionId = connectionIdProvider(webSocket) + recorder.onOpen(connectionId, webSocket.request().url.toString()) + registerSenderIfAbsent(connectionId, webSocket) + } + + /** + * Skipped when a sender is already registered, because [DevConsoleRecordingWebSocket.wrap] + * registers its own. The wrapper's sender records through the wrapper's `send`, so letting + * the listener replace it would record every host frame twice. + */ + private fun registerSenderIfAbsent( + connectionId: String, + webSocket: WebSocket, + ) { + if (recorder.senders.canSend(connectionId)) return + recorder.senders.register( + connectionId, + SocketProtocol.WEBSOCKET, + SocketSender { request -> sendDirect(webSocket, connectionId, request.text) }, + ) + } + + private fun sendDirect( + webSocket: WebSocket, + connectionId: String, + text: String, + ): SocketSendResult { + if (!webSocket.send(text)) return SocketSendResult.Rejected(SEND_QUEUE_FULL_REASON) + recorder.onMessage(connectionId, SocketDirection.SENT, text, "text/plain") + return SocketSendResult.Sent } override fun onMessage( @@ -73,7 +108,9 @@ class DevConsoleOkHttpWebSocketListener code: Int, reason: String, ) { - recorder.onClosed(connectionIdProvider(webSocket)) + val connectionId = connectionIdProvider(webSocket) + recorder.onClosed(connectionId) + recorder.senders.unregister(connectionId) delegate?.onClosed(webSocket, code, reason) } @@ -82,7 +119,9 @@ class DevConsoleOkHttpWebSocketListener t: Throwable, response: Response?, ) { - recorder.onFailure(connectionIdProvider(webSocket), t) + val connectionId = connectionIdProvider(webSocket) + recorder.onFailure(connectionId, t) + recorder.senders.unregister(connectionId) delegate?.onFailure(webSocket, t, response) } } @@ -93,6 +132,19 @@ class DevConsoleRecordingWebSocket private constructor( private val recorder: SocketRecorder, private val connectionId: String, ) : WebSocket { + /** + * Registered here, not by the listener, so a registry send goes through this wrapper's own + * `send` and is recorded exactly once. Replacing the listener's sender is the point: the + * documented dual-wiring would otherwise record the same frame twice. + */ + init { + recorder.senders.register( + connectionId, + SocketProtocol.WEBSOCKET, + SocketSender { request -> sendRegistered(request.text) }, + ) + } + override fun request() = delegate.request() override fun queueSize(): Long = delegate.queueSize() @@ -120,14 +172,19 @@ class DevConsoleRecordingWebSocket private constructor( ): Boolean = delegate.close(code, reason).also { accepted -> if (accepted) recorder.onClosing(connectionId, code, reason) + recorder.senders.unregister(connectionId) } override fun cancel() { delegate.cancel() + recorder.senders.unregister(connectionId) // Not a failure: an intentional cancel by the host, so it must not read as ERROR severity. recorder.onCancelled(connectionId, "Cancelled by host") } + private fun sendRegistered(text: String): SocketSendResult = + if (send(text)) SocketSendResult.Sent else SocketSendResult.Rejected(SEND_QUEUE_FULL_REASON) + companion object { fun wrap( delegate: WebSocket, diff --git a/sdk/socket-okhttp/src/test/kotlin/io/devconsole/socket/okhttp/DevConsoleOkHttpWebSocketListenerTest.kt b/sdk/socket-okhttp/src/test/kotlin/io/devconsole/socket/okhttp/DevConsoleOkHttpWebSocketListenerTest.kt index 8ce619d..5cf0118 100644 --- a/sdk/socket-okhttp/src/test/kotlin/io/devconsole/socket/okhttp/DevConsoleOkHttpWebSocketListenerTest.kt +++ b/sdk/socket-okhttp/src/test/kotlin/io/devconsole/socket/okhttp/DevConsoleOkHttpWebSocketListenerTest.kt @@ -8,7 +8,10 @@ import io.devconsole.socket.SocketDirection import io.devconsole.socket.SocketLifecycleType import io.devconsole.socket.SocketMessage import io.devconsole.socket.SocketPayload +import io.devconsole.socket.SocketProtocol import io.devconsole.socket.SocketRecorder +import io.devconsole.socket.SocketSendRequest +import io.devconsole.socket.SocketSendResult import okhttp3.Protocol import okhttp3.Request import okhttp3.Response @@ -127,6 +130,104 @@ class DevConsoleOkHttpWebSocketListenerTest { assertEquals(SocketLifecycleType.CANCELLED, store.lifecycleEvents("socket-1").last().type) } + @Test + fun `listener registers a sender that sends through okhttp and records one sent frame`() { + val store = InMemorySocketStore() + val recorder = SocketRecorder(RedactionEngine(RedactionPolicy.recommended()), store) + val listener = DevConsoleOkHttpWebSocketListener(recorder, connectionIdProvider = { "socket-1" }) + val socket = FakeWebSocket() + + listener.recordOpen(socket) + + assertTrue(recorder.senders.canSend("socket-1")) + assertEquals(SocketProtocol.WEBSOCKET, recorder.senders.protocol("socket-1")) + assertEquals(SocketSendResult.Sent, recorder.senders.send("socket-1", SocketSendRequest("hello"))) + assertEquals(listOf("hello"), socket.sentTexts) + assertEquals(listOf(SocketDirection.SENT), store.messages("socket-1").map(SocketMessage::direction)) + } + + @Test + fun `a send is recorded once when the listener opened the socket before it was wrapped`() { + val store = InMemorySocketStore() + val recorder = SocketRecorder(RedactionEngine(RedactionPolicy.recommended()), store) + val listener = DevConsoleOkHttpWebSocketListener(recorder, connectionIdProvider = { "socket-1" }) + val delegate = FakeWebSocket() + + listener.recordOpen(delegate) + DevConsoleRecordingWebSocket.wrap(delegate, recorder) { "socket-1" } + + assertEquals(SocketSendResult.Sent, recorder.senders.send("socket-1", SocketSendRequest("hello"))) + + assertEquals(1, delegate.sendCount) + assertEquals(1, store.messages("socket-1").size) + } + + @Test + fun `a send is recorded once when the socket was wrapped before the listener opened it`() { + val store = InMemorySocketStore() + val recorder = SocketRecorder(RedactionEngine(RedactionPolicy.recommended()), store) + val listener = DevConsoleOkHttpWebSocketListener(recorder, connectionIdProvider = { "socket-1" }) + val delegate = FakeWebSocket() + + DevConsoleRecordingWebSocket.wrap(delegate, recorder) { "socket-1" } + listener.recordOpen(delegate) + + assertEquals(SocketSendResult.Sent, recorder.senders.send("socket-1", SocketSendRequest("hello"))) + + assertEquals(1, delegate.sendCount) + assertEquals(1, store.messages("socket-1").size) + } + + @Test + fun `a frame okhttp refuses is reported as a rejection and is not recorded`() { + val store = InMemorySocketStore() + val recorder = SocketRecorder(RedactionEngine(RedactionPolicy.recommended()), store) + val listener = DevConsoleOkHttpWebSocketListener(recorder, connectionIdProvider = { "socket-1" }) + val socket = FakeWebSocket().apply { sendAccepted = false } + + listener.recordOpen(socket) + + assertEquals( + SocketSendResult.Rejected("Send queue full or socket closing"), + recorder.senders.send("socket-1", SocketSendRequest("hello")), + ) + assertTrue(store.messages("socket-1").isEmpty()) + } + + @Test + fun `the listener unregisters the sender when the socket closes or fails`() { + val store = InMemorySocketStore() + val recorder = SocketRecorder(RedactionEngine(RedactionPolicy.recommended()), store) + val listener = DevConsoleOkHttpWebSocketListener(recorder, connectionIdProvider = { "socket-1" }) + val socket = FakeWebSocket() + + listener.recordOpen(socket) + assertTrue(recorder.senders.canSend("socket-1")) + listener.onClosed(socket, 1000, "bye") + assertFalse(recorder.senders.canSend("socket-1")) + + listener.recordOpen(socket) + assertTrue(recorder.senders.canSend("socket-1")) + listener.onFailure(socket, IllegalStateException("dropped"), null) + assertFalse(recorder.senders.canSend("socket-1")) + } + + @Test + fun `the wrapper unregisters its sender on close and on cancel`() { + val store = InMemorySocketStore() + val recorder = SocketRecorder(RedactionEngine(RedactionPolicy.recommended()), store) + + val closed = DevConsoleRecordingWebSocket.wrap(FakeWebSocket(), recorder) { "socket-1" } + assertTrue(recorder.senders.canSend("socket-1")) + closed.close(1000, "bye") + assertFalse(recorder.senders.canSend("socket-1")) + + val cancelled = DevConsoleRecordingWebSocket.wrap(FakeWebSocket(), recorder) { "socket-2" } + assertTrue(recorder.senders.canSend("socket-2")) + cancelled.cancel() + assertFalse(recorder.senders.canSend("socket-2")) + } + private fun fakeResponse(): Response = Response .Builder() @@ -172,6 +273,8 @@ class DevConsoleOkHttpWebSocketListenerTest { private class FakeWebSocket : WebSocket { var sendCount = 0 + var sendAccepted = true + val sentTexts = mutableListOf() override fun request(): Request = Request.Builder().url("wss://api.test/socket").build() @@ -179,12 +282,13 @@ class DevConsoleOkHttpWebSocketListenerTest { override fun send(text: String): Boolean { sendCount += 1 - return true + sentTexts += text + return sendAccepted } override fun send(bytes: ByteString): Boolean { sendCount += 1 - return true + return sendAccepted } override fun close( diff --git a/sdk/socket-paho/src/main/kotlin/io/devconsole/socket/paho/DevConsolePahoMqtt.kt b/sdk/socket-paho/src/main/kotlin/io/devconsole/socket/paho/DevConsolePahoMqtt.kt index b22ecf4..efa1860 100644 --- a/sdk/socket-paho/src/main/kotlin/io/devconsole/socket/paho/DevConsolePahoMqtt.kt +++ b/sdk/socket-paho/src/main/kotlin/io/devconsole/socket/paho/DevConsolePahoMqtt.kt @@ -8,6 +8,9 @@ import io.devconsole.socket.MqttFrameMetadata import io.devconsole.socket.SocketDirection import io.devconsole.socket.SocketProtocol import io.devconsole.socket.SocketRecorder +import io.devconsole.socket.SocketSendRequest +import io.devconsole.socket.SocketSendResult +import io.devconsole.socket.SocketSender import org.eclipse.paho.client.mqttv3.IMqttAsyncClient import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken import org.eclipse.paho.client.mqttv3.IMqttToken @@ -15,6 +18,9 @@ import org.eclipse.paho.client.mqttv3.MqttCallback import org.eclipse.paho.client.mqttv3.MqttCallbackExtended import org.eclipse.paho.client.mqttv3.MqttMessage +/** Also enforced by the registry; kept here so a directly-invoked sender cannot publish to no topic. */ +private const val MISSING_TOPIC_REASON = "MQTT publish requires a non-blank topic" + /** Paho adapter that records MQTT callbacks without altering the client's own control flow. */ class DevConsolePahoMqttCallback @JvmOverloads @@ -73,6 +79,15 @@ class DevConsoleRecordingMqttPublisher private constructor( private val recorder: SocketRecorder, val connectionId: String, ) { + /** Publishes through this class's own `publish`, so a registry send is recorded exactly once. */ + init { + recorder.senders.register( + connectionId, + SocketProtocol.MQTT, + SocketSender { request -> sendFromRegistry(request) }, + ) + } + fun publish( topic: String, message: MqttMessage, @@ -93,10 +108,35 @@ class DevConsoleRecordingMqttPublisher private constructor( fun disconnect(): IMqttToken = delegate.disconnect().also { + recorder.senders.unregister(connectionId) recorder.onClosing(connectionId) recorder.onClosed(connectionId) } + /** + * Connection state is checked at send time rather than at registration time: `connectionLost` + * keeps the sender registered because Paho reconnects on its own, and the dashboard should get + * [SocketSendResult.NotConnected] only for as long as the gap actually lasts. + */ + private fun sendFromRegistry(request: SocketSendRequest): SocketSendResult { + val topic = request.topic + return when { + !delegate.isConnected -> SocketSendResult.NotConnected + topic == null -> SocketSendResult.Rejected(MISSING_TOPIC_REASON) + else -> + runCatching { + publish(topic, request.text.toByteArray(Charsets.UTF_8), request.qos, request.retained) + }.fold( + onSuccess = { SocketSendResult.Sent }, + onFailure = { failure -> + SocketSendResult.Rejected( + failure.message?.takeIf(String::isNotBlank) ?: failure.javaClass.simpleName, + ) + }, + ) + } + } + private fun recordSent( topic: String, payload: ByteArray, diff --git a/sdk/socket-paho/src/test/kotlin/io/devconsole/socket/paho/DevConsolePahoMqttTest.kt b/sdk/socket-paho/src/test/kotlin/io/devconsole/socket/paho/DevConsolePahoMqttTest.kt index 647969b..1acb006 100644 --- a/sdk/socket-paho/src/test/kotlin/io/devconsole/socket/paho/DevConsolePahoMqttTest.kt +++ b/sdk/socket-paho/src/test/kotlin/io/devconsole/socket/paho/DevConsolePahoMqttTest.kt @@ -12,6 +12,8 @@ import io.devconsole.socket.SocketDirection import io.devconsole.socket.SocketPayload import io.devconsole.socket.SocketProtocol import io.devconsole.socket.SocketRecorder +import io.devconsole.socket.SocketSendRequest +import io.devconsole.socket.SocketSendResult import org.eclipse.paho.client.mqttv3.DisconnectedBufferOptions import org.eclipse.paho.client.mqttv3.IMqttActionListener import org.eclipse.paho.client.mqttv3.IMqttAsyncClient @@ -132,9 +134,78 @@ class DevConsolePahoMqttTest { assertTrue(connection.messages.isEmpty()) } + @Test + fun `registry send publishes through the publisher and records exactly one sent frame`() { + val store = InMemorySocketStore() + val recorder = SocketRecorder(RedactionEngine(RedactionPolicy.recommended()), store) + val client = FakeMqttAsyncClient() + val publisher = DevConsolePahoMqtt.install(client, recorder) + + assertTrue(recorder.senders.canSend(publisher.connectionId)) + assertEquals(SocketProtocol.MQTT, recorder.senders.protocol(publisher.connectionId)) + + val result = + recorder.senders.send( + publisher.connectionId, + SocketSendRequest("hello", topic = "devconsole/demo/hello", qos = 1, retained = true), + ) + + assertEquals(SocketSendResult.Sent, result) + val stored = store.messages(publisher.connectionId).single() + assertEquals(SocketDirection.SENT, stored.direction) + assertEquals("devconsole/demo/hello", MqttFrameMetadata.topic(stored.contentType)) + assertEquals(1, MqttFrameMetadata.qos(stored.contentType)) + assertEquals(true, MqttFrameMetadata.retained(stored.contentType)) + } + + @Test + fun `a send while disconnected is NotConnected and a broker failure is Rejected`() { + val store = InMemorySocketStore() + val recorder = SocketRecorder(RedactionEngine(RedactionPolicy.recommended()), store) + val client = FakeMqttAsyncClient() + val publisher = DevConsolePahoMqtt.install(client, recorder) + val request = SocketSendRequest("hello", topic = "devconsole/demo/hello") + + client.connected = false + assertEquals(SocketSendResult.NotConnected, recorder.senders.send(publisher.connectionId, request)) + + client.connected = true + client.publishFailure = IllegalStateException("broker refused") + val rejected = recorder.senders.send(publisher.connectionId, request) + assertEquals(SocketSendResult.Rejected("broker refused"), rejected) + + assertTrue(store.messages(publisher.connectionId).isEmpty()) + } + + @Test + fun `connectionLost keeps the sender registered while disconnect removes it`() { + val store = InMemorySocketStore() + val recorder = SocketRecorder(RedactionEngine(RedactionPolicy.recommended()), store) + val client = FakeMqttAsyncClient() + val publisher = DevConsolePahoMqtt.install(client, recorder) + val callback = requireNotNull(client.callback) + + client.connected = false + callback.connectionLost(IllegalStateException("connection dropped")) + + assertTrue(recorder.senders.canSend(publisher.connectionId)) + val sendResult = + recorder.senders.send( + publisher.connectionId, + SocketSendRequest("hello", topic = "devconsole/demo/hello"), + ) + assertEquals(SocketSendResult.NotConnected, sendResult) + + publisher.disconnect() + + assertFalse(recorder.senders.canSend(publisher.connectionId)) + } + private class FakeMqttAsyncClient : IMqttAsyncClient { var callback: MqttCallbackExtended? = null var lastToken: IMqttDeliveryToken? = null + var connected = true + var publishFailure: RuntimeException? = null override fun setCallback(callback: MqttCallback) { this.callback = callback as MqttCallbackExtended @@ -144,7 +215,7 @@ class DevConsolePahoMqttTest { override fun getClientId(): String = "fake-client" - override fun isConnected(): Boolean = true + override fun isConnected(): Boolean = connected override fun connect(): IMqttToken = FakeToken() @@ -190,7 +261,10 @@ class DevConsolePahoMqttTest { payload: ByteArray, qos: Int, retained: Boolean, - ): IMqttDeliveryToken = FakeDeliveryToken().also { lastToken = it } + ): IMqttDeliveryToken { + publishFailure?.let { throw it } + return FakeDeliveryToken().also { lastToken = it } + } override fun publish( topic: String, diff --git a/sdk/socket/api/socket.api b/sdk/socket/api/socket.api index 1bd7c99..bb00b1b 100644 --- a/sdk/socket/api/socket.api +++ b/sdk/socket/api/socket.api @@ -263,11 +263,13 @@ public final class io/devconsole/socket/SocketRecorder { public static final field Companion Lio/devconsole/socket/SocketRecorder$Companion; public static final field MAX_BINARY_FRAME_PREVIEW_BYTES I public static final field MAX_TEXT_PREVIEW_CHARS I - public fun (Lio/devconsole/security/RedactionEngine;Lio/devconsole/socket/SocketStore;ZLkotlin/jvm/functions/Function0;)V - public synthetic fun (Lio/devconsole/security/RedactionEngine;Lio/devconsole/socket/SocketStore;ZLkotlin/jvm/functions/Function0;ILkotlin/jvm/internal/DefaultConstructorMarker;)V - public fun (Lio/devconsole/security/RedactionEngine;Lio/devconsole/socket/SocketStore;ZLkotlin/jvm/functions/Function0;Lio/devconsole/socket/BinaryPreviewPolicy;)V + public fun (Lio/devconsole/security/RedactionEngine;Lio/devconsole/socket/SocketStore;ZLkotlin/jvm/functions/Function0;Lio/devconsole/socket/BinaryPreviewPolicy;Lio/devconsole/socket/SocketSenderRegistry;)V + public synthetic fun (Lio/devconsole/security/RedactionEngine;Lio/devconsole/socket/SocketStore;ZLkotlin/jvm/functions/Function0;Lio/devconsole/socket/BinaryPreviewPolicy;Lio/devconsole/socket/SocketSenderRegistry;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public fun (Lio/devconsole/security/RedactionEngine;Lio/devconsole/socket/SocketStore;ZLkotlin/jvm/functions/Function0;Lio/devconsole/socket/SocketSenderRegistry;)V + public synthetic fun (Lio/devconsole/security/RedactionEngine;Lio/devconsole/socket/SocketStore;ZLkotlin/jvm/functions/Function0;Lio/devconsole/socket/SocketSenderRegistry;ILkotlin/jvm/internal/DefaultConstructorMarker;)V public final fun bindToCurrentSession ()Lio/devconsole/socket/SocketRecorder; public final fun getProtocol ()Lio/devconsole/socket/SocketProtocol; + public final fun getSenders ()Lio/devconsole/socket/SocketSenderRegistry; public final fun onBinaryMessage (Ljava/lang/String;Lio/devconsole/socket/SocketDirection;JLjava/lang/String;)V public final fun onBinaryMessage (Ljava/lang/String;Lio/devconsole/socket/SocketDirection;[BLjava/lang/String;)V public static synthetic fun onBinaryMessage$default (Lio/devconsole/socket/SocketRecorder;Ljava/lang/String;Lio/devconsole/socket/SocketDirection;JLjava/lang/String;ILjava/lang/Object;)V @@ -298,6 +300,78 @@ public final class io/devconsole/socket/SocketRecorder { public final class io/devconsole/socket/SocketRecorder$Companion { } +public final class io/devconsole/socket/SocketSendRequest { + public fun (Ljava/lang/String;Ljava/lang/String;IZ)V + public synthetic fun (Ljava/lang/String;Ljava/lang/String;IZILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1 ()Ljava/lang/String; + public final fun component2 ()Ljava/lang/String; + public final fun component3 ()I + public final fun component4 ()Z + public final fun copy (Ljava/lang/String;Ljava/lang/String;IZ)Lio/devconsole/socket/SocketSendRequest; + public static synthetic fun copy$default (Lio/devconsole/socket/SocketSendRequest;Ljava/lang/String;Ljava/lang/String;IZILjava/lang/Object;)Lio/devconsole/socket/SocketSendRequest; + public fun equals (Ljava/lang/Object;)Z + public final fun getQos ()I + public final fun getRetained ()Z + public final fun getText ()Ljava/lang/String; + public final fun getTopic ()Ljava/lang/String; + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + +public abstract interface class io/devconsole/socket/SocketSendResult { +} + +public final class io/devconsole/socket/SocketSendResult$NotConnected : io/devconsole/socket/SocketSendResult { + public static final field INSTANCE Lio/devconsole/socket/SocketSendResult$NotConnected; + public fun equals (Ljava/lang/Object;)Z + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + +public final class io/devconsole/socket/SocketSendResult$Rejected : io/devconsole/socket/SocketSendResult { + public fun (Ljava/lang/String;)V + public final fun component1 ()Ljava/lang/String; + public final fun copy (Ljava/lang/String;)Lio/devconsole/socket/SocketSendResult$Rejected; + public static synthetic fun copy$default (Lio/devconsole/socket/SocketSendResult$Rejected;Ljava/lang/String;ILjava/lang/Object;)Lio/devconsole/socket/SocketSendResult$Rejected; + public fun equals (Ljava/lang/Object;)Z + public final fun getReason ()Ljava/lang/String; + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + +public final class io/devconsole/socket/SocketSendResult$Sent : io/devconsole/socket/SocketSendResult { + public static final field INSTANCE Lio/devconsole/socket/SocketSendResult$Sent; + public fun equals (Ljava/lang/Object;)Z + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + +public final class io/devconsole/socket/SocketSendResult$Unsupported : io/devconsole/socket/SocketSendResult { + public static final field INSTANCE Lio/devconsole/socket/SocketSendResult$Unsupported; + public fun equals (Ljava/lang/Object;)Z + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + +public abstract interface class io/devconsole/socket/SocketSender { + public abstract fun send (Lio/devconsole/socket/SocketSendRequest;)Lio/devconsole/socket/SocketSendResult; +} + +public final class io/devconsole/socket/SocketSenderRegistry { + public static final field Companion Lio/devconsole/socket/SocketSenderRegistry$Companion; + public static final field MAX_TEXT_BYTES I + public fun ()V + public final fun canSend (Ljava/lang/String;)Z + public final fun clear ()V + public final fun protocol (Ljava/lang/String;)Lio/devconsole/socket/SocketProtocol; + public final fun register (Ljava/lang/String;Lio/devconsole/socket/SocketProtocol;Lio/devconsole/socket/SocketSender;)V + public final fun send (Ljava/lang/String;Lio/devconsole/socket/SocketSendRequest;)Lio/devconsole/socket/SocketSendResult; + public final fun unregister (Ljava/lang/String;)V +} + +public final class io/devconsole/socket/SocketSenderRegistry$Companion { +} + public abstract interface class io/devconsole/socket/SocketStore { public abstract fun append (Lio/devconsole/socket/SocketMessage;)V public fun appendLifecycle (Lio/devconsole/socket/SocketLifecycleEvent;)V diff --git a/sdk/socket/src/main/kotlin/io/devconsole/socket/SocketCapture.kt b/sdk/socket/src/main/kotlin/io/devconsole/socket/SocketCapture.kt index 64d9063..53d8057 100644 --- a/sdk/socket/src/main/kotlin/io/devconsole/socket/SocketCapture.kt +++ b/sdk/socket/src/main/kotlin/io/devconsole/socket/SocketCapture.kt @@ -466,6 +466,12 @@ class SocketRecorder( private val store: SocketStore, private val enabled: Boolean = true, private val clock: () -> Long = System::currentTimeMillis, + /** + * Shared with every copy this recorder produces. Adapters register one sender per live + * connection on the copy they happen to hold, so the copies must resolve the same registry -- + * a per-copy instance would make the dashboard's id look unsendable after any `with*` call. + */ + val senders: SocketSenderRegistry = SocketSenderRegistry(), ) { private var binaryPreviewPolicy: BinaryPreviewPolicy = BinaryPreviewPolicy.NONE private var sessionIdProvider: (() -> String?)? = null @@ -485,7 +491,8 @@ class SocketRecorder( enabled: Boolean, clock: () -> Long, binaryPreviewPolicy: BinaryPreviewPolicy, - ) : this(redaction, store, enabled, clock) { + senders: SocketSenderRegistry = SocketSenderRegistry(), + ) : this(redaction, store, enabled, clock, senders) { this.binaryPreviewPolicy = binaryPreviewPolicy } @@ -502,7 +509,7 @@ class SocketRecorder( * MQTT adapter without either mutating the other's protocol. */ fun withProtocol(protocol: SocketProtocol): SocketRecorder = - SocketRecorder(redaction, store, enabled, clock).also { + SocketRecorder(redaction, store, enabled, clock, senders).also { it.binaryPreviewPolicy = binaryPreviewPolicy it.sessionIdProvider = sessionIdProvider it.capturedSessionId = capturedSessionId @@ -515,7 +522,7 @@ class SocketRecorder( /** Freezes the current app-run for delayed listener callbacks. */ fun bindToCurrentSession(): SocketRecorder = - SocketRecorder(redaction, store, enabled, clock).also { + SocketRecorder(redaction, store, enabled, clock, senders).also { it.binaryPreviewPolicy = binaryPreviewPolicy it.sessionIdProvider = sessionIdProvider val provider = sessionIdProvider diff --git a/sdk/socket/src/main/kotlin/io/devconsole/socket/SocketSenders.kt b/sdk/socket/src/main/kotlin/io/devconsole/socket/SocketSenders.kt new file mode 100644 index 0000000..1f59800 --- /dev/null +++ b/sdk/socket/src/main/kotlin/io/devconsole/socket/SocketSenders.kt @@ -0,0 +1,156 @@ +/** + * @author Shakib + * @since 04/11/26 + */ +package io.devconsole.socket + +/** + * One host-initiated frame, addressed to a connection id by [SocketSenderRegistry]. + * + * [topic], [qos] and [retained] describe an MQTT publish and are ignored by a WebSocket sender. They + * live on the same type because the dashboard composer already posts one payload to both protocols; + * a per-protocol request type would only duplicate it and force the server routes to branch earlier. + */ +data class SocketSendRequest( + val text: String, + val topic: String? = null, + val qos: Int = 0, + val retained: Boolean = false, +) + +/** + * Outcome of [SocketSender.send], modelled as values rather than exceptions so the caller can show + * why a frame did not go out without any adapter having to decide what to throw. + */ +sealed interface SocketSendResult { + /** The transport accepted the frame. The adapter records it as SENT itself, exactly once. */ + data object Sent : SocketSendResult + + /** The transport refused the frame for a caller-visible reason (queue full, invalid parameters). */ + data class Rejected( + val reason: String, + ) : SocketSendResult + + /** The id is unknown, or the MQTT client behind it is currently disconnected. */ + data object NotConnected : SocketSendResult + + /** + * The connection's protocol has no send capability in this build. Reserved so that a protocol + * added later can decline cleanly instead of the dashboard mistaking it for a transport failure. + */ + data object Unsupported : SocketSendResult +} + +/** + * Writes one frame over a live connection. Implementations hand the frame to the host's own socket + * or client wrapper, so redaction and SENT recording stay on the adapter side and are never repeated + * by the registry. + */ +fun interface SocketSender { + fun send(request: SocketSendRequest): SocketSendResult +} + +/** + * Maps connection ids to the adapter that can write on them. + * + * The dashboard only knows ids from the inspector, while socket objects belong to the host app, so + * sending has to resolve an id -- never a socket reference -- at call time. Adapters register when a + * connection opens and unregister when it closes, and every access takes one lock because those + * callbacks arrive on the socket's own thread while the dashboard sends from the Ktor thread. The + * sender call itself is made outside the lock: it is host code of unknown cost. + */ +class SocketSenderRegistry { + private val lock = Any() + private val senders = linkedMapOf() + + /** + * Registers (or replaces) the sender for [connectionId]. Replacing is deliberate: a host that + * wraps an already-open socket with the OkHttp adapter's recording wrapper must hand delivery to + * the wrapper, otherwise the same frame would be recorded once by the listener's sender and once + * more by the wrapper's own `send`. + */ + fun register( + connectionId: String, + protocol: SocketProtocol, + sender: SocketSender, + ) { + synchronized(lock) { senders[connectionId] = Registration(protocol, sender) } + } + + /** Removes [connectionId]'s sender, so a closed connection can no longer be written to by id. */ + fun unregister(connectionId: String) { + synchronized(lock) { senders.remove(connectionId) } + } + + fun canSend(connectionId: String): Boolean = synchronized(lock) { connectionId in senders } + + /** The protocol registered for [connectionId], or null when nothing can write to it. */ + fun protocol(connectionId: String): SocketProtocol? = synchronized(lock) { senders[connectionId]?.protocol } + + /** + * Validates [request] against the registered protocol, then hands it to that adapter. An unknown + * id is [SocketSendResult.NotConnected]; a sender that throws is reported as a rejection so a + * buggy adapter can never take the dashboard's request thread down with it. + */ + fun send( + connectionId: String, + request: SocketSendRequest, + ): SocketSendResult { + val registration = synchronized(lock) { senders[connectionId] } ?: return SocketSendResult.NotConnected + val rejection = rejectionReason(registration.protocol, request) + return if (rejection == null) { + deliver(registration.sender, request) + } else { + SocketSendResult.Rejected(rejection) + } + } + + /** Drops every sender, matching the other capture registries, which are cleared when a session ends. */ + fun clear() { + synchronized(lock) { senders.clear() } + } + + private fun deliver( + sender: SocketSender, + request: SocketSendRequest, + ): SocketSendResult = + runCatching { sender.send(request) }.getOrElse { failure -> + SocketSendResult.Rejected(failure.message?.takeIf(String::isNotBlank) ?: failure.javaClass.simpleName) + } + + /** + * An oversized frame is refused rather than truncated: a truncated frame reads as a protocol + * error to the server, and the inspector already cuts its own text preview at the same size. + */ + private fun rejectionReason( + protocol: SocketProtocol, + request: SocketSendRequest, + ): String? { + if (request.text.encodeToByteArray().size > MAX_TEXT_BYTES) { + return "Frame exceeds the $MAX_TEXT_KIB KiB send limit" + } + return if (protocol == SocketProtocol.MQTT) mqttRejectionReason(request) else null + } + + private fun mqttRejectionReason(request: SocketSendRequest): String? = + when { + request.topic.isNullOrBlank() -> "MQTT publish requires a non-blank topic" + request.qos !in MIN_MQTT_QOS..MAX_MQTT_QOS -> "MQTT qos must be 0, 1 or 2" + else -> null + } + + private data class Registration( + val protocol: SocketProtocol, + val sender: SocketSender, + ) + + companion object { + private const val MAX_TEXT_KIB = 64 + private const val BYTES_PER_KIB = 1024 + private const val MIN_MQTT_QOS = 0 + private const val MAX_MQTT_QOS = 2 + + /** Upper bound for a single send, in UTF-8 bytes, shared with the inspector's text preview cap. */ + const val MAX_TEXT_BYTES: Int = MAX_TEXT_KIB * BYTES_PER_KIB + } +} diff --git a/sdk/socket/src/test/kotlin/io/devconsole/socket/SocketSenderRegistryTest.kt b/sdk/socket/src/test/kotlin/io/devconsole/socket/SocketSenderRegistryTest.kt new file mode 100644 index 0000000..d274daf --- /dev/null +++ b/sdk/socket/src/test/kotlin/io/devconsole/socket/SocketSenderRegistryTest.kt @@ -0,0 +1,149 @@ +/** + * @author Shakib + * @since 04/11/26 + */ +package io.devconsole.socket + +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.assertSame +import org.junit.Assert.assertTrue +import org.junit.Test + +class SocketSenderRegistryTest { + @Test + fun `registered sender receives the request and its result is returned unchanged`() { + val registry = SocketSenderRegistry() + val received = mutableListOf() + registry.register( + "ws-1", + SocketProtocol.WEBSOCKET, + SocketSender { request -> + received += request + SocketSendResult.Sent + }, + ) + + assertTrue(registry.canSend("ws-1")) + assertEquals(SocketProtocol.WEBSOCKET, registry.protocol("ws-1")) + + val request = SocketSendRequest("hello") + assertEquals(SocketSendResult.Sent, registry.send("ws-1", request)) + assertEquals(listOf(request), received) + } + + @Test + fun `unknown and unregistered connections report NotConnected`() { + val registry = SocketSenderRegistry() + + assertEquals(SocketSendResult.NotConnected, registry.send("missing", SocketSendRequest("hi"))) + + registry.register("ws-1", SocketProtocol.WEBSOCKET, SocketSender { SocketSendResult.Sent }) + registry.unregister("ws-1") + + assertFalse(registry.canSend("ws-1")) + assertNull(registry.protocol("ws-1")) + assertEquals(SocketSendResult.NotConnected, registry.send("ws-1", SocketSendRequest("hi"))) + } + + @Test + fun `clear drops every registration`() { + val registry = SocketSenderRegistry() + registry.register("ws-1", SocketProtocol.WEBSOCKET, SocketSender { SocketSendResult.Sent }) + registry.register("mqtt-1", SocketProtocol.MQTT, SocketSender { SocketSendResult.Sent }) + + registry.clear() + + assertFalse(registry.canSend("ws-1")) + assertFalse(registry.canSend("mqtt-1")) + } + + @Test + fun `text over the size cap is rejected before it reaches the sender`() { + var calls = 0 + val registry = SocketSenderRegistry() + registry.register( + "ws-1", + SocketProtocol.WEBSOCKET, + SocketSender { + calls += 1 + SocketSendResult.Sent + }, + ) + val oversized = "x".repeat(SocketSenderRegistry.MAX_TEXT_BYTES + 1) + + val rejected = registry.send("ws-1", SocketSendRequest(oversized)) + + assertTrue(rejected is SocketSendResult.Rejected) + assertEquals(0, calls) + assertEquals( + SocketSendResult.Sent, + registry.send("ws-1", SocketSendRequest("x".repeat(SocketSenderRegistry.MAX_TEXT_BYTES))), + ) + } + + @Test + fun `mqtt needs a topic and a qos in range`() { + var calls = 0 + val registry = SocketSenderRegistry() + registry.register( + "mqtt-1", + SocketProtocol.MQTT, + SocketSender { + calls += 1 + SocketSendResult.Sent + }, + ) + + val rejectedRequests = + listOf( + SocketSendRequest("hi"), + SocketSendRequest("hi", topic = " "), + SocketSendRequest("hi", topic = "a/b", qos = 3), + SocketSendRequest("hi", topic = "a/b", qos = -1), + ) + + assertTrue(rejectedRequests.all { registry.send("mqtt-1", it) is SocketSendResult.Rejected }) + assertEquals(0, calls) + + assertEquals( + SocketSendResult.Sent, + registry.send("mqtt-1", SocketSendRequest("hi", topic = "a/b", qos = 2)), + ) + } + + @Test + fun `websocket ignores the mqtt-only fields`() { + val registry = SocketSenderRegistry() + registry.register("ws-1", SocketProtocol.WEBSOCKET, SocketSender { SocketSendResult.Sent }) + + assertEquals(SocketSendResult.Sent, registry.send("ws-1", SocketSendRequest("hi", qos = 9))) + } + + @Test + fun `a sender that throws becomes a rejection instead of escaping`() { + val registry = SocketSenderRegistry() + registry.register("ws-1", SocketProtocol.WEBSOCKET, SocketSender { error("boom") }) + + assertEquals(SocketSendResult.Rejected("boom"), registry.send("ws-1", SocketSendRequest("hi"))) + } + + @Test + fun `every recorder copy shares the same registry instance`() { + val recorder = SocketRecorder(RedactionEngine(RedactionPolicy.recommended()), InMemorySocketStore()) + + assertSame(recorder.senders, recorder.withProtocol(SocketProtocol.MQTT).senders) + assertSame(recorder.senders, recorder.bindToCurrentSession().senders) + assertSame(recorder.senders, recorder.withSessionIdProvider { "session" }.senders) + assertSame(recorder.senders, recorder.withProtocol(SocketProtocol.MQTT).bindToCurrentSession().senders) + + recorder + .withProtocol(SocketProtocol.MQTT) + .senders + .register("mqtt-1", SocketProtocol.MQTT, SocketSender { SocketSendResult.Sent }) + assertTrue(recorder.senders.canSend("mqtt-1")) + } +} diff --git a/sdk/storage-api/api/storage-api.api b/sdk/storage-api/api/storage-api.api index c4240bd..cd686e2 100644 --- a/sdk/storage-api/api/storage-api.api +++ b/sdk/storage-api/api/storage-api.api @@ -210,12 +210,19 @@ public final class io/devconsole/storage/api/SessionRetentionPolicy { public abstract interface class io/devconsole/storage/api/SessionStore { public abstract fun crash (Ljava/lang/String;JLkotlin/coroutines/Continuation;)Ljava/lang/Object; + public fun delete (Ljava/lang/String;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; public abstract fun end (Ljava/lang/String;JLkotlin/coroutines/Continuation;)Ljava/lang/Object; public abstract fun session (Ljava/lang/String;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; public abstract fun sessions (Lkotlin/coroutines/Continuation;)Ljava/lang/Object; + public fun setPinned (Ljava/lang/String;ZLkotlin/coroutines/Continuation;)Ljava/lang/Object; public abstract fun start (Lio/devconsole/storage/api/StoredSession;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; } +public final class io/devconsole/storage/api/SessionStore$DefaultImpls { + public static fun delete (Lio/devconsole/storage/api/SessionStore;Ljava/lang/String;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; + public static fun setPinned (Lio/devconsole/storage/api/SessionStore;Ljava/lang/String;ZLkotlin/coroutines/Continuation;)Ljava/lang/Object; +} + public final class io/devconsole/storage/api/StoredAttachment { public fun (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;JJZLjava/lang/String;ZLjava/lang/String;Lio/devconsole/storage/api/RedactionApplicability;)V public final fun component1 ()Ljava/lang/String; @@ -334,14 +341,15 @@ public final class io/devconsole/storage/api/StoredEvidenceReport { } public final class io/devconsole/storage/api/StoredSession { - public fun (Ljava/lang/String;Lio/devconsole/storage/api/StoredSessionStatus;JJLjava/lang/Long;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Long;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Integer;Ljava/lang/String;JJ)V - public synthetic fun (Ljava/lang/String;Lio/devconsole/storage/api/StoredSessionStatus;JJLjava/lang/Long;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Long;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Integer;Ljava/lang/String;JJILkotlin/jvm/internal/DefaultConstructorMarker;)V + public fun (Ljava/lang/String;Lio/devconsole/storage/api/StoredSessionStatus;JJLjava/lang/Long;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Long;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Integer;Ljava/lang/String;JJZ)V + public synthetic fun (Ljava/lang/String;Lio/devconsole/storage/api/StoredSessionStatus;JJLjava/lang/Long;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Long;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Integer;Ljava/lang/String;JJZILkotlin/jvm/internal/DefaultConstructorMarker;)V public final fun component1 ()Ljava/lang/String; public final fun component10 ()Ljava/lang/String; public final fun component11 ()Ljava/lang/Integer; public final fun component12 ()Ljava/lang/String; public final fun component13 ()J public final fun component14 ()J + public final fun component15 ()Z public final fun component2 ()Lio/devconsole/storage/api/StoredSessionStatus; public final fun component3 ()J public final fun component4 ()J @@ -350,8 +358,8 @@ public final class io/devconsole/storage/api/StoredSession { public final fun component7 ()Ljava/lang/String; public final fun component8 ()Ljava/lang/Long; public final fun component9 ()Ljava/lang/String; - public final fun copy (Ljava/lang/String;Lio/devconsole/storage/api/StoredSessionStatus;JJLjava/lang/Long;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Long;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Integer;Ljava/lang/String;JJ)Lio/devconsole/storage/api/StoredSession; - public static synthetic fun copy$default (Lio/devconsole/storage/api/StoredSession;Ljava/lang/String;Lio/devconsole/storage/api/StoredSessionStatus;JJLjava/lang/Long;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Long;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Integer;Ljava/lang/String;JJILjava/lang/Object;)Lio/devconsole/storage/api/StoredSession; + public final fun copy (Ljava/lang/String;Lio/devconsole/storage/api/StoredSessionStatus;JJLjava/lang/Long;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Long;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Integer;Ljava/lang/String;JJZ)Lio/devconsole/storage/api/StoredSession; + public static synthetic fun copy$default (Lio/devconsole/storage/api/StoredSession;Ljava/lang/String;Lio/devconsole/storage/api/StoredSessionStatus;JJLjava/lang/Long;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Long;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Integer;Ljava/lang/String;JJZILjava/lang/Object;)Lio/devconsole/storage/api/StoredSession; public fun equals (Ljava/lang/Object;)Z public final fun getAppVersionCode ()Ljava/lang/Long; public final fun getAppVersionName ()Ljava/lang/String; @@ -363,6 +371,7 @@ public final class io/devconsole/storage/api/StoredSession { public final fun getEndedAtMs ()Ljava/lang/Long; public final fun getEstimatedBytes ()J public final fun getId ()Ljava/lang/String; + public final fun getPinned ()Z public final fun getRecordCount ()J public final fun getStartedAtMonotonicNs ()J public final fun getStartedAtMs ()J diff --git a/sdk/storage-api/src/main/kotlin/io/devconsole/storage/api/EventStore.kt b/sdk/storage-api/src/main/kotlin/io/devconsole/storage/api/EventStore.kt index c005c5a..d5104d3 100644 --- a/sdk/storage-api/src/main/kotlin/io/devconsole/storage/api/EventStore.kt +++ b/sdk/storage-api/src/main/kotlin/io/devconsole/storage/api/EventStore.kt @@ -200,6 +200,8 @@ data class StoredSession( val deviceOsVersion: String? = null, val recordCount: Long = 0, val estimatedBytes: Long = 0, + /** Retention never deletes a pinned run; only an explicit delete or unpin does. */ + val pinned: Boolean = false, ) /** Durable app-run lifecycle and history source. */ @@ -219,6 +221,15 @@ interface SessionStore { suspend fun sessions(): List suspend fun session(sessionId: String): StoredSession? + + /** Deletes a completed or crashed run with all its captures; false for the active run or an unknown id. */ + suspend fun delete(sessionId: String): Boolean = false + + /** Pins or unpins a completed or crashed run; false when the run cannot be pinned. */ + suspend fun setPinned( + sessionId: String, + pinned: Boolean, + ): Boolean = false } /** Limits applied to retained app-run sessions by a persistence implementation. */ diff --git a/sdk/storage-room/api/storage-room.api b/sdk/storage-room/api/storage-room.api index df4b6fe..aa9e5ce 100644 --- a/sdk/storage-room/api/storage-room.api +++ b/sdk/storage-room/api/storage-room.api @@ -88,6 +88,7 @@ public abstract class io/devconsole/storage/room/DevConsoleDatabase : androidx/r public static final field MIGRATION_2_3 Landroidx/room/migration/Migration; public static final field MIGRATION_3_4 Landroidx/room/migration/Migration; public static final field MIGRATION_4_5 Landroidx/room/migration/Migration; + public static final field MIGRATION_5_6 Landroidx/room/migration/Migration; public fun ()V public abstract fun attachmentDao ()Lio/devconsole/storage/room/AttachmentDao; public abstract fun captureRuleDao ()Lio/devconsole/storage/room/CaptureRuleDao; @@ -113,6 +114,7 @@ public final class io/devconsole/storage/room/DevConsoleDatabase_Impl : io/devco } public abstract interface class io/devconsole/storage/room/EventDao { + public abstract fun activeSessionTrimCandidates (Ljava/lang/String;)Ljava/util/List; public abstract fun deleteByIds (Ljava/util/List;)V public abstract fun deleteOlderThan (J)I public abstract fun deleteSession (Ljava/lang/String;)V @@ -120,8 +122,7 @@ public abstract interface class io/devconsole/storage/room/EventDao { public abstract fun eventCount ()J public abstract fun eventsForSession (Ljava/lang/String;)Ljava/util/List; public abstract fun insertAll (Ljava/util/List;)V - public abstract fun oldestLowSeverityFirst (I)Ljava/util/List; - public abstract fun oldestUnbookmarkedLowSeverityFirstForSession (Ljava/lang/String;I)Ljava/util/List; + public abstract fun quotaCandidates ()Ljava/util/List; public abstract fun recentEvents (I)Ljava/util/List; public abstract fun recentEventsByPlugin (Ljava/util/List;I)Ljava/util/List; public abstract fun recentEventsForSession (Ljava/lang/String;I)Ljava/util/List; @@ -132,6 +133,7 @@ public abstract interface class io/devconsole/storage/room/EventDao { public final class io/devconsole/storage/room/EventDao_Impl : io/devconsole/storage/room/EventDao { public fun (Landroidx/room/RoomDatabase;)V + public fun activeSessionTrimCandidates (Ljava/lang/String;)Ljava/util/List; public fun deleteByIds (Ljava/util/List;)V public fun deleteOlderThan (J)I public fun deleteSession (Ljava/lang/String;)V @@ -140,8 +142,7 @@ public final class io/devconsole/storage/room/EventDao_Impl : io/devconsole/stor public fun eventsForSession (Ljava/lang/String;)Ljava/util/List; public static fun getRequiredConverters ()Ljava/util/List; public fun insertAll (Ljava/util/List;)V - public fun oldestLowSeverityFirst (I)Ljava/util/List; - public fun oldestUnbookmarkedLowSeverityFirstForSession (Ljava/lang/String;I)Ljava/util/List; + public fun quotaCandidates ()Ljava/util/List; public fun recentEvents (I)Ljava/util/List; public fun recentEventsByPlugin (Ljava/util/List;I)Ljava/util/List; public fun recentEventsForSession (Ljava/lang/String;I)Ljava/util/List; @@ -168,6 +169,12 @@ public final class io/devconsole/storage/room/EventEntity { public fun (Ljava/lang/String;Ljava/lang/String;JLjava/lang/String;Ljava/lang/String;JJILjava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;I)V } +public final class io/devconsole/storage/room/EventPruneCandidate { + public field bytes J + public field id Ljava/lang/String; + public fun ()V +} + public final class io/devconsole/storage/room/EventPruneResult { public fun (IIJJ)V public final fun component1 ()I @@ -347,10 +354,12 @@ public final class io/devconsole/storage/room/RoomSessionStore : io/devconsole/s public fun (Lio/devconsole/storage/room/DevConsoleDatabase;Lio/devconsole/storage/room/FileAttachmentStore;Lio/devconsole/storage/api/SessionRetentionPolicy;Lio/devconsole/storage/room/RoomRetentionCoordinator;Lkotlin/jvm/functions/Function0;)V public synthetic fun (Lio/devconsole/storage/room/DevConsoleDatabase;Lio/devconsole/storage/room/FileAttachmentStore;Lio/devconsole/storage/api/SessionRetentionPolicy;Lio/devconsole/storage/room/RoomRetentionCoordinator;Lkotlin/jvm/functions/Function0;ILkotlin/jvm/internal/DefaultConstructorMarker;)V public fun crash (Ljava/lang/String;JLkotlin/coroutines/Continuation;)Ljava/lang/Object; + public fun delete (Ljava/lang/String;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; public fun end (Ljava/lang/String;JLkotlin/coroutines/Continuation;)Ljava/lang/Object; public final fun enforceRetention (Ljava/lang/String;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; public fun session (Ljava/lang/String;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; public fun sessions (Lkotlin/coroutines/Continuation;)Ljava/lang/Object; + public fun setPinned (Ljava/lang/String;ZLkotlin/coroutines/Continuation;)Ljava/lang/Object; public fun start (Lio/devconsole/storage/api/StoredSession;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; public final fun withPolicy (Lio/devconsole/storage/api/SessionRetentionPolicy;)Lio/devconsole/storage/room/RoomSessionStore; public final fun withRecovery (Lkotlin/jvm/functions/Function0;Lkotlin/jvm/functions/Function1;)Lio/devconsole/storage/room/RoomSessionStore; @@ -378,6 +387,7 @@ public abstract interface class io/devconsole/storage/room/SessionDao { public abstract fun session (Ljava/lang/String;)Lio/devconsole/storage/room/SessionEntity; public abstract fun sessionCount ()J public abstract fun sessions ()Ljava/util/List; + public abstract fun setPinned (Ljava/lang/String;Z)I public abstract fun totalEstimatedBytes ()J } @@ -396,6 +406,7 @@ public final class io/devconsole/storage/room/SessionDao_Impl : io/devconsole/st public fun session (Ljava/lang/String;)Lio/devconsole/storage/room/SessionEntity; public fun sessionCount ()J public fun sessions ()Ljava/util/List; + public fun setPinned (Ljava/lang/String;Z)I public fun totalEstimatedBytes ()J } @@ -410,15 +421,17 @@ public final class io/devconsole/storage/room/SessionEntity { public final field endedAtMs Ljava/lang/Long; public final field estimatedBytes J public final field id Ljava/lang/String; + public final field pinned Z public final field recordCount J public final field startedAtMonotonicNs J public final field startedAtMs J public final field status Ljava/lang/String; - public fun (Ljava/lang/String;Ljava/lang/String;JJLjava/lang/Long;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Long;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Integer;Ljava/lang/String;JJ)V + public fun (Ljava/lang/String;Ljava/lang/String;JJLjava/lang/Long;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Long;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Integer;Ljava/lang/String;JJZ)V } public final class io/devconsole/storage/room/SessionRetentionPruner { public fun (Lio/devconsole/storage/room/DevConsoleDatabase;Lio/devconsole/storage/room/FileAttachmentStore;)V + public final fun deleteFinished (Ljava/lang/String;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; public final fun prune (Lio/devconsole/storage/api/SessionRetentionPolicy;Ljava/lang/String;JLkotlin/coroutines/Continuation;)Ljava/lang/Object; } diff --git a/sdk/storage-room/schemas/io.devconsole.storage.room.DevConsoleDatabase/6.json b/sdk/storage-room/schemas/io.devconsole.storage.room.DevConsoleDatabase/6.json new file mode 100644 index 0000000..f0455e6 --- /dev/null +++ b/sdk/storage-room/schemas/io.devconsole.storage.room.DevConsoleDatabase/6.json @@ -0,0 +1,603 @@ +{ + "formatVersion": 1, + "database": { + "version": 6, + "identityHash": "f3e9d762e3e99547af47481cf770e1b5", + "entities": [ + { + "tableName": "events", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `session_id` TEXT NOT NULL, `sequence` INTEGER NOT NULL, `plugin_id` TEXT NOT NULL, `type` TEXT NOT NULL, `wall_time_ms` INTEGER NOT NULL, `mono_time_ns` INTEGER NOT NULL, `severity` INTEGER NOT NULL, `summary` TEXT NOT NULL, `correlation_id` TEXT, `tags_json` TEXT NOT NULL, `payload_json` TEXT, `attachment_id` TEXT, `schema_version` INTEGER NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "sessionId", + "columnName": "session_id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "sequence", + "columnName": "sequence", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "pluginId", + "columnName": "plugin_id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "type", + "columnName": "type", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "wallTimeMs", + "columnName": "wall_time_ms", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "monoTimeNs", + "columnName": "mono_time_ns", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "severity", + "columnName": "severity", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "summary", + "columnName": "summary", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "correlationId", + "columnName": "correlation_id", + "affinity": "TEXT" + }, + { + "fieldPath": "tagsJson", + "columnName": "tags_json", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "payloadJson", + "columnName": "payload_json", + "affinity": "TEXT" + }, + { + "fieldPath": "attachmentId", + "columnName": "attachment_id", + "affinity": "TEXT" + }, + { + "fieldPath": "schemaVersion", + "columnName": "schema_version", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_events_session_id", + "unique": false, + "columnNames": [ + "session_id" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_events_session_id` ON `${TABLE_NAME}` (`session_id`)" + }, + { + "name": "index_events_plugin_id", + "unique": false, + "columnNames": [ + "plugin_id" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_events_plugin_id` ON `${TABLE_NAME}` (`plugin_id`)" + }, + { + "name": "index_events_type", + "unique": false, + "columnNames": [ + "type" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_events_type` ON `${TABLE_NAME}` (`type`)" + }, + { + "name": "index_events_wall_time_ms", + "unique": false, + "columnNames": [ + "wall_time_ms" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_events_wall_time_ms` ON `${TABLE_NAME}` (`wall_time_ms`)" + }, + { + "name": "index_events_correlation_id", + "unique": false, + "columnNames": [ + "correlation_id" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_events_correlation_id` ON `${TABLE_NAME}` (`correlation_id`)" + } + ] + }, + { + "tableName": "attachments", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `event_id` TEXT NOT NULL, `session_id` TEXT NOT NULL, `mime_type` TEXT NOT NULL, `original_length` INTEGER NOT NULL, `stored_length` INTEGER NOT NULL, `truncated` INTEGER NOT NULL, `sha256` TEXT NOT NULL, `is_redacted` INTEGER NOT NULL, `relative_path` TEXT NOT NULL, `created_wall_time_ms` INTEGER NOT NULL, `is_bookmarked` INTEGER NOT NULL, `pending_deletion` INTEGER NOT NULL, `redaction_applicability` TEXT NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "eventId", + "columnName": "event_id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "sessionId", + "columnName": "session_id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "mimeType", + "columnName": "mime_type", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "originalLength", + "columnName": "original_length", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "storedLength", + "columnName": "stored_length", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "truncated", + "columnName": "truncated", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "sha256", + "columnName": "sha256", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "isRedacted", + "columnName": "is_redacted", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "relativePath", + "columnName": "relative_path", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdWallTimeMs", + "columnName": "created_wall_time_ms", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isBookmarked", + "columnName": "is_bookmarked", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "pendingDeletion", + "columnName": "pending_deletion", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "redactionApplicability", + "columnName": "redaction_applicability", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_attachments_event_id", + "unique": false, + "columnNames": [ + "event_id" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_attachments_event_id` ON `${TABLE_NAME}` (`event_id`)" + }, + { + "name": "index_attachments_session_id", + "unique": false, + "columnNames": [ + "session_id" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_attachments_session_id` ON `${TABLE_NAME}` (`session_id`)" + }, + { + "name": "index_attachments_created_wall_time_ms", + "unique": false, + "columnNames": [ + "created_wall_time_ms" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_attachments_created_wall_time_ms` ON `${TABLE_NAME}` (`created_wall_time_ms`)" + } + ] + }, + { + "tableName": "timeline_annotations", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`event_id` TEXT NOT NULL, `bookmarked` INTEGER NOT NULL, `note` TEXT, PRIMARY KEY(`event_id`))", + "fields": [ + { + "fieldPath": "eventId", + "columnName": "event_id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "bookmarked", + "columnName": "bookmarked", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "note", + "columnName": "note", + "affinity": "TEXT" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "event_id" + ] + } + }, + { + "tableName": "sessions", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `status` TEXT NOT NULL, `started_at_ms` INTEGER NOT NULL, `started_at_monotonic_ns` INTEGER NOT NULL, `ended_at_ms` INTEGER, `application_id` TEXT, `app_version_name` TEXT, `app_version_code` INTEGER, `build_type` TEXT, `device_model` TEXT, `device_api_level` INTEGER, `device_os_version` TEXT, `record_count` INTEGER NOT NULL, `estimated_bytes` INTEGER NOT NULL, `pinned` INTEGER NOT NULL DEFAULT 0, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "status", + "columnName": "status", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "startedAtMs", + "columnName": "started_at_ms", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "startedAtMonotonicNs", + "columnName": "started_at_monotonic_ns", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "endedAtMs", + "columnName": "ended_at_ms", + "affinity": "INTEGER" + }, + { + "fieldPath": "applicationId", + "columnName": "application_id", + "affinity": "TEXT" + }, + { + "fieldPath": "appVersionName", + "columnName": "app_version_name", + "affinity": "TEXT" + }, + { + "fieldPath": "appVersionCode", + "columnName": "app_version_code", + "affinity": "INTEGER" + }, + { + "fieldPath": "buildType", + "columnName": "build_type", + "affinity": "TEXT" + }, + { + "fieldPath": "deviceModel", + "columnName": "device_model", + "affinity": "TEXT" + }, + { + "fieldPath": "deviceApiLevel", + "columnName": "device_api_level", + "affinity": "INTEGER" + }, + { + "fieldPath": "deviceOsVersion", + "columnName": "device_os_version", + "affinity": "TEXT" + }, + { + "fieldPath": "recordCount", + "columnName": "record_count", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "estimatedBytes", + "columnName": "estimated_bytes", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "pinned", + "columnName": "pinned", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_sessions_status", + "unique": false, + "columnNames": [ + "status" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_sessions_status` ON `${TABLE_NAME}` (`status`)" + }, + { + "name": "index_sessions_started_at_ms", + "unique": false, + "columnNames": [ + "started_at_ms" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_sessions_started_at_ms` ON `${TABLE_NAME}` (`started_at_ms`)" + }, + { + "name": "index_sessions_ended_at_ms", + "unique": false, + "columnNames": [ + "ended_at_ms" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_sessions_ended_at_ms` ON `${TABLE_NAME}` (`ended_at_ms`)" + } + ] + }, + { + "tableName": "capture_rules", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `host` TEXT NOT NULL, `method` TEXT, `path_prefix` TEXT, `enabled` INTEGER NOT NULL, `position` INTEGER NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "host", + "columnName": "host", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "method", + "columnName": "method", + "affinity": "TEXT" + }, + { + "fieldPath": "pathPrefix", + "columnName": "path_prefix", + "affinity": "TEXT" + }, + { + "fieldPath": "enabled", + "columnName": "enabled", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "position", + "columnName": "position", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + } + }, + { + "tableName": "evidence_items", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `session_id` TEXT NOT NULL, `kind` TEXT NOT NULL, `subject_id` TEXT NOT NULL, `label` TEXT NOT NULL, `flagged_at_ms` INTEGER NOT NULL, `snapshot_json` TEXT NOT NULL, `attachment_id` TEXT, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "sessionId", + "columnName": "session_id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "subjectId", + "columnName": "subject_id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "label", + "columnName": "label", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "flaggedAtMs", + "columnName": "flagged_at_ms", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "snapshotJson", + "columnName": "snapshot_json", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "attachmentId", + "columnName": "attachment_id", + "affinity": "TEXT" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_evidence_items_subject", + "unique": true, + "columnNames": [ + "session_id", + "kind", + "subject_id" + ], + "orders": [], + "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_evidence_items_subject` ON `${TABLE_NAME}` (`session_id`, `kind`, `subject_id`)" + }, + { + "name": "index_evidence_items_session_id", + "unique": false, + "columnNames": [ + "session_id" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_evidence_items_session_id` ON `${TABLE_NAME}` (`session_id`)" + } + ] + }, + { + "tableName": "evidence_reports", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`session_id` TEXT NOT NULL, `severity` TEXT NOT NULL, `summary` TEXT, `expected` TEXT, `actual` TEXT, `updated_at_ms` INTEGER NOT NULL, PRIMARY KEY(`session_id`))", + "fields": [ + { + "fieldPath": "sessionId", + "columnName": "session_id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "severity", + "columnName": "severity", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "summary", + "columnName": "summary", + "affinity": "TEXT" + }, + { + "fieldPath": "expected", + "columnName": "expected", + "affinity": "TEXT" + }, + { + "fieldPath": "actual", + "columnName": "actual", + "affinity": "TEXT" + }, + { + "fieldPath": "updatedAtMs", + "columnName": "updated_at_ms", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "session_id" + ] + } + } + ], + "setupQueries": [ + "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)", + "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, 'f3e9d762e3e99547af47481cf770e1b5')" + ] + } +} \ No newline at end of file diff --git a/sdk/storage-room/src/androidTest/kotlin/io/devconsole/storage/room/EvidenceCascadeDeletionInstrumentedTest.kt b/sdk/storage-room/src/androidTest/kotlin/io/devconsole/storage/room/EvidenceCascadeDeletionInstrumentedTest.kt index da65eb4..e9f0b7d 100644 --- a/sdk/storage-room/src/androidTest/kotlin/io/devconsole/storage/room/EvidenceCascadeDeletionInstrumentedTest.kt +++ b/sdk/storage-room/src/androidTest/kotlin/io/devconsole/storage/room/EvidenceCascadeDeletionInstrumentedTest.kt @@ -57,7 +57,7 @@ class EvidenceCascadeDeletionInstrumentedTest { runBlocking { val sessionId = UUID.randomUUID().toString() database.sessionDao().insertIfAbsent( - SessionEntity(sessionId, "COMPLETED", 0, 0, 0L, null, null, null, null, null, null, null, 0, 0), + SessionEntity(sessionId, "COMPLETED", 0, 0, 0L, null, null, null, null, null, null, null, 0, 0, false), ) val evidenceStore = RoomEvidenceStore(database) evidenceStore.flag( diff --git a/sdk/storage-room/src/androidTest/kotlin/io/devconsole/storage/room/Migration5To6InstrumentedTest.kt b/sdk/storage-room/src/androidTest/kotlin/io/devconsole/storage/room/Migration5To6InstrumentedTest.kt new file mode 100644 index 0000000..adc7255 --- /dev/null +++ b/sdk/storage-room/src/androidTest/kotlin/io/devconsole/storage/room/Migration5To6InstrumentedTest.kt @@ -0,0 +1,48 @@ +/** + * @author Shakib + * @since 03/11/26 + */ +package io.devconsole.storage.room + +import androidx.room.testing.MigrationTestHelper +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith + +/** [DevConsoleDatabase.MIGRATION_5_6] adds `sessions.pinned`, defaulting every existing run to unpinned. */ +@RunWith(AndroidJUnit4::class) +class Migration5To6InstrumentedTest { + @get:Rule + val helper: MigrationTestHelper = + MigrationTestHelper( + InstrumentationRegistry.getInstrumentation(), + DevConsoleDatabase::class.java, + ) + + @Test + fun migratingAV5DatabaseKeepsEveryRunAndLeavesThemUnpinned() { + val v5 = helper.createDatabase(TEST_DB_NAME, 5) + v5.execSQL( + "INSERT INTO sessions " + + "(id, status, started_at_ms, started_at_monotonic_ns, record_count, estimated_bytes) " + + "VALUES ('session-1', 'COMPLETED', 0, 0, 2, 100)", + ) + v5.close() + + val v6 = helper.runMigrationsAndValidate(TEST_DB_NAME, 6, true, DevConsoleDatabase.MIGRATION_5_6) + + v6.query("SELECT pinned FROM sessions WHERE id = 'session-1'").use { cursor -> + assertTrue(cursor.moveToFirst()) + assertEquals(0, cursor.getInt(0)) + } + v6.close() + } + + private companion object { + const val TEST_DB_NAME = "migration-5-6-test" + } +} diff --git a/sdk/storage-room/src/androidTest/kotlin/io/devconsole/storage/room/RoomEventStoreInstrumentedTest.kt b/sdk/storage-room/src/androidTest/kotlin/io/devconsole/storage/room/RoomEventStoreInstrumentedTest.kt index 50e4590..72e55eb 100644 --- a/sdk/storage-room/src/androidTest/kotlin/io/devconsole/storage/room/RoomEventStoreInstrumentedTest.kt +++ b/sdk/storage-room/src/androidTest/kotlin/io/devconsole/storage/room/RoomEventStoreInstrumentedTest.kt @@ -76,6 +76,9 @@ class RoomEventStoreInstrumentedTest { fun retainedEventsPluginFilterSurvivesACrowdedSessionAndACrashedPreviousRun() = runBlocking { val store = RoomEventStore(database, RoomRetentionCoordinator()) + // Real wall times: the first insert runs the age prune, and 1970 timestamps (0..50 ms) + // were deleted as expired before the query ever ran, failing the test for the wrong reason. + val base = System.currentTimeMillis() - 60_000 val crash = StoredEvent( id = "crash-1", @@ -83,7 +86,7 @@ class RoomEventStoreInstrumentedTest { sequence = 0, pluginId = "crash", type = "crash.uncaught", - wallTimeMs = 0, + wallTimeMs = base, monoTimeNs = 0, severity = 5, summary = "fatal", @@ -96,7 +99,7 @@ class RoomEventStoreInstrumentedTest { sequence = index.toLong(), pluginId = "logs", type = "logs.line", - wallTimeMs = (index + 1).toLong(), + wallTimeMs = base + index + 1, monoTimeNs = (index + 1).toLong(), severity = 1, summary = "line $index", diff --git a/sdk/storage-room/src/main/java/io/devconsole/storage/room/DevConsoleDatabase.java b/sdk/storage-room/src/main/java/io/devconsole/storage/room/DevConsoleDatabase.java index 9ada8a6..1935600 100644 --- a/sdk/storage-room/src/main/java/io/devconsole/storage/room/DevConsoleDatabase.java +++ b/sdk/storage-room/src/main/java/io/devconsole/storage/room/DevConsoleDatabase.java @@ -16,7 +16,7 @@ EvidenceItemEntity.class, EvidenceReportEntity.class }, - version = 5, + version = 6, exportSchema = true) public abstract class DevConsoleDatabase extends RoomDatabase { public static final Migration MIGRATION_1_2 = new Migration(1, 2) { @@ -106,6 +106,14 @@ public void migrate(@NonNull SupportSQLiteDatabase database) { } }; + /** Pinned runs are kept by retention until unpinned. */ + public static final Migration MIGRATION_5_6 = new Migration(5, 6) { + @Override + public void migrate(@NonNull SupportSQLiteDatabase database) { + database.execSQL("ALTER TABLE `sessions` ADD COLUMN `pinned` INTEGER NOT NULL DEFAULT 0"); + } + }; + public abstract EventDao eventDao(); public abstract AttachmentDao attachmentDao(); public abstract TimelineAnnotationDao timelineAnnotationDao(); diff --git a/sdk/storage-room/src/main/java/io/devconsole/storage/room/EventDao.java b/sdk/storage-room/src/main/java/io/devconsole/storage/room/EventDao.java index fa77be8..7768a5d 100644 --- a/sdk/storage-room/src/main/java/io/devconsole/storage/room/EventDao.java +++ b/sdk/storage-room/src/main/java/io/devconsole/storage/room/EventDao.java @@ -75,15 +75,31 @@ public interface EventDao { ") ORDER BY mono_time_ns ASC, sequence ASC, id ASC") List recentEvents(int limit); - @Query("SELECT id FROM events ORDER BY severity ASC, wall_time_ms ASC LIMIT :limit") - List oldestLowSeverityFirst(int limit); + @Query("SELECT id, 96 + LENGTH(CAST(id AS BLOB)) + LENGTH(CAST(session_id AS BLOB)) + " + + "LENGTH(CAST(plugin_id AS BLOB)) + LENGTH(CAST(type AS BLOB)) + " + + "LENGTH(CAST(summary AS BLOB)) + LENGTH(CAST(tags_json AS BLOB)) + " + + "LENGTH(CAST(COALESCE(correlation_id, '') AS BLOB)) + " + + "LENGTH(CAST(COALESCE(payload_json, '') AS BLOB)) + " + + "LENGTH(CAST(COALESCE(attachment_id, '') AS BLOB)) AS bytes " + + "FROM events WHERE id NOT IN (SELECT event_id FROM timeline_annotations WHERE bookmarked = 1) " + + "ORDER BY severity ASC, wall_time_ms ASC, sequence ASC, id ASC") + List quotaCandidates(); + + @Query("SELECT id, 96 + LENGTH(CAST(id AS BLOB)) + LENGTH(CAST(session_id AS BLOB)) + " + + "LENGTH(CAST(plugin_id AS BLOB)) + LENGTH(CAST(type AS BLOB)) + " + + "LENGTH(CAST(summary AS BLOB)) + LENGTH(CAST(tags_json AS BLOB)) + " + + "LENGTH(CAST(COALESCE(correlation_id, '') AS BLOB)) + " + + "LENGTH(CAST(COALESCE(payload_json, '') AS BLOB)) + " + + "LENGTH(CAST(COALESCE(attachment_id, '') AS BLOB)) AS bytes " + + "FROM events WHERE session_id = :sessionId " + + "AND id NOT IN (SELECT event_id FROM timeline_annotations WHERE bookmarked = 1) " + + "AND NOT EXISTS (SELECT 1 FROM attachments WHERE attachments.event_id = events.id) " + + "ORDER BY severity ASC, wall_time_ms ASC, sequence ASC, id ASC") + List activeSessionTrimCandidates(String sessionId); @Query("DELETE FROM events WHERE id IN (:ids)") void deleteByIds(List ids); - @Query("SELECT id FROM events WHERE session_id = :sessionId AND id NOT IN (SELECT event_id FROM timeline_annotations WHERE bookmarked = 1) AND NOT EXISTS (SELECT 1 FROM attachments WHERE attachments.event_id = events.id) ORDER BY severity ASC, wall_time_ms ASC LIMIT :limit") - List oldestUnbookmarkedLowSeverityFirstForSession(String sessionId, int limit); - /** Distinct owning sessions for rows a global age-based prune is about to delete, captured before the delete. */ @Query("SELECT DISTINCT session_id FROM events WHERE wall_time_ms < :cutoffEpochMs") List sessionIdsOlderThan(long cutoffEpochMs); diff --git a/sdk/storage-room/src/main/java/io/devconsole/storage/room/EventPruneCandidate.java b/sdk/storage-room/src/main/java/io/devconsole/storage/room/EventPruneCandidate.java new file mode 100644 index 0000000..142c5ad --- /dev/null +++ b/sdk/storage-room/src/main/java/io/devconsole/storage/room/EventPruneCandidate.java @@ -0,0 +1,18 @@ +/** + * @author Shakib + * @since 04/11/26 + */ +package io.devconsole.storage.room; + +import androidx.room.ColumnInfo; + +/** Lightweight ordered event projection used by retention scans. */ +public final class EventPruneCandidate { + @ColumnInfo(name = "id") + public String id; + + @ColumnInfo(name = "bytes") + public long bytes; + + public EventPruneCandidate() {} +} diff --git a/sdk/storage-room/src/main/java/io/devconsole/storage/room/SessionDao.java b/sdk/storage-room/src/main/java/io/devconsole/storage/room/SessionDao.java index ca27381..b714af5 100644 --- a/sdk/storage-room/src/main/java/io/devconsole/storage/room/SessionDao.java +++ b/sdk/storage-room/src/main/java/io/devconsole/storage/room/SessionDao.java @@ -19,12 +19,15 @@ public interface SessionDao { @Query("SELECT * FROM sessions ORDER BY started_at_ms DESC, id DESC") List sessions(); - @Query("SELECT * FROM sessions WHERE status IN ('COMPLETED', 'CRASHED') AND COALESCE(ended_at_ms, started_at_ms) < :cutoffEpochMs ORDER BY COALESCE(ended_at_ms, started_at_ms) ASC, id ASC") + @Query("SELECT * FROM sessions WHERE status IN ('COMPLETED', 'CRASHED') AND pinned = 0 AND COALESCE(ended_at_ms, started_at_ms) < :cutoffEpochMs ORDER BY COALESCE(ended_at_ms, started_at_ms) ASC, id ASC") List expiredCompleted(long cutoffEpochMs); - @Query("SELECT * FROM sessions WHERE status IN ('COMPLETED', 'CRASHED') ORDER BY COALESCE(ended_at_ms, started_at_ms) ASC, id ASC") + @Query("SELECT * FROM sessions WHERE status IN ('COMPLETED', 'CRASHED') AND pinned = 0 ORDER BY COALESCE(ended_at_ms, started_at_ms) ASC, id ASC") List completedOldestFirst(); + @Query("UPDATE sessions SET pinned = :pinned WHERE id = :sessionId AND status IN ('COMPLETED', 'CRASHED')") + int setPinned(String sessionId, boolean pinned); + @Query("SELECT * FROM sessions WHERE status = 'DELETING' ORDER BY COALESCE(ended_at_ms, started_at_ms) ASC, id ASC") List deletingSessions(); diff --git a/sdk/storage-room/src/main/java/io/devconsole/storage/room/SessionEntity.java b/sdk/storage-room/src/main/java/io/devconsole/storage/room/SessionEntity.java index 7179a0e..b74a803 100644 --- a/sdk/storage-room/src/main/java/io/devconsole/storage/room/SessionEntity.java +++ b/sdk/storage-room/src/main/java/io/devconsole/storage/room/SessionEntity.java @@ -30,12 +30,13 @@ public final class SessionEntity { @Nullable @ColumnInfo(name = "device_os_version") public final String deviceOsVersion; @ColumnInfo(name = "record_count") public final long recordCount; @ColumnInfo(name = "estimated_bytes") public final long estimatedBytes; + @ColumnInfo(name = "pinned", defaultValue = "0") public final boolean pinned; public SessionEntity(@NonNull String id, @NonNull String status, long startedAtMs, long startedAtMonotonicNs, @Nullable Long endedAtMs, @Nullable String applicationId, @Nullable String appVersionName, @Nullable Long appVersionCode, @Nullable String buildType, @Nullable String deviceModel, @Nullable Integer deviceApiLevel, - @Nullable String deviceOsVersion, long recordCount, long estimatedBytes) { + @Nullable String deviceOsVersion, long recordCount, long estimatedBytes, boolean pinned) { this.id = id; this.status = status; this.startedAtMs = startedAtMs; @@ -50,5 +51,6 @@ public SessionEntity(@NonNull String id, @NonNull String status, long startedAtM this.deviceOsVersion = deviceOsVersion; this.recordCount = recordCount; this.estimatedBytes = estimatedBytes; + this.pinned = pinned; } } diff --git a/sdk/storage-room/src/main/kotlin/io/devconsole/storage/room/EventQuotaPruner.kt b/sdk/storage-room/src/main/kotlin/io/devconsole/storage/room/EventQuotaPruner.kt index dbc8543..e739217 100644 --- a/sdk/storage-room/src/main/kotlin/io/devconsole/storage/room/EventQuotaPruner.kt +++ b/sdk/storage-room/src/main/kotlin/io/devconsole/storage/room/EventQuotaPruner.kt @@ -12,7 +12,7 @@ data class EventPruneResult( ) /** - * Deletes expired events, then bounded batches of the oldest lowest-severity quota candidates. + * Deletes expired events, then selects the oldest lowest-severity quota candidates in one ordered scan. * * This prune is global (row-first), not session-scoped, so it can remove rows belonging to any * session -- not just the one whose write triggered it. [onSessionsPruned] is the correction hook @@ -50,30 +50,34 @@ class EventQuotaPruner( affectedSessions += eventDao.sessionIdsOlderThan(cutoffEpochMs) eventDao.deleteOlderThan(cutoffEpochMs) } - var count = eventDao.eventCount() - var bytes = eventDao.estimatedStoredBytes() - var quotaDeleted = 0 - while (count > maxEvents || bytes > maxBytes) { - val countExcess = (count - maxEvents).coerceAtLeast(0) - val limit = - countExcess - .coerceAtLeast(1) - .coerceAtMost(PRUNE_BATCH_SIZE.toLong()) - .toInt() - val ids = eventDao.oldestLowSeverityFirst(limit) - if (ids.isEmpty()) break - affectedSessions += eventDao.sessionIdsForIds(ids) - eventDao.deleteByIds(ids) - quotaDeleted += ids.size - count = eventDao.eventCount() - bytes = eventDao.estimatedStoredBytes() + val count = eventDao.eventCount() + val bytes = eventDao.estimatedStoredBytes() + val mustDrop = (count - maxEvents).coerceAtLeast(0) + // The candidate scan reads every row's id + byte weight; skip it when already within both caps. + val candidates = if (mustDrop > 0 || bytes > maxBytes) eventDao.quotaCandidates() else emptyList() + var dropCount = 0 + var bytesAfterDelete = bytes + for (candidate in candidates) { + if (dropCount.toLong() >= mustDrop && bytesAfterDelete <= maxBytes) break + bytesAfterDelete -= candidate.bytes + dropCount++ } + val ids = candidates.take(dropCount).map { it.id } + if (ids.isNotEmpty()) { + ids.chunked(PRUNE_BATCH_SIZE).forEach { batch -> + affectedSessions += eventDao.sessionIdsForIds(batch) + eventDao.deleteByIds(batch) + } + } + val quotaDeleted = ids.size + val remainingCount = count - quotaDeleted + val remainingBytes = bytes - candidates.take(quotaDeleted).sumOf { it.bytes } if (affectedSessions.isNotEmpty()) onSessionsPruned(affectedSessions) return EventPruneResult( expiredCount = expired, quotaCount = quotaDeleted, - remainingCount = count, - remainingBytes = bytes, + remainingCount = remainingCount, + remainingBytes = remainingBytes, ) } diff --git a/sdk/storage-room/src/main/kotlin/io/devconsole/storage/room/RoomEventStore.kt b/sdk/storage-room/src/main/kotlin/io/devconsole/storage/room/RoomEventStore.kt index a809073..4b5a629 100644 --- a/sdk/storage-room/src/main/kotlin/io/devconsole/storage/room/RoomEventStore.kt +++ b/sdk/storage-room/src/main/kotlin/io/devconsole/storage/room/RoomEventStore.kt @@ -85,7 +85,21 @@ class RoomEventStore( ): RoomEventStore = apply { this.databaseProvider = databaseProvider - this.recover = recover + this.recover = { failure -> + recover(failure) + coordinator.activeSession?.let { session -> + try { + val recoveredDatabase = databaseProvider() + recoveredDatabase.runInTransaction { + recoveredDatabase.sessionDao().insertIfAbsent(session.toSessionEntity()) + } + } catch (cancelled: CancellationException) { + throw cancelled + } catch (_: Exception) { + // Suppress failure re-creating active session so recovery does not fail. + } + } + } } override suspend fun insert(events: List): EventStoreWriteResult = diff --git a/sdk/storage-room/src/main/kotlin/io/devconsole/storage/room/RoomRetentionCoordinator.kt b/sdk/storage-room/src/main/kotlin/io/devconsole/storage/room/RoomRetentionCoordinator.kt index 9890357..09d879c 100644 --- a/sdk/storage-room/src/main/kotlin/io/devconsole/storage/room/RoomRetentionCoordinator.kt +++ b/sdk/storage-room/src/main/kotlin/io/devconsole/storage/room/RoomRetentionCoordinator.kt @@ -1,5 +1,6 @@ package io.devconsole.storage.room +import io.devconsole.storage.api.StoredSession import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock @@ -7,5 +8,8 @@ import kotlinx.coroutines.sync.withLock class RoomRetentionCoordinator { private val mutex = Mutex() + @Volatile + internal var activeSession: StoredSession? = null + suspend fun exclusive(block: suspend () -> T): T = mutex.withLock { block() } } diff --git a/sdk/storage-room/src/main/kotlin/io/devconsole/storage/room/RoomSessionStore.kt b/sdk/storage-room/src/main/kotlin/io/devconsole/storage/room/RoomSessionStore.kt index 023f48f..947cf97 100644 --- a/sdk/storage-room/src/main/kotlin/io/devconsole/storage/room/RoomSessionStore.kt +++ b/sdk/storage-room/src/main/kotlin/io/devconsole/storage/room/RoomSessionStore.kt @@ -4,6 +4,7 @@ package io.devconsole.storage.room import io.devconsole.storage.api.SessionRetentionPolicy import io.devconsole.storage.api.SessionStore +import io.devconsole.storage.api.StoredAttachment import io.devconsole.storage.api.StoredSession import io.devconsole.storage.api.StoredSessionStatus import kotlinx.coroutines.CancellationException @@ -52,6 +53,7 @@ class RoomSessionStore( activeDatabase.sessionDao().insertIfAbsent(session.toEntity()) activeDatabase.sessionDao().refreshUsage(session.id) } + coordinator.activeSession = session SessionRetentionPruner(activeDatabase, attachmentFiles).prune(policy, session.id, clock()) } } @@ -91,6 +93,23 @@ class RoomSessionStore( } } + override suspend fun delete(sessionId: String): Boolean = + coordinator.exclusive { + withContext(Dispatchers.IO) { + execute(false) { activeDatabase -> + SessionRetentionPruner(activeDatabase, attachmentFiles).deleteFinished(sessionId) + } + } + } + + override suspend fun setPinned( + sessionId: String, + pinned: Boolean, + ): Boolean = + withContext(Dispatchers.IO) { + execute(false) { activeDatabase -> activeDatabase.sessionDao().setPinned(sessionId, pinned) > 0 } + } + private suspend fun finish( sessionId: String, status: StoredSessionStatus, @@ -102,6 +121,7 @@ class RoomSessionStore( execute(Unit) { activeDatabase -> activeDatabase.sessionDao().refreshUsage(sessionId) activeDatabase.sessionDao().finish(sessionId, status.name, endedAtMs) + if (coordinator.activeSession?.id == sessionId) coordinator.activeSession = null SessionRetentionPruner(activeDatabase, attachmentFiles).prune(policy, null, clock()) } } @@ -144,10 +164,14 @@ class RoomSessionStore( } /** Session-first retention: delete whole completed runs, then trim only an oversized active run. */ -class SessionRetentionPruner( +class SessionRetentionPruner internal constructor( private val database: DevConsoleDatabase, - private val attachmentFiles: FileAttachmentStore, + /** Injected so tests can simulate a failed file delete without subclassing [FileAttachmentStore]. */ + private val deleteAttachment: suspend (StoredAttachment) -> FileDeletion, ) { + constructor(database: DevConsoleDatabase, attachmentFiles: FileAttachmentStore) : + this(database, attachmentFiles::delete) + // The capacity-trim loop below breaks both when no further candidate exists and when a // deletion fails partway; a single-exit rewrite would obscure which condition stopped pruning. @Suppress("LoopWithTooManyJumpStatements") @@ -159,19 +183,25 @@ class SessionRetentionPruner( val sessions = database.sessionDao() val cutoff = (nowMs - policy.maxAgeMs).coerceAtLeast(0) for (session in sessions.deletingSessions()) { - if (!completeSessionDeletion(session.id)) return + completeSessionDeletion(session.id) } reconcilePending() - for (session in sessions.expiredCompleted(cutoff)) { - if (!deleteSession(session)) return - } + for (session in sessions.expiredCompleted(cutoff)) deleteSession(session) while ( sessions.sessionCount() > policy.maxSessions || sessions.totalEstimatedBytes() > policy.maxBytes ) { - val candidate = sessions.completedOldestFirst().firstOrNull() ?: break - if (!deleteSession(candidate)) break + val candidates = sessions.completedOldestFirst() + if (candidates.isEmpty()) break + var deleted = false + for (candidate in candidates) { + if (deleteSession(candidate)) { + deleted = true + break + } + } + if (!deleted) break } val active = activeSessionId?.let(sessions::session) ?: return @@ -187,6 +217,12 @@ class SessionRetentionPruner( } } + /** Explicit delete of one completed or crashed run, pinned or not; the active run is refused. */ + suspend fun deleteFinished(sessionId: String): Boolean { + val session = database.sessionDao().session(sessionId) ?: return false + return session.status in FINISHED_STATUSES && deleteSession(session) + } + private suspend fun deleteSession(session: SessionEntity): Boolean { // Tombstone the run and its files first. A crash leaves its bytes accounted and blocks // session-aware writers; the next retention pass completes the same deletion. @@ -220,15 +256,27 @@ class SessionRetentionPruner( ) { val attachments = database.attachmentDao() for (attachment in attachments.oldestUnbookmarkedForSession(sessionId)) { - if (sessionBytes(sessionId) <= maxBytes) return + if (sessionBytes(sessionId) <= maxBytes) break database.runInTransaction { attachments.markPendingDeletion(attachment.id) } reconcilePendingForSession(sessionId) } - while (sessionBytes(sessionId) > maxBytes) { - val ids = database.eventDao().oldestUnbookmarkedLowSeverityFirstForSession(sessionId, 1) - if (ids.isEmpty()) return - database.timelineAnnotationDao().deleteEvents(ids) - database.eventDao().deleteByIds(ids) + val currentBytes = sessionBytes(sessionId) + if (currentBytes <= maxBytes) return + val events = database.eventDao().activeSessionTrimCandidates(sessionId) + var bytesAfterDelete = currentBytes + val idsToDelete = mutableListOf() + for (entity in events) { + if (bytesAfterDelete <= maxBytes) break + bytesAfterDelete -= entity.bytes + idsToDelete += entity.id + } + if (idsToDelete.isNotEmpty()) { + idsToDelete.chunked(EVENT_PRUNE_BATCH_SIZE).forEach { batch -> + database.runInTransaction { + database.timelineAnnotationDao().deleteEvents(batch) + database.eventDao().deleteByIds(batch) + } + } } } @@ -252,17 +300,26 @@ class SessionRetentionPruner( } private suspend fun reconcilePendingForSession(sessionId: String): Boolean { + var failedDeletes = 0 for (attachment in database.attachmentDao().pendingDeletionForSession(sessionId)) { - if (attachmentFiles.delete(attachment.toStoredAttachment()) == FileDeletion.Failed) return false + if (deleteAttachment(attachment.toStoredAttachment()) == FileDeletion.Failed) { + failedDeletes++ + continue + } database.attachmentDao().deleteById(attachment.id) } database.sessionDao().refreshUsage(sessionId) - return true + // Keep failed rows pending; the next prune pass will retry them. + return failedDeletes == 0 } } +private const val EVENT_PRUNE_BATCH_SIZE = 256 + private fun Long?.orZero(): Long = this ?: 0L +private val FINISHED_STATUSES = setOf(StoredSessionStatus.COMPLETED.name, StoredSessionStatus.CRASHED.name) + private fun StoredSession.toEntity(): SessionEntity = SessionEntity( id, @@ -279,9 +336,12 @@ private fun StoredSession.toEntity(): SessionEntity = deviceOsVersion, recordCount, estimatedBytes, + pinned, ) -private fun SessionEntity.toStoredSession(): StoredSession = +internal fun StoredSession.toSessionEntity(): SessionEntity = toEntity() + +internal fun SessionEntity.toStoredSession(): StoredSession = StoredSession( id = id, status = StoredSessionStatus.valueOf(status), @@ -297,4 +357,5 @@ private fun SessionEntity.toStoredSession(): StoredSession = deviceOsVersion = deviceOsVersion, recordCount = recordCount, estimatedBytes = estimatedBytes, + pinned = pinned, ) diff --git a/sdk/storage-room/src/test/kotlin/io/devconsole/storage/room/EventQuotaPrunerTest.kt b/sdk/storage-room/src/test/kotlin/io/devconsole/storage/room/EventQuotaPrunerTest.kt index 769cfd0..abf840e 100644 --- a/sdk/storage-room/src/test/kotlin/io/devconsole/storage/room/EventQuotaPrunerTest.kt +++ b/sdk/storage-room/src/test/kotlin/io/devconsole/storage/room/EventQuotaPrunerTest.kt @@ -11,7 +11,11 @@ import org.junit.Test private class FakeEventDao : EventDao { val events = linkedMapOf() - val requestedDeleteLimits = mutableListOf() + var orderedScans = 0 + var finalCountScans = 0 + var finalByteScans = 0 + val bookmarked = mutableSetOf() + val attached = mutableSetOf() override fun insertAll(events: List) { events.forEach { this.events[it.id] = it } @@ -25,7 +29,10 @@ private class FakeEventDao : EventDao { .forEach { this.events.remove(it.id) } } - override fun eventCount(): Long = events.size.toLong() + override fun eventCount(): Long { + finalCountScans++ + return events.size.toLong() + } override fun deleteOlderThan(cutoffEpochMs: Long): Int { val expired = events.values.filter { it.wallTimeMs < cutoffEpochMs }.map { it.id } @@ -33,22 +40,30 @@ private class FakeEventDao : EventDao { return expired.size } - override fun estimatedStoredBytes(): Long = - events.values.sumOf { - 96L + it.summary.encodeToByteArray().size + (it.payloadJson?.encodeToByteArray()?.size ?: 0) - } + override fun estimatedStoredBytes(): Long { + finalByteScans++ + return events.values.sumOf { it.toStoredEvent().estimatedStorageBytes() } + } + + override fun quotaCandidates(): List { + orderedScans++ + return events.values + .filter { it.id !in bookmarked } + .sortedWith( + compareBy { it.severity }.thenBy { it.wallTimeMs }.thenBy { it.sequence }.thenBy { it.id }, + ).map { it.pruneCandidate() } + } override fun recentEvents(limit: Int): List = events.values .sortedWith(compareBy { it.monoTimeNs }.thenBy { it.sequence }.thenBy { it.id }) .takeLast(limit) - override fun oldestLowSeverityFirst(limit: Int): List = + override fun activeSessionTrimCandidates(sessionId: String): List = events.values - .sortedWith(compareBy({ it.severity }, { it.wallTimeMs })) - .take(limit) - .map { it.id } - .also { requestedDeleteLimits += limit } + .filter { it.sessionId == sessionId && it.id !in bookmarked && it.id !in attached } + .sortedWith(compareBy({ it.severity }, { it.wallTimeMs }, { it.sequence }, { it.id })) + .map { it.pruneCandidate() } override fun recentEventsForSession( sessionId: String, @@ -90,16 +105,6 @@ private class FakeEventDao : EventDao { ).take(limit) .sortedWith(compareBy { it.wallTimeMs }.thenBy { it.sequence }.thenBy { it.id }) - override fun oldestUnbookmarkedLowSeverityFirstForSession( - sessionId: String, - limit: Int, - ): List = - events.values - .filter { it.sessionId == sessionId } - .sortedWith(compareBy({ it.severity }, { it.wallTimeMs })) - .take(limit) - .map { it.id } - override fun deleteByIds(ids: List) { ids.forEach { events.remove(it) } } @@ -113,6 +118,12 @@ private class FakeEventDao : EventDao { override fun sessionIdsForIds(ids: List): List = ids.mapNotNull { events[it]?.sessionId }.distinct() } +private fun EventEntity.pruneCandidate(): EventPruneCandidate = + EventPruneCandidate().also { + it.id = id + it.bytes = toStoredEvent().estimatedStorageBytes() + } + private fun event( id: String, severity: Int, @@ -251,10 +262,31 @@ class EventQuotaPrunerTest { assertEquals(1, result.expiredCount) assertEquals(1, result.quotaCount) assertEquals(setOf("new-error"), dao.events.keys) - assertTrue(dao.requestedDeleteLimits.all { it <= 256 }) assertTrue(result.remainingBytes <= 150) } + @Test + fun `byte-only overage trims all required rows in one ordered scan`() = + runBlocking { + val dao = FakeEventDao() + dao.insertAll(listOf(event("one", 0, 1), event("two", 0, 2), event("three", 0, 3))) + dao.attached += "one" + val initialBytes = dao.estimatedStoredBytes() + + val result = + EventQuotaPruner(dao).pruneTo( + 10, + initialBytes - event("one", 0, 1).toStoredEvent().estimatedStorageBytes(), + Long.MIN_VALUE, + ) + + assertEquals(1, result.quotaCount) + assertEquals(setOf("two", "three"), dao.events.keys) + assertEquals(1, dao.orderedScans) + assertEquals(1, dao.finalCountScans) + assertEquals(2, dao.finalByteScans) // one setup estimate and one prune estimate + } + @Test fun `reports every distinct session touched by an age-based expiry so their usage counters can be corrected`() = runBlocking { @@ -308,4 +340,19 @@ class EventQuotaPrunerTest { assertTrue(prunedSessions.isEmpty()) } + + @Test + fun `quota pruning skips bookmarked events and deletes eligible rows in one scan`() = + runBlocking { + val dao = FakeEventDao() + dao.insertAll(listOf(event("protected", 0, 0), event("drop-1", 0, 1), event("drop-2", 0, 2))) + dao.bookmarked += "protected" + + EventQuotaPruner(dao).pruneTo(maxEvents = 1) + + assertEquals(setOf("protected"), dao.events.keys) + assertEquals(1, dao.orderedScans) + assertEquals(1, dao.finalCountScans) + assertEquals(1, dao.finalByteScans) + } } diff --git a/sdk/storage-room/src/test/kotlin/io/devconsole/storage/room/RoomEventStoreRetainedEventsFilterTest.kt b/sdk/storage-room/src/test/kotlin/io/devconsole/storage/room/RoomEventStoreRetainedEventsFilterTest.kt index 716224e..8f8cac6 100644 --- a/sdk/storage-room/src/test/kotlin/io/devconsole/storage/room/RoomEventStoreRetainedEventsFilterTest.kt +++ b/sdk/storage-room/src/test/kotlin/io/devconsole/storage/room/RoomEventStoreRetainedEventsFilterTest.kt @@ -192,17 +192,14 @@ private class FakePluginFilterEventDao : EventDao { override fun recentEvents(limit: Int): List = events.values.sortedBy { it.wallTimeMs }.takeLast(limit) - override fun oldestLowSeverityFirst(limit: Int): List = emptyList() + override fun quotaCandidates(): List = emptyList() + + override fun activeSessionTrimCandidates(sessionId: String): List = emptyList() override fun deleteByIds(ids: List) { ids.forEach { events.remove(it) } } - override fun oldestUnbookmarkedLowSeverityFirstForSession( - sessionId: String, - limit: Int, - ): List = emptyList() - override fun sessionIdsOlderThan(cutoffEpochMs: Long): List = emptyList() override fun sessionIdsForIds(ids: List): List = emptyList() diff --git a/sdk/storage-room/src/test/kotlin/io/devconsole/storage/room/SessionRetentionPrunerTest.kt b/sdk/storage-room/src/test/kotlin/io/devconsole/storage/room/SessionRetentionPrunerTest.kt index 4c9da67..c13e0f2 100644 --- a/sdk/storage-room/src/test/kotlin/io/devconsole/storage/room/SessionRetentionPrunerTest.kt +++ b/sdk/storage-room/src/test/kotlin/io/devconsole/storage/room/SessionRetentionPrunerTest.kt @@ -6,9 +6,13 @@ package io.devconsole.storage.room import androidx.room.DatabaseConfiguration import androidx.sqlite.db.SupportSQLiteOpenHelper +import io.devconsole.storage.api.EventStoreWriteResult import io.devconsole.storage.api.SessionRetentionPolicy +import io.devconsole.storage.api.StoredSession +import io.devconsole.storage.api.StoredSessionStatus import kotlinx.coroutines.runBlocking import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue import org.junit.Test import java.nio.file.Files @@ -25,6 +29,40 @@ import java.nio.file.Files * real, Room-built database this module's plain JVM unit tests cannot construct. */ class SessionRetentionPrunerTest { + @Test + fun `retention keeps pinned runs even when they are over count and age limits`() = + runBlocking { + val eventDao = FakeTrimEventDao() + val attachmentDao = FakeTrimAttachmentDao() + val sessionDao = FakeTrimSessionDao(eventDao, attachmentDao) + sessionDao.put(fakeSession("run-a", estimatedBytes = 10, recordCount = 1).withStatus("COMPLETED", 1)) + sessionDao.put(fakeSession("run-b", estimatedBytes = 10, recordCount = 1).withStatus("CRASHED", 2)) + assertEquals(1, sessionDao.setPinned("run-a", true)) + assertEquals(1, sessionDao.setPinned("run-b", true)) + val database = fakeTrimDatabase(sessionDao, eventDao, attachmentDao) + val files = FileAttachmentStore(Files.createTempDirectory("prune-pin-test").toFile()) + val policy = SessionRetentionPolicy(maxSessions = 1, maxAgeMs = 1, maxBytes = 1_000) + + SessionRetentionPruner(database, files).prune(policy, activeSessionId = null, nowMs = 1_000) + + assertEquals(setOf("run-a", "run-b"), sessionDao.sessions().map { it.id }.toSet()) + } + + @Test + fun `an explicit delete refuses the active run`() = + runBlocking { + val eventDao = FakeTrimEventDao() + val attachmentDao = FakeTrimAttachmentDao() + val sessionDao = FakeTrimSessionDao(eventDao, attachmentDao) + sessionDao.put(fakeSession("active-run", estimatedBytes = 10, recordCount = 1)) + val database = fakeTrimDatabase(sessionDao, eventDao, attachmentDao) + val files = FileAttachmentStore(Files.createTempDirectory("prune-active-test").toFile()) + + assertFalse(SessionRetentionPruner(database, files).deleteFinished("active-run")) + assertEquals(0, sessionDao.setPinned("active-run", true)) + assertEquals(listOf("active-run"), sessionDao.sessions().map { it.id }) + } + @Test fun `a no-op pass on an already-under-budget active session never re-aggregates usage`() = runBlocking { @@ -47,8 +85,7 @@ class SessionRetentionPrunerTest { val eventDao = FakeTrimEventDao() val attachmentDao = FakeTrimAttachmentDao() val sessionDao = FakeTrimSessionDao(eventDao, attachmentDao) - // 5 events at the fake's fixed 100-byte weight each = 500 total; a 250-byte budget - // must evict the 3 oldest-lowest-severity events (0, 1, 2), leaving 3 and 4. + // Five equal-sized events under a two-event budget must evict the three oldest rows. repeat(5) { index -> eventDao.events[ "event-$index", @@ -60,28 +97,195 @@ class SessionRetentionPrunerTest { wallTimeMs = index.toLong(), ) } - sessionDao.put(fakeSession("session-1", estimatedBytes = 500, recordCount = 5)) + val eventWeight = trimEventBytes(eventDao.events.getValue("event-0")) + sessionDao.put(fakeSession("session-1", estimatedBytes = eventWeight * 5, recordCount = 5)) val database = fakeTrimDatabase(sessionDao, eventDao, attachmentDao) val files = FileAttachmentStore(Files.createTempDirectory("prune-trim-test").toFile()) - val policy = SessionRetentionPolicy(maxSessions = 10, maxAgeMs = Long.MAX_VALUE / 2, maxBytes = 250) + val policy = + SessionRetentionPolicy(maxSessions = 10, maxAgeMs = Long.MAX_VALUE / 2, maxBytes = eventWeight * 2) SessionRetentionPruner(database, files).prune(policy, activeSessionId = "session-1", nowMs = 1_000) assertEquals(setOf("event-3", "event-4"), eventDao.events.keys) - assertEquals(200L, sessionDao.session("session-1")?.estimatedBytes) + assertEquals(eventWeight * 2, sessionDao.session("session-1")?.estimatedBytes) assertEquals(2L, sessionDao.session("session-1")?.recordCount) // The trim path is expected to pay for full recomputes -- pruning is rare, unlike the // per-write path the no-op test above guards. assertTrue(sessionDao.refreshUsageCalls > 0) } + + @Test + fun `active trim batches all selected rows and preserves bookmarked event`() = + runBlocking { + val eventDao = FakeTrimEventDao() + val attachmentDao = FakeTrimAttachmentDao() + val sessionDao = FakeTrimSessionDao(eventDao, attachmentDao) + repeat(5) { index -> + eventDao.events["event-$index"] = trimEvent("event-$index", "session-1", index, index.toLong()) + } + eventDao.protected += "event-0" + val eventWeight = trimEventBytes(eventDao.events.getValue("event-0")) + sessionDao.put(fakeSession("session-1", estimatedBytes = eventWeight * 5, recordCount = 5)) + val database = fakeTrimDatabase(sessionDao, eventDao, attachmentDao) + + SessionRetentionPruner( + database, + FileAttachmentStore(Files.createTempDirectory("prune-batch-test").toFile()), + ).prune( + SessionRetentionPolicy(maxSessions = 10, maxAgeMs = Long.MAX_VALUE / 2, maxBytes = eventWeight * 2), + "session-1", + 1_000, + ) + + assertEquals(setOf("event-0", "event-4"), eventDao.events.keys) + assertEquals(1, eventDao.candidateScans) + assertEquals(1, eventDao.deleteCalls) + } + + @Test + fun `failed attachment delete does not stop quota pruning`() = + runBlocking { + val eventDao = FakeTrimEventDao() + val attachmentDao = FakeTrimAttachmentDao() + val sessionDao = FakeTrimSessionDao(eventDao, attachmentDao) + eventDao.events["event-0"] = trimEvent("event-0", "session-1", 0, 0) + eventDao.events["event-1"] = trimEvent("event-1", "session-1", 1, 1) + val attachment = + AttachmentEntity( + "attachment", + "event-0", + "session-1", + "image/png", + 1, + 700, + false, + "hash", + true, + "session-1/attachments/file.bin", + 0, + false, + true, + "NOT_APPLICABLE", + ) + attachmentDao.insert(attachment) + attachmentDao.pending += attachment.id + eventDao.attached += "event-0" + sessionDao.put(fakeSession("session-1", estimatedBytes = 900, recordCount = 3)) + val database = fakeTrimDatabase(sessionDao, eventDao, attachmentDao) + SessionRetentionPruner(database) { FileDeletion.Failed }.prune( + SessionRetentionPolicy(maxSessions = 10, maxAgeMs = Long.MAX_VALUE / 2, maxBytes = 100), + "session-1", + 1_000, + ) + assertEquals(setOf("event-0"), eventDao.events.keys) + assertTrue(attachmentDao.pending.contains(attachment.id)) + } + + @Test + fun `corruption recovery restores active session before retrying event insert`() = + runBlocking { + val staleEventDao = FakeTrimEventDao() + val staleAttachmentDao = FakeTrimAttachmentDao() + val staleSessionDao = FakeTrimSessionDao(staleEventDao, staleAttachmentDao) + val staleDatabase = + fakeTrimDatabase(staleSessionDao, staleEventDao, staleAttachmentDao, failSessionLookup = true) + val freshEventDao = FakeTrimEventDao() + val freshAttachmentDao = FakeTrimAttachmentDao() + val freshSessionDao = FakeTrimSessionDao(freshEventDao, freshAttachmentDao) + var currentDatabase = staleDatabase + val coordinator = + RoomRetentionCoordinator().apply { + activeSession = StoredSession("active-session", StoredSessionStatus.ACTIVE, 10L) + } + val store = + RoomEventStore(staleDatabase, coordinator) + .withRecovery({ currentDatabase }, { + currentDatabase = fakeTrimDatabase(freshSessionDao, freshEventDao, freshAttachmentDao) + }) + .withSessionFirstRetention() + val session = StoredSession("active-session", StoredSessionStatus.ACTIVE, 10L) + + val result = + store.insert( + listOf( + io.devconsole.storage.api.StoredEvent( + id = "event-1", + sessionId = session.id, + sequence = 1, + pluginId = "system", + type = "system.event", + wallTimeMs = 11, + monoTimeNs = 12, + severity = 1, + summary = "ready", + tagsJson = "{}", + ), + ), + ) + + assertEquals(EventStoreWriteResult.Success(1), result) + assertEquals("ACTIVE", freshSessionDao.session(session.id)?.status) + } + + @Test + fun `recovery hook failure returns unavailable instead of escaping event insert`() = + runBlocking { + val eventDao = FakeTrimEventDao() + val attachmentDao = FakeTrimAttachmentDao() + val sessionDao = FakeTrimSessionDao(eventDao, attachmentDao) + val staleDatabase = fakeTrimDatabase(sessionDao, eventDao, attachmentDao, failSessionLookup = true) + val store = + RoomEventStore(staleDatabase, RoomRetentionCoordinator()) + .withRecovery({ staleDatabase }, { throw IllegalStateException("recovery failed") }) + .withSessionFirstRetention() + + val result = + store.insert( + listOf( + io.devconsole.storage.api.StoredEvent( + id = "event-1", + sessionId = "active-session", + sequence = 1, + pluginId = "system", + type = "system.event", + wallTimeMs = 11, + monoTimeNs = 12, + severity = 1, + summary = "ready", + tagsJson = "{}", + ), + ), + ) + + assertEquals(EventStoreWriteResult.Unavailable, result) + } + + @Test + fun `start remembers active session metadata on shared coordinator`() = + runBlocking { + val eventDao = FakeTrimEventDao() + val attachmentDao = FakeTrimAttachmentDao() + val sessionDao = FakeTrimSessionDao(eventDao, attachmentDao) + val coordinator = RoomRetentionCoordinator() + val store = + RoomSessionStore( + fakeTrimDatabase(sessionDao, eventDao, attachmentDao), + FileAttachmentStore(Files.createTempDirectory("active-session-test").toFile()), + SessionRetentionPolicy(10, Long.MAX_VALUE / 2, 10_000), + coordinator, + ) + val session = StoredSession("active-session", StoredSessionStatus.ACTIVE, 10L) + + store.start(session) + + assertEquals(session, coordinator.activeSession) + } } /** - * A fixed per-event weight keeps the arithmetic easy to reason about; the real byte formula is - * covered by EventUsageEstimateTest. + * Fake usage totals use the production per-event estimate so trim selection and usage correction + * agree exactly. */ -private const val FAKE_EVENT_BYTE_WEIGHT = 100L - private fun fakeSession( id: String, estimatedBytes: Long, @@ -101,6 +305,7 @@ private fun fakeSession( null, recordCount, estimatedBytes, + false, ) private fun trimEvent( @@ -125,10 +330,19 @@ private fun trimEvent( 1, ) +private fun trimEventBytes(event: EventEntity): Long = event.toStoredEvent().estimatedStorageBytes() + +private fun EventEntity.pruneCandidate(): EventPruneCandidate = + EventPruneCandidate().also { + it.id = id + it.bytes = trimEventBytes(this) + } + private fun fakeTrimDatabase( sessionDao: SessionDao, eventDao: EventDao, attachmentDao: AttachmentDao, + failSessionLookup: Boolean = false, ): DevConsoleDatabase = object : DevConsoleDatabase() { // Room 2.7.x still declares createOpenHelper as abstract (it became non-abstract in 2.8+); @@ -136,13 +350,26 @@ private fun fakeTrimDatabase( override fun createOpenHelper(config: DatabaseConfiguration): SupportSQLiteOpenHelper = error("not touched by these tests") + override fun runInTransaction(body: Runnable) { + body.run() + } + + override fun runInTransaction(body: java.util.concurrent.Callable): V = body.call() + override fun eventDao(): EventDao = eventDao override fun attachmentDao(): AttachmentDao = attachmentDao override fun timelineAnnotationDao(): TimelineAnnotationDao = FakeTrimTimelineAnnotationDao() - override fun sessionDao(): SessionDao = sessionDao + override fun sessionDao(): SessionDao = + if (failSessionLookup) { + object : SessionDao by sessionDao { + override fun session(sessionId: String): SessionEntity? = error("database disk image is malformed") + } + } else { + sessionDao + } override fun captureRuleDao(): CaptureRuleDao = error("SessionRetentionPruner never touches capture rules") @@ -160,9 +387,7 @@ private fun fakeTrimDatabase( } /** - * Recomputes usage from the linked fake event/attachment DAOs, mirroring refreshUsage's real - * aggregation closely enough for these tests: a fixed per-event weight instead of the exact byte - * formula (see FAKE_EVENT_BYTE_WEIGHT). + * Recomputes usage from the linked fake event/attachment DAOs using the production event estimate. */ private class FakeTrimSessionDao( private val eventDao: FakeTrimEventDao, @@ -188,14 +413,21 @@ private class FakeTrimSessionDao( override fun expiredCompleted(cutoffEpochMs: Long): List = sessions.values.filter { - it.status in setOf("COMPLETED", "CRASHED") && (it.endedAtMs ?: it.startedAtMs) < cutoffEpochMs + it.status in setOf("COMPLETED", "CRASHED") && !it.pinned && (it.endedAtMs ?: it.startedAtMs) < cutoffEpochMs } override fun completedOldestFirst(): List = - sessions.values.filter { - it.status in - setOf("COMPLETED", "CRASHED") - } + sessions.values.filter { it.status in setOf("COMPLETED", "CRASHED") && !it.pinned } + + override fun setPinned( + sessionId: String, + pinned: Boolean, + ): Int { + val current = sessions[sessionId] + if (current == null || current.status !in setOf("COMPLETED", "CRASHED")) return 0 + sessions[sessionId] = current.withPinned(pinned) + return 1 + } override fun deletingSessions(): List = sessions.values.filter { it.status == "DELETING" } @@ -228,7 +460,7 @@ private class FakeTrimSessionDao( val estimatedBytes = eventDao.events.values .filter { it.sessionId == sessionId } - .size * FAKE_EVENT_BYTE_WEIGHT + + .sumOf(::trimEventBytes) + attachmentDao.attachments.values .filter { it.sessionId == sessionId } .sumOf { it.storedLength } @@ -267,6 +499,7 @@ private fun SessionEntity.withStatus( deviceOsVersion, recordCount, estimatedBytes, + pinned, ) private fun SessionEntity.withUsage( @@ -287,10 +520,15 @@ private fun SessionEntity.withUsage( deviceOsVersion, newRecordCount, newEstimatedBytes, + pinned, ) private class FakeTrimEventDao : EventDao { val events = linkedMapOf() + val protected = mutableSetOf() + val attached = mutableSetOf() + var candidateScans = 0 + var deleteCalls = 0 override fun insertAll(events: List) { events.forEach { this.events[it.id] = it } @@ -314,15 +552,15 @@ private class FakeTrimEventDao : EventDao { return expired.size } - override fun estimatedStoredBytes(): Long = events.size * FAKE_EVENT_BYTE_WEIGHT + override fun estimatedStoredBytes(): Long = events.values.sumOf(::trimEventBytes) override fun recentEvents(limit: Int): List = events.values.toList().takeLast(limit) - override fun oldestLowSeverityFirst(limit: Int): List = + override fun quotaCandidates(): List = events.values - .sortedWith(compareBy({ it.severity }, { it.wallTimeMs })) - .take(limit) - .map { it.id } + .filter { it.id !in protected } + .sortedWith(compareBy({ it.severity }, { it.wallTimeMs }, { it.sequence }, { it.id })) + .map { it.pruneCandidate() } override fun recentEventsForSession( sessionId: String, @@ -341,17 +579,18 @@ private class FakeTrimEventDao : EventDao { limit: Int, ): List = events.values.filter { it.pluginId in pluginIds }.takeLast(limit) - override fun oldestUnbookmarkedLowSeverityFirstForSession( - sessionId: String, - limit: Int, - ): List = + override fun activeSessionTrimCandidates(sessionId: String): List = events.values - .filter { it.sessionId == sessionId } - .sortedWith(compareBy({ it.severity }, { it.wallTimeMs })) - .take(limit) - .map { it.id } + .filter { + it.sessionId == sessionId && + it.id !in protected && + it.id !in attached + }.sortedWith(compareBy({ it.severity }, { it.wallTimeMs }, { it.sequence }, { it.id })) + .map { it.pruneCandidate() } + .also { candidateScans++ } override fun deleteByIds(ids: List) { + deleteCalls++ ids.forEach { events.remove(it) } } @@ -366,7 +605,7 @@ private class FakeTrimEventDao : EventDao { private class FakeTrimAttachmentDao : AttachmentDao { val attachments = linkedMapOf() - private val pending = mutableSetOf() + val pending = mutableSetOf() override fun insert(attachment: AttachmentEntity) { attachments[attachment.id] = attachment @@ -424,3 +663,22 @@ private class FakeTrimTimelineAnnotationDao : TimelineAnnotationDao { override fun deleteEvents(eventIds: List) = Unit } + +private fun SessionEntity.withPinned(newPinned: Boolean) = + SessionEntity( + id, + status, + startedAtMs, + startedAtMonotonicNs, + endedAtMs, + applicationId, + appVersionName, + appVersionCode, + buildType, + deviceModel, + deviceApiLevel, + deviceOsVersion, + recordCount, + estimatedBytes, + newPinned, + ) diff --git a/sdk/timeline/api/timeline.api b/sdk/timeline/api/timeline.api index 3734bbb..2f9a190 100644 --- a/sdk/timeline/api/timeline.api +++ b/sdk/timeline/api/timeline.api @@ -51,8 +51,9 @@ public final class io/devconsole/timeline/CursorMarker { } public final class io/devconsole/timeline/InMemoryTimeline : io/devconsole/timeline/Timeline, io/devconsole/timeline/TimelineAppender { - public static final field LEGACY_MONOTONIC_NANOS J public fun (Ljava/util/List;Lio/devconsole/timeline/CursorCodec;)V + public fun (Ljava/util/List;Lio/devconsole/timeline/CursorCodec;I)V + public synthetic fun (Ljava/util/List;Lio/devconsole/timeline/CursorCodec;IILkotlin/jvm/internal/DefaultConstructorMarker;)V public fun append (Lio/devconsole/storage/api/StoredEvent;)V public fun contains (Ljava/lang/String;)Z public fun page (Lio/devconsole/timeline/TimelineQuery;)Lio/devconsole/timeline/TimelinePage; diff --git a/sdk/timeline/src/main/kotlin/io/devconsole/timeline/Timeline.kt b/sdk/timeline/src/main/kotlin/io/devconsole/timeline/Timeline.kt index a7e702b..6f17d8c 100644 --- a/sdk/timeline/src/main/kotlin/io/devconsole/timeline/Timeline.kt +++ b/sdk/timeline/src/main/kotlin/io/devconsole/timeline/Timeline.kt @@ -8,6 +8,9 @@ import javax.crypto.spec.SecretKeySpec import kotlin.io.encoding.Base64 import kotlin.io.encoding.ExperimentalEncodingApi +private const val DEFAULT_CAPACITY = 5_000 +private const val LEGACY_MONOTONIC_NANOS = Long.MIN_VALUE + enum class TimelineSort { ASC, DESC } data class TimelineQuery( @@ -91,109 +94,123 @@ interface TimelineAppender { } /** Reference timeline query implementation used by tests and by the future Room adapter. */ -class InMemoryTimeline( - initialEvents: List, - private val cursors: CursorCodec, -) : Timeline, - TimelineAppender { - private val events = initialEvents.toMutableList() - - // Chained plugin/type/severity/correlation/query/time-range/cursor filters inflate the McCabe - // count; splitting them would fragment one cohesive paging pass across multiple functions. - @Suppress("CyclomaticComplexMethod") - @Synchronized - override fun page(query: TimelineQuery): TimelinePage { - val cursor = query.cursor?.let { cursors.decode(it, query.scope()) } ?: CursorDecodeResult.Missing - if (cursor is CursorDecodeResult.Invalid) return TimelinePage.InvalidCursor - val marker = (cursor as? CursorDecodeResult.Valid)?.marker - val comparator = - compareBy { it.monoTimeNs } - .thenBy { it.sequence } - .thenBy { it.id } - // Not comparator.reversed(): that resolves to java.util.Comparator's default method - // (API 24) over the Kotlin extension, which crashes below minSdk 24. - val directedComparator = - if (query.sort == TimelineSort.ASC) comparator else Comparator { a, b -> comparator.compare(b, a) } - val matching = - events - .asSequence() - .filter { event -> query.pluginIds.isEmpty() || event.pluginId in query.pluginIds } - .filter { event -> query.types.isEmpty() || event.type in query.types } - .filter { event -> query.severities.isEmpty() || event.severity in query.severities } - .filter { event -> query.correlationId == null || event.correlationId == query.correlationId } - .filter { event -> query.query == null || event.summary.contains(query.query, ignoreCase = true) } - .filter { event -> query.fromEpochMs == null || event.wallTimeMs >= query.fromEpochMs!! } - .filter { event -> query.toEpochMs == null || event.wallTimeMs <= query.toEpochMs!! } - .sortedWith(directedComparator) - .filter { event -> marker == null || event.isAfter(marker, query.sort) } - .take(query.limit + 1) - .toList() - val pageEvents = matching.take(query.limit) - val hasMore = matching.size > query.limit - val nextCursor = - if (hasMore) { - pageEvents.lastOrNull()?.let { - cursors.encode( - CursorMarker(it.sequence, it.id).withMonotonicNanos(it.monoTimeNs), - query.scope(), - ) - } - } else { - null - } - return TimelinePage.Success(pageEvents, nextCursor, hasMore) - } +class InMemoryTimeline + @JvmOverloads + constructor( + initialEvents: List, + private val cursors: CursorCodec, + private val capacity: Int = DEFAULT_CAPACITY, + ) : Timeline, + TimelineAppender { + private val events = ArrayDeque() + private val eventIds = HashSet() + + init { + require(capacity > 0) { "capacity must be positive" } + initialEvents.takeLast(capacity).forEach(::append) + } - @Synchronized - override fun contains(eventId: String): Boolean = events.any { it.id == eventId } + // Chained plugin/type/severity/correlation/query/time-range/cursor filters inflate the McCabe + // count; splitting them would fragment one cohesive paging pass across multiple functions. + @Suppress("CyclomaticComplexMethod") + @Synchronized + override fun page(query: TimelineQuery): TimelinePage { + val cursor = query.cursor?.let { cursors.decode(it, query.scope()) } ?: CursorDecodeResult.Missing + if (cursor is CursorDecodeResult.Invalid) return TimelinePage.InvalidCursor + val marker = (cursor as? CursorDecodeResult.Valid)?.marker + val comparator = + compareBy { it.monoTimeNs } + .thenBy { it.sequence } + .thenBy { it.id } + // Not comparator.reversed(): that resolves to java.util.Comparator's default method + // (API 24) over the Kotlin extension, which crashes below minSdk 24. + val directedComparator = + if (query.sort == TimelineSort.ASC) comparator else Comparator { a, b -> comparator.compare(b, a) } + val matching = + events + .asSequence() + .filter { event -> query.pluginIds.isEmpty() || event.pluginId in query.pluginIds } + .filter { event -> query.types.isEmpty() || event.type in query.types } + .filter { event -> query.severities.isEmpty() || event.severity in query.severities } + .filter { event -> query.correlationId == null || event.correlationId == query.correlationId } + .filter { event -> query.query == null || event.summary.contains(query.query, ignoreCase = true) } + .filter { event -> query.fromEpochMs == null || event.wallTimeMs >= query.fromEpochMs!! } + .filter { event -> query.toEpochMs == null || event.wallTimeMs <= query.toEpochMs!! } + .sortedWith(directedComparator) + .filter { event -> marker == null || event.isAfter(marker, query.sort) } + .take(query.limit + 1) + .toList() + val pageEvents = matching.take(query.limit) + val hasMore = matching.size > query.limit + val nextCursor = + if (hasMore) { + pageEvents.lastOrNull()?.let { + cursors.encode( + CursorMarker(it.sequence, it.id).withMonotonicNanos(it.monoTimeNs), + query.scope(), + ) + } + } else { + null + } + return TimelinePage.Success(pageEvents, nextCursor, hasMore) + } - @Synchronized - override fun append(event: StoredEvent) { - events += event - } + @Synchronized + override fun contains(eventId: String): Boolean = eventId in eventIds - /** Atomically replaces hydrated history when the active app-run changes. */ - @Synchronized - fun replace(events: List) { - this.events.clear() - this.events.addAll(events) - } + @Synchronized + override fun append(event: StoredEvent) { + if (!eventIds.add(event.id)) return + events.addLast(event) + if (events.size > capacity) eventIds.remove(events.removeFirst().id) + } - /** Replaces one app-run while retaining events appended for that same run during hydration. */ - @Synchronized - fun replaceSession( - sessionId: String, - persisted: List, - ) { - val merged = LinkedHashMap() - persisted.filter { it.sessionId == sessionId }.forEach { merged[it.id] = it } - // Not Map.putIfAbsent: that is API 24 (java.util.Map default method) and crashes below minSdk 24. - events.filter { it.sessionId == sessionId }.forEach { if (it.id !in merged) merged[it.id] = it } - events.clear() - events.addAll(merged.values) - } + /** Atomically replaces hydrated history when the active app-run changes. */ + @Synchronized + fun replace(events: List) { + this.events.clear() + eventIds.clear() + events.takeLast(capacity).forEach { + if (eventIds.add(it.id)) this.events.addLast(it) + } + } - private fun StoredEvent.isAfter( - marker: CursorMarker, - sort: TimelineSort, - ): Boolean { - val compared = - if (marker.monotonicNanos == LEGACY_MONOTONIC_NANOS) { - sequence.compareTo(marker.sequence).takeIf { it != 0 } ?: id.compareTo(marker.id) - } else { - monoTimeNs - .compareTo(marker.monotonicNanos) - .takeIf { it != 0 } - ?: sequence.compareTo(marker.sequence).takeIf { it != 0 } - ?: id.compareTo(marker.id) + /** Replaces one app-run while retaining events appended for that same run during hydration. */ + @Synchronized + fun replaceSession( + sessionId: String, + persisted: List, + ) { + val merged = LinkedHashMap() + persisted.filter { it.sessionId == sessionId }.forEach { merged[it.id] = it } + // Not Map.putIfAbsent: that is API 24 (java.util.Map default method) and crashes below minSdk 24. + events.filter { it.sessionId == sessionId }.forEach { if (it.id !in merged) merged[it.id] = it } + val retained = merged.values.toList() + events.clear() + eventIds.clear() + retained.takeLast(capacity).forEach { + if (eventIds.add(it.id)) events.addLast(it) } - return if (sort == TimelineSort.ASC) compared > 0 else compared < 0 - } + } - private companion object { - const val LEGACY_MONOTONIC_NANOS = Long.MIN_VALUE + private fun StoredEvent.isAfter( + marker: CursorMarker, + sort: TimelineSort, + ): Boolean { + val compared = + if (marker.monotonicNanos == LEGACY_MONOTONIC_NANOS) { + sequence.compareTo(marker.sequence).takeIf { it != 0 } ?: id.compareTo(marker.id) + } else { + monoTimeNs + .compareTo(marker.monotonicNanos) + .takeIf { it != 0 } + ?: sequence.compareTo(marker.sequence).takeIf { it != 0 } + ?: id.compareTo(marker.id) + } + return if (sort == TimelineSort.ASC) compared > 0 else compared < 0 + } } -} data class CursorMarker( val sequence: Long, diff --git a/sdk/timeline/src/test/kotlin/io/devconsole/timeline/InMemoryTimelineTest.kt b/sdk/timeline/src/test/kotlin/io/devconsole/timeline/InMemoryTimelineTest.kt index 6489f70..0da6fd4 100644 --- a/sdk/timeline/src/test/kotlin/io/devconsole/timeline/InMemoryTimelineTest.kt +++ b/sdk/timeline/src/test/kotlin/io/devconsole/timeline/InMemoryTimelineTest.kt @@ -2,6 +2,7 @@ package io.devconsole.timeline import io.devconsole.storage.api.StoredEvent import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue import org.junit.Test @@ -13,6 +14,55 @@ class InMemoryTimelineTest { event(id = "c", sequence = 3, plugin = "network", summary = "response"), ) + @Test + fun `append evicts oldest events and removes their ids`() { + val timeline = InMemoryTimeline(emptyList(), CursorCodec("cursor-secret-128".encodeToByteArray()), capacity = 3) + val appended = (1L..5L).map { event("event-$it", it, "system", "event $it") } + + appended.forEach(timeline::append) + + val page = timeline.page(TimelineQuery(limit = 10)) as TimelinePage.Success + assertEquals(listOf("event-3", "event-4", "event-5"), page.events.map(StoredEvent::id)) + assertTrue(!timeline.contains("event-1")) + assertTrue(!timeline.contains("event-2")) + assertTrue(timeline.contains("event-3")) + } + + @Test + fun `append deduplicates event ids`() { + val timeline = InMemoryTimeline(emptyList(), CursorCodec("cursor-secret-128".encodeToByteArray()), capacity = 2) + val event = event("same", 1, "system", "original") + + timeline.append(event) + timeline.append(event.copy(summary = "duplicate")) + + val page = timeline.page(TimelineQuery()) as TimelinePage.Success + assertEquals(listOf("original"), page.events.map(StoredEvent::summary)) + } + + @Test + fun `append remains practical across a large bounded stream`() { + val timeline = + InMemoryTimeline( + emptyList(), + CursorCodec("cursor-secret-128".encodeToByteArray()), + capacity = 5_000, + ) + val startedAt = System.nanoTime() + + (1L..100_000L).forEach { sequence -> + timeline.append(event("event-$sequence", sequence, "system", "event $sequence")) + } + + val elapsedMs = (System.nanoTime() - startedAt) / 1_000_000 + assertTrue("100k bounded appends took ${elapsedMs}ms", elapsedMs < 10_000) + assertFalse(timeline.contains("event-1")) + assertTrue(timeline.contains("event-100000")) + val newest = timeline.page(TimelineQuery(limit = 500, sort = TimelineSort.DESC)) as TimelinePage.Success + assertEquals(500, newest.events.size) + assertEquals("event-100000", newest.events.first().id) + } + @Test fun `paginates by opaque cursor without duplicating events`() { val timeline = InMemoryTimeline(events, CursorCodec("cursor-secret-128".encodeToByteArray())) diff --git a/sdk/ui-compose/api/ui-compose.api b/sdk/ui-compose/api/ui-compose.api index c9215cd..6eba324 100644 --- a/sdk/ui-compose/api/ui-compose.api +++ b/sdk/ui-compose/api/ui-compose.api @@ -21,10 +21,14 @@ public final class io/devconsole/ui/compose/ComposableSingletons$InspectorContro public static final field INSTANCE Lio/devconsole/ui/compose/ComposableSingletons$InspectorControlScreenKt; public fun ()V public final fun getLambda$-153603954$ui_compose_release ()Lkotlin/jvm/functions/Function2; - public final fun getLambda$-1946392255$ui_compose_release ()Lkotlin/jvm/functions/Function3; - public final fun getLambda$-63518038$ui_compose_release ()Lkotlin/jvm/functions/Function3; - public final fun getLambda$-703251647$ui_compose_release ()Lkotlin/jvm/functions/Function3; + public final fun getLambda$-1581515133$ui_compose_release ()Lkotlin/jvm/functions/Function3; + public final fun getLambda$-647928564$ui_compose_release ()Lkotlin/jvm/functions/Function3; + public final fun getLambda$-846880938$ui_compose_release ()Lkotlin/jvm/functions/Function3; public final fun getLambda$1476698320$ui_compose_release ()Lkotlin/jvm/functions/Function2; + public final fun getLambda$1634393397$ui_compose_release ()Lkotlin/jvm/functions/Function3; + public final fun getLambda$1786299793$ui_compose_release ()Lkotlin/jvm/functions/Function3; + public final fun getLambda$349785120$ui_compose_release ()Lkotlin/jvm/functions/Function3; + public final fun getLambda$85198047$ui_compose_release ()Lkotlin/jvm/functions/Function3; } public final class io/devconsole/ui/compose/ComposableSingletons$InspectorDataScreenKt { @@ -84,9 +88,18 @@ public final class io/devconsole/ui/compose/ComposableSingletons$InspectorDetail public final class io/devconsole/ui/compose/ComposableSingletons$InspectorFilesSectionKt { public static final field INSTANCE Lio/devconsole/ui/compose/ComposableSingletons$InspectorFilesSectionKt; public fun ()V + public final fun getLambda$-683734953$ui_compose_release ()Lkotlin/jvm/functions/Function2; public final fun getLambda$663131892$ui_compose_release ()Lkotlin/jvm/functions/Function2; } +public final class io/devconsole/ui/compose/ComposableSingletons$InspectorFlagEditDialogsKt { + public static final field INSTANCE Lio/devconsole/ui/compose/ComposableSingletons$InspectorFlagEditDialogsKt; + public fun ()V + public final fun getLambda$-1824323684$ui_compose_release ()Lkotlin/jvm/functions/Function3; + public final fun getLambda$-1874799346$ui_compose_release ()Lkotlin/jvm/functions/Function3; + public final fun getLambda$1236119533$ui_compose_release ()Lkotlin/jvm/functions/Function2; +} + public final class io/devconsole/ui/compose/ComposableSingletons$InspectorMockRuleEditorKt { public static final field INSTANCE Lio/devconsole/ui/compose/ComposableSingletons$InspectorMockRuleEditorKt; public fun ()V @@ -101,12 +114,16 @@ public final class io/devconsole/ui/compose/ComposableSingletons$InspectorMoreSc public final fun getLambda$-1671241350$ui_compose_release ()Lkotlin/jvm/functions/Function3; public final fun getLambda$-1899534585$ui_compose_release ()Lkotlin/jvm/functions/Function3; public final fun getLambda$-1943295944$ui_compose_release ()Lkotlin/jvm/functions/Function3; + public final fun getLambda$-512121597$ui_compose_release ()Lkotlin/jvm/functions/Function3; public final fun getLambda$-605975602$ui_compose_release ()Lkotlin/jvm/functions/Function3; public final fun getLambda$1129667334$ui_compose_release ()Lkotlin/jvm/functions/Function2; public final fun getLambda$1180200415$ui_compose_release ()Lkotlin/jvm/functions/Function3; public final fun getLambda$1347851092$ui_compose_release ()Lkotlin/jvm/functions/Function2; + public final fun getLambda$2078997819$ui_compose_release ()Lkotlin/jvm/functions/Function3; public final fun getLambda$364036633$ui_compose_release ()Lkotlin/jvm/functions/Function3; + public final fun getLambda$472592726$ui_compose_release ()Lkotlin/jvm/functions/Function2; public final fun getLambda$636091227$ui_compose_release ()Lkotlin/jvm/functions/Function3; + public final fun getLambda$745029013$ui_compose_release ()Lkotlin/jvm/functions/Function2; public final fun getLambda$908145821$ui_compose_release ()Lkotlin/jvm/functions/Function3; public final fun getLambda$91982039$ui_compose_release ()Lkotlin/jvm/functions/Function3; } @@ -124,6 +141,7 @@ public final class io/devconsole/ui/compose/ComposableSingletons$InspectorObserv public fun ()V public final fun getLambda$-1292996319$ui_compose_release ()Lkotlin/jvm/functions/Function3; public final fun getLambda$1311345751$ui_compose_release ()Lkotlin/jvm/functions/Function3; + public final fun getLambda$590426329$ui_compose_release ()Lkotlin/jvm/functions/Function3; } public final class io/devconsole/ui/compose/ComposableSingletons$InspectorObservePreviewsKt { @@ -155,9 +173,13 @@ public final class io/devconsole/ui/compose/ComposableSingletons$InspectorObserv public final class io/devconsole/ui/compose/ComposableSingletons$InspectorObserveScreenKt { public static final field INSTANCE Lio/devconsole/ui/compose/ComposableSingletons$InspectorObserveScreenKt; public fun ()V + public final fun getLambda$-1123959598$ui_compose_release ()Lkotlin/jvm/functions/Function2; + public final fun getLambda$-1817680841$ui_compose_release ()Lkotlin/jvm/functions/Function3; public final fun getLambda$-606130299$ui_compose_release ()Lkotlin/jvm/functions/Function2; + public final fun getLambda$-894513415$ui_compose_release ()Lkotlin/jvm/functions/Function3; public final fun getLambda$1105471844$ui_compose_release ()Lkotlin/jvm/functions/Function2; public final fun getLambda$1281281800$ui_compose_release ()Lkotlin/jvm/functions/Function2; + public final fun getLambda$561940337$ui_compose_release ()Lkotlin/jvm/functions/Function2; } public final class io/devconsole/ui/compose/ComposableSingletons$InspectorObserveSignalsKt { @@ -174,9 +196,40 @@ public final class io/devconsole/ui/compose/ComposableSingletons$InspectorObserv public final class io/devconsole/ui/compose/ComposableSingletons$InspectorObserveTrafficTabKt { public static final field INSTANCE Lio/devconsole/ui/compose/ComposableSingletons$InspectorObserveTrafficTabKt; public fun ()V - public final fun getLambda$-1894236537$ui_compose_release ()Lkotlin/jvm/functions/Function3; - public final fun getLambda$-361684419$ui_compose_release ()Lkotlin/jvm/functions/Function3; - public final fun getLambda$1397675452$ui_compose_release ()Lkotlin/jvm/functions/Function3; + public final fun getLambda$-1233546674$ui_compose_release ()Lkotlin/jvm/functions/Function2; + public final fun getLambda$-1342708358$ui_compose_release ()Lkotlin/jvm/functions/Function3; + public final fun getLambda$-166503003$ui_compose_release ()Lkotlin/jvm/functions/Function3; + public final fun getLambda$-284139772$ui_compose_release ()Lkotlin/jvm/functions/Function3; + public final fun getLambda$-48866234$ui_compose_release ()Lkotlin/jvm/functions/Function3; +} + +public final class io/devconsole/ui/compose/ComposableSingletons$InspectorPastRunBannerKt { + public static final field INSTANCE Lio/devconsole/ui/compose/ComposableSingletons$InspectorPastRunBannerKt; + public fun ()V + public final fun getLambda$-1389283010$ui_compose_release ()Lkotlin/jvm/functions/Function2; + public final fun getLambda$-958366209$ui_compose_release ()Lkotlin/jvm/functions/Function2; +} + +public final class io/devconsole/ui/compose/ComposableSingletons$InspectorRemoteConfigOverrideDialogKt { + public static final field INSTANCE Lio/devconsole/ui/compose/ComposableSingletons$InspectorRemoteConfigOverrideDialogKt; + public fun ()V + public final fun getLambda$-110703630$ui_compose_release ()Lkotlin/jvm/functions/Function2; + public final fun getLambda$1103500298$ui_compose_release ()Lkotlin/jvm/functions/Function3; +} + +public final class io/devconsole/ui/compose/ComposableSingletons$InspectorResendSheetKt { + public static final field INSTANCE Lio/devconsole/ui/compose/ComposableSingletons$InspectorResendSheetKt; + public fun ()V + public final fun getLambda$-874316641$ui_compose_release ()Lkotlin/jvm/functions/Function2; + public final fun getLambda$1211526174$ui_compose_release ()Lkotlin/jvm/functions/Function2; + public final fun getLambda$822247335$ui_compose_release ()Lkotlin/jvm/functions/Function2; +} + +public final class io/devconsole/ui/compose/ComposableSingletons$InspectorSocketComposerKt { + public static final field INSTANCE Lio/devconsole/ui/compose/ComposableSingletons$InspectorSocketComposerKt; + public fun ()V + public final fun getLambda$1235213031$ui_compose_release ()Lkotlin/jvm/functions/Function2; + public final fun getLambda$2017947477$ui_compose_release ()Lkotlin/jvm/functions/Function2; } public final class io/devconsole/ui/compose/DatabaseBrowserActions { @@ -258,6 +311,28 @@ public final class io/devconsole/ui/compose/InspectorAction$CaptureScreenshot : public fun toString ()Ljava/lang/String; } +public final class io/devconsole/ui/compose/InspectorAction$ClearAllRemoteConfigOverrides : io/devconsole/ui/compose/InspectorAction { + public static final field $stable I + public static final field INSTANCE Lio/devconsole/ui/compose/InspectorAction$ClearAllRemoteConfigOverrides; + public fun equals (Ljava/lang/Object;)Z + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + +public final class io/devconsole/ui/compose/InspectorAction$ClearRemoteConfigOverride : io/devconsole/ui/compose/InspectorAction { + public static final field $stable I + public fun (Ljava/lang/String;Ljava/lang/String;)V + public final fun component1 ()Ljava/lang/String; + public final fun component2 ()Ljava/lang/String; + public final fun copy (Ljava/lang/String;Ljava/lang/String;)Lio/devconsole/ui/compose/InspectorAction$ClearRemoteConfigOverride; + public static synthetic fun copy$default (Lio/devconsole/ui/compose/InspectorAction$ClearRemoteConfigOverride;Ljava/lang/String;Ljava/lang/String;ILjava/lang/Object;)Lio/devconsole/ui/compose/InspectorAction$ClearRemoteConfigOverride; + public fun equals (Ljava/lang/Object;)Z + public final fun getKey ()Ljava/lang/String; + public final fun getProviderId ()Ljava/lang/String; + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + public final class io/devconsole/ui/compose/InspectorAction$ClearTransactionSelection : io/devconsole/ui/compose/InspectorAction { public static final field $stable I public static final field INSTANCE Lio/devconsole/ui/compose/InspectorAction$ClearTransactionSelection; @@ -328,6 +403,18 @@ public final class io/devconsole/ui/compose/InspectorAction$DeleteMockRule : io/ public fun toString ()Ljava/lang/String; } +public final class io/devconsole/ui/compose/InspectorAction$DeleteSession : io/devconsole/ui/compose/InspectorAction { + public static final field $stable I + public fun (Ljava/lang/String;)V + public final fun component1 ()Ljava/lang/String; + public final fun copy (Ljava/lang/String;)Lio/devconsole/ui/compose/InspectorAction$DeleteSession; + public static synthetic fun copy$default (Lio/devconsole/ui/compose/InspectorAction$DeleteSession;Ljava/lang/String;ILjava/lang/Object;)Lio/devconsole/ui/compose/InspectorAction$DeleteSession; + public fun equals (Ljava/lang/Object;)Z + public final fun getId ()Ljava/lang/String; + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + public final class io/devconsole/ui/compose/InspectorAction$DismissCommandResult : io/devconsole/ui/compose/InspectorAction { public static final field $stable I public static final field INSTANCE Lio/devconsole/ui/compose/InspectorAction$DismissCommandResult; @@ -456,6 +543,14 @@ public final class io/devconsole/ui/compose/InspectorAction$PreviewFile : io/dev public fun toString ()Ljava/lang/String; } +public final class io/devconsole/ui/compose/InspectorAction$PurgeCapturedData : io/devconsole/ui/compose/InspectorAction { + public static final field $stable I + public static final field INSTANCE Lio/devconsole/ui/compose/InspectorAction$PurgeCapturedData; + public fun equals (Ljava/lang/Object;)Z + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + public final class io/devconsole/ui/compose/InspectorAction$Refresh : io/devconsole/ui/compose/InspectorAction { public static final field $stable I public static final field INSTANCE Lio/devconsole/ui/compose/InspectorAction$Refresh; @@ -514,6 +609,30 @@ public final class io/devconsole/ui/compose/InspectorAction$SelectSession : io/d public fun toString ()Ljava/lang/String; } +public final class io/devconsole/ui/compose/InspectorAction$SelectTrafficHost : io/devconsole/ui/compose/InspectorAction { + public static final field $stable I + public fun (Ljava/lang/String;)V + public final fun component1 ()Ljava/lang/String; + public final fun copy (Ljava/lang/String;)Lio/devconsole/ui/compose/InspectorAction$SelectTrafficHost; + public static synthetic fun copy$default (Lio/devconsole/ui/compose/InspectorAction$SelectTrafficHost;Ljava/lang/String;ILjava/lang/Object;)Lio/devconsole/ui/compose/InspectorAction$SelectTrafficHost; + public fun equals (Ljava/lang/Object;)Z + public final fun getHost ()Ljava/lang/String; + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + +public final class io/devconsole/ui/compose/InspectorAction$SelectTrafficStatusClass : io/devconsole/ui/compose/InspectorAction { + public static final field $stable I + public fun (Lio/devconsole/ui/compose/TrafficStatusClass;)V + public final fun component1 ()Lio/devconsole/ui/compose/TrafficStatusClass; + public final fun copy (Lio/devconsole/ui/compose/TrafficStatusClass;)Lio/devconsole/ui/compose/InspectorAction$SelectTrafficStatusClass; + public static synthetic fun copy$default (Lio/devconsole/ui/compose/InspectorAction$SelectTrafficStatusClass;Lio/devconsole/ui/compose/TrafficStatusClass;ILjava/lang/Object;)Lio/devconsole/ui/compose/InspectorAction$SelectTrafficStatusClass; + public fun equals (Ljava/lang/Object;)Z + public final fun getStatusClass ()Lio/devconsole/ui/compose/TrafficStatusClass; + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + public final class io/devconsole/ui/compose/InspectorAction$SelectTransactions : io/devconsole/ui/compose/InspectorAction { public static final field $stable I public fun (Ljava/util/Set;)V @@ -526,6 +645,27 @@ public final class io/devconsole/ui/compose/InspectorAction$SelectTransactions : public fun toString ()Ljava/lang/String; } +public final class io/devconsole/ui/compose/InspectorAction$SendSocketFrame : io/devconsole/ui/compose/InspectorAction { + public static final field $stable I + public fun (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;IZ)V + public synthetic fun (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;IZILkotlin/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 ()I + public final fun component5 ()Z + public final fun copy (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;IZ)Lio/devconsole/ui/compose/InspectorAction$SendSocketFrame; + public static synthetic fun copy$default (Lio/devconsole/ui/compose/InspectorAction$SendSocketFrame;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;IZILjava/lang/Object;)Lio/devconsole/ui/compose/InspectorAction$SendSocketFrame; + public fun equals (Ljava/lang/Object;)Z + public final fun getConnectionId ()Ljava/lang/String; + public final fun getQos ()I + public final fun getRetained ()Z + public final fun getText ()Ljava/lang/String; + public final fun getTopic ()Ljava/lang/String; + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + public final class io/devconsole/ui/compose/InspectorAction$ServerStartPermissionResult : io/devconsole/ui/compose/InspectorAction { public static final field $stable I public fun (Z)V @@ -538,6 +678,18 @@ public final class io/devconsole/ui/compose/InspectorAction$ServerStartPermissio public fun toString ()Ljava/lang/String; } +public final class io/devconsole/ui/compose/InspectorAction$SetCapturePaused : io/devconsole/ui/compose/InspectorAction { + public static final field $stable I + public fun (Z)V + public final fun component1 ()Z + public final fun copy (Z)Lio/devconsole/ui/compose/InspectorAction$SetCapturePaused; + public static synthetic fun copy$default (Lio/devconsole/ui/compose/InspectorAction$SetCapturePaused;ZILjava/lang/Object;)Lio/devconsole/ui/compose/InspectorAction$SetCapturePaused; + public fun equals (Ljava/lang/Object;)Z + public final fun getPaused ()Z + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + public final class io/devconsole/ui/compose/InspectorAction$SetCaptureRuleEnabled : io/devconsole/ui/compose/InspectorAction { public static final field $stable I public fun (Ljava/lang/String;Z)V @@ -610,6 +762,22 @@ public final class io/devconsole/ui/compose/InspectorAction$SetPreference : io/d public fun toString ()Ljava/lang/String; } +public final class io/devconsole/ui/compose/InspectorAction$SetRemoteConfigOverride : io/devconsole/ui/compose/InspectorAction { + public static final field $stable I + public fun (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)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 copy (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Lio/devconsole/ui/compose/InspectorAction$SetRemoteConfigOverride; + public static synthetic fun copy$default (Lio/devconsole/ui/compose/InspectorAction$SetRemoteConfigOverride;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ILjava/lang/Object;)Lio/devconsole/ui/compose/InspectorAction$SetRemoteConfigOverride; + public fun equals (Ljava/lang/Object;)Z + public final fun getKey ()Ljava/lang/String; + public final fun getProviderId ()Ljava/lang/String; + public final fun getValue ()Ljava/lang/String; + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + public final class io/devconsole/ui/compose/InspectorAction$SetServerRunning : io/devconsole/ui/compose/InspectorAction { public static final field $stable I public fun (Z)V @@ -622,6 +790,20 @@ public final class io/devconsole/ui/compose/InspectorAction$SetServerRunning : i public fun toString ()Ljava/lang/String; } +public final class io/devconsole/ui/compose/InspectorAction$SetSessionPinned : io/devconsole/ui/compose/InspectorAction { + public static final field $stable I + public fun (Ljava/lang/String;Z)V + public final fun component1 ()Ljava/lang/String; + public final fun component2 ()Z + public final fun copy (Ljava/lang/String;Z)Lio/devconsole/ui/compose/InspectorAction$SetSessionPinned; + public static synthetic fun copy$default (Lio/devconsole/ui/compose/InspectorAction$SetSessionPinned;Ljava/lang/String;ZILjava/lang/Object;)Lio/devconsole/ui/compose/InspectorAction$SetSessionPinned; + public fun equals (Ljava/lang/Object;)Z + public final fun getId ()Ljava/lang/String; + public final fun getPinned ()Z + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + public final class io/devconsole/ui/compose/InspectorAction$ShareFile : io/devconsole/ui/compose/InspectorAction { public static final field $stable I public fun (Ljava/lang/String;Ljava/lang/String;)V @@ -904,11 +1086,15 @@ public final class io/devconsole/ui/compose/InspectorCrashUi { public abstract interface class io/devconsole/ui/compose/InspectorDataSource { public fun captureRules ()Ljava/util/List; public fun captureScreenshot (Lkotlin/coroutines/Continuation;)Ljava/lang/Object; + public fun capturesForSession (Ljava/lang/String;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; + public fun clearAllRemoteConfigOverrides ()Lio/devconsole/ui/compose/InspectorCommandResult; + public fun clearRemoteConfigOverride (Ljava/lang/String;Ljava/lang/String;)Lio/devconsole/ui/compose/InspectorCommandResult; public fun clearTransactions ()Lio/devconsole/ui/compose/InspectorCommandResult; public fun crashesForSession (Ljava/lang/String;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; public abstract fun deleteCaptureRule (Ljava/lang/String;)Lio/devconsole/ui/compose/InspectorCommandResult; public abstract fun deleteFile (Ljava/lang/String;Ljava/lang/String;)Lio/devconsole/ui/compose/InspectorCommandResult; public abstract fun deleteMockRule (Ljava/lang/String;)Lio/devconsole/ui/compose/InspectorCommandResult; + public fun deleteSession (Ljava/lang/String;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; public abstract fun execute (Lio/devconsole/ui/compose/InspectorComposerRequest;)Lio/devconsole/ui/compose/InspectorCommandResult; public abstract fun executeSql (Ljava/lang/String;Ljava/lang/String;)Lio/devconsole/ui/compose/InspectorSqlResultUi; public abstract fun exportHar (Ljava/util/Set;)Lio/devconsole/ui/compose/InspectorCommandResult; @@ -922,24 +1108,34 @@ public abstract interface class io/devconsole/ui/compose/InspectorDataSource { public fun flaggedCrashIds (Ljava/lang/String;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; public static synthetic fun flaggedCrashIds$default (Lio/devconsole/ui/compose/InspectorDataSource;Ljava/lang/String;Lkotlin/coroutines/Continuation;ILjava/lang/Object;)Ljava/lang/Object; public fun flaggedTransactionIds (Lkotlin/coroutines/Continuation;)Ljava/lang/Object; + public fun isCapturePaused ()Z public abstract fun listFiles (Ljava/lang/String;Ljava/lang/String;)Lio/devconsole/ui/compose/InspectorFileListingUi; public abstract fun listTables (Ljava/lang/String;)Lio/devconsole/ui/compose/InspectorDatabaseListingUi; public fun logsForSession (Ljava/lang/String;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; public fun mockRules ()Ljava/util/List; public fun onNotificationPermissionGranted ()V public abstract fun previewFile (Ljava/lang/String;Ljava/lang/String;)Lio/devconsole/ui/compose/InspectorFilePreviewUi; + public fun purgeCapturedData (Lkotlin/coroutines/Continuation;)Ljava/lang/Object; public abstract fun queryTable (Ljava/lang/String;Ljava/lang/String;)Lio/devconsole/ui/compose/InspectorQueryResultUi; public abstract fun removePreference (Ljava/lang/String;Ljava/lang/String;)Lio/devconsole/ui/compose/InspectorCommandResult; public fun revokePrincipal (Ljava/lang/String;)Lio/devconsole/ui/compose/InspectorCommandResult; + public fun sendSocketFrame (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;IZ)Lio/devconsole/ui/compose/InspectorCommandResult; + public static synthetic fun sendSocketFrame$default (Lio/devconsole/ui/compose/InspectorDataSource;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;IZILjava/lang/Object;)Lio/devconsole/ui/compose/InspectorCommandResult; + public fun setCapturePaused (Z)Lio/devconsole/ui/compose/InspectorCommandResult; public abstract fun setCaptureRuleEnabled (Ljava/lang/String;Z)Lio/devconsole/ui/compose/InspectorCommandResult; public abstract fun setFeatureFlag (Ljava/lang/String;Ljava/lang/String;)Lio/devconsole/ui/compose/InspectorCommandResult; public abstract fun setMockRuleEnabled (Ljava/lang/String;Z)Lio/devconsole/ui/compose/InspectorCommandResult; public abstract fun setMocksEnabled (Z)Lio/devconsole/ui/compose/InspectorCommandResult; public abstract fun setPreference (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Lio/devconsole/ui/compose/InspectorCommandResult; + public fun setRemoteConfigOverride (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Lio/devconsole/ui/compose/InspectorCommandResult; public fun setServerRunning (Z)Lio/devconsole/ui/compose/InspectorCommandResult; + public fun setSessionPinned (Ljava/lang/String;ZLkotlin/coroutines/Continuation;)Ljava/lang/Object; public fun shareableFilePath (Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; public abstract fun snapshot ()Lio/devconsole/ui/compose/InspectorSnapshot; public fun snapshot (Lio/devconsole/ui/compose/InspectorTrafficQuery;)Lio/devconsole/ui/compose/InspectorSnapshot; + public fun socketSendProtocol (Ljava/lang/String;)Ljava/lang/String; + public fun supportsCaptureControl ()Z + public fun supportsRemoteConfigOverrides ()Z public fun supportsServerControl ()Z public fun unflagCrash (Ljava/lang/String;Ljava/lang/String;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; public static synthetic fun unflagCrash$default (Lio/devconsole/ui/compose/InspectorDataSource;Ljava/lang/String;Ljava/lang/String;Lkotlin/coroutines/Continuation;ILjava/lang/Object;)Ljava/lang/Object; @@ -951,8 +1147,12 @@ public abstract interface class io/devconsole/ui/compose/InspectorDataSource { public final class io/devconsole/ui/compose/InspectorDataSource$DefaultImpls { public static fun captureRules (Lio/devconsole/ui/compose/InspectorDataSource;)Ljava/util/List; public static fun captureScreenshot (Lio/devconsole/ui/compose/InspectorDataSource;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; + public static fun capturesForSession (Lio/devconsole/ui/compose/InspectorDataSource;Ljava/lang/String;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; + public static fun clearAllRemoteConfigOverrides (Lio/devconsole/ui/compose/InspectorDataSource;)Lio/devconsole/ui/compose/InspectorCommandResult; + public static fun clearRemoteConfigOverride (Lio/devconsole/ui/compose/InspectorDataSource;Ljava/lang/String;Ljava/lang/String;)Lio/devconsole/ui/compose/InspectorCommandResult; public static fun clearTransactions (Lio/devconsole/ui/compose/InspectorDataSource;)Lio/devconsole/ui/compose/InspectorCommandResult; public static fun crashesForSession (Lio/devconsole/ui/compose/InspectorDataSource;Ljava/lang/String;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; + public static fun deleteSession (Lio/devconsole/ui/compose/InspectorDataSource;Ljava/lang/String;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; public static synthetic fun exportHar$default (Lio/devconsole/ui/compose/InspectorDataSource;Ljava/util/Set;ILjava/lang/Object;)Lio/devconsole/ui/compose/InspectorCommandResult; public static synthetic fun exportPostman$default (Lio/devconsole/ui/compose/InspectorDataSource;Ljava/util/Set;ILjava/lang/Object;)Lio/devconsole/ui/compose/InspectorCommandResult; public static fun exportSessionZip (Lio/devconsole/ui/compose/InspectorDataSource;)Lio/devconsole/ui/compose/InspectorCommandResult; @@ -962,13 +1162,23 @@ public final class io/devconsole/ui/compose/InspectorDataSource$DefaultImpls { public static fun flaggedCrashIds (Lio/devconsole/ui/compose/InspectorDataSource;Ljava/lang/String;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; public static synthetic fun flaggedCrashIds$default (Lio/devconsole/ui/compose/InspectorDataSource;Ljava/lang/String;Lkotlin/coroutines/Continuation;ILjava/lang/Object;)Ljava/lang/Object; public static fun flaggedTransactionIds (Lio/devconsole/ui/compose/InspectorDataSource;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; + public static fun isCapturePaused (Lio/devconsole/ui/compose/InspectorDataSource;)Z public static fun logsForSession (Lio/devconsole/ui/compose/InspectorDataSource;Ljava/lang/String;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; public static fun mockRules (Lio/devconsole/ui/compose/InspectorDataSource;)Ljava/util/List; public static fun onNotificationPermissionGranted (Lio/devconsole/ui/compose/InspectorDataSource;)V + public static fun purgeCapturedData (Lio/devconsole/ui/compose/InspectorDataSource;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; public static fun revokePrincipal (Lio/devconsole/ui/compose/InspectorDataSource;Ljava/lang/String;)Lio/devconsole/ui/compose/InspectorCommandResult; + public static fun sendSocketFrame (Lio/devconsole/ui/compose/InspectorDataSource;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;IZ)Lio/devconsole/ui/compose/InspectorCommandResult; + public static synthetic fun sendSocketFrame$default (Lio/devconsole/ui/compose/InspectorDataSource;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;IZILjava/lang/Object;)Lio/devconsole/ui/compose/InspectorCommandResult; + public static fun setCapturePaused (Lio/devconsole/ui/compose/InspectorDataSource;Z)Lio/devconsole/ui/compose/InspectorCommandResult; + public static fun setRemoteConfigOverride (Lio/devconsole/ui/compose/InspectorDataSource;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Lio/devconsole/ui/compose/InspectorCommandResult; public static fun setServerRunning (Lio/devconsole/ui/compose/InspectorDataSource;Z)Lio/devconsole/ui/compose/InspectorCommandResult; + public static fun setSessionPinned (Lio/devconsole/ui/compose/InspectorDataSource;Ljava/lang/String;ZLkotlin/coroutines/Continuation;)Ljava/lang/Object; public static fun shareableFilePath (Lio/devconsole/ui/compose/InspectorDataSource;Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; public static fun snapshot (Lio/devconsole/ui/compose/InspectorDataSource;Lio/devconsole/ui/compose/InspectorTrafficQuery;)Lio/devconsole/ui/compose/InspectorSnapshot; + public static fun socketSendProtocol (Lio/devconsole/ui/compose/InspectorDataSource;Ljava/lang/String;)Ljava/lang/String; + public static fun supportsCaptureControl (Lio/devconsole/ui/compose/InspectorDataSource;)Z + public static fun supportsRemoteConfigOverrides (Lio/devconsole/ui/compose/InspectorDataSource;)Z public static fun supportsServerControl (Lio/devconsole/ui/compose/InspectorDataSource;)Z public static fun unflagCrash (Lio/devconsole/ui/compose/InspectorDataSource;Ljava/lang/String;Ljava/lang/String;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; public static synthetic fun unflagCrash$default (Lio/devconsole/ui/compose/InspectorDataSource;Ljava/lang/String;Ljava/lang/String;Lkotlin/coroutines/Continuation;ILjava/lang/Object;)Ljava/lang/Object; @@ -1176,10 +1386,24 @@ public final class io/devconsole/ui/compose/InspectorLogUi { public fun toString ()Ljava/lang/String; } +public final class io/devconsole/ui/compose/InspectorMockActionType : java/lang/Enum { + public static final field BODY_REPLACEMENT Lio/devconsole/ui/compose/InspectorMockActionType; + public static final field CONNECTION_FAILURE Lio/devconsole/ui/compose/InspectorMockActionType; + public static final field MAP_REMOTE Lio/devconsole/ui/compose/InspectorMockActionType; + public static final field OTHER Lio/devconsole/ui/compose/InspectorMockActionType; + public static final field STATIC Lio/devconsole/ui/compose/InspectorMockActionType; + public static final field STATUS_OVERRIDE Lio/devconsole/ui/compose/InspectorMockActionType; + public static final field THROTTLE Lio/devconsole/ui/compose/InspectorMockActionType; + public static final field TIMEOUT Lio/devconsole/ui/compose/InspectorMockActionType; + public static fun getEntries ()Lkotlin/enums/EnumEntries; + public static fun valueOf (Ljava/lang/String;)Lio/devconsole/ui/compose/InspectorMockActionType; + public static fun values ()[Lio/devconsole/ui/compose/InspectorMockActionType; +} + public final class io/devconsole/ui/compose/InspectorMockRuleUi { public static final field $stable I - public fun (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ILjava/lang/String;ILjava/lang/String;ZLjava/util/Map;Ljava/lang/Long;JLjava/lang/Long;Ljava/lang/String;)V - public synthetic fun (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ILjava/lang/String;ILjava/lang/String;ZLjava/util/Map;Ljava/lang/Long;JLjava/lang/Long;Ljava/lang/String;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public fun (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ILjava/lang/String;ILjava/lang/String;ZLjava/util/Map;Ljava/lang/Long;JLjava/lang/Long;Ljava/lang/String;ZLio/devconsole/ui/compose/InspectorMockActionType;Ljava/lang/Long;Ljava/lang/String;Ljava/lang/Long;Ljava/lang/Long;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Integer;Ljava/util/Map;Ljava/util/Map;Ljava/lang/String;)V + public synthetic fun (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ILjava/lang/String;ILjava/lang/String;ZLjava/util/Map;Ljava/lang/Long;JLjava/lang/Long;Ljava/lang/String;ZLio/devconsole/ui/compose/InspectorMockActionType;Ljava/lang/Long;Ljava/lang/String;Ljava/lang/Long;Ljava/lang/Long;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Integer;Ljava/util/Map;Ljava/util/Map;Ljava/lang/String;ILkotlin/jvm/internal/DefaultConstructorMarker;)V public final fun component1 ()Ljava/lang/String; public final fun component10 ()Ljava/lang/String; public final fun component11 ()Z @@ -1188,7 +1412,20 @@ public final class io/devconsole/ui/compose/InspectorMockRuleUi { public final fun component14 ()J public final fun component15 ()Ljava/lang/Long; public final fun component16 ()Ljava/lang/String; + public final fun component17 ()Z + public final fun component18 ()Lio/devconsole/ui/compose/InspectorMockActionType; + public final fun component19 ()Ljava/lang/Long; public final fun component2 ()Ljava/lang/String; + public final fun component20 ()Ljava/lang/String; + public final fun component21 ()Ljava/lang/Long; + public final fun component22 ()Ljava/lang/Long; + public final fun component23 ()Ljava/lang/String; + public final fun component24 ()Ljava/lang/String; + public final fun component25 ()Ljava/lang/String; + public final fun component26 ()Ljava/lang/Integer; + public final fun component27 ()Ljava/util/Map; + public final fun component28 ()Ljava/util/Map; + public final fun component29 ()Ljava/lang/String; public final fun component3 ()Ljava/lang/String; public final fun component4 ()Ljava/lang/String; public final fun component5 ()Ljava/lang/String; @@ -1196,13 +1433,17 @@ public final class io/devconsole/ui/compose/InspectorMockRuleUi { public final fun component7 ()I public final fun component8 ()Ljava/lang/String; public final fun component9 ()I - public final fun copy (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ILjava/lang/String;ILjava/lang/String;ZLjava/util/Map;Ljava/lang/Long;JLjava/lang/Long;Ljava/lang/String;)Lio/devconsole/ui/compose/InspectorMockRuleUi; - public static synthetic fun copy$default (Lio/devconsole/ui/compose/InspectorMockRuleUi;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ILjava/lang/String;ILjava/lang/String;ZLjava/util/Map;Ljava/lang/Long;JLjava/lang/Long;Ljava/lang/String;ILjava/lang/Object;)Lio/devconsole/ui/compose/InspectorMockRuleUi; + public final fun copy (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ILjava/lang/String;ILjava/lang/String;ZLjava/util/Map;Ljava/lang/Long;JLjava/lang/Long;Ljava/lang/String;ZLio/devconsole/ui/compose/InspectorMockActionType;Ljava/lang/Long;Ljava/lang/String;Ljava/lang/Long;Ljava/lang/Long;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Integer;Ljava/util/Map;Ljava/util/Map;Ljava/lang/String;)Lio/devconsole/ui/compose/InspectorMockRuleUi; + public static synthetic fun copy$default (Lio/devconsole/ui/compose/InspectorMockRuleUi;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ILjava/lang/String;ILjava/lang/String;ZLjava/util/Map;Ljava/lang/Long;JLjava/lang/Long;Ljava/lang/String;ZLio/devconsole/ui/compose/InspectorMockActionType;Ljava/lang/Long;Ljava/lang/String;Ljava/lang/Long;Ljava/lang/Long;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Integer;Ljava/util/Map;Ljava/util/Map;Ljava/lang/String;ILjava/lang/Object;)Lio/devconsole/ui/compose/InspectorMockRuleUi; public fun equals (Ljava/lang/Object;)Z public final fun getActionLabel ()Ljava/lang/String; + public final fun getActionType ()Lio/devconsole/ui/compose/InspectorMockActionType; public final fun getBody ()Ljava/lang/String; + public final fun getBodyPredicate ()Ljava/lang/String; public final fun getDelayMs ()Ljava/lang/Long; public final fun getEnabled ()Z + public final fun getFailureMessage ()Ljava/lang/String; + public final fun getHeaderPredicates ()Ljava/util/Map; public final fun getHeaders ()Ljava/util/Map; public final fun getHitCount ()J public final fun getHost ()Ljava/lang/String; @@ -1211,10 +1452,19 @@ public final class io/devconsole/ui/compose/InspectorMockRuleUi { public final fun getMethod ()Ljava/lang/String; public final fun getPathPattern ()Ljava/lang/String; public final fun getPriority ()I + public final fun getQueryPredicates ()Ljava/util/Map; + public final fun getRemoteHost ()Ljava/lang/String; + public final fun getRemotePath ()Ljava/lang/String; + public final fun getRemotePort ()Ljava/lang/Integer; + public final fun getRemoteScheme ()Ljava/lang/String; + public final fun getResponseBodyTruncated ()Z public final fun getScheme ()Ljava/lang/String; public final fun getScope ()Ljava/lang/String; public final fun getSourceBodySnapshot ()Ljava/lang/String; public final fun getStatusCode ()I + public final fun getThrottleBytesPerSecond ()Ljava/lang/Long; + public final fun getThrottleLatencyMs ()Ljava/lang/Long; + public final fun getTimeoutMs ()Ljava/lang/Long; public fun hashCode ()I public fun toString ()Ljava/lang/String; } @@ -1293,17 +1543,22 @@ public final class io/devconsole/ui/compose/InspectorQueryResultUi { 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 fun (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZLjava/lang/String;Ljava/lang/String;)V + public synthetic fun (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZLjava/lang/String;Ljava/lang/String;ILkotlin/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 final fun component6 ()Ljava/lang/String; + public final fun component7 ()Ljava/lang/String; + public final fun copy (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZLjava/lang/String;Ljava/lang/String;)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;ZZLjava/lang/String;Ljava/lang/String;ILjava/lang/Object;)Lio/devconsole/ui/compose/InspectorRemoteConfigEntryUi; public fun equals (Ljava/lang/Object;)Z public final fun getKey ()Ljava/lang/String; + public final fun getOverridden ()Z + public final fun getProviderSource ()Ljava/lang/String; + public final fun getProviderValue ()Ljava/lang/String; public final fun getRedacted ()Z public final fun getSource ()Ljava/lang/String; public final fun getTruncated ()Z @@ -1355,26 +1610,48 @@ public abstract interface class io/devconsole/ui/compose/InspectorServerStartPer public abstract fun serverStartPermission ()Ljava/lang/String; } +public final class io/devconsole/ui/compose/InspectorSessionCaptures { + public static final field $stable I + public fun ()V + public fun (Ljava/util/List;Ljava/util/List;Ljava/util/List;)V + public synthetic fun (Ljava/util/List;Ljava/util/List;Ljava/util/List;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1 ()Ljava/util/List; + public final fun component2 ()Ljava/util/List; + public final fun component3 ()Ljava/util/List; + public final fun copy (Ljava/util/List;Ljava/util/List;Ljava/util/List;)Lio/devconsole/ui/compose/InspectorSessionCaptures; + public static synthetic fun copy$default (Lio/devconsole/ui/compose/InspectorSessionCaptures;Ljava/util/List;Ljava/util/List;Ljava/util/List;ILjava/lang/Object;)Lio/devconsole/ui/compose/InspectorSessionCaptures; + public fun equals (Ljava/lang/Object;)Z + public final fun getPushEvents ()Ljava/util/List; + public final fun getSockets ()Ljava/util/List; + public final fun getTransactions ()Ljava/util/List; + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + public final class io/devconsole/ui/compose/InspectorSessionUi { public static final field $stable I - public fun (Ljava/lang/String;JLjava/lang/String;Ljava/lang/String;JJ)V - public synthetic fun (Ljava/lang/String;JLjava/lang/String;Ljava/lang/String;JJILkotlin/jvm/internal/DefaultConstructorMarker;)V + public fun (Ljava/lang/String;JLjava/lang/String;Ljava/lang/String;JJZZ)V + public synthetic fun (Ljava/lang/String;JLjava/lang/String;Ljava/lang/String;JJZZILkotlin/jvm/internal/DefaultConstructorMarker;)V public final fun component1 ()Ljava/lang/String; public final fun component2 ()J public final fun component3 ()Ljava/lang/String; public final fun component4 ()Ljava/lang/String; public final fun component5 ()J public final fun component6 ()J - public final fun copy (Ljava/lang/String;JLjava/lang/String;Ljava/lang/String;JJ)Lio/devconsole/ui/compose/InspectorSessionUi; - public static synthetic fun copy$default (Lio/devconsole/ui/compose/InspectorSessionUi;Ljava/lang/String;JLjava/lang/String;Ljava/lang/String;JJILjava/lang/Object;)Lio/devconsole/ui/compose/InspectorSessionUi; + public final fun component7 ()Z + public final fun component8 ()Z + public final fun copy (Ljava/lang/String;JLjava/lang/String;Ljava/lang/String;JJZZ)Lio/devconsole/ui/compose/InspectorSessionUi; + public static synthetic fun copy$default (Lio/devconsole/ui/compose/InspectorSessionUi;Ljava/lang/String;JLjava/lang/String;Ljava/lang/String;JJZZILjava/lang/Object;)Lio/devconsole/ui/compose/InspectorSessionUi; public fun equals (Ljava/lang/Object;)Z public final fun getEstimatedBytes ()J public final fun getId ()Ljava/lang/String; public final fun getLabel ()Ljava/lang/String; + public final fun getPinned ()Z public final fun getRecordCount ()J public final fun getStartedAtEpochMs ()J public final fun getStatus ()Ljava/lang/String; public fun hashCode ()I + public final fun isCurrent ()Z public fun toString ()Ljava/lang/String; } @@ -1544,53 +1821,62 @@ 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;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;Z)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;ZIILkotlin/jvm/internal/DefaultConstructorMarker;)V + public fun (ZZZZLjava/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;ZLjava/util/Map;Ljava/util/List;Ljava/util/List;Lio/devconsole/ui/compose/InspectorFileListingUi;Lio/devconsole/ui/compose/InspectorFilePreviewUi;Ljava/lang/String;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;ZLio/devconsole/ui/compose/TrafficStatusClass;Ljava/lang/String;)V + public synthetic fun (ZZZZLjava/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;ZLjava/util/Map;Ljava/util/List;Ljava/util/List;Lio/devconsole/ui/compose/InspectorFileListingUi;Lio/devconsole/ui/compose/InspectorFilePreviewUi;Ljava/lang/String;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;ZLio/devconsole/ui/compose/TrafficStatusClass;Ljava/lang/String;IILkotlin/jvm/internal/DefaultConstructorMarker;)V public final fun component1 ()Z - public final fun component10 ()Ljava/util/List; + public final fun component10 ()Lio/devconsole/ui/compose/InspectorCommandResult; public final fun component11 ()Ljava/util/List; public final fun component12 ()Ljava/util/List; - public final fun component13 ()Ljava/util/Set; - public final fun component14 ()Ljava/util/Set; - public final fun component15 ()Lio/devconsole/ui/compose/ObserveTab; + public final fun component13 ()Ljava/util/List; + public final fun component14 ()Ljava/util/List; + public final fun component15 ()Ljava/util/Set; public final fun component16 ()Ljava/util/Set; - public final fun component17 ()Ljava/util/List; - public final fun component18 ()Ljava/util/List; + public final fun component17 ()Lio/devconsole/ui/compose/ObserveTab; + public final fun component18 ()Ljava/util/Set; public final fun component19 ()Ljava/util/List; public final fun component2 ()Z public final fun component20 ()Ljava/util/List; 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 component22 ()Z + public final fun component23 ()Ljava/util/Map; + public final fun component24 ()Ljava/util/List; 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 ()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 component26 ()Lio/devconsole/ui/compose/InspectorFileListingUi; + public final fun component27 ()Lio/devconsole/ui/compose/InspectorFilePreviewUi; + public final fun component28 ()Ljava/lang/String; + public final fun component29 ()Ljava/lang/String; + public final fun component3 ()Z + public final fun component30 ()Ljava/util/List; + public final fun component31 ()Lio/devconsole/ui/compose/InspectorDatabaseListingUi; + public final fun component32 ()Lio/devconsole/ui/compose/InspectorQueryResultUi; + public final fun component33 ()Lio/devconsole/ui/compose/InspectorSqlResultUi; + public final fun component34 ()Ljava/util/List; + public final fun component35 ()Ljava/lang/String; public final fun component36 ()Z - public final fun component37 ()Ljava/util/Set; - public final fun component38 ()Z - 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 component37 ()Lio/devconsole/ui/compose/InspectorHealthUi; + public final fun component38 ()Lio/devconsole/ui/compose/InspectorBrowserUi; + public final fun component39 ()Lio/devconsole/ui/compose/InspectorRetentionUi; + public final fun component4 ()Z + public final fun component40 ()Lio/devconsole/api/ScreenshotResult; + public final fun component41 ()Z + public final fun component42 ()Ljava/util/Set; + public final fun component43 ()Z + public final fun component44 ()Lio/devconsole/ui/compose/TrafficStatusClass; + public final fun component45 ()Ljava/lang/String; + public final fun component5 ()Ljava/util/List; + public final fun component6 ()Lio/devconsole/ui/compose/InspectorEditingUi; + public final fun component7 ()Z + public final fun component8 ()Ljava/util/List; 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;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;Z)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;ZIILjava/lang/Object;)Lio/devconsole/ui/compose/InspectorState; + public final fun copy (ZZZZLjava/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;ZLjava/util/Map;Ljava/util/List;Ljava/util/List;Lio/devconsole/ui/compose/InspectorFileListingUi;Lio/devconsole/ui/compose/InspectorFilePreviewUi;Ljava/lang/String;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;ZLio/devconsole/ui/compose/TrafficStatusClass;Ljava/lang/String;)Lio/devconsole/ui/compose/InspectorState; + public static synthetic fun copy$default (Lio/devconsole/ui/compose/InspectorState;ZZZZLjava/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;ZLjava/util/Map;Ljava/util/List;Ljava/util/List;Lio/devconsole/ui/compose/InspectorFileListingUi;Lio/devconsole/ui/compose/InspectorFilePreviewUi;Ljava/lang/String;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;ZLio/devconsole/ui/compose/TrafficStatusClass;Ljava/lang/String;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; public final fun getCapabilities ()Lio/devconsole/ui/compose/InspectorEditingUi; public final fun getCaptureCategories ()Ljava/util/Set; + public final fun getCaptureControlSupported ()Z + public final fun getCapturePaused ()Z public final fun getCaptureRules ()Ljava/util/List; public final fun getCrashes ()Ljava/util/List; public final fun getDatabaseListing ()Lio/devconsole/ui/compose/InspectorDatabaseListingUi; @@ -1598,6 +1884,7 @@ public final class io/devconsole/ui/compose/InspectorState { public final fun getFeatureFlags ()Ljava/util/List; public final fun getFileListing ()Lio/devconsole/ui/compose/InspectorFileListingUi; public final fun getFilePreview ()Lio/devconsole/ui/compose/InspectorFilePreviewUi; + public final fun getFilePreviewName ()Ljava/lang/String; public final fun getFileRoots ()Ljava/util/List; public final fun getFlaggedCrashIds ()Ljava/util/Set; public final fun getFlaggedTransactionIds ()Ljava/util/Set; @@ -1615,15 +1902,19 @@ public final class io/devconsole/ui/compose/InspectorState { public final fun getQueryResult ()Lio/devconsole/ui/compose/InspectorQueryResultUi; public final fun getRedactionEnabled ()Z public final fun getRemoteConfig ()Ljava/util/List; + public final fun getRemoteConfigOverridesEditable ()Z public final fun getRetention ()Lio/devconsole/ui/compose/InspectorRetentionUi; public final fun getSelectedSessionId ()Ljava/lang/String; public final fun getSelectedTransactionIds ()Ljava/util/Set; public final fun getServerControlSupported ()Z public final fun getSessionLogsLoading ()Z public final fun getSessions ()Ljava/util/List; + public final fun getSocketSendProtocols ()Ljava/util/Map; public final fun getSockets ()Ljava/util/List; public final fun getSqlResult ()Lio/devconsole/ui/compose/InspectorSqlResultUi; public final fun getStateProviders ()Ljava/util/List; + public final fun getTrafficHost ()Ljava/lang/String; + public final fun getTrafficStatusClass ()Lio/devconsole/ui/compose/TrafficStatusClass; public final fun getTransactions ()Ljava/util/List; public fun hashCode ()I public fun toString ()Ljava/lang/String; @@ -1687,14 +1978,16 @@ public final class io/devconsole/ui/compose/InspectorTimingPhasesUi { public final class io/devconsole/ui/compose/InspectorTrafficQuery { public static final field $stable I public fun ()V - public fun (Ljava/lang/String;Ljava/lang/String;Lio/devconsole/ui/compose/TrafficStatusClass;)V - public synthetic fun (Ljava/lang/String;Ljava/lang/String;Lio/devconsole/ui/compose/TrafficStatusClass;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public fun (Ljava/lang/String;Ljava/lang/String;Lio/devconsole/ui/compose/TrafficStatusClass;Ljava/lang/String;)V + public synthetic fun (Ljava/lang/String;Ljava/lang/String;Lio/devconsole/ui/compose/TrafficStatusClass;Ljava/lang/String;ILkotlin/jvm/internal/DefaultConstructorMarker;)V public final fun component1 ()Ljava/lang/String; public final fun component2 ()Ljava/lang/String; public final fun component3 ()Lio/devconsole/ui/compose/TrafficStatusClass; - public final fun copy (Ljava/lang/String;Ljava/lang/String;Lio/devconsole/ui/compose/TrafficStatusClass;)Lio/devconsole/ui/compose/InspectorTrafficQuery; - public static synthetic fun copy$default (Lio/devconsole/ui/compose/InspectorTrafficQuery;Ljava/lang/String;Ljava/lang/String;Lio/devconsole/ui/compose/TrafficStatusClass;ILjava/lang/Object;)Lio/devconsole/ui/compose/InspectorTrafficQuery; + public final fun component4 ()Ljava/lang/String; + public final fun copy (Ljava/lang/String;Ljava/lang/String;Lio/devconsole/ui/compose/TrafficStatusClass;Ljava/lang/String;)Lio/devconsole/ui/compose/InspectorTrafficQuery; + public static synthetic fun copy$default (Lio/devconsole/ui/compose/InspectorTrafficQuery;Ljava/lang/String;Ljava/lang/String;Lio/devconsole/ui/compose/TrafficStatusClass;Ljava/lang/String;ILjava/lang/Object;)Lio/devconsole/ui/compose/InspectorTrafficQuery; public fun equals (Ljava/lang/Object;)Z + public final fun getHost ()Ljava/lang/String; public final fun getMethod ()Ljava/lang/String; public final fun getSearch ()Ljava/lang/String; public final fun getStatusClass ()Lio/devconsole/ui/compose/TrafficStatusClass; @@ -1704,8 +1997,8 @@ public final class io/devconsole/ui/compose/InspectorTrafficQuery { public final class io/devconsole/ui/compose/InspectorTransactionUi { public static final field $stable I - public fun (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Integer;Ljava/lang/Long;JLjava/util/Map;Ljava/util/Map;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Lio/devconsole/ui/compose/InspectorBodyKind;ZLio/devconsole/ui/compose/InspectorTimingPhasesUi;ZLjava/lang/String;)V - public synthetic fun (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Integer;Ljava/lang/Long;JLjava/util/Map;Ljava/util/Map;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Lio/devconsole/ui/compose/InspectorBodyKind;ZLio/devconsole/ui/compose/InspectorTimingPhasesUi;ZLjava/lang/String;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public fun (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Integer;Ljava/lang/Long;JLjava/util/Map;Ljava/util/Map;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Lio/devconsole/ui/compose/InspectorBodyKind;ZZLio/devconsole/ui/compose/InspectorTimingPhasesUi;ZLjava/lang/String;)V + public synthetic fun (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Integer;Ljava/lang/Long;JLjava/util/Map;Ljava/util/Map;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Lio/devconsole/ui/compose/InspectorBodyKind;ZZLio/devconsole/ui/compose/InspectorTimingPhasesUi;ZLjava/lang/String;ILkotlin/jvm/internal/DefaultConstructorMarker;)V public final fun component1 ()Ljava/lang/String; public final fun component10 ()Ljava/lang/String; public final fun component11 ()Ljava/lang/String; @@ -1713,9 +2006,10 @@ public final class io/devconsole/ui/compose/InspectorTransactionUi { public final fun component13 ()Ljava/lang/String; public final fun component14 ()Lio/devconsole/ui/compose/InspectorBodyKind; public final fun component15 ()Z - public final fun component16 ()Lio/devconsole/ui/compose/InspectorTimingPhasesUi; - public final fun component17 ()Z - public final fun component18 ()Ljava/lang/String; + public final fun component16 ()Z + public final fun component17 ()Lio/devconsole/ui/compose/InspectorTimingPhasesUi; + public final fun component18 ()Z + public final fun component19 ()Ljava/lang/String; public final fun component2 ()Ljava/lang/String; public final fun component3 ()Ljava/lang/String; public final fun component4 ()Ljava/lang/String; @@ -1724,8 +2018,8 @@ public final class io/devconsole/ui/compose/InspectorTransactionUi { public final fun component7 ()J public final fun component8 ()Ljava/util/Map; public final fun component9 ()Ljava/util/Map; - public final fun copy (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Integer;Ljava/lang/Long;JLjava/util/Map;Ljava/util/Map;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Lio/devconsole/ui/compose/InspectorBodyKind;ZLio/devconsole/ui/compose/InspectorTimingPhasesUi;ZLjava/lang/String;)Lio/devconsole/ui/compose/InspectorTransactionUi; - public static synthetic fun copy$default (Lio/devconsole/ui/compose/InspectorTransactionUi;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Integer;Ljava/lang/Long;JLjava/util/Map;Ljava/util/Map;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Lio/devconsole/ui/compose/InspectorBodyKind;ZLio/devconsole/ui/compose/InspectorTimingPhasesUi;ZLjava/lang/String;ILjava/lang/Object;)Lio/devconsole/ui/compose/InspectorTransactionUi; + public final fun copy (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Integer;Ljava/lang/Long;JLjava/util/Map;Ljava/util/Map;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Lio/devconsole/ui/compose/InspectorBodyKind;ZZLio/devconsole/ui/compose/InspectorTimingPhasesUi;ZLjava/lang/String;)Lio/devconsole/ui/compose/InspectorTransactionUi; + public static synthetic fun copy$default (Lio/devconsole/ui/compose/InspectorTransactionUi;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Integer;Ljava/lang/Long;JLjava/util/Map;Ljava/util/Map;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Lio/devconsole/ui/compose/InspectorBodyKind;ZZLio/devconsole/ui/compose/InspectorTimingPhasesUi;ZLjava/lang/String;ILjava/lang/Object;)Lio/devconsole/ui/compose/InspectorTransactionUi; public fun equals (Ljava/lang/Object;)Z public final fun getDurationMs ()Ljava/lang/Long; public final fun getError ()Ljava/lang/String; @@ -1738,6 +2032,7 @@ public final class io/devconsole/ui/compose/InspectorTransactionUi { public final fun getRequestBodyTruncated ()Z public final fun getRequestHeaders ()Ljava/util/Map; public final fun getRequestPreview ()Ljava/lang/String; + public final fun getResponseBodyTruncated ()Z public final fun getResponseHeaders ()Ljava/util/Map; public final fun getResponsePreview ()Ljava/lang/String; public final fun getStartedAtEpochMs ()J diff --git a/sdk/ui-compose/build.gradle.kts b/sdk/ui-compose/build.gradle.kts index 56d5bc3..35483e1 100644 --- a/sdk/ui-compose/build.gradle.kts +++ b/sdk/ui-compose/build.gradle.kts @@ -7,6 +7,7 @@ plugins { android { namespace = "io.devconsole.ui.compose" + defaultConfig { consumerProguardFiles("consumer-rules.pro") } buildFeatures { compose = true } } diff --git a/sdk/ui-compose/consumer-rules.pro b/sdk/ui-compose/consumer-rules.pro new file mode 100644 index 0000000..5fa2d43 --- /dev/null +++ b/sdk/ui-compose/consumer-rules.pro @@ -0,0 +1 @@ +-keep class io.devconsole.internal.enabled.UiComposeCaptureMarker { *; } diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/internal/enabled/UiComposeCaptureMarker.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/internal/enabled/UiComposeCaptureMarker.kt new file mode 100644 index 0000000..a877a24 --- /dev/null +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/internal/enabled/UiComposeCaptureMarker.kt @@ -0,0 +1,9 @@ +/** + * @author Shakib + * @since 04/11/26 + */ +package io.devconsole.internal.enabled + +internal object UiComposeCaptureMarker { + const val SIGNATURE = "DEVCONSOLE_ENABLED_UI_COMPOSE_V1" +} diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/DevConsoleWorkspace.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/DevConsoleWorkspace.kt index fb9f9f4..02b9997 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/DevConsoleWorkspace.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/DevConsoleWorkspace.kt @@ -10,6 +10,7 @@ import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material3.LocalContentColor @@ -24,6 +25,7 @@ import androidx.compose.runtime.mutableStateMapOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.runtime.saveable.SaveableStateHolder import androidx.compose.runtime.saveable.listSaver import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.saveable.rememberSaveableStateHolder @@ -196,53 +198,74 @@ private fun WorkspaceContent( } } val destinationContent: @Composable (Modifier) -> Unit = { contentModifier -> - Box(modifier = contentModifier) { - for (destination in visibleDestinations.filter { it == selected || it.name in visited }) { - key(destination) { - DestinationHost(active = destination == selected) { - stateHolder.SaveableStateProvider(destination.name) { - when (destination) { - InspectorDestination.OBSERVE -> - ObserveRoute( - onToggleTheme = onToggleTheme, - onDetailOverlayOpen = { open -> overlays[destination] = open }, - ) - InspectorDestination.CONTROL -> - ControlRoute( - onToggleTheme = onToggleTheme, - onDetailOverlayOpen = { open -> overlays[destination] = open }, - ) - InspectorDestination.DATA -> DataRoute(onToggleTheme = onToggleTheme) - InspectorDestination.MORE -> MoreRoute(onToggleTheme = onToggleTheme) - } - } - } - } - } - } + WorkspaceDestinations( + destinations = visibleDestinations.filter { it == selected || it.name in visited }, + selected = selected, + stateHolder = stateHolder, + onToggleTheme = onToggleTheme, + onDetailOverlayOpen = { destination, open -> overlays[destination] = open }, + modifier = contentModifier, + ) } - if (navigationLayout == InspectorNavigationLayout.Bar) { - Scaffold( - modifier = modifier, - containerColor = DevConsoleTheme.colors.ground, - bottomBar = { - if (!detailOverlayOpen) { - InspectorNavigationBar( - items = rememberWorkspaceNavItems(selected, visibleDestinations, onDestinationSelected), - ) - } - }, - ) { padding -> - destinationContent(Modifier.fillMaxSize().padding(padding)) - } - } else { - Row(modifier = modifier) { - if (!detailOverlayOpen) { + // One tree for both layouts, with destinationContent always at the same call site: rememberSaveable + // keys state by composition position, so branching Scaffold-vs-Row around it meant a rotation + // (bar <-> rail) restored nothing -- an open detail or editor silently closed on every turn. + val showBar = navigationLayout == InspectorNavigationLayout.Bar && !detailOverlayOpen + val showRail = navigationLayout != InspectorNavigationLayout.Bar && !detailOverlayOpen + Scaffold( + modifier = modifier, + containerColor = DevConsoleTheme.colors.ground, + bottomBar = { + if (showBar) { + InspectorNavigationBar( + items = rememberWorkspaceNavItems(selected, visibleDestinations, onDestinationSelected), + ) + } + }, + ) { padding -> + Row(modifier = Modifier.fillMaxSize().padding(padding)) { + if (showRail) { InspectorNavigationRail( items = rememberWorkspaceNavItems(selected, visibleDestinations, onDestinationSelected), ) } - destinationContent(Modifier.weight(1f)) + destinationContent(Modifier.weight(1f).fillMaxHeight()) + } + } +} + +/** Every composed destination, stacked; only [selected] is placed (see [DestinationHost]). */ +@Composable +private fun WorkspaceDestinations( + destinations: List, + selected: InspectorDestination, + stateHolder: SaveableStateHolder, + onToggleTheme: () -> Unit, + onDetailOverlayOpen: (InspectorDestination, Boolean) -> Unit, + modifier: Modifier = Modifier, +) { + Box(modifier = modifier) { + for (destination in destinations) { + key(destination) { + DestinationHost(active = destination == selected) { + stateHolder.SaveableStateProvider(destination.name) { + when (destination) { + InspectorDestination.OBSERVE -> + ObserveRoute( + onToggleTheme = onToggleTheme, + onDetailOverlayOpen = { open -> onDetailOverlayOpen(destination, open) }, + ) + InspectorDestination.CONTROL -> + ControlRoute( + onToggleTheme = onToggleTheme, + onDetailOverlayOpen = { open -> onDetailOverlayOpen(destination, open) }, + ) + InspectorDestination.DATA -> DataRoute(onToggleTheme = onToggleTheme) + InspectorDestination.MORE -> MoreRoute(onToggleTheme = onToggleTheme) + } + } + } + } } } } diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorAction.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorAction.kt index d015d3e..872e6cf 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorAction.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorAction.kt @@ -47,6 +47,27 @@ sealed interface InspectorAction { val id: String?, ) : InspectorAction + /** Applies a status-class filter to the traffic snapshot, e.g. from the traffic tab's chips. */ + data class SelectTrafficStatusClass( + val statusClass: TrafficStatusClass, + ) : InspectorAction + + /** Applies an exact-host filter to the traffic snapshot; null shows every host. */ + data class SelectTrafficHost( + val host: String?, + ) : InspectorAction + + /** Pins or unpins a finished run so retention keeps it. */ + data class SetSessionPinned( + val id: String, + val pinned: Boolean, + ) : InspectorAction + + /** Deletes a finished run and all its captures; selecting it again falls back to live. */ + data class DeleteSession( + val id: String, + ) : InspectorAction + /** * Toggles [id]'s evidence-tray flag through the durable `EvidenceStore` -- flags it if * unflagged, unflags it if already flagged, per [InspectorState.flaggedTransactionIds]. @@ -179,6 +200,42 @@ sealed interface InspectorAction { val running: Boolean, ) : InspectorAction + /** The More surface's "Pause capture" switch; the Observe screen's Resume banner also uses it. */ + data class SetCapturePaused( + val paused: Boolean, + ) : InspectorAction + + /** + * The More surface's destructive "Purge captured data" action. The surface is expected to + * confirm before dispatching this. + */ + data object PurgeCapturedData : InspectorAction + + /** Sends one frame over a live socket connection; the composer clears only on success. */ + data class SendSocketFrame( + val connectionId: String, + val text: String, + val topic: String? = null, + val qos: Int = 0, + val retained: Boolean = false, + ) : InspectorAction + + /** Applies a local Remote Config override for [key] on [providerId]. */ + data class SetRemoteConfigOverride( + val providerId: String, + val key: String, + val value: String, + ) : InspectorAction + + /** Removes the local override for [key] on [providerId], restoring the provider's value. */ + data class ClearRemoteConfigOverride( + val providerId: String, + val key: String, + ) : InspectorAction + + /** Removes every local Remote Config override. */ + data object ClearAllRemoteConfigOverrides : InspectorAction + /** The More surface's screenshot capture button, next to the export actions. */ data object CaptureScreenshot : InspectorAction diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorCodeBlock.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorCodeBlock.kt index af0fb37..2ac541e 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorCodeBlock.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorCodeBlock.kt @@ -157,6 +157,8 @@ internal fun CodeLineRow( } } +private const val MAX_RENDERED_LINE_CHARS = 4_000 + @Composable private fun CodeSpan( text: String, @@ -165,8 +167,22 @@ private fun CodeSpan( lineHeight: TextUnit, highlights: List = emptyList(), ) { + val (displayText, displayHighlights) = + if (text.length <= MAX_RENDERED_LINE_CHARS) { + text to highlights + } else { + val truncatedLength = MAX_RENDERED_LINE_CHARS + val remaining = text.length - truncatedLength + val clippedHighlights = + highlights.mapNotNull { h -> + val start = h.start.coerceIn(0, truncatedLength) + val end = h.endExclusive.coerceIn(start, truncatedLength) + if (start < end) h.copy(start = start, endExclusive = end) else null + } + "${text.take(truncatedLength)}… (+$remaining chars)" to clippedHighlights + } Text( - inspectorHighlightedText(text, highlights, DevConsoleTheme.colors), + inspectorHighlightedText(displayText, displayHighlights, DevConsoleTheme.colors), color = color, fontFamily = FontFamily.Monospace, fontSize = fontSize, 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 83a92df..c82635e 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.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.LazyListScope import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.material3.AlertDialog import androidx.compose.material3.IconButton @@ -39,6 +40,8 @@ import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.saveable.Saver +import androidx.compose.runtime.saveable.listSaver import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment @@ -46,6 +49,7 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.semantics.Role import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.SpanStyle import androidx.compose.ui.text.buildAnnotatedString import androidx.compose.ui.text.font.FontFamily @@ -64,6 +68,111 @@ import androidx.lifecycle.viewmodel.compose.viewModel import io.devconsole.api.CaptureCategory import kotlinx.coroutines.launch +private val MockRuleEditorTargetSaver: Saver = + listSaver( + save = { target -> + when (target) { + null -> listOf("closed") + is MockRuleEditorTarget.New -> + listOf( + "new", + target.draft.id, + target.draft.method, + target.draft.pathPattern, + target.draft.actionLabel, + target.draft.statusCode, + target.draft.body, + target.draft.headers.toMockRuleHeaderLines(), + target.draft.scope, + target.draft.host, + target.draft.scheme, + target.draft.priority, + target.draft.enabled, + target.draft.delayMs, + target.draft.hitCount, + target.draft.lastHitEpochMs, + target.draft.sourceBodySnapshot, + target.draft.responseBodyTruncated, + target.prefillNote, + target.sourceKey, + ) + is MockRuleEditorTarget.Edit -> + listOf( + "edit", + target.rule.id, + target.rule.method, + target.rule.pathPattern, + target.rule.actionLabel, + target.rule.statusCode, + target.rule.body, + target.rule.headers.toMockRuleHeaderLines(), + target.rule.scope, + target.rule.host, + target.rule.scheme, + target.rule.priority, + target.rule.enabled, + target.rule.delayMs, + target.rule.hitCount, + target.rule.lastHitEpochMs, + target.rule.sourceBodySnapshot, + target.rule.responseBodyTruncated, + ) + } + }, + restore = { saved -> + when (saved[0]) { + "new" -> + MockRuleEditorTarget.New( + draft = + InspectorMockRuleUi( + id = saved[1] as String, + method = saved[2] as String?, + pathPattern = saved[3] as String, + actionLabel = saved[4] as String, + statusCode = saved[5] as Int, + body = saved[6] as String, + headers = parseMockRuleHeaderLines(saved[7] as String).headers, + scope = saved[8] as String, + host = saved[9] as String?, + scheme = saved[10] as String?, + priority = saved[11] as Int, + enabled = saved[12] as Boolean, + delayMs = saved[13] as Long?, + hitCount = saved[14] as Long, + lastHitEpochMs = saved[15] as Long?, + sourceBodySnapshot = saved[16] as String?, + responseBodyTruncated = saved[17] as Boolean, + ), + prefillNote = saved[18] as String?, + sourceKey = saved[19] as String, + ) + "edit" -> + MockRuleEditorTarget.Edit( + InspectorMockRuleUi( + id = saved[1] as String, + method = saved[2] as String?, + pathPattern = saved[3] as String, + actionLabel = saved[4] as String, + statusCode = saved[5] as Int, + body = saved[6] as String, + headers = parseMockRuleHeaderLines(saved[7] as String).headers, + scope = saved[8] as String, + host = saved[9] as String?, + scheme = saved[10] as String?, + priority = saved[11] as Int, + enabled = saved[12] as Boolean, + delayMs = saved[13] as Long?, + hitCount = saved[14] as Long, + lastHitEpochMs = saved[15] as Long?, + sourceBodySnapshot = saved[16] as String?, + responseBodyTruncated = saved[17] as Boolean, + ), + ) + else -> null + } + }, + ) + /** * Stateful entry point wired into the CONTROL destination. Theme is owned by [DevConsoleWorkspace] * and reaches this screen as ambient [DevConsoleTheme.colors] -- [onToggleTheme] is the only theme @@ -81,8 +190,11 @@ internal fun ControlRoute( val snackbarHostState = remember { SnackbarHostState() } val scope = rememberCoroutineScope() var heroCollapsed by rememberSaveable { mutableStateOf(true) } // starts collapsed - var editorTarget by remember { mutableStateOf(null) } + var editorTarget by rememberSaveable(stateSaver = MockRuleEditorTargetSaver) { + mutableStateOf(null) + } var pendingDeleteId by remember { mutableStateOf(null) } + var editingFlag by remember { mutableStateOf(null) } LifecycleStartEffect(Unit) { viewModel.dispatch(InspectorAction.Refresh) @@ -111,11 +223,25 @@ internal fun ControlRoute( heroCollapsed = heroCollapsed, onToggleHero = { heroCollapsed = !heroCollapsed }, onToggleTheme = onToggleTheme, - onToggleMockRule = { id, enabled -> viewModel.dispatch(InspectorAction.SetMockRuleEnabled(id, enabled)) }, - onNewMockRule = { editorTarget = MockRuleEditorTarget.New() }, - onEditMockRule = { rule -> editorTarget = editMockRuleTargetOrToast(rule, scope, snackbarHostState) }, + onToggleMockRule = { id, enabled -> + if (state.capabilities.mocks) viewModel.dispatch(InspectorAction.SetMockRuleEnabled(id, enabled)) + }, + onNewMockRule = { if (state.capabilities.mocks) editorTarget = MockRuleEditorTarget.New() }, + onEditMockRule = { rule -> + if (state.capabilities.mocks) editorTarget = editMockRuleTargetOrToast(rule, scope, snackbarHostState) + }, onDeleteMockRule = { id -> pendingDeleteId = id }, - onToggleFlag = { flag -> toggleControlFlag(flag, viewModel, scope, snackbarHostState) }, + onToggleFlag = { flag -> + applyFlagTap( + flag = flag, + featureFlagsEnabled = state.capabilities.featureFlags, + onLocked = { + scope.launch { snackbarHostState.showSnackbar("${flag.key} is locked by the host") } + }, + onSetValue = { key, value -> viewModel.dispatch(InspectorAction.SetFeatureFlag(key, value)) }, + onEditNonBoolean = { editingFlag = it }, + ) + }, modifier = Modifier.fillMaxSize(), ) SnackbarHost(hostState = snackbarHostState, modifier = Modifier.align(Alignment.BottomCenter).padding(16.dp)) @@ -147,6 +273,56 @@ internal fun ControlRoute( onDismiss = { pendingDeleteId = null }, ) } + FeatureFlagEditingDialog( + flag = editingFlag, + enabled = lifecycleState.isAtLeast(Lifecycle.State.STARTED), + onSetValue = { key, value -> viewModel.dispatch(InspectorAction.SetFeatureFlag(key, value)) }, + onDismiss = { editingFlag = null }, + ) +} + +/** + * Routes a feature-flag row tap: a boolean flips in place, any other mutable type opens its editor + * (see [FeatureFlagEditingDialog]), and a host-locked flag only reports why it cannot change. Kept + * out of [ControlRoute]'s body so that composable stays inside the complexity budget. + */ +private fun applyFlagTap( + flag: InspectorFeatureFlagUi, + featureFlagsEnabled: Boolean, + onLocked: () -> Unit, + onSetValue: (String, String) -> Unit, + onEditNonBoolean: (InspectorFeatureFlagUi) -> Unit, +) { + if (!featureFlagsEnabled) return + when { + !flag.mutable -> onLocked() + flag.type == "BOOLEAN" -> onSetValue(flag.key, if (flag.value == "true") "false" else "true") + else -> onEditNonBoolean(flag) + } +} + +/** + * Routes the flag being edited to the matching dialog: a radio list when the flag names its + * [InspectorFeatureFlagUi.allowedValues], a typed field otherwise. Both confirm through the same + * [InspectorAction.SetFeatureFlag] path a boolean toggle already uses. + */ +@Composable +private fun FeatureFlagEditingDialog( + flag: InspectorFeatureFlagUi?, + enabled: Boolean, + onSetValue: (String, String) -> Unit, + onDismiss: () -> Unit, +) { + if (flag == null || !enabled) return + val confirm: (String) -> Unit = { value -> + onSetValue(flag.key, value) + onDismiss() + } + if (flag.allowedValues.isNotEmpty()) { + FeatureFlagChoiceDialog(flag = flag, onConfirm = confirm, onDismiss = onDismiss) + } else { + FeatureFlagTextDialog(flag = flag, onConfirm = confirm, onDismiss = onDismiss) + } } /** @@ -167,26 +343,6 @@ private fun editMockRuleTargetOrToast( null } -/** Booleans toggle in place; multi-value flags have no on-device editor. */ -private fun toggleControlFlag( - flag: InspectorFeatureFlagUi, - viewModel: InspectorViewModel, - scope: kotlinx.coroutines.CoroutineScope, - snackbarHostState: SnackbarHostState, -) { - when { - !flag.mutable -> scope.launch { snackbarHostState.showSnackbar("${flag.key} is locked by the host") } - flag.type == "BOOLEAN" -> { - val next = if (flag.value == "true") "false" else "true" - viewModel.dispatch(InspectorAction.SetFeatureFlag(flag.key, next)) - } - else -> - scope.launch { - snackbarHostState.showSnackbar("${flag.key} has more than two values — edit it on the dashboard") - } - } -} - /** * Stateless, previewable Control surface with grouped mock rules and feature flags. */ @@ -205,7 +361,6 @@ internal fun ControlScreen( modifier: Modifier = Modifier, ) { val colors = DevConsoleTheme.colors - val switchColors = controlSwitchColors(colors) Column(modifier = modifier.fillMaxSize().background(colors.ground)) { InspectorTopArea( subLine = "", @@ -220,37 +375,21 @@ internal fun ControlScreen( // at init, the section (header, New-rule affordance and rows) does not exist at all, // rather than rendering with a permanently-empty/disabled list. if (state.captures(CaptureCategory.MOCKS)) { - item(contentType = "mock_rules_header") { MockRulesHeader(onNewMockRule, colors) } - if (state.mockRules.isEmpty()) { - item(contentType = "mock_rules_empty") { MockRulesEmptyNote(colors) } - } else { - itemsIndexed( - items = state.mockRules, - key = { _, rule -> rule.id }, - contentType = { _, _ -> "mock_rule" }, - ) { index, rule -> - Column(Modifier.groupedPanelItem(GroupPosition.of(index, state.mockRules.size))) { - MockRuleRow(rule, onToggleMockRule, onEditMockRule, onDeleteMockRule, colors, switchColors) - } - } - } - item(contentType = "mock_rules_spacer") { Spacer(Modifier.height(8.dp)) } + mockRulesItems(state, onNewMockRule, onToggleMockRule, onEditMockRule, onDeleteMockRule) } // Flags belong to the STATE category; `state.featureFlags` is already emptied by the // data source when STATE is off, but the explicit gate keeps this defensive against a // directly-navigated route the way DATA's sections are (see InspectorDataScreen). - if (state.captures(CaptureCategory.STATE) && state.featureFlags.isNotEmpty()) { - item(contentType = "feature_flags_header") { GroupLabel("Feature flags") } - itemsIndexed( - items = state.featureFlags, - key = { _, flag -> flag.key }, - contentType = { _, _ -> "feature_flag" }, - ) { index, flag -> - Column(Modifier.groupedPanelItem(GroupPosition.of(index, state.featureFlags.size))) { - FlagRow(flag, colors, switchColors) { onToggleFlag(flag) } - } + if (shouldShowFeatureFlags(state)) { + featureFlagItems(state, onToggleFlag) + } + if (isControlEmpty(state)) { + item(contentType = "control_empty") { + InspectorEmptyState( + EmptySpot.Control, + controlEmptyMessage(), + ) } - item(contentType = "feature_flags_spacer") { 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 @@ -260,18 +399,105 @@ internal fun ControlScreen( } } +private fun LazyListScope.mockRulesItems( + state: InspectorState, + onNewMockRule: () -> Unit, + onToggleMockRule: (String, Boolean) -> Unit, + onEditMockRule: (InspectorMockRuleUi) -> Unit, + onDeleteMockRule: (String) -> Unit, +) { + item(contentType = "mock_rules_header") { + MockRulesHeader(onNewMockRule, DevConsoleTheme.colors, enabled = state.capabilities.mocks) + } + if (!state.capabilities.mocks) { + item(contentType = "mock_rules_disabled") { + Text( + "Mock editing is disabled by the host.", + color = DevConsoleTheme.colors.muted, + modifier = Modifier.padding(16.dp), + ) + } + } else if (state.mockRules.isEmpty()) { + item(contentType = "mock_rules_empty") { MockRulesEmptyNote(DevConsoleTheme.colors) } + } else { + itemsIndexed( + state.mockRules, + key = { _, rule -> rule.id }, + contentType = { _, _ -> "mock_rule" }, + ) { index, rule -> + val colors = DevConsoleTheme.colors + Column(Modifier.groupedPanelItem(GroupPosition.of(index, state.mockRules.size))) { + MockRuleRow( + rule, + onToggleMockRule, + onEditMockRule, + onDeleteMockRule, + colors, + controlSwitchColors(colors), + true, + ) + } + } + } + item(contentType = "mock_rules_spacer") { Spacer(Modifier.height(8.dp)) } +} + +private fun LazyListScope.featureFlagItems( + state: InspectorState, + onToggleFlag: (InspectorFeatureFlagUi) -> Unit, +) { + item(contentType = "feature_flags_header") { GroupLabel("Feature flags") } + if (!state.capabilities.featureFlags) { + item(contentType = "feature_flags_disabled") { + Text( + "Feature flag editing is disabled by the host.", + color = DevConsoleTheme.colors.muted, + modifier = Modifier.padding(16.dp), + ) + } + } + if (state.capabilities.featureFlags) { + itemsIndexed( + state.featureFlags, + key = { _, flag -> flag.key }, + contentType = { _, _ -> "feature_flag" }, + ) { index, flag -> + val colors = DevConsoleTheme.colors + Column(Modifier.groupedPanelItem(GroupPosition.of(index, state.featureFlags.size))) { + FlagRow(flag, colors, controlSwitchColors(colors), enabled = true) { onToggleFlag(flag) } + } + } + } + item(contentType = "feature_flags_spacer") { Spacer(Modifier.height(8.dp)) } +} + +private fun isControlEmpty(state: InspectorState): Boolean = + state.mockRules.isEmpty() && + state.featureFlags.isEmpty() && + (!state.captures(CaptureCategory.MOCKS) || !state.capabilities.mocks) && + (!state.captures(CaptureCategory.STATE) || !state.capabilities.featureFlags) + +private fun shouldShowFeatureFlags(state: InspectorState): Boolean = + state.captures(CaptureCategory.STATE) && + (state.featureFlags.isNotEmpty() || !state.capabilities.featureFlags) + +private fun controlEmptyMessage(): String = + "No mock rules or feature flags are available. Enable MOCKS and STATE capture categories and " + + "editing capabilities in the host app." + /** "Mock rules" group label plus the New rule affordance. */ @Composable private fun MockRulesHeader( onNewRule: () -> Unit, colors: DevConsoleColors, + enabled: Boolean, ) { Row( modifier = Modifier.fillMaxWidth().padding(bottom = 8.dp), verticalAlignment = Alignment.CenterVertically, ) { GroupLabel("Mock rules", modifier = Modifier.weight(1f)) - IconButton(onClick = onNewRule, modifier = Modifier.padding(end = 12.dp)) { + IconButton(onClick = onNewRule, enabled = enabled, modifier = Modifier.padding(end = 12.dp)) { DevConsoleIcon(R.drawable.devconsole_ic_composer, "New rule", Modifier, colors.muted, 22.dp) } } @@ -295,41 +521,14 @@ private fun MockRuleRow( onDelete: (String) -> Unit, colors: DevConsoleColors, switchColors: SwitchColors, + enabled: Boolean, ) { - val subtitleText = - remember(rule) { - val match = - buildString { - append("returns ") - append(rule.statusCode) - // "Static response (200)" only repeats the status already printed above. - if (rule.actionLabel.isNotBlank() && !rule.actionLabel.startsWith("Static response")) { - append(" · ${rule.actionLabel}") - } - if (rule.hitCount > 0) { - append(" · ${rule.hitCount} hit${if (rule.hitCount == 1L) "" else "s"}") - rule.lastHitEpochMs?.let { append(" · ${formatRelativeHitTime(it)}") } - } - } - buildAnnotatedString { - append("returns ") - withStyle( - SpanStyle( - color = - when (rule.statusCode) { - in 500..599 -> colors.error - in 400..499 -> colors.warn - else -> colors.muted - }, - ), - ) { append(rule.statusCode.toString()) } - append(match.substringAfter("returns ${rule.statusCode}")) - } - } + val subtitleText = remember(rule) { mockRuleSubtitle(rule, colors) } Row( Modifier .fillMaxWidth() .combinedClickable( + enabled = enabled, onClick = { onEdit(rule) }, onLongClick = { onDelete(rule.id) }, onLongClickLabel = "Delete mock rule", @@ -368,6 +567,7 @@ private fun MockRuleRow( checked = rule.enabled, onCheckedChange = { checked -> onToggle(rule.id, checked) }, colors = switchColors, + enabled = enabled, modifier = Modifier.semantics { contentDescription = "${if (rule.enabled) "Disable" else "Enable"} mock rule ${rule.id}" @@ -442,20 +642,24 @@ private fun FlagRow( flag: InspectorFeatureFlagUi, colors: DevConsoleColors, switchColors: SwitchColors, + enabled: Boolean, onClick: () -> Unit, ) { val isBool = flag.type == "BOOLEAN" val isOn = flag.value == "true" + val subtitle = + listOfNotNull( + if (!isBool) flag.value else null, + if (flag.isOverridden) "overridden" else null, + flag.description.takeIf { it.isNotBlank() }, + if (!flag.mutable) "locked" else null, + ).joinToString(" · ") TonalListRow( leadText = "", leadColor = colors.muted, leadContainerColor = colors.panel, title = flag.key, - subtitle = - listOfNotNull( - if (!isBool) flag.value else null, - if (flag.isOverridden) "overridden" else null, - ).joinToString(" · "), + subtitle = subtitle, trailValue = "", trailContent = { if (isBool) { @@ -463,12 +667,14 @@ private fun FlagRow( checked = isOn, onCheckedChange = { onClick() }, colors = switchColors, + enabled = enabled && flag.mutable && isBool, modifier = Modifier.semantics { contentDescription = "Toggle feature flag ${flag.key}" }, ) } }, mergeDescendants = false, - onClick = onClick, + // Both shapes are editable: a boolean toggles in place, everything else opens its editor. + onClick = { if (enabled && flag.mutable) onClick() }, ) } @@ -540,3 +746,61 @@ private fun ControlScreenPreview() { ) } } + +/** `800` -> `800 ms`, `1200` -> `1.2 s`, `3000` -> `3 s`. */ +internal fun formatMockDelay(delayMs: Long): String = + when { + delayMs < 1_000 -> "$delayMs ms" + delayMs % 1_000 == 0L -> "${delayMs / 1_000} s" + else -> "${delayMs / 1_000}.${(delayMs % 1_000).toString().padStart(3, '0').trimEnd('0')} s" + } + +/** + * "if debug=1", "if debug=1 +2" or "if body matches" -- why a rule that shares a path with another + * only sometimes applies. `null` when the rule matches on method and path alone. + */ +internal fun mockRuleConditionHint(rule: InspectorMockRuleUi): String? { + val conditions = + rule.queryPredicates.map { (key, value) -> "$key=$value" } + + rule.headerPredicates.map { (key, value) -> "$key: $value" } + + listOfNotNull(rule.bodyPredicate?.takeIf(String::isNotBlank)?.let { "body matches" }) + val first = conditions.firstOrNull() ?: return null + return "if $first" + if (conditions.size > 1) " +${conditions.size - 1}" else "" +} + +/** + * "returns 200 after 1.2 s · 3 hits · 2m ago" for a static response; a fault or traffic-shaping rule never + * returns its own status, so it leads with its action ("Timeout (3000ms) · 1 hit") instead. + */ +private fun mockRuleSubtitle( + rule: InspectorMockRuleUi, + colors: DevConsoleColors, +): AnnotatedString = + buildAnnotatedString { + if (rule.actionType == InspectorMockActionType.STATIC) { + append("returns ") + val statusColor = + when (rule.statusCode) { + in 500..599 -> colors.error + in 400..499 -> colors.warn + else -> colors.muted + } + withStyle(SpanStyle(color = statusColor)) { append(rule.statusCode.toString()) } + // The action label ("Static response (200)", "Delay (1200ms) → Static response (200)") only + // repeats what is already printed; the delay is the one extra fact worth a few characters. + rule.delayMs?.takeIf { it > 0 }?.let { append(" after ${formatMockDelay(it)}") } + } else { + append( + rule.actionLabel.ifBlank { + rule.actionType.name + .lowercase() + .replace('_', ' ') + }, + ) + } + mockRuleConditionHint(rule)?.let { append(" · $it") } + if (rule.hitCount > 0) { + append(" · ${rule.hitCount} hit${if (rule.hitCount == 1L) "" else "s"}") + rule.lastHitEpochMs?.let { append(" · ${formatRelativeHitTime(it)}") } + } + } diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorCrashGrouping.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorCrashGrouping.kt new file mode 100644 index 0000000..c55c7ca --- /dev/null +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorCrashGrouping.kt @@ -0,0 +1,121 @@ +/** + * @author Shakib + * @since 03/11/26 + */ +package io.devconsole.ui.compose + +private val FRAMEWORK_PACKAGE_PREFIXES = + listOf( + "java.", + "javax.", + "kotlin.", + "kotlinx.", + "android.", + "androidx.", + "com.android.", + "dalvik.", + "libcore.", + "sun.", + ) + +/** A group of crashes sharing the same [crashFingerprint], ordered with the [newest] crash first. */ +internal data class InspectorCrashGroup( + val fingerprint: String, + val newest: InspectorCrashUi, + val count: Int, + val lastSeenEpochMs: Long, + val crashes: List, +) + +/** + * Computes a stable grouping fingerprint for [crash]: + * - Exception class (first line of `stackTrace` up to `':'`, or `summary`'s leading class name). + * - First stack frame line (`"at ..."`) whose package does not start with any framework prefix + * (`java.`, `javax.`, `kotlin.`, `kotlinx.`, `android.`, `androidx.`, `com.android.`, `dalvik.`, + * `libcore.`, `sun.`), falling back to the first frame if every frame is from a framework package. + * - Keeps `"Class.method"` without the trailing `"(File.kt:123)"` so the same crash at a moved line + * still groups together. + */ +internal fun crashFingerprint(crash: InspectorCrashUi): String { + val lines = + crash.stackTrace + .lineSequence() + .map { it.trim() } + .filter { it.isNotEmpty() } + .toList() + val exceptionClass = extractExceptionClass(lines, crash.summary) + val frameMethods = + lines + .filter { it.startsWith("at ") } + .mapNotNull(::extractFrameClassMethod) + val primaryFrame = + frameMethods.firstOrNull { frame -> !isFrameworkFrame(frame) } + ?: frameMethods.firstOrNull() + return if (primaryFrame != null) "$exceptionClass|$primaryFrame" else exceptionClass +} + +private fun extractExceptionClass( + nonEmptyLines: List, + summary: String, +): String { + val candidateFromStack = + nonEmptyLines + .firstOrNull { line -> !line.startsWith("at ") && !line.startsWith("\"") && !line.startsWith("...") } + ?.substringBefore(':') + ?.trim() + ?.takeIf { it.isNotEmpty() } + val summaryHead = summary.substringBefore(':').trim() + return candidateFromStack + ?: summaryHead.takeIf { it.isNotEmpty() }?.let(::exceptionClassFromSummary) + ?: nonEmptyLines + .firstOrNull() + ?.substringBefore(':') + ?.trim() + .orEmpty() +} + +/** A summary like "java.io.IOException boom" names its class first; otherwise keep the whole head. */ +private fun exceptionClassFromSummary(summaryHead: String): String { + val leadingToken = summaryHead.substringBefore(' ').trim() + val looksLikeClass = '.' in leadingToken || leadingToken.endsWith("Exception") || leadingToken.endsWith("Error") + return if (looksLikeClass) leadingToken else summaryHead +} + +private fun extractFrameClassMethod(frameLine: String): String? { + val afterAt = frameLine.removePrefix("at ").trim() + if (afterAt.isEmpty()) return null + val withoutSource = afterAt.substringBefore('(').trim() + val withoutModule = withoutSource.substringAfterLast('/') + return withoutModule.takeIf { it.isNotEmpty() } +} + +private fun isFrameworkFrame(classMethod: String): Boolean = + FRAMEWORK_PACKAGE_PREFIXES.any { prefix -> classMethod.startsWith(prefix) } + +/** True when at least two crashes in [crashes] share the same [crashFingerprint]. */ +internal fun hasDuplicateCrashFingerprints(crashes: List): Boolean { + if (crashes.size < 2) return false + val seen = mutableSetOf() + return crashes.any { crash -> !seen.add(crashFingerprint(crash)) } +} + +/** + * Groups [crashes] by [crashFingerprint], picking the newest crash (`maxBy timestampEpochMs`) as + * the group representative and ordering groups newest-first (`sortedByDescending { it.lastSeenEpochMs }`). + */ +internal fun groupCrashes(crashes: List): List { + if (crashes.isEmpty()) return emptyList() + val sortedNewestFirst = crashes.sortedByDescending { it.timestampEpochMs } + return sortedNewestFirst + .groupBy(::crashFingerprint) + .map { (fingerprint, members) -> + val newest = members.first() + InspectorCrashGroup( + fingerprint = fingerprint, + newest = newest, + count = members.size, + lastSeenEpochMs = newest.timestampEpochMs, + crashes = members, + ) + }.sortedByDescending { it.lastSeenEpochMs } +} diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDataScreen.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDataScreen.kt index 4da16c2..0b957e8 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDataScreen.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDataScreen.kt @@ -33,8 +33,11 @@ import androidx.compose.foundation.lazy.LazyListScope import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.SnackbarHost +import androidx.compose.material3.SnackbarHostState import androidx.compose.material3.Text import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember @@ -72,6 +75,12 @@ internal fun DataRoute( ) { val state by viewModel.state.collectAsStateWithLifecycle() var heroCollapsed by rememberSaveable { mutableStateOf(true) } + val snackbarHostState = remember { SnackbarHostState() } + LaunchedEffect(state.lastCommandResult) { + val result = state.lastCommandResult ?: return@LaunchedEffect + snackbarHostState.showSnackbar(result.toFlashMessage()) + viewModel.dispatch(InspectorAction.DismissCommandResult) + } LifecycleStartEffect(Unit) { viewModel.dispatch(InspectorAction.Refresh) onStopOrDispose { } @@ -96,6 +105,7 @@ internal fun DataRoute( onExecuteSql = { database, sql -> viewModel.dispatch(InspectorAction.ExecuteSql(database, sql)) }, ), modifier = modifier, + snackbarHostState = snackbarHostState, ) } @@ -141,6 +151,7 @@ internal fun DataScreen( databaseActions: DatabaseBrowserActions, modifier: Modifier = Modifier, initialSource: String? = null, + snackbarHostState: SnackbarHostState = remember { SnackbarHostState() }, ) { val colors = DevConsoleTheme.colors val hero = rememberDataHero(state) @@ -154,77 +165,72 @@ internal fun DataScreen( val fadeSpec = feedbackSpec() // imePadding() keeps the SQL console above the soft keyboard; a no-op while the IME is hidden. - Column(modifier = modifier.fillMaxSize().background(colors.ground).imePadding()) { - AnimatedContent( - targetState = active, - transitionSpec = { fadeIn(animationSpec = fadeSpec) togetherWith fadeOut(animationSpec = fadeSpec) }, - label = "dataSourceScreen", - modifier = Modifier.fillMaxSize(), - ) { sourceKey -> - when (sourceKey) { - null -> - DataSourceList(state, hero, heroCollapsed, onToggleHero, onToggleTheme, colors) { - activeSource = it - } - "preferences" -> { - DataSourceSubScreen(title = "Preferences", onBack = { activeSource = null }) { - LazyColumn( - modifier = Modifier.weight(1f), - contentPadding = PaddingValues(top = 4.dp, bottom = 16.dp), - ) { - dataPreferenceRows(state, colors) + Box(modifier = modifier.fillMaxSize().background(colors.ground).imePadding()) { + Column(modifier = Modifier.fillMaxSize()) { + AnimatedContent( + targetState = active, + transitionSpec = { fadeIn(animationSpec = fadeSpec) togetherWith fadeOut(animationSpec = fadeSpec) }, + label = "dataSourceScreen", + modifier = Modifier.fillMaxSize(), + ) { sourceKey -> + when (sourceKey) { + null -> + DataSourceList(state, hero, heroCollapsed, onToggleHero, onToggleTheme, colors) { + activeSource = it } - } - } - "database" -> { - DataSourceSubScreen(title = "Database", onBack = { activeSource = null }) { - Column( - modifier = - Modifier - .weight(1f) - .verticalScroll(rememberScrollState()) - .padding(top = 4.dp, bottom = 16.dp), - ) { - DatabaseSection( - state = state, - canWrite = state.capabilities.database, - actions = databaseActions, - ) + "preferences" -> { + DataSourceSubScreen(title = "Preferences", onBack = { activeSource = null }) { + LazyColumn( + modifier = Modifier.weight(1f), + contentPadding = PaddingValues(top = 4.dp, bottom = 16.dp), + ) { dataPreferenceRows(state, colors) } } } - } - "files" -> { - DataSourceSubScreen(title = "Files", onBack = { activeSource = null }) { - Column( - modifier = - Modifier - .weight(1f) - .verticalScroll(rememberScrollState()) - .padding(top = 4.dp, bottom = 16.dp), - ) { - FilesSection( - state = state, - canEdit = state.capabilities.files, - actions = fileActions, - ) + "database" -> + DataSourceSubScreen(title = "Database", onBack = { activeSource = null }) { + Column( + modifier = + Modifier + .weight(1f) + .verticalScroll(rememberScrollState()) + .padding(top = 4.dp, bottom = 16.dp), + ) { + DatabaseSection( + state = state, + canWrite = state.capabilities.database, + actions = databaseActions, + ) + } } - } - } - "state" -> { - DataSourceSubScreen(title = "App state", onBack = { activeSource = null }) { - Column( - modifier = - Modifier - .weight(1f) - .verticalScroll(rememberScrollState()) - .padding(top = 4.dp, bottom = 16.dp), - ) { - DataStateProviders(state, colors) + "files" -> + DataSourceSubScreen(title = "Files", onBack = { activeSource = null }) { + Column( + modifier = + Modifier + .weight(1f) + .verticalScroll(rememberScrollState()) + .padding(top = 4.dp, bottom = 16.dp), + ) { + FilesSection(state = state, canEdit = state.capabilities.files, actions = fileActions) + } + } + "state" -> + DataSourceSubScreen(title = "App state", onBack = { activeSource = null }) { + Column( + modifier = + Modifier + .weight(1f) + .verticalScroll(rememberScrollState()) + .padding(top = 4.dp, bottom = 16.dp), + ) { DataStateProviders(state, colors) } } - } } } } + SnackbarHost( + hostState = snackbarHostState, + modifier = Modifier.align(Alignment.BottomCenter).padding(16.dp), + ) } } @@ -271,7 +277,7 @@ private fun DataSourceList( if (state.captures(CaptureCategory.INSPECTION)) { DataSourceRow( "Preferences", - "${state.preferenceFiles.size} files", + countLabel(state.preferenceFiles.size, "file"), R.drawable.devconsole_ic_preferences, ) { onOpenSource("preferences") @@ -279,8 +285,8 @@ private fun DataSourceList( GroupedPanelDivider() DataSourceRow( "Database", - state.databaseListing?.let { "${it.name} · ${it.tables.size} tables" } - ?: "${state.databases.size} databases", + state.databaseListing?.let { "${it.name} · ${countLabel(it.tables.size, "table")}" } + ?: countLabel(state.databases.size, "database"), R.drawable.devconsole_ic_database, ) { onOpenSource("database") @@ -288,8 +294,8 @@ private fun DataSourceList( GroupedPanelDivider() DataSourceRow( "Files", - state.fileListing?.let { "${it.entries.size} items" } - ?: "${state.fileRoots.size} roots", + state.fileListing?.let { countLabel(it.entries.size, "item") } + ?: countLabel(state.fileRoots.size, "root"), R.drawable.devconsole_ic_files, ) { onOpenSource("files") @@ -299,7 +305,7 @@ private fun DataSourceList( if (state.captures(CaptureCategory.INSPECTION)) GroupedPanelDivider() DataSourceRow( "App state", - state.stateProviders.size.let { "$it ${if (it == 1) "provider" else "providers"}" }, + countLabel(state.stateProviders.size, "provider"), R.drawable.devconsole_ic_mocks, ) { onOpenSource("state") 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 f60901f..52aaaa5 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 @@ -31,7 +31,7 @@ data class InspectorTransactionUi( val host: String, val path: String, val statusCode: Int?, - val durationMs: Long?, + val durationMs: Long? = null, /** Wall-clock start of the capture, epoch ms; 0 when the adapter predates this field. */ val startedAtEpochMs: Long = 0, val requestHeaders: Map = emptyMap(), @@ -48,6 +48,8 @@ data class InspectorTransactionUi( */ val requestBodyKind: InspectorBodyKind = InspectorBodyKind.ABSENT, val requestBodyTruncated: Boolean = false, + /** True when the response preview was shortened by the capture byte limit. */ + val responseBodyTruncated: Boolean = false, /** Per-phase network timing, when the underlying transport captured it; see [InspectorTimingPhasesUi]. */ val timingPhases: InspectorTimingPhasesUi = InspectorTimingPhasesUi(), /** True when a mock rule answered this request instead of the real network -- from the `mocked` capture tag. */ @@ -176,6 +178,8 @@ data class InspectorTrafficQuery( val search: String = "", val method: String? = null, val statusClass: TrafficStatusClass = TrafficStatusClass.ALL, + /** Exact host to show, or null for every host. */ + val host: String? = null, ) data class InspectorMockRuleUi( @@ -205,8 +209,50 @@ data class InspectorMockRuleUi( * the create/edit form passes it through untouched rather than binding it to a field. */ val sourceBodySnapshot: String? = null, + /** True when a capture-derived source response preview was truncated at capture time. */ + val responseBodyTruncated: Boolean = false, + /** + * Which `MockAction` shape this rule carries. [InspectorMockActionType.OTHER] is the read-only + * bucket for shapes the on-device form cannot express losslessly (sequence/template/passthrough, + * or a delayed non-static action) -- [isEditableOnDevice] refuses those. + */ + val actionType: InspectorMockActionType = InspectorMockActionType.STATIC, + /** [InspectorMockActionType.TIMEOUT]: how long the mocked request hangs, in ms. */ + val timeoutMs: Long? = null, + /** [InspectorMockActionType.CONNECTION_FAILURE]: optional custom failure message. */ + val failureMessage: String? = null, + /** [InspectorMockActionType.THROTTLE]: throughput cap in bytes per second. */ + val throttleBytesPerSecond: Long? = null, + /** [InspectorMockActionType.THROTTLE]: added latency in ms. */ + val throttleLatencyMs: Long? = null, + /** [InspectorMockActionType.MAP_REMOTE]: replacement scheme; null leaves it unchanged. */ + val remoteScheme: String? = null, + /** [InspectorMockActionType.MAP_REMOTE]: replacement host; null leaves it unchanged. */ + val remoteHost: String? = null, + /** [InspectorMockActionType.MAP_REMOTE]: replacement path; null leaves it unchanged. */ + val remotePath: String? = null, + /** [InspectorMockActionType.MAP_REMOTE]: replacement port; null leaves it unchanged. */ + val remotePort: Int? = null, + /** Request query parameters a request must carry for the rule to match. */ + val queryPredicates: Map = emptyMap(), + /** Request headers a request must carry for the rule to match. */ + val headerPredicates: Map = emptyMap(), + /** Request body regex the rule only matches when body matching is enabled; null means any. */ + val bodyPredicate: String? = null, ) +/** The on-device editable mock actions; [OTHER] covers shapes the form refuses to rewrite. */ +enum class InspectorMockActionType { + STATIC, + STATUS_OVERRIDE, + BODY_REPLACEMENT, + CONNECTION_FAILURE, + TIMEOUT, + THROTTLE, + MAP_REMOTE, + OTHER, +} + data class InspectorSocketFrameUi( val direction: String, val frameType: String, @@ -397,6 +443,10 @@ data class InspectorSessionUi( val status: String = "UNKNOWN", val recordCount: Long = 0, val estimatedBytes: Long = 0, + /** True for the run this process is capturing right now; it is browsed live, never as a past run. */ + val isCurrent: Boolean = false, + /** Kept by retention until unpinned. */ + val pinned: Boolean = false, ) /** Mirrors [io.devconsole.server.api.SdkHealthSnapshot]'s counter types (all `Long`, plus `state`). */ @@ -458,7 +508,13 @@ data class InspectorRemoteConfigEntryUi( val source: String, val redacted: Boolean = false, val truncated: Boolean = false, -) + /** The provider's own (redacted) value while a local override replaces it; null otherwise. */ + val providerValue: String? = null, + /** Wire name of the source [providerValue] came from; null when no override is active. */ + val providerSource: String? = null, +) { + val overridden: Boolean get() = providerSource != null +} /** One Remote Config provider and its fetch state, as shown on the Observe surface's Config tab. */ data class InspectorRemoteConfigUi( @@ -472,6 +528,13 @@ data class InspectorRemoteConfigUi( val unavailableReason: String? = null, ) +/** One run's traffic captures, as returned by [InspectorDataSource.capturesForSession]. */ +data class InspectorSessionCaptures( + val transactions: List = emptyList(), + val sockets: List = emptyList(), + val pushEvents: List = emptyList(), +) + data class InspectorSnapshot( val available: Boolean = false, val transactions: List = emptyList(), @@ -571,6 +634,22 @@ interface InspectorDataSource { */ suspend fun crashesForSession(sessionId: String?): List = snapshot().crashes + /** Pins or unpins a finished run against retention. Unavailable without durable storage. */ + suspend fun setSessionPinned( + sessionId: String, + pinned: Boolean, + ): InspectorCommandResult = InspectorCommandResult.Unavailable + + /** Deletes a finished run and its captures. Unavailable without durable storage. */ + suspend fun deleteSession(sessionId: String): InspectorCommandResult = InspectorCommandResult.Unavailable + + /** + * Network, socket and push captures for a past run (null means the live run), shown by the + * Observe tabs while a retained run is selected. Defaults to the live snapshot's lists. + */ + suspend fun capturesForSession(sessionId: String?): InspectorSessionCaptures = + snapshot().let { InspectorSessionCaptures(it.transactions, it.sockets, it.pushEvents) } + /** * Evidence-tray flag state for captured network transactions, durable via `EvidenceStore` -- * the same store the dashboard's evidence tray reads and writes, so a flag made on this device @@ -611,6 +690,47 @@ interface InspectorDataSource { sessionId: String? = null, ): InspectorCommandResult = InspectorCommandResult.Unavailable + /** + * The wire protocol this adapter can write a frame on for [connectionId] -- "websocket" or + * "mqtt" -- or null when the connection cannot be written to (closed, unknown, or no adapter + * registered). Defaults to null so every existing adapter and fake keeps compiling; the send + * composer is hidden while this is null. + */ + fun socketSendProtocol(connectionId: String): String? = null + + /** + * Sends [text] as one frame over the live connection [connectionId]; [topic], [qos] and + * [retained] describe an MQTT publish and are ignored by a WebSocket sender. Success means the + * transport accepted the frame, so the composer clears only on success. Defaults to + * [InspectorCommandResult.Unavailable] like this interface's other optional commands. + */ + fun sendSocketFrame( + connectionId: String, + text: String, + topic: String? = null, + qos: Int = 0, + retained: Boolean = false, + ): InspectorCommandResult = InspectorCommandResult.Unavailable + + /** True when this adapter can apply local Remote Config overrides; gates the in-app editor. */ + fun supportsRemoteConfigOverrides(): Boolean = false + + /** Overrides [key] on [providerId] with [value] locally; the provider's own value is kept. */ + fun setRemoteConfigOverride( + providerId: String, + key: String, + value: String, + ): InspectorCommandResult = InspectorCommandResult.Unavailable + + /** Removes the local override for [key] on [providerId], restoring the provider's value. */ + fun clearRemoteConfigOverride( + providerId: String, + key: String, + ): InspectorCommandResult = InspectorCommandResult.Unavailable + + /** Removes every local Remote Config override. */ + fun clearAllRemoteConfigOverrides(): InspectorCommandResult = InspectorCommandResult.Unavailable + fun execute(request: InspectorComposerRequest): InspectorCommandResult fun setMocksEnabled(enabled: Boolean): InspectorCommandResult @@ -710,6 +830,33 @@ interface InspectorDataSource { */ fun clearTransactions(): InspectorCommandResult = InspectorCommandResult.Unavailable + /** + * Whether this adapter can pause/resume live capture and purge captured data at all -- the More + * screen's Capture group is hidden when false, matching [supportsServerControl]'s convention. + * Defaults to false so every existing adapter and fake keeps compiling and behaving unchanged. + */ + fun supportsCaptureControl(): Boolean = false + + /** + * Whether live capture is currently paused. Defaults to false ("capturing") for adapters that + * never pause, so callers can read this unconditionally. + */ + fun isCapturePaused(): Boolean = false + + /** + * Pauses or resumes live capture of requests, sockets, logs and push events, backing the More + * screen's "Pause capture" switch. Defaults to [InspectorCommandResult.Unavailable] like the + * other optional commands on this interface. + */ + fun setCapturePaused(paused: Boolean): InspectorCommandResult = InspectorCommandResult.Unavailable + + /** + * Removes this run's captured traffic and deletes old unpinned runs, backing the More screen's + * destructive "Purge captured data" action. The [InspectorCommandResult.Success] summary + * reports exactly what was removed. Defaults to [InspectorCommandResult.Unavailable]. + */ + suspend fun purgeCapturedData(): InspectorCommandResult = InspectorCommandResult.Unavailable + /** * Exports captured network traffic as a HAR file, sharing the result via the same * `FileProvider`/Share-sheet flow as [shareableFilePath]. [transactionIds] mirrors whatever the diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDatabaseSection.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDatabaseSection.kt index cce5e82..99949d4 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDatabaseSection.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDatabaseSection.kt @@ -20,16 +20,19 @@ import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Text import androidx.compose.material3.minimumInteractiveComponentSize import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember +import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalFocusManager import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.semantics.semantics import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp @@ -50,15 +53,25 @@ internal fun DatabaseSection( ) { // Defensive: databases belong to the INSPECTION category -- see FilesSection's identical guard. if (!state.captures(CaptureCategory.INSPECTION)) return + // With a single database there is nothing to choose: open it so its tables and the SQL console + // are ready instead of asking for a tap on the only chip. Keyed on the list, so it runs once per + // listing and never loops when the open fails. + val onlyDatabase = state.databases.singleOrNull() + LaunchedEffect(onlyDatabase) { + if (onlyDatabase != null && state.databaseListing == null) actions.onOpenDatabase(onlyDatabase) + } Column(verticalArrangement = Arrangement.spacedBy(12.dp)) { when { state.databases.isEmpty() -> InspectorEmptyState(EmptySpot.Database, "No app databases found.") else -> { - DatabaseChips( - databases = state.databases, - selected = state.databaseListing?.name, - onOpenDatabase = actions.onOpenDatabase, - ) + // The tables card already names the only database, so a one-chip picker is noise. + if (onlyDatabase == null) { + DatabaseChips( + databases = state.databases, + selected = state.databaseListing?.name, + onOpenDatabase = actions.onOpenDatabase, + ) + } state.databaseListing?.let { listing -> DatabaseTablesCard(listing = listing, onOpenTable = actions.onOpenTable) } @@ -178,6 +191,11 @@ private fun QueryResultTable(result: InspectorQueryResultUi) { modifier = Modifier.horizontalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(4.dp), ) { + Text( + text = "${result.rows.size} ${if (result.rows.size == 1) "row" else "rows"}", + color = colors.muted, + style = TerminalType.labelSmall, + ) Row { result.columns.forEach { column -> Text( @@ -187,7 +205,7 @@ private fun QueryResultTable(result: InspectorQueryResultUi) { fontWeight = FontWeight.Bold, style = TerminalType.bodySmall, modifier = Modifier.width(160.dp).padding(8.dp), - textAlign = TextAlign.End, + textAlign = TextAlign.Start, ) } } @@ -195,13 +213,17 @@ private fun QueryResultTable(result: InspectorQueryResultUi) { GroupedPanelDivider() Row { row.forEach { value -> + // Long values (a CREATE TABLE statement, a JSON blob) would otherwise wrap into a + // column dozens of lines tall and push every other row off screen. Text( value, color = colors.muted, fontFamily = FontFamily.Monospace, style = TerminalType.bodySmall, + maxLines = QUERY_CELL_MAX_LINES, + overflow = TextOverflow.Ellipsis, modifier = Modifier.width(160.dp).padding(8.dp), - textAlign = TextAlign.End, + textAlign = TextAlign.Start, ) } } @@ -226,11 +248,29 @@ private fun SqlConsoleCard( val colors = DevConsoleTheme.colors GroupedPanel { Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) { - Text("SQL console", color = colors.ink) - var draft by remember { mutableStateOf("") } + Text( + text = selectedDatabase?.let { "SQL console · $it" } ?: "SQL console", + color = colors.ink, + ) + var draft by rememberSaveable { mutableStateOf("") } + val focusManager = LocalFocusManager.current OutlinedTextField( value = draft, onValueChange = { draft = it }, + placeholder = { + Text( + text = + if (selectedDatabase == + null + ) { + "Pick a database above first" + } else { + "SELECT * FROM table LIMIT 50" + }, + color = colors.muted, + style = TerminalType.bodySmall.copy(fontFamily = FontFamily.Monospace), + ) + }, textStyle = TerminalType.bodySmall.copy(fontFamily = FontFamily.Monospace), shape = RoundedCornerShape(12.dp), colors = @@ -247,16 +287,20 @@ private fun SqlConsoleCard( text = "Read-only — enable the database capability to run write statements.", ) } - val canRun = selectedDatabase != null && draft.isNotBlank() - if (canRun) { - InspectorPillButton( - label = "RUN", - onClick = { onExecuteSql(requireNotNull(selectedDatabase), draft) }, - containerColor = colors.signal, - contentColor = colors.signalInk, - modifier = Modifier.semantics { contentDescription = "Run SQL statement" }, - ) - } + // Always shown (disabled until there is something to run) so the action is discoverable + // before typing; it used to appear only once the field had text, under the keyboard. + InspectorPillButton( + label = "RUN", + onClick = { + // Drop the keyboard so the result, rendered just below, is actually visible. + focusManager.clearFocus() + selectedDatabase?.let { database -> onExecuteSql(database, draft) } + }, + containerColor = colors.signal, + contentColor = colors.signalInk, + enabled = selectedDatabase != null && draft.isNotBlank(), + modifier = Modifier.semantics { contentDescription = "Run SQL statement" }, + ) sqlResult?.let { SqlResultView(it) } } } @@ -269,7 +313,7 @@ private fun SqlResultView(result: InspectorSqlResultUi) { is InspectorSqlResultUi.Rows -> QueryResultTable(result.result) is InspectorSqlResultUi.Wrote -> Text( - text = "${result.affectedRows} row(s) affected", + text = "${result.affectedRows} ${if (result.affectedRows == 1) "row" else "rows"} affected", color = colors.ink, style = TerminalType.bodySmall, ) @@ -339,3 +383,5 @@ private fun DatabaseSectionReadOnlyPreview() { ) } } + +private const val QUERY_CELL_MAX_LINES = 3 diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorEmptyState.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorEmptyState.kt index d36be74..c1e8ed2 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorEmptyState.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorEmptyState.kt @@ -41,6 +41,7 @@ internal enum class EmptySpot( Search(R.drawable.devconsole_spot_search, R.drawable.devconsole_spot_search_accent), Folder(R.drawable.devconsole_spot_folder, R.drawable.devconsole_spot_folder_accent), Database(R.drawable.devconsole_spot_database, R.drawable.devconsole_spot_database_accent), + Control(R.drawable.devconsole_spot_mocks, R.drawable.devconsole_spot_mocks_accent), } @Composable diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorFilesSection.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorFilesSection.kt index 71151f0..d37b8b8 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorFilesSection.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorFilesSection.kt @@ -13,9 +13,14 @@ import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.AlertDialog import androidx.compose.material3.Text import androidx.compose.material3.minimumInteractiveComponentSize import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip @@ -27,6 +32,8 @@ import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import io.devconsole.api.CaptureCategory +private const val FILE_LIST_INITIAL_LIMIT = 200 + /** * Grouped callbacks for the read-only-by-default app file browser. Delete and share are both * capability-gated -- share hands the caller a real, unredacted file, the same reasoning that gates @@ -46,6 +53,7 @@ internal fun FilesSection( canEdit: Boolean, actions: FileBrowserActions, ) { + var pendingDelete by remember { mutableStateOf?>(null) } // Defensive: files belong to the INSPECTION category. Hiding the DATA destination entirely // (DevConsoleWorkspace.workspaceNavItems) is the primary gate, but this section stays inert on // its own too, in case something ever reaches it by a route other than that nav item. @@ -59,15 +67,48 @@ internal fun FilesSection( selected = state.fileListing?.root, onOpenRoot = actions.onOpenPath, ) - state.fileListing?.let { listing -> - FileListingCard(listing = listing, canEdit = canEdit, actions = actions) - } state.filePreview?.let { preview -> - FilePreviewCard(preview = preview, onClose = actions.onClosePreview) + FilePreviewCard(preview = preview, name = state.filePreviewName, onClose = actions.onClosePreview) + } + state.fileListing?.let { listing -> + FileListingCard(listing = listing, canEdit = canEdit, actions = actions) { root, path -> + pendingDelete = root to path + } } } } } + pendingDelete?.let { (root, path) -> + val name = path.substringAfterLast('/') + AlertDialog( + onDismissRequest = { pendingDelete = null }, + title = { Text("Delete file?") }, + text = { Text("\"$name\" will be permanently deleted from $root. This can't be undone.") }, + confirmButton = { + Text( + "DELETE", + color = DevConsoleTheme.colors.error, + modifier = + Modifier + .clickable { + actions.onDelete(root, path) + pendingDelete = null + }.padding(12.dp), + ) + }, + dismissButton = { + Text( + "CANCEL", + color = DevConsoleTheme.colors.muted, + modifier = + Modifier + .clickable { + pendingDelete = null + }.padding(12.dp), + ) + }, + ) + } } @Composable @@ -105,6 +146,7 @@ private fun FileListingCard( listing: InspectorFileListingUi, canEdit: Boolean, actions: FileBrowserActions, + onDelete: (String, String) -> Unit, ) { GroupedPanel { val here = if (listing.relativePath.isEmpty()) listing.root else "${listing.root}/${listing.relativePath}" @@ -130,9 +172,18 @@ private fun FileListingCard( modifier = Modifier.padding(16.dp), ) } else { - listing.entries.forEach { entry -> + listing.entries.take(FILE_LIST_INITIAL_LIMIT).forEach { entry -> GroupedPanelDivider() - FileEntryRow(root = listing.root, entry = entry, canEdit = canEdit, actions = actions) + FileEntryRow(root = listing.root, entry = entry, canEdit = canEdit, actions = actions) { + onDelete(listing.root, entry.relativePath) + } + } + if (listing.entries.size > FILE_LIST_INITIAL_LIMIT) { + Text( + "Showing first $FILE_LIST_INITIAL_LIMIT of ${listing.entries.size} entries.", + color = DevConsoleTheme.colors.muted, + modifier = Modifier.padding(16.dp), + ) } } } @@ -149,6 +200,7 @@ private fun FileEntryRow( entry: InspectorFileEntryUi, canEdit: Boolean, actions: FileBrowserActions, + onDelete: () -> Unit, ) { val colors = DevConsoleTheme.colors Column(modifier = Modifier.fillMaxWidth()) { @@ -168,7 +220,7 @@ private fun FileEntryRow( } }, ) - if (canEdit && !entry.isDirectory) FileEntryActions(root, entry, actions) + if (canEdit && !entry.isDirectory) FileEntryActions(root, entry, actions, onDelete) } } @@ -177,10 +229,12 @@ private fun FileEntryActions( root: String, entry: InspectorFileEntryUi, actions: FileBrowserActions, + onDelete: () -> Unit, ) { - Row(modifier = Modifier.padding(bottom = 8.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) { + // 6dp + each label's own 10dp padding lines the labels up with the row title's 16dp inset. + Row(modifier = Modifier.padding(start = 6.dp, bottom = 8.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) { FileEntryActionText("SHARE", "Share file ${entry.name}") { actions.onShare(root, entry.relativePath) } - FileEntryActionText("DEL", "Delete file ${entry.name}") { actions.onDelete(root, entry.relativePath) } + FileEntryActionText("DELETE", "Delete file ${entry.name}", onDelete) } } @@ -233,6 +287,7 @@ private fun FileRow( @Composable private fun FilePreviewCard( preview: InspectorFilePreviewUi, + name: String?, onClose: () -> Unit, ) { val colors = DevConsoleTheme.colors @@ -243,7 +298,7 @@ private fun FilePreviewCard( horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically, ) { - Text("Preview", color = colors.ink) + Text(name?.let { "Preview · $it" } ?: "Preview", color = colors.ink) Text( text = "CLOSE", color = colors.muted, diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorFlagEditDialogs.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorFlagEditDialogs.kt new file mode 100644 index 0000000..44063e2 --- /dev/null +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorFlagEditDialogs.kt @@ -0,0 +1,157 @@ +/** + * @author Shakib + * @since 03/11/26 + */ +@file:Suppress("FunctionNaming", "MagicNumber") + +package io.devconsole.ui.compose + +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.RadioButton +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.input.KeyboardType +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp + +private val NUMERIC_FLAG_TYPES = setOf("INT", "INTEGER", "LONG", "NUMBER") +private val DECIMAL_FLAG_TYPES = setOf("FLOAT", "DOUBLE", "DECIMAL") + +/** True for the flag types a soft numeric keypad suits. */ +internal fun flagValueUsesNumericKeyboard(type: String): Boolean = + type.uppercase() in NUMERIC_FLAG_TYPES || type.uppercase() in DECIMAL_FLAG_TYPES + +/** Decimal-point keypad for fractional types; the plain number pad otherwise. */ +internal fun flagValueKeyboardType(type: String): KeyboardType = + if (type.uppercase() in DECIMAL_FLAG_TYPES) KeyboardType.Decimal else KeyboardType.Number + +/** + * Validates a typed flag value against its declared type: booleans must be literal true/false and + * numeric types must parse. Every other type (the free-form STRING flags) accepts any non-blank text. + */ +internal fun isValidFeatureFlagValue( + type: String, + value: String, +): Boolean { + val trimmed = value.trim() + if (trimmed.isEmpty()) return false + return when { + type.equals("BOOLEAN", ignoreCase = true) -> trimmed.lowercase() == "true" || trimmed.lowercase() == "false" + flagValueUsesNumericKeyboard(type) -> trimmed.toDoubleOrNull() != null + else -> true + } +} + +/** + * Single-choice editor for a mutable flag whose [InspectorFeatureFlagUi.allowedValues] names the + * only values the host accepts. Picking an option confirms immediately; there is nothing to type. + */ +@Composable +internal fun FeatureFlagChoiceDialog( + flag: InspectorFeatureFlagUi, + onConfirm: (String) -> Unit, + onDismiss: () -> Unit, +) { + AlertDialog( + onDismissRequest = onDismiss, + title = { Text(flag.key) }, + text = { + Column(Modifier.verticalScroll(rememberScrollState())) { + flag.allowedValues.forEach { option -> + Row( + modifier = + Modifier + .fillMaxWidth() + .clickable { onConfirm(option) } + .padding(vertical = 6.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + RadioButton(selected = option == flag.value, onClick = { onConfirm(option) }) + Text(option, fontSize = 14.sp, modifier = Modifier.padding(start = 8.dp)) + } + } + } + }, + confirmButton = {}, + dismissButton = { + TextButton(onClick = onDismiss) { Text("Cancel") } + }, + ) +} + +/** + * Free-text editor for a mutable flag with no declared option list (STRING and numeric types). + * [InspectorFeatureFlagUi.defaultValue] is one tap away, and an invalid number keeps Set disabled + * rather than sending a value the host would reject. + */ +@Composable +internal fun FeatureFlagTextDialog( + flag: InspectorFeatureFlagUi, + onConfirm: (String) -> Unit, + onDismiss: () -> Unit, +) { + val colors = DevConsoleTheme.colors + var value by rememberSaveable(flag.key) { mutableStateOf(flag.value) } + val numeric = flagValueUsesNumericKeyboard(flag.type) + val valid = isValidFeatureFlagValue(flag.type, value) + AlertDialog( + onDismissRequest = onDismiss, + title = { Text(flag.key) }, + text = { + Column { + OutlinedTextField( + value = value, + onValueChange = { value = it }, + singleLine = true, + isError = !valid, + keyboardOptions = + if (numeric) { + KeyboardOptions(keyboardType = flagValueKeyboardType(flag.type)) + } else { + KeyboardOptions.Default + }, + modifier = Modifier.fillMaxWidth(), + ) + if (!valid) { + Text( + "Enter a valid ${flag.type.lowercase()} value", + color = colors.error, + fontSize = 12.sp, + modifier = Modifier.padding(top = 4.dp), + ) + } + Text( + "Default: ${flag.defaultValue}", + color = colors.muted, + fontSize = 12.sp, + modifier = Modifier.padding(top = 8.dp), + ) + TextButton(onClick = { onConfirm(flag.defaultValue) }) { + Text("Reset to default", color = colors.signal, fontSize = 13.sp) + } + } + }, + confirmButton = { + TextButton(onClick = { onConfirm(value.trim()) }, enabled = valid) { Text("Set") } + }, + dismissButton = { + TextButton(onClick = onDismiss) { Text("Cancel", color = colors.muted) } + }, + ) +} diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorMockRuleEditor.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorMockRuleEditor.kt index 277f18c..7f7a52a 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorMockRuleEditor.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorMockRuleEditor.kt @@ -35,6 +35,9 @@ import androidx.compose.foundation.relocation.bringIntoViewRequester import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.Checkbox +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.minimumInteractiveComponentSize @@ -152,10 +155,7 @@ private fun MockRuleEditorTarget.formSourceKey(): String = } /** - * Bundle-friendly [Saver] for a nullable [MockRuleEditorTarget.New] so the sheet's *open/closed* - * state (not just its individual field values, which already use [rememberSaveable]) survives a - * configuration change such as rotation. Every [InspectorMockRuleUi] field is a primitive or - * a [Map] of strings, so the map is flattened via the same header-line format the form fields use. + * Bundle-friendly [Saver] for a nullable new-rule target, preserving draft metadata and open state. */ internal val MockRuleEditorNewSaver: Saver = listSaver( @@ -178,9 +178,22 @@ internal val MockRuleEditorNewSaver: Saver = draft?.delayMs, draft?.hitCount, draft?.lastHitEpochMs, + draft?.sourceBodySnapshot, + draft?.responseBodyTruncated, target?.prefillNote, target?.sourceKey, - draft?.sourceBodySnapshot, + draft?.actionType?.ordinal, + draft?.timeoutMs, + draft?.failureMessage, + draft?.throttleBytesPerSecond, + draft?.throttleLatencyMs, + draft?.remoteScheme, + draft?.remoteHost, + draft?.remotePath, + draft?.remotePort, + draft?.queryPredicates?.toMockRulePredicateLines(), + draft?.headerPredicates?.toMockRulePredicateLines(), + draft?.bodyPredicate, ) }, restore = { saved -> @@ -203,10 +216,29 @@ internal val MockRuleEditorNewSaver: Saver = delayMs = saved[13] as Long?, hitCount = saved[14] as Long, lastHitEpochMs = saved[15] as Long?, - sourceBodySnapshot = saved[18] as String?, + sourceBodySnapshot = saved[16] as String?, + responseBodyTruncated = saved[17] as Boolean, + actionType = + InspectorMockActionType.entries[ + (saved.getOrNull(20) as? Int ?: InspectorMockActionType.STATIC.ordinal) + .coerceIn(0, InspectorMockActionType.entries.lastIndex), + ], + timeoutMs = saved.getOrNull(21) as Long?, + failureMessage = saved.getOrNull(22) as String?, + throttleBytesPerSecond = saved.getOrNull(23) as Long?, + throttleLatencyMs = saved.getOrNull(24) as Long?, + remoteScheme = saved.getOrNull(25) as String?, + remoteHost = saved.getOrNull(26) as String?, + remotePath = saved.getOrNull(27) as String?, + remotePort = saved.getOrNull(28) as Int?, + queryPredicates = + parseMockRulePredicateLines(saved.getOrNull(29) as? String ?: "").predicates, + headerPredicates = + parseMockRulePredicateLines(saved.getOrNull(30) as? String ?: "").predicates, + bodyPredicate = saved.getOrNull(31) as String?, ), - prefillNote = saved[16] as String?, - sourceKey = saved[17] as String, + prefillNote = saved[18] as String?, + sourceKey = saved[19] as String, ) }, ) @@ -215,11 +247,35 @@ internal val MOCK_RULE_METHODS = listOf("ALL", "GET", "POST", "PUT", "PATCH", "D /** Everything the sheet's Save button needs validated, recomputed via [remember] as the fields change. */ private data class MockRuleFormErrors( - val id: String?, - val status: String?, - val delay: String?, + val id: String? = null, + val status: String? = null, + val delay: String? = null, + val timeout: String? = null, + val throttleRate: String? = null, + val throttleLatency: String? = null, + val remote: String? = null, + val remoteScheme: String? = null, + val remoteHost: String? = null, + val remotePath: String? = null, + val remotePort: String? = null, ) { - val isValid: Boolean get() = id == null && status == null && delay == null + val allErrors: List + get() = + listOfNotNull( + id, + status, + delay, + timeout, + throttleRate, + throttleLatency, + remote, + remoteScheme, + remoteHost, + remotePath, + remotePort, + ) + + val isValid: Boolean get() = allErrors.isEmpty() } /** @@ -238,16 +294,13 @@ internal fun MockRuleEditorScreen( modifier: Modifier = Modifier, onDelete: (() -> Unit)? = null, ) { - val initial = - when (target) { - is MockRuleEditorTarget.Edit -> target.rule - is MockRuleEditorTarget.New -> target.draft - } + val initial = target.initialRule() val isNew = target is MockRuleEditorTarget.New val colors = DevConsoleTheme.colors val form = rememberMockRuleFormFields(initial, target.formSourceKey()) val errors = rememberMockRuleFormErrors(form) var showErrors by remember { mutableStateOf(false) } + var acknowledgedTruncatedBody by rememberSaveable(target.formSourceKey()) { mutableStateOf(false) } var advancedExpanded by rememberSaveable { mutableStateOf(false) } // Collapsed when the rule already carries headers -- a capture prefill dumps 20+ lines here and // pushed status/body off-screen. A blank rule opens expanded: nothing to hide, and the field is @@ -287,31 +340,33 @@ internal fun MockRuleEditorScreen( // Save is never a silent no-op: the delay field lives inside the collapsed // Advanced expander, so a delay-only error would otherwise be invisible at // the point of interaction (the footer is pinned while content scrolls). - if (showErrors && !errors.isValid) { - MockRuleSaveErrorSummary(errors, colors) - } - MockRuleEditorFooter( + MockRuleEditorFooterContent( + errors = errors, + showErrors = showErrors, colors = colors, onCancel = onCancel, onSaveClick = { showErrors = true if (errors.delay != null) advancedExpanded = true - if (errors.isValid) onSave(form.toMockRule(initial)) + val bodyCleared = !isTruncatedCapture(target) || acknowledgedTruncatedBody + if (errors.isValid && bodyCleared) onSave(form.toMockRule(initial)) }, ) } } }, ) { - MockRuleEditorPrimaryFields(form, colors, isNew, errors, showErrors) - MockRuleEditorBodyFields( + MockRuleEditorFormContent( form = form, + target = target, colors = colors, + isNew = isNew, + errors = errors, showErrors = showErrors, - delayError = errors.delay, advancedExpanded = advancedExpanded, onAdvancedExpandedChange = { advancedExpanded = it }, - prefillNote = (target as? MockRuleEditorTarget.New)?.prefillNote, + acknowledgedTruncatedBody = acknowledgedTruncatedBody, + onAcknowledgeTruncatedBody = { acknowledgedTruncatedBody = it }, bodyState = bodyState, headersExpanded = headersExpanded, onHeadersExpandedChange = { headersExpanded = it }, @@ -353,25 +408,151 @@ internal fun MockRuleEditorScreen( } @Composable -private fun rememberMockRuleFormErrors(form: MockRuleFormFields): MockRuleFormErrors = - remember(form.id.value, form.statusText.value, form.delayText.value) { +private fun MockRuleEditorFooterContent( + errors: MockRuleFormErrors, + showErrors: Boolean, + colors: DevConsoleColors, + onCancel: () -> Unit, + onSaveClick: () -> Unit, +) { + // Errors stay hidden until the first Save: a fresh form (blank id, a just-picked action) is + // incomplete, not wrong, and greeting it in red reads as a failure the user didn't cause. + if (showErrors && !errors.isValid) MockRuleSaveErrorSummary(errors, colors) + MockRuleEditorFooter(colors, onCancel, onSaveClick) +} + +@Composable +private fun MockRuleEditorFormContent( + form: MockRuleFormFields, + target: MockRuleEditorTarget, + colors: DevConsoleColors, + isNew: Boolean, + errors: MockRuleFormErrors, + showErrors: Boolean, + advancedExpanded: Boolean, + onAdvancedExpandedChange: (Boolean) -> Unit, + acknowledgedTruncatedBody: Boolean, + onAcknowledgeTruncatedBody: (Boolean) -> Unit, + bodyState: MockRuleBodyEditorState, + headersExpanded: Boolean, + onHeadersExpandedChange: (Boolean) -> Unit, +) { + MockRuleEditorPrimaryFields(form, colors, isNew, errors, showErrors) + MockRuleEditorActionFields(form, colors, errors, showErrors) + MockRuleEditorBodyFields( + form = form, + colors = colors, + showErrors = showErrors, + delayError = errors.delay, + advancedExpanded = advancedExpanded, + onAdvancedExpandedChange = onAdvancedExpandedChange, + prefillNote = (target as? MockRuleEditorTarget.New)?.prefillNote, + truncationWarning = + if (isTruncatedCapture(target)) { + "Captured response was truncated. Review or edit the body, then confirm below before saving." + } else { + null + }, + acknowledgedTruncatedBody = acknowledgedTruncatedBody, + onAcknowledgeTruncatedBody = onAcknowledgeTruncatedBody, + bodyState = bodyState, + headersExpanded = headersExpanded, + onHeadersExpandedChange = onHeadersExpandedChange, + ) +} + +private fun MockRuleEditorTarget.initialRule(): InspectorMockRuleUi = + when (this) { + is MockRuleEditorTarget.Edit -> rule + is MockRuleEditorTarget.New -> draft + } + +@Composable +private fun rememberMockRuleFormErrors(form: MockRuleFormFields): MockRuleFormErrors { + val type = form.actionType.value + return remember( + type, + form.id.value, + form.statusText.value, + form.delayText.value, + form.timeoutText.value, + form.throttleKbpsText.value, + form.throttleLatencyText.value, + form.remoteSchemeText.value, + form.remoteHostText.value, + form.remotePortText.value, + form.remotePathText.value, + ) { MockRuleFormErrors( id = mockRuleIdError(form.id.value.trim()), status = - mockRuleStatusError( - form.statusText.value - .trim() - .toIntOrNull(), - ), + if (type.usesStatusCode) { + mockRuleStatusError( + form.statusText.value + .trim() + .toIntOrNull(), + ) + } else { + null + }, delay = - mockRuleDelayError( - form.delayText.value.trim(), - form.delayText.value - .trim() - .toLongOrNull(), - ), + if (type == InspectorMockActionType.STATIC) { + mockRuleDelayError( + form.delayText.value.trim(), + form.delayText.value + .trim() + .toLongOrNull(), + ) + } else { + null + }, + timeout = if (type == InspectorMockActionType.TIMEOUT) form.timeoutError() else null, + throttleRate = if (type == InspectorMockActionType.THROTTLE) form.throttleRateError() else null, + throttleLatency = if (type == InspectorMockActionType.THROTTLE) form.throttleLatencyError() else null, + remote = if (type == InspectorMockActionType.MAP_REMOTE) form.mapRemoteError() else null, + remoteScheme = if (type == InspectorMockActionType.MAP_REMOTE) form.remoteSchemeError() else null, + remoteHost = if (type == InspectorMockActionType.MAP_REMOTE) form.remoteHostError() else null, + remotePath = if (type == InspectorMockActionType.MAP_REMOTE) form.remotePathError() else null, + remotePort = if (type == InspectorMockActionType.MAP_REMOTE) form.remotePortError() else null, ) } +} + +private val InspectorMockActionType.usesStatusCode: Boolean + get() = this == InspectorMockActionType.STATIC || this == InspectorMockActionType.STATUS_OVERRIDE + +private fun MockRuleFormFields.timeoutError(): String? = + mockRuleTimeoutError(timeoutText.value.trim(), timeoutText.value.trim().toLongOrNull()) + +private fun MockRuleFormFields.throttleRateError(): String? { + val bytesPerSecond = + throttleKbpsText.value + .trim() + .toLongOrNull() + ?.times(MOCK_RULE_BYTES_PER_KB) + return mockRuleThrottleRateError(throttleKbpsText.value.trim(), bytesPerSecond) +} + +private fun MockRuleFormFields.throttleLatencyError(): String? = + mockRuleThrottleLatencyError(throttleLatencyText.value.trim(), throttleLatencyText.value.trim().toLongOrNull()) + +private fun MockRuleFormFields.mapRemoteError(): String? = + mockRuleMapRemoteError( + hasAnyField = + remoteSchemeText.value.isNotBlank() || + remoteHostText.value.isNotBlank() || + remotePortText.value.isNotBlank() || + remotePathText.value.isNotBlank(), + ) + +private fun MockRuleFormFields.remoteSchemeError(): String? = mockRuleRemoteSchemeError(remoteSchemeText.value.trim()) + +private fun MockRuleFormFields.remoteHostError(): String? = mockRuleRemoteHostError(remoteHostText.value.trim()) + +private fun MockRuleFormFields.remotePathError(): String? = mockRuleRemotePathError(remotePathText.value.trim()) + +private fun MockRuleFormFields.remotePortError(): String? = + mockRuleRemotePortError(remotePortText.value.trim(), remotePortText.value.trim().toIntOrNull()) @Composable private fun MockRuleEditorFooter( @@ -389,7 +570,11 @@ private fun MockRuleEditorFooter( contentColor = colors.ink, outlined = true, ), - InspectorFooterAction(label = "Save rule", onClick = onSaveClick, weight = 2f), + InspectorFooterAction( + label = "Save rule", + onClick = onSaveClick, + weight = 2f, + ), ), ) } @@ -400,7 +585,7 @@ private fun MockRuleSaveErrorSummary( errors: MockRuleFormErrors, colors: DevConsoleColors, ) { - val count = listOfNotNull(errors.id, errors.status, errors.delay).size + val count = errors.allErrors.size Text( "Fix $count field${if (count == 1) "" else "s"} before saving", color = colors.error, @@ -440,17 +625,169 @@ private fun MockRuleEditorPrimaryFields( modifier = Modifier.padding(bottom = 16.dp).horizontalScroll(rememberScrollState()), ) MockRuleTextField("Path regex", form.pathPattern.value, { form.pathPattern.value = it }, colors, placeholder = ".*") + MockRuleActionPicker( + selected = form.actionType.value, + onSelect = form::selectActionType, + colors = colors, + ) + if (form.actionType.value.usesStatusCode) { + MockRuleTextField( + "Status", + form.statusText.value, + { form.statusText.value = it.filter(Char::isDigit) }, + colors, + placeholder = "200", + errorText = if (showErrors) errors.status else null, + ) + } +} + +/** The "Action" dropdown: the seven shapes the on-device sheet can build losslessly. */ +@Composable +private fun MockRuleActionPicker( + selected: InspectorMockActionType, + onSelect: (InspectorMockActionType) -> Unit, + colors: DevConsoleColors, +) { + var expanded by remember { mutableStateOf(false) } + MockRuleFieldLabel("Action", colors) + Box(modifier = Modifier.fillMaxWidth().padding(bottom = 16.dp)) { + Row( + modifier = + Modifier + .fillMaxWidth() + .heightIn(min = 48.dp) + .clip(RoundedCornerShape(12.dp)) + .border(1.dp, colors.line, RoundedCornerShape(12.dp)) + .background(colors.panel) + .clickable(role = Role.Button) { expanded = true } + .padding(horizontal = 16.dp) + .semantics { contentDescription = "Action, ${selected.label()}" }, + verticalAlignment = Alignment.CenterVertically, + ) { + Text( + selected.label(), + color = colors.ink, + fontSize = 14.sp, + fontFamily = FontFamily.Monospace, + modifier = Modifier.weight(1f), + ) + Text("▾", color = colors.muted, fontSize = 14.sp) + } + DropdownMenu(expanded = expanded, onDismissRequest = { expanded = false }) { + MOCK_RULE_ACTION_TYPES.forEach { type -> + DropdownMenuItem( + text = { Text(type.label()) }, + onClick = { + expanded = false + onSelect(type) + }, + modifier = Modifier.semantics { contentDescription = "Action ${type.label()}" }, + ) + } + } + } +} + +/** The fields that only exist for one action type; STATIC's fields live in the main body section. */ +@Composable +private fun MockRuleEditorActionFields( + form: MockRuleFormFields, + colors: DevConsoleColors, + errors: MockRuleFormErrors, + showErrors: Boolean, +) { + when (form.actionType.value) { + InspectorMockActionType.CONNECTION_FAILURE -> + MockRuleTextField( + "Failure message (optional)", + form.failureMessageText.value, + { form.failureMessageText.value = it }, + colors, + placeholder = "DevConsole simulated connection failure", + ) + InspectorMockActionType.TIMEOUT -> + MockRuleTextField( + "Timeout (ms)", + form.timeoutText.value, + { form.timeoutText.value = it.filter(Char::isDigit) }, + colors, + placeholder = "1000", + errorText = if (showErrors) errors.timeout else null, + ) + InspectorMockActionType.THROTTLE -> { + MockRuleTextField( + "Rate (KB/s)", + form.throttleKbpsText.value, + { form.throttleKbpsText.value = it.filter(Char::isDigit) }, + colors, + placeholder = "64", + errorText = if (showErrors) errors.throttleRate else null, + ) + MockRuleTextField( + "Latency (ms)", + form.throttleLatencyText.value, + { form.throttleLatencyText.value = it.filter(Char::isDigit) }, + colors, + placeholder = "0", + errorText = if (showErrors) errors.throttleLatency else null, + ) + } + InspectorMockActionType.MAP_REMOTE -> MockRuleMapRemoteFields(form, colors, errors, showErrors) + else -> Unit + } +} + +@Composable +private fun MockRuleMapRemoteFields( + form: MockRuleFormFields, + colors: DevConsoleColors, + errors: MockRuleFormErrors, + showErrors: Boolean, +) { + if (showErrors && errors.remote != null) { + Text( + errors.remote, + color = colors.error, + fontSize = 11.5.sp, + modifier = Modifier.padding(bottom = 8.dp), + ) + } MockRuleTextField( - "Status", - form.statusText.value, - { form.statusText.value = it.filter(Char::isDigit) }, + "Scheme", + form.remoteSchemeText.value, + { form.remoteSchemeText.value = it }, + colors, + placeholder = "https", + errorText = if (showErrors) errors.remoteScheme else null, + ) + MockRuleTextField( + "Host", + form.remoteHostText.value, + { form.remoteHostText.value = it }, + colors, + placeholder = "staging.example.test", + errorText = if (showErrors) errors.remoteHost else null, + ) + MockRuleTextField( + "Port", + form.remotePortText.value, + { form.remotePortText.value = it.filter(Char::isDigit) }, colors, - placeholder = "200", - errorText = if (showErrors) errors.status else null, + placeholder = "443", + errorText = if (showErrors) errors.remotePort else null, + ) + MockRuleTextField( + "Path", + form.remotePathText.value, + { form.remotePathText.value = it }, + colors, + placeholder = "/v2/orders", + errorText = if (showErrors) errors.remotePath else null, ) } -@Suppress("LongParameterList") // One real input per field group this scaffold's content slot renders. +@Suppress("LongParameterList", "LongMethod") // One real input per field group this scaffold renders. @Composable private fun MockRuleEditorBodyFields( form: MockRuleFormFields, @@ -460,25 +797,58 @@ private fun MockRuleEditorBodyFields( advancedExpanded: Boolean, onAdvancedExpandedChange: (Boolean) -> Unit, prefillNote: String?, + truncationWarning: String?, + acknowledgedTruncatedBody: Boolean, + onAcknowledgeTruncatedBody: (Boolean) -> Unit, headersExpanded: Boolean, onHeadersExpandedChange: (Boolean) -> Unit, bodyState: MockRuleBodyEditorState, ) { - MockRuleHeadersSection( - form = form, - colors = colors, - expanded = headersExpanded, - onToggle = { onHeadersExpandedChange(!headersExpanded) }, - ) - MockRuleBodyField( - value = form.bodyText.value, - onValueChange = { form.bodyText.value = it }, - colors = colors, - state = bodyState, - ) + when (form.actionType.value) { + InspectorMockActionType.STATIC -> { + MockRuleHeadersSection( + form = form, + colors = colors, + expanded = headersExpanded, + onToggle = { onHeadersExpandedChange(!headersExpanded) }, + ) + MockRuleBodyField( + value = form.bodyText.value, + onValueChange = { form.bodyText.value = it }, + colors = colors, + state = bodyState, + ) + } + InspectorMockActionType.BODY_REPLACEMENT -> + MockRuleBodyField( + value = form.bodyText.value, + onValueChange = { form.bodyText.value = it }, + colors = colors, + state = bodyState, + ) + else -> Unit + } if (prefillNote != null) { WarnNote(prefillNote, modifier = Modifier.padding(bottom = 16.dp)) } + if (truncationWarning != null) { + WarnNote(truncationWarning, modifier = Modifier.padding(bottom = 8.dp)) + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = + Modifier + .clickable { + onAcknowledgeTruncatedBody(!acknowledgedTruncatedBody) + }.padding(bottom = 16.dp), + ) { + Checkbox( + checked = acknowledgedTruncatedBody, + onCheckedChange = onAcknowledgeTruncatedBody, + ) + Text("I reviewed the captured body", color = colors.ink) + } + } + MockRuleMatchConditionsSection(form = form, colors = colors) CollapsibleSection( label = "Advanced options", expanded = advancedExpanded, @@ -489,6 +859,96 @@ private fun MockRuleEditorBodyFields( } } +/** + * Request-matching predicates: query params and headers as `key=value` lines plus a body regex. + * Lines without `=` are counted and shown as a non-blocking hint, matching the headers section. + */ +@Composable +private fun MockRuleMatchConditionsSection( + form: MockRuleFormFields, + colors: DevConsoleColors, +) { + val query = remember(form.queryPredicatesText.value) { parseMockRulePredicateLines(form.queryPredicatesText.value) } + val headers = + remember(form.headerPredicatesText.value) { parseMockRulePredicateLines(form.headerPredicatesText.value) } + var expanded by rememberSaveable { mutableStateOf(query.skippedLines + headers.skippedLines > 0) } + val skipped = query.skippedLines + headers.skippedLines + CollapsibleSection( + label = "Match conditions", + expanded = expanded, + onToggle = { expanded = !expanded }, + meta = + if (skipped == 0) { + ( + query.predicates.size + headers.predicates.size + + if (form.bodyPredicateText.value.isBlank()) 0 else 1 + ).let { count -> + when (count) { + 0 -> "Any request" + 1 -> "1 condition" + else -> "$count conditions" + } + } + } else { + "${query.predicates.size + headers.predicates.size} \u00b7 $skipped ignored" + }, + metaColor = if (skipped > 0) colors.warn else colors.muted, + modifier = Modifier.padding(bottom = 12.dp), + ) { + Column(Modifier.padding(12.dp)) { + MockRuleMultilineField( + label = "Query predicates (key=value)", + value = form.queryPredicatesText.value, + onValueChange = { form.queryPredicatesText.value = it }, + colors = colors, + placeholder = "page=1", + ) + MockRuleMultilineField( + label = "Header predicates (key=value)", + value = form.headerPredicatesText.value, + onValueChange = { form.headerPredicatesText.value = it }, + colors = colors, + placeholder = "Accept=application/json", + ) + MockRuleTextField( + "Body regex (whole body, up to 8 KB)", + form.bodyPredicateText.value, + { form.bodyPredicateText.value = it }, + colors, + placeholder = ".*\"paid\".*", + ) + } + } +} + +@Composable +private fun MockRuleMultilineField( + label: String, + value: String, + onValueChange: (String) -> Unit, + colors: DevConsoleColors, + placeholder: String, +) { + var focused by remember { mutableStateOf(false) } + Column(Modifier.fillMaxWidth().padding(bottom = 16.dp)) { + MockRuleFieldLabel(label, colors) + Box( + modifier = + Modifier + .fillMaxWidth() + .heightIn(min = 72.dp) + .onFocusChanged { focused = it.hasFocus } + .clip(RoundedCornerShape(12.dp)) + .border(1.dp, if (focused) colors.signal else colors.line, RoundedCornerShape(12.dp)) + .background(colors.panel) + .padding(horizontal = 16.dp, vertical = 12.dp) + .semantics(mergeDescendants = true) { contentDescription = label }, + ) { + InspectorMultilineTextField(value, onValueChange, placeholder, colors.ink, colors.text3) + } + } +} + @Composable private fun MockRuleAdvancedFields( form: MockRuleFormFields, @@ -512,14 +972,16 @@ private fun MockRuleAdvancedFields( ) MockRuleTextField("Scheme", form.scheme.value, { form.scheme.value = it }, colors, placeholder = "https") MockRuleTextField("Host", form.host.value, { form.host.value = it }, colors, placeholder = "api.example.test") - MockRuleTextField( - "Delay (ms)", - form.delayText.value, - { form.delayText.value = it.filter(Char::isDigit) }, - colors, - placeholder = "0", - errorText = if (showErrors) delayError else null, - ) + if (form.actionType.value == InspectorMockActionType.STATIC) { + MockRuleTextField( + "Delay (ms)", + form.delayText.value, + { form.delayText.value = it.filter(Char::isDigit) }, + colors, + placeholder = "0", + errorText = if (showErrors) delayError else null, + ) + } } } @@ -1147,8 +1609,45 @@ private class MockRuleFormFields( val scheme: MutableState, val host: MutableState, val delayText: MutableState, + val actionType: MutableState, + val timeoutText: MutableState, + val failureMessageText: MutableState, + val throttleKbpsText: MutableState, + val throttleLatencyText: MutableState, + val remoteSchemeText: MutableState, + val remoteHostText: MutableState, + val remotePortText: MutableState, + val remotePathText: MutableState, + val queryPredicatesText: MutableState, + val headerPredicatesText: MutableState, + val bodyPredicateText: MutableState, ) +/** + * Switches the rule's action and seeds that action's required fields when they are still empty, so + * picking "Timeout" or "Throttle" yields a rule that saves as-is instead of a blank, failing field. + * Anything the user already typed is kept. + */ +private fun MockRuleFormFields.selectActionType(type: InspectorMockActionType) { + actionType.value = type + when (type) { + InspectorMockActionType.TIMEOUT -> timeoutText.fillIfBlank(MOCK_RULE_DEFAULT_TIMEOUT_MS) + InspectorMockActionType.THROTTLE -> { + throttleKbpsText.fillIfBlank(MOCK_RULE_DEFAULT_THROTTLE_KBPS) + throttleLatencyText.fillIfBlank("0") + } + InspectorMockActionType.STATIC, InspectorMockActionType.STATUS_OVERRIDE -> statusText.fillIfBlank("200") + else -> Unit + } +} + +private fun MutableState.fillIfBlank(default: String) { + if (value.isBlank()) value = default +} + +private const val MOCK_RULE_DEFAULT_TIMEOUT_MS = "1000" +private const val MOCK_RULE_DEFAULT_THROTTLE_KBPS = "64" + /** Appends [value] to [base] only when it isn't already there -- never drops or reorders [base]. */ internal fun chipsIncluding( base: List, @@ -1189,12 +1688,44 @@ private fun rememberMockRuleFormFields( .orEmpty(), ) }, + actionType = + rememberSaveable(sourceKey) { + mutableStateOf( + initial.actionType.takeUnless { it == InspectorMockActionType.OTHER } + ?: InspectorMockActionType.STATIC, + ) + }, + timeoutText = rememberSaveable(sourceKey) { mutableStateOf(initial.timeoutMs?.toString().orEmpty()) }, + failureMessageText = rememberSaveable(sourceKey) { mutableStateOf(initial.failureMessage.orEmpty()) }, + throttleKbpsText = + rememberSaveable(sourceKey) { + // Rounded up, not truncated: a rule stored at 1000 B/s must not open showing "0" + // KB/s and block Save until the user retypes a value that was already valid. + mutableStateOf( + initial.throttleBytesPerSecond + ?.let { (it + MOCK_RULE_BYTES_PER_KB - 1) / MOCK_RULE_BYTES_PER_KB } + ?.toString() + .orEmpty(), + ) + }, + throttleLatencyText = + rememberSaveable(sourceKey) { mutableStateOf(initial.throttleLatencyMs?.toString().orEmpty()) }, + remoteSchemeText = rememberSaveable(sourceKey) { mutableStateOf(initial.remoteScheme.orEmpty()) }, + remoteHostText = rememberSaveable(sourceKey) { mutableStateOf(initial.remoteHost.orEmpty()) }, + remotePortText = rememberSaveable(sourceKey) { mutableStateOf(initial.remotePort?.toString().orEmpty()) }, + remotePathText = rememberSaveable(sourceKey) { mutableStateOf(initial.remotePath.orEmpty()) }, + queryPredicatesText = + rememberSaveable(sourceKey) { mutableStateOf(initial.queryPredicates.toMockRulePredicateLines()) }, + headerPredicatesText = + rememberSaveable(sourceKey) { mutableStateOf(initial.headerPredicates.toMockRulePredicateLines()) }, + bodyPredicateText = rememberSaveable(sourceKey) { mutableStateOf(initial.bodyPredicate.orEmpty()) }, ) } /** [initial]'s id-independent fields (actionLabel, enabled, hitCount, lastHitEpochMs) pass through untouched. */ -private fun MockRuleFormFields.toMockRule(initial: InspectorMockRuleUi): InspectorMockRuleUi = - InspectorMockRuleUi( +private fun MockRuleFormFields.toMockRule(initial: InspectorMockRuleUi): InspectorMockRuleUi { + val type = actionType.value + return InspectorMockRuleUi( id = id.value.trim(), method = method.value.takeIf { it != "ALL" }, pathPattern = pathPattern.value.trim().ifBlank { ".*" }, @@ -1204,18 +1735,53 @@ private fun MockRuleFormFields.toMockRule(initial: InspectorMockRuleUi): Inspect priority = priorityText.value.trim().toIntOrNull() ?: 0, scope = scope.value, statusCode = statusText.value.trim().toIntOrNull() ?: initial.statusCode, - body = bodyText.value, + // The editor shows JSON pretty-printed; an untouched body is saved byte-for-byte as it was. + body = bodyText.value.takeUnless { it == prettyOrRaw(initial.body) } ?: initial.body, enabled = initial.enabled, headers = parseMockRuleHeaderLines(headersText.value).headers, delayMs = delayText.value .trim() .toLongOrNull() - ?.takeIf { it > 0 }, + ?.takeIf { it > 0 && type == InspectorMockActionType.STATIC }, hitCount = initial.hitCount, lastHitEpochMs = initial.lastHitEpochMs, sourceBodySnapshot = initial.sourceBodySnapshot, + actionType = type, + timeoutMs = + timeoutText.value + .trim() + .toLongOrNull() + .takeIf { type == InspectorMockActionType.TIMEOUT }, + failureMessage = + failureMessageText.value + .trim() + .takeIf { type == InspectorMockActionType.CONNECTION_FAILURE && it.isNotBlank() }, + throttleBytesPerSecond = + throttleKbpsText.value + .trim() + .toLongOrNull() + ?.times(MOCK_RULE_BYTES_PER_KB) + .takeIf { type == InspectorMockActionType.THROTTLE }, + throttleLatencyMs = + (throttleLatencyText.value.trim().toLongOrNull() ?: 0L) + .takeIf { type == InspectorMockActionType.THROTTLE }, + remoteScheme = + remoteSchemeText.value.trim().takeIf { type == InspectorMockActionType.MAP_REMOTE && it.isNotBlank() }, + remoteHost = + remoteHostText.value.trim().takeIf { type == InspectorMockActionType.MAP_REMOTE && it.isNotBlank() }, + remotePath = + remotePathText.value.trim().takeIf { type == InspectorMockActionType.MAP_REMOTE && it.isNotBlank() }, + remotePort = + remotePortText.value + .trim() + .toIntOrNull() + .takeIf { type == InspectorMockActionType.MAP_REMOTE }, + queryPredicates = parseMockRulePredicateLines(queryPredicatesText.value).predicates, + headerPredicates = parseMockRulePredicateLines(headerPredicatesText.value).predicates, + bodyPredicate = bodyPredicateText.value.trim().takeIf { it.isNotBlank() }, ) +} /** * Header names describing the *original transport framing* of the captured response -- never valid @@ -1233,11 +1799,14 @@ private val BINARY_PREVIEW_PLACEHOLDER = Regex("""\[binary, \d+ bytes]""") private const val CAPTURE_PREFILL_BINARY_NOTE = "The captured response body is binary and can't be prefilled here — enter one manually." +private fun isTruncatedCapture(target: MockRuleEditorTarget): Boolean = + (target as? MockRuleEditorTarget.New)?.draft?.responseBodyTruncated == true + /** * Prefills a brand-new rule from a captured transaction -- the net detail's "Mock this response" * action. [existingIds] lets [suggestMockRuleId] avoid suggesting an id that already names a rule. * [InspectorTransactionUi.responsePreview] is a *redacted, possibly-truncated* capture preview, not - * the real payload -- the prefilled body is editable, so that needs no on-screen caveat. A binary + * the real payload. Truncated bodies require explicit review before saving. A binary * response's literal `"[binary, N bytes]"` placeholder, though, is never usable as a body, so it * prefills empty and carries a [MockRuleEditorTarget.New.prefillNote] saying to enter one by hand. */ @@ -1256,6 +1825,7 @@ internal fun mockRuleDraftFromTransaction( statusCode = transaction.statusCode ?: 200, body = if (isBinary) "" else preview, sourceBodySnapshot = if (isBinary) null else preview, + responseBodyTruncated = transaction.responseBodyTruncated, headers = transaction.responseHeaders.filterKeys { name -> name.lowercase(Locale.US) !in MOCK_DRAFT_STRIPPED_HEADERS diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorMockRuleForm.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorMockRuleForm.kt index 698405b..41902f6 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorMockRuleForm.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorMockRuleForm.kt @@ -2,6 +2,8 @@ * @author Shakib * @since 05/08/26 */ +@file:Suppress("TooManyFunctions") // One small validator/parser per editable mock-rule field, grouped with the form. + package io.devconsole.ui.compose import java.util.Locale @@ -18,7 +20,11 @@ internal val MOCK_RULE_SCOPES = listOf("SESSION", "PERSISTENT_INTERNAL", "TEST_F /** Inline-error text for the id field, or null when valid; mirrors FullInspectorDataSource.upsertMockRule. */ internal fun mockRuleIdError(id: String): String? = - if (id.matches(MOCK_RULE_ID_REGEX)) null else "Letters, digits, . _ - only -- can't start with . _ or -" + when { + id.isBlank() -> "Give the rule an id, e.g. rule-checkout" + id.matches(MOCK_RULE_ID_REGEX) -> null + else -> "Letters, digits, . _ - only -- can't start with . _ or -" + } /** Inline-error text for the status field, or null when valid; mirrors FullInspectorDataSource.upsertMockRule. */ internal fun mockRuleStatusError(statusCode: Int?): String? { @@ -65,18 +71,146 @@ internal fun parseMockRuleHeaderLines(text: String): ParsedMockRuleHeaders { internal fun Map.toMockRuleHeaderLines(): String = entries.joinToString("\n") { (k, v) -> "$k: $v" } +/** Every editable action type offered by the sheet's Action dropdown, in display order. */ +internal val MOCK_RULE_ACTION_TYPES = + listOf( + InspectorMockActionType.STATIC, + InspectorMockActionType.STATUS_OVERRIDE, + InspectorMockActionType.BODY_REPLACEMENT, + InspectorMockActionType.CONNECTION_FAILURE, + InspectorMockActionType.TIMEOUT, + InspectorMockActionType.THROTTLE, + InspectorMockActionType.MAP_REMOTE, + ) + +internal fun InspectorMockActionType.label(): String = + when (this) { + InspectorMockActionType.STATIC -> "Static response" + InspectorMockActionType.STATUS_OVERRIDE -> "Status override" + InspectorMockActionType.BODY_REPLACEMENT -> "Body replacement" + InspectorMockActionType.CONNECTION_FAILURE -> "Connection failure" + InspectorMockActionType.TIMEOUT -> "Timeout" + InspectorMockActionType.THROTTLE -> "Throttle" + InspectorMockActionType.MAP_REMOTE -> "Map remote" + InspectorMockActionType.OTHER -> "Other (read-only)" + } + /** - * Whether a rule's action round-trips through the create/edit sheet without data loss. Only - * `StaticResponse` and `Delay(StaticResponse)` do -- `upsertMockRule` always builds a plain - * `StaticResponse` (`FullInspectorDataSource.kt:299-303`), so opening the editor on anything else - * (`TemplateResponse`/`ConnectionFailure`/`Timeout`/`StatusOverride`/`BodyReplacement`/`Passthrough`) - * and pressing Save would silently replace a fault-injection or template rule with an empty 200. - * Discriminated via [InspectorMockRuleUi.actionLabel] since the UI model carries no richer - * action-kind field; the prefixes are `MockAction.toLabel()`'s exact literals - * (`FullInspectorDataSource.kt:701-708`) -- "Static response (…)" / "Delay (…ms)". + * Whether a rule's action round-trips through the create/edit sheet without data loss. Decided by + * [InspectorMockRuleUi.actionType]: every shape the sheet can rebuild is editable, and + * [InspectorMockActionType.OTHER] (sequence/template/passthrough, or a delayed non-static action) + * is not -- opening the editor on one of those and pressing Save would silently replace it. */ -internal fun InspectorMockRuleUi.isEditableOnDevice(): Boolean = - actionLabel.startsWith("Static response") || actionLabel.startsWith("Delay") +internal fun InspectorMockRuleUi.isEditableOnDevice(): Boolean = actionType != InspectorMockActionType.OTHER + +/** + * Label-based fallback kept for callers that only have [InspectorMockRuleUi.actionLabel]. Every + * editable action type except `OTHER` is accepted; a Delay is editable only when its wrapped action + * is explicitly the static response action (mirrors FullInspectorDataSource.toUi's mapping). + */ +internal fun isEditableMockActionLabel(actionLabel: String): Boolean = + MOCK_RULE_ACTION_TYPES.any { actionLabel.startsWith(it.label()) } || + ( + actionLabel.startsWith("Delay (") && + actionLabel.substringAfter(" → ", missingDelimiterValue = "").startsWith("Static response") + ) + +private const val MOCK_RULE_MAX_THROTTLE_BYTES_PER_SECOND = 104_857_600L +internal const val MOCK_RULE_BYTES_PER_KB = 1_024L +internal const val MOCK_RULE_MIN_REMOTE_PORT = 1 +internal const val MOCK_RULE_MAX_REMOTE_PORT = 65_535 + +/** Timeout is a required 0-30000 ms value; mirrors `MockAction.Timeout`'s constructor range. */ +internal fun mockRuleTimeoutError( + timeoutText: String, + timeoutMs: Long?, +): String? = + when { + timeoutText.isBlank() || timeoutMs == null -> "Must be a number" + timeoutMs !in 0..MOCK_RULE_MAX_DELAY_MS -> "Must be 0-$MOCK_RULE_MAX_DELAY_MS ms" + else -> null + } + +/** Throttle rate is entered in KB/s and validated against `MockAction.Throttle`'s byte range. */ +internal fun mockRuleThrottleRateError( + kbpsText: String, + bytesPerSecond: Long?, +): String? { + val maxKbps = MOCK_RULE_MAX_THROTTLE_BYTES_PER_SECOND / MOCK_RULE_BYTES_PER_KB + return when { + kbpsText.isBlank() || bytesPerSecond == null -> "Must be a number" + bytesPerSecond !in 1..MOCK_RULE_MAX_THROTTLE_BYTES_PER_SECOND -> "Must be 1-$maxKbps KB/s" + else -> null + } +} + +/** Throttle latency is optional; a blank field means no added latency. */ +internal fun mockRuleThrottleLatencyError( + latencyText: String, + latencyMs: Long?, +): String? = + when { + latencyText.isBlank() -> null + latencyMs == null -> "Must be a number" + latencyMs !in 0..MOCK_RULE_MAX_DELAY_MS -> "Must be 0-$MOCK_RULE_MAX_DELAY_MS ms" + else -> null + } + +/** `MockAction.MapRemote` requires at least one replacement field. */ +internal fun mockRuleMapRemoteError(hasAnyField: Boolean): String? = + if (hasAnyField) null else "Set at least one of scheme, host, port or path" + +/** Mirrors `MockAction.MapRemote`'s scheme constraint. */ +internal fun mockRuleRemoteSchemeError(scheme: String): String? = + when { + scheme.isBlank() -> null + scheme.lowercase(Locale.US) !in setOf("http", "https") -> "Must be http or https" + else -> null + } + +/** Mirrors `MockAction.MapRemote`'s host constraint. */ +internal fun mockRuleRemoteHostError(host: String): String? = + if (host.isBlank() || '/' !in host) null else "Must not contain '/'" + +/** Mirrors `MockAction.MapRemote`'s path constraint. */ +internal fun mockRuleRemotePathError(path: String): String? = + if (path.isBlank() || path.startsWith('/')) null else "Must start with '/'" + +/** Port is optional; a blank field leaves the port unchanged. */ +internal fun mockRuleRemotePortError( + portText: String, + port: Int?, +): String? = + when { + portText.isBlank() -> null + port == null -> "Must be a number" + port !in MOCK_RULE_MIN_REMOTE_PORT..MOCK_RULE_MAX_REMOTE_PORT -> + "Must be $MOCK_RULE_MIN_REMOTE_PORT-$MOCK_RULE_MAX_REMOTE_PORT" + else -> null + } + +/** [skippedLines] counts lines with no `key=value` shape -- shown as a non-blocking hint. */ +internal data class ParsedMockRulePredicates( + val predicates: Map, + val skippedLines: Int, +) + +/** Parses the multiline `key=value` convention used for query and header predicates. */ +internal fun parseMockRulePredicateLines(text: String): ParsedMockRulePredicates { + var skipped = 0 + val predicates = LinkedHashMap() + text.lineSequence().map { it.trim() }.filter { it.isNotEmpty() }.forEach { line -> + val equalsIndex = line.indexOf('=') + if (equalsIndex <= 0) { + skipped++ + } else { + predicates[line.substring(0, equalsIndex).trim()] = line.substring(equalsIndex + 1).trim() + } + } + return ParsedMockRulePredicates(predicates, skipped) +} + +internal fun Map.toMockRulePredicateLines(): String = entries.joinToString("\n") { (k, v) -> "$k=$v" } private const val MOCK_RULE_ID_MAX_LENGTH = 128 diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorMoreScreen.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorMoreScreen.kt index 4b7476e..8aa00a0 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorMoreScreen.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorMoreScreen.kt @@ -6,6 +6,7 @@ package io.devconsole.ui.compose +import android.content.ActivityNotFoundException import android.content.res.Configuration import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.background @@ -22,6 +23,7 @@ import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.selection.toggleable import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.AlertDialog @@ -30,7 +32,11 @@ import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.OutlinedButton import androidx.compose.material3.SnackbarHost import androidx.compose.material3.SnackbarHostState +import androidx.compose.material3.Switch +import androidx.compose.material3.SwitchColors +import androidx.compose.material3.SwitchDefaults import androidx.compose.material3.Text +import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue @@ -96,6 +102,10 @@ private const val SERVER_STATE_PERMISSION_REQUIRED = "PermissionRequired" /** How often [MoreRoute] re-reads the snapshot while visible -- see the poll's own doc. */ private const val MORE_SCREEN_REFRESH_INTERVAL_MS = 5_000L +/** The Capture group's "Pause capture" subtitle -- says what pausing actually excludes. */ +private const val CAPTURE_PAUSE_SUBTITLE = + "New requests, sockets, logs and push stay out of the timeline while paused" + /** Stateful entry point wired into the MORE destination. Theme is owned by [DevConsoleWorkspace]. */ @Composable internal fun MoreRoute( @@ -188,6 +198,10 @@ internal fun MoreRoute( @Suppress("LongParameterList") // One real interaction per field; see doc above. internal data class MoreActions( val onSetServerRunning: (Boolean) -> Unit, + /** The Capture group's "Pause capture" switch; takes the desired next state. */ + val onSetCapturePaused: (Boolean) -> Unit, + /** The Capture group's destructive purge action, dispatched only after confirmation. */ + val onPurgeCapturedData: () -> Unit, val onCopyUrl: (String) -> Unit, val onCopyCode: (String) -> Unit, val onShowQr: (String) -> Unit, @@ -196,7 +210,8 @@ internal data class MoreActions( val onExportSessionZip: () -> Unit, val onCaptureScreenshot: () -> Unit, val onRevoke: (String) -> Unit, - val onSelectSession: (String) -> Unit, + val onSelectSession: (String?) -> Unit, + val onShowMessage: (String) -> Unit = {}, ) @Composable @@ -211,6 +226,8 @@ private fun rememberMoreActions( return remember(viewModel, clipboard) { MoreActions( onSetServerRunning = { running -> viewModel.dispatch(InspectorAction.SetServerRunning(running)) }, + onSetCapturePaused = { paused -> viewModel.dispatch(InspectorAction.SetCapturePaused(paused)) }, + onPurgeCapturedData = { viewModel.dispatch(InspectorAction.PurgeCapturedData) }, onCopyUrl = { url -> clipboard.setText(AnnotatedString(url)) currentShowMessage("$url copied") @@ -226,6 +243,7 @@ private fun rememberMoreActions( onCaptureScreenshot = { viewModel.dispatch(InspectorAction.CaptureScreenshot) }, onRevoke = { id -> viewModel.dispatch(InspectorAction.RevokePrincipal(id)) }, onSelectSession = { id -> viewModel.dispatch(InspectorAction.SelectSession(id)) }, + onShowMessage = { message -> currentShowMessage(message) }, ) } } @@ -276,6 +294,10 @@ internal fun MoreScreen( ) { val colors = DevConsoleTheme.colors val running = state.health?.state == SERVER_STATE_RUNNING + // Plain state, matching Observe's clear-captures confirmation: losing an open dialog on a + // rotation is harmless, and this one is a destructive action worth re-confirming. + var purgeConfirmationVisible by remember { mutableStateOf(false) } + val showPurgeConfirmation = { purgeConfirmationVisible = true } Column(modifier = modifier.fillMaxSize().background(colors.ground)) { InspectorTopArea( subLine = "", @@ -320,6 +342,20 @@ internal fun MoreScreen( item(key = "more_export_runs", contentType = "export_row") { RetainedRunsRow(state, actions, colors) } + if (state.captureControlSupported) { + item(key = "more_capture_title", contentType = "panel_title") { + MorePanelTitle("Capture") + } + item(key = "more_capture_pause", contentType = "capture_row") { + CapturePauseRow(state.capturePaused, actions) + } + item(key = "more_capture_div_1", contentType = "divider") { + GroupedPanelDivider() + } + item(key = "more_capture_purge", contentType = "capture_row") { + PurgeCapturedDataRow(colors, onShowConfirmation = showPurgeConfirmation) + } + } item(key = "more_settings_title", contentType = "panel_title") { MorePanelTitle("Settings") } @@ -340,8 +376,96 @@ internal fun MoreScreen( } } } + if (purgeConfirmationVisible) { + PurgeCapturedConfirmDialog( + onConfirm = { + purgeConfirmationVisible = false + actions.onPurgeCapturedData() + }, + onDismiss = { purgeConfirmationVisible = false }, + ) + } +} + +/** + * The More screen's "Pause capture" switch. The whole row is one toggleable switch node, so the row + * and the switch can never disagree, and the title is set like the neighbouring panel rows rather + * than in the monospace of data-key rows. The subtitle wraps: it is the only place that says what + * pausing excludes. + */ +@Composable +private fun CapturePauseRow( + paused: Boolean, + actions: MoreActions, +) { + val colors = DevConsoleTheme.colors + Row( + modifier = + Modifier + .fillMaxWidth() + .heightIn(min = 56.dp) + .toggleable(value = paused, role = Role.Switch, onValueChange = actions.onSetCapturePaused) + .padding(horizontal = 16.dp, vertical = 12.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(12.dp), + ) { + Column(modifier = Modifier.weight(1f)) { + Text("Pause capture", color = colors.ink, fontSize = 16.sp) + Text( + CAPTURE_PAUSE_SUBTITLE, + color = colors.muted, + fontSize = 13.sp, + modifier = Modifier.padding(top = 2.dp), + ) + } + Switch(checked = paused, onCheckedChange = null, colors = captureSwitchColors(colors)) + } +} + +/** Destructive row: asks through [PurgeCapturedConfirmDialog] before dispatching anything. */ +@Composable +private fun PurgeCapturedDataRow( + colors: DevConsoleColors, + onShowConfirmation: () -> Unit, +) { + MorePanelRow( + title = "Purge captured data", + description = "Removes this run's captured traffic and old unpinned runs", + meta = "Keeps pinned", + titleColor = colors.error, + onClick = onShowConfirmation, + ) +} + +@Composable +private fun PurgeCapturedConfirmDialog( + onConfirm: () -> Unit, + onDismiss: () -> Unit, +) { + val colors = DevConsoleTheme.colors + AlertDialog( + onDismissRequest = onDismiss, + title = { Text("Purge captured data?") }, + text = { Text("Removes this run's captured traffic and old unpinned runs. Pinned runs are kept.") }, + confirmButton = { + TextButton(onClick = onConfirm) { Text("Purge", color = colors.error) } + }, + dismissButton = { + TextButton(onClick = onDismiss) { Text("Cancel", color = colors.ink) } + }, + ) } +@Composable +private fun captureSwitchColors(colors: DevConsoleColors): SwitchColors = + SwitchDefaults.colors( + checkedTrackColor = colors.signal, + checkedThumbColor = colors.signalInk, + uncheckedTrackColor = colors.surface3, + uncheckedThumbColor = colors.muted, + uncheckedBorderColor = colors.borderStrong, + ) + @Composable private fun MorePanelTitle(title: String) { Text( @@ -361,6 +485,8 @@ private fun MorePanelRow( description: String = "", onClick: (() -> Unit)? = null, metaContent: (@Composable () -> Unit)? = null, + /** Override for destructive rows (e.g. "Purge captured data"), which paint their label in error. */ + titleColor: Color? = null, ) { val colors = DevConsoleTheme.colors Row( @@ -375,7 +501,7 @@ private fun MorePanelRow( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp), ) { - Text(title, modifier = Modifier.weight(1f), color = colors.ink, fontSize = 16.sp) + Text(title, modifier = Modifier.weight(1f), color = titleColor ?: colors.ink, fontSize = 16.sp) if (metaContent != null) { metaContent() } else if (meta.isNotBlank()) { @@ -441,7 +567,18 @@ private fun BrowserDashboardPanel( ), InspectorUrlAction( "Open URL", - { uriHandler.openUri(url) }, + { + runCatching { uriHandler.openUri(url) } + .onFailure { failure -> + if (failure is ActivityNotFoundException || + failure is SecurityException + ) { + actions.onShowMessage("No app can open this URL") + } else { + actions.onShowMessage("Unable to open this URL") + } + } + }, colors.panel, colors.muted, icon = { @@ -613,12 +750,20 @@ private fun ExportHarRow( if (selection.isEmpty()) { EXPORT_ALL_SUBTITLE } else { - "Redacted · ${selection.size} selected transaction(s)" + "Redacted · ${countLabel(selection.size, "selected transaction")}" } MorePanelRow( title = "HAR", description = subtitle, - meta = if (selection.isEmpty()) "${state.transactions.size} txns" else "${selection.size} selected", + meta = + if (selection.isEmpty()) { + countLabel( + state.transactions.size, + "request", + ) + } else { + "${selection.size} selected" + }, onClick = actions.onExportHar, ) } @@ -634,12 +779,20 @@ private fun ExportPostmanRow( if (selection.isEmpty()) { EXPORT_ALL_SUBTITLE } else { - "Redacted · ${selection.size} selected transaction(s)" + "Redacted · ${countLabel(selection.size, "selected transaction")}" } MorePanelRow( title = "Postman collection", description = subtitle, - meta = if (selection.isEmpty()) "${state.transactions.size} txns" else "${selection.size} selected", + meta = + if (selection.isEmpty()) { + countLabel( + state.transactions.size, + "request", + ) + } else { + "${selection.size} selected" + }, onClick = actions.onExportPostman, ) } @@ -700,7 +853,31 @@ private fun RetainedRunsRow( ) if (expanded) { Column(modifier = Modifier.padding(bottom = 8.dp)) { - state.sessions.forEach { session -> + GroupedPanelDivider() + TonalListRow( + leadText = "", + leadColor = colors.muted, + leadContainerColor = colors.panel, + title = "Current run (live)", + subtitle = "Live capture session", + trailValue = "", + trailValueColor = colors.muted, + trailContent = + if (state.selectedSessionId == null) { + { + InspectorGlyphIcon( + InspectorGlyph.Check, + "Selected", + tint = colors.ink, + size = 18.dp, + ) + } + } else { + null + }, + onClick = { actions.onSelectSession(null) }, + ) + state.sessions.filterNot(InspectorSessionUi::isCurrent).forEach { session -> GroupedPanelDivider() TonalListRow( leadText = "", @@ -837,6 +1014,7 @@ private fun moreScreenPreviewState() = InspectorState( available = true, serverControlSupported = true, + captureControlSupported = true, sessions = listOf( InspectorSessionUi( @@ -869,6 +1047,8 @@ private fun moreScreenPreviewState() = private fun moreScreenPreviewActions() = MoreActions( onSetServerRunning = {}, + onSetCapturePaused = {}, + onPurgeCapturedData = {}, onCopyUrl = {}, onCopyCode = {}, onShowQr = {}, diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorNavComponents.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorNavComponents.kt index 48751d6..1cdf2be 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorNavComponents.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorNavComponents.kt @@ -60,6 +60,7 @@ import androidx.compose.ui.graphics.Path import androidx.compose.ui.layout.onGloballyPositioned import androidx.compose.ui.layout.positionInParent import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.semantics.selected import androidx.compose.ui.semantics.semantics import androidx.compose.ui.text.font.FontWeight @@ -85,6 +86,11 @@ internal fun InspectorTopArea( modifier: Modifier = Modifier, actions: List = emptyList(), live: Boolean = true, + liveLabel: String = "Live", + liveActive: Boolean = true, + /** When non-null the live indicator becomes a toggle pill announced by [liveDescription]. */ + onLiveClick: (() -> Unit)? = null, + liveDescription: String? = null, ) { val colors = DevConsoleTheme.colors Column(modifier = modifier) { @@ -94,13 +100,26 @@ internal fun InspectorTopArea( ) { Text(title, color = colors.ink, style = MaterialTheme.typography.headlineSmall) if (live) { + val liveColor = if (liveActive) colors.signal else colors.muted + val pillModifier = + if (onLiveClick == null) { + Modifier.padding(start = 12.dp) + } else { + Modifier + .padding(start = 4.dp) + .clip(RoundedCornerShape(50)) + .clickable(role = Role.Button, onClick = onLiveClick) + .semantics(mergeDescendants = true) { + liveDescription?.let { contentDescription = it } + }.padding(horizontal = 8.dp, vertical = 6.dp) + } Row( - modifier = Modifier.padding(start = 12.dp), + modifier = pillModifier, horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically, ) { - Box(Modifier.size(8.dp).clip(CircleShape).background(colors.signal)) - Text("Live", color = colors.signal, fontSize = 13.sp) + Box(Modifier.size(8.dp).clip(CircleShape).background(liveColor)) + Text(liveLabel, color = liveColor, fontSize = 13.sp) } } Spacer(Modifier.weight(1f)) diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorNetworkSnippets.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorNetworkSnippets.kt index e1dbec1..583c26d 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorNetworkSnippets.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorNetworkSnippets.kt @@ -29,13 +29,14 @@ private fun InspectorTransactionUi.sendableRequestBody(): String? { /** * Reproduces a captured transaction as a composer request so Replay reuses the existing * [InspectorDataSource.execute] path (capability gate + exact-host allow-list) unchanged. A - * binary request body is never fabricated from its `[binary, N bytes]` placeholder text. + * binary request body is never fabricated from its `[binary, N bytes]` placeholder text, and a + * header whose captured value was redacted is dropped rather than sent as its `` marker. */ internal fun InspectorTransactionUi.toComposerRequest(): InspectorComposerRequest = InspectorComposerRequest( method = method, url = displayUrl(), - headers = requestHeaders, + headers = requestHeaders.filterValues { !it.isRedactedValue() }, body = sendableRequestBody(), ) diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveCrashesTab.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveCrashesTab.kt index 39c87c2..8c736d3 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveCrashesTab.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveCrashesTab.kt @@ -7,6 +7,7 @@ package io.devconsole.ui.compose +import androidx.compose.foundation.background import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Spacer @@ -16,11 +17,23 @@ import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.itemsIndexed +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.Text import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color +import androidx.compose.ui.semantics.clearAndSetSemantics +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp import java.util.Locale /** @@ -42,20 +55,24 @@ internal fun CrashesTabContent( } val searched = remember(state.crashes, ui.crashesSearch) { - val query = ui.crashesSearch.trim().lowercase(Locale.US) + val query = ui.crashesSearch.trim() if (query.isEmpty()) { state.crashes } else { state.crashes.filter { crash -> - crash.summary.lowercase(Locale.US).contains(query) || - crash.thread.lowercase(Locale.US).contains(query) || - crash.stackTrace.lowercase(Locale.US).contains(query) + crash.summary.contains(query, ignoreCase = true) || + crash.thread.contains(query, ignoreCase = true) || + crash.stackTrace.contains(query, ignoreCase = true) } } } val rowsNewestFirst = remember(searched) { searched.sortedByDescending { it.timestampEpochMs } } - - val arrivals = rememberArrivals(rowsNewestFirst.map { it.id }) + val defaultGroupSimilar = remember(state.crashes) { hasDuplicateCrashFingerprints(state.crashes) } + var userGroupSimilarOverride by rememberSaveable { mutableStateOf(null) } + val groupSimilar = userGroupSimilarOverride ?: defaultGroupSimilar + val groupedRows = remember(rowsNewestFirst) { groupCrashes(rowsNewestFirst) } + val arrivalIds = remember(rowsNewestFirst) { rowsNewestFirst.map { it.id } } + val arrivals = rememberArrivals(arrivalIds) LazyColumn( modifier = Modifier.fillMaxSize(), contentPadding = PaddingValues(top = 12.dp, bottom = 24.dp), @@ -72,22 +89,63 @@ internal fun CrashesTabContent( } if (state.crashes.isNotEmpty()) { item { CrashesHero(state.crashes, ui, actions, colors) } - item { Spacer(Modifier.height(12.dp)) } + item { Spacer(Modifier.height(8.dp)) } + item { + CrashesGroupSimilarBar( + groupSimilar = groupSimilar, + groupCount = groupedRows.size, + onToggle = { userGroupSimilarOverride = !groupSimilar }, + ) + } + item { Spacer(Modifier.height(4.dp)) } } if (rowsNewestFirst.isEmpty()) item { ObserveTabEmptyState("No matching crashes.", EmptySpot.Search) } - itemsIndexed(rowsNewestFirst, key = { _, crash -> crash.id }) { index, crash -> - CrashRow( - crash = crash, - isFlagged = crash.id in ui.flaggedCrashIds, - colors = colors, - modifier = Modifier.animateItem().groupedPanelItem(GroupPosition.of(index, rowsNewestFirst.size)), - isArrival = crash.id in arrivals, - onClick = { actions.onOpenCrashDetail(crash.id) }, - ) + if (groupSimilar) { + itemsIndexed(groupedRows, key = { _, group -> "group:${group.fingerprint}" }) { index, group -> + CrashGroupRow( + group = group, + isFlagged = group.crashes.any { it.id in ui.flaggedCrashIds }, + colors = colors, + modifier = Modifier.animateItem().groupedPanelItem(GroupPosition.of(index, groupedRows.size)), + isArrival = group.newest.id in arrivals, + onClick = { actions.onOpenCrashDetail(group.newest.id) }, + ) + } + } else { + itemsIndexed(rowsNewestFirst, key = { _, crash -> crash.id }) { index, crash -> + CrashRow( + crash = crash, + isFlagged = crash.id in ui.flaggedCrashIds, + colors = colors, + modifier = Modifier.animateItem().groupedPanelItem(GroupPosition.of(index, rowsNewestFirst.size)), + isArrival = crash.id in arrivals, + onClick = { actions.onOpenCrashDetail(crash.id) }, + ) + } } } } +@Composable +private fun CrashesGroupSimilarBar( + groupSimilar: Boolean, + groupCount: Int, + onToggle: () -> Unit, +) { + FilterChipRow( + chips = + listOf( + InspectorFilterChip( + id = "group-similar", + label = "Group similar", + selected = groupSimilar, + count = if (groupSimilar && groupCount > 0) groupCount.toString() else null, + ), + ), + onChipClick = { onToggle() }, + ) +} + @Composable private fun CrashesHero( crashes: List, @@ -98,7 +156,7 @@ private fun CrashesHero( if (ui.crashesHeroCollapsed) { HeroBar( value = crashes.size.toString(), - label = "crashes and ANRs this session", + label = if (crashes.size == 1) "crash or ANR this session" else "crashes and ANRs this session", onExpand = actions.onToggleCrashesHero, valueColor = colors.error, labelColor = colors.error, @@ -147,3 +205,52 @@ private fun CrashRow( ) } } + +@Suppress("LongParameterList") +@Composable +private fun CrashGroupRow( + group: InspectorCrashGroup, + isFlagged: Boolean, + colors: DevConsoleColors, + onClick: () -> Unit, + modifier: Modifier = Modifier, + isArrival: Boolean = false, +) { + val crash = group.newest + val crumbCount = crash.breadcrumbs.size + val crumbNoun = if (crumbCount == 1) "breadcrumb" else "breadcrumbs" + val occurrenceNoun = if (group.count == 1) "occurrence" else "occurrences" + Column(modifier = modifier.fillMaxWidth()) { + TonalListRow( + isArrival = isArrival, + leadText = if (crash.kind.equals("ANR", ignoreCase = true)) "ANR" else "CRASH", + leadColor = colors.muted, + leadContainerColor = Color.Transparent, + title = if (crash.summary.length > 40) crash.summary.take(40) + "…" else crash.summary, + subtitle = "${crash.thread.ifBlank { "unknown thread" }} · $crumbCount $crumbNoun", + trailValue = formatCaptureClockTime(group.lastSeenEpochMs), + trailValueColor = colors.muted, + // A ×1 badge on every ungrouped row is noise; the count only says something once it repeats. + trailContent = { + if (group.count > 1) { + Text( + text = "×${group.count}", + modifier = + Modifier + .clip(RoundedCornerShape(6.dp)) + .background(colors.surface3) + .padding(horizontal = 6.dp, vertical = 2.dp) + .clearAndSetSemantics { contentDescription = "${group.count} $occurrenceNoun" }, + color = colors.ink, + fontFamily = FontFamily.Monospace, + fontSize = 12.sp, + fontWeight = FontWeight.SemiBold, + maxLines = 1, + ) + } + }, + containerColor = if (isFlagged) colors.surface2 else Color.Transparent, + onClick = onClick, + ) + } +} 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 9c4c908..6cbf02a 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 @@ -27,6 +27,8 @@ import androidx.compose.runtime.setValue import androidx.compose.runtime.snapshots.SnapshotStateMap import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color +import androidx.compose.ui.semantics.paneTitle +import androidx.compose.ui.semantics.semantics import androidx.compose.ui.unit.dp import java.util.Locale @@ -565,6 +567,8 @@ internal fun InspectorObserveDetailScreen( modifier: Modifier = Modifier, searchPlaceholder: String = DEFAULT_DETAIL_SEARCH_PLACEHOLDER, searchOptions: InspectorDetailSearchOptions? = null, + /** Kind-specific content rendered after the sections, e.g. the socket frame's send composer. */ + trailingContent: (@Composable () -> Unit)? = null, ) { val tabs = remember(sections) { sections.map { it.tab }.distinct().sortedBy { it.ordinal } } val showTabs = tabs.size > 1 @@ -663,7 +667,10 @@ internal fun InspectorObserveDetailScreen( return } - Surface(modifier = modifier.fillMaxSize(), color = colors.ground) { + Surface( + modifier = modifier.fillMaxSize().semantics { paneTitle = "${header.kindLabel} detail: ${header.title}" }, + color = colors.ground, + ) { Column(modifier = Modifier.fillMaxSize().imePadding()) { InspectorDetailHeader( kindLabel = header.kindLabel, @@ -720,6 +727,7 @@ internal fun InspectorObserveDetailScreen( onToggleSection = { key, expanded -> openState[key] = !expanded }, onExpandCodeFullScreen = { key -> fullScreenSectionKey = key }, footerActions = footerActions, + trailingContent = trailingContent, modifier = Modifier.weight(1f), ) } @@ -809,6 +817,7 @@ private fun ObserveDetailTabBody( onExpandCodeFullScreen: (String) -> Unit, footerActions: List, modifier: Modifier = Modifier, + trailingContent: (@Composable () -> Unit)? = null, ) { Column( modifier = @@ -840,6 +849,8 @@ private fun ObserveDetailTabBody( } } } + // After the sections, so the frame the operator opened stays the first thing they read. + trailingContent?.invoke() if (overviewVisible) ObserveDetailActionRows(footerActions) } } diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveDetailPanels.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveDetailPanels.kt index 50a2022..76e124f 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveDetailPanels.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveDetailPanels.kt @@ -25,6 +25,7 @@ import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.text.selection.SelectionContainer import androidx.compose.material3.IconButton import androidx.compose.material3.Text import androidx.compose.runtime.Composable @@ -113,7 +114,9 @@ internal fun ObserveDetailPanel( enter = expandVertically(feedbackSpec(InspectorMotion.EXPAND_MS)) + fadeIn(feedbackSpec()), exit = shrinkVertically(feedbackSpec()) + fadeOut(feedbackSpec()), ) { - Column(content = content) + SelectionContainer { + Column(content = content) + } } } } 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 aa69591..f4c8f7b 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 @@ -152,3 +152,10 @@ internal fun shareTextSnippet( context.startActivity(Intent.createChooser(sendIntent, chooserTitle)) } } + +/** "1 file" / "3 files": a count with its noun in the right number. */ +internal fun countLabel( + count: Int, + singular: String, + plural: String = "${singular}s", +): String = "$count ${if (count == 1) singular else plural}" diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveLogDetail.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveLogDetail.kt index e5e43e5..9ae14a8 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveLogDetail.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveLogDetail.kt @@ -48,19 +48,18 @@ private fun logSections( ), InspectorDetailSectionSpec( InspectorExchangeSection.PRIMARY_BODY.key, - "Context", + if (log.detail.looksLikeStackTrace()) "Stack trace" else "Context", contextBody, copyDescription = "Copy context", onCopy = contextCopy, ), - InspectorDetailSectionSpec( - InspectorExchangeSection.SECONDARY_HEADERS.key, - "Related transaction", - InspectorDetailSectionBody.Empty("This event is not linked to a transaction."), - ), ) } +/** A recorded throwable renders as `Type: message` followed by `at frame` lines. */ +internal fun String?.looksLikeStackTrace(): Boolean = + this != null && lineSequence().drop(1).any { it.trimStart().startsWith("at ") } + private fun logFooterActions( colors: DevConsoleColors, isBookmarked: Boolean, @@ -131,9 +130,10 @@ internal fun logDetailContent( ), ), sections = logSections(log, colors, leadColor, copyText), - // No body section exists for a log event -- keep General (the first section) open so the - // screen doesn't land all-collapsed. - initiallyOpenSectionKeys = setOf("general"), + // General is always open; the context (usually a stack trace on WARN/ERROR) opens too when + // there is one, since it is the part an operator came here to read. + initiallyOpenSectionKeys = + setOfNotNull("general", InspectorExchangeSection.PRIMARY_BODY.key.takeIf { log.detail != null }), footerActions = logFooterActions(colors, isBookmarked, onToggleBookmark, copyPayload, copyText), ) } diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveNetDetail.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveNetDetail.kt index 44d0a4c..5946bba 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveNetDetail.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveNetDetail.kt @@ -2,6 +2,8 @@ * @author Shakib * @since 04/08/26 */ +@file:Suppress("TooManyFunctions") + package io.devconsole.ui.compose import androidx.compose.ui.graphics.Color @@ -158,9 +160,9 @@ private fun netGeneralEntries( if (transaction.isMocked) { val ruleId = transaction.mockRuleId ?: "unknown" val diffSuffix = mockDiffNoticeSuffix(mockDiff).orEmpty() - add(InspectorKeyValue("source", "mock rule $ruleId$diffSuffix", colors.warn)) + add(InspectorKeyValue("Source", "mock rule $ruleId$diffSuffix", colors.warn)) } - transaction.error?.let { add(InspectorKeyValue("error", it, colors.error)) } + transaction.error?.let { add(InspectorKeyValue("Error", it, colors.error)) } } /** The request payload + response body sections, in that order -- see [textPreviewSection]. */ @@ -206,6 +208,146 @@ private fun netBodySections( ) } +private fun netDecodedJwtSections( + jwts: List, + colors: DevConsoleColors, + copyText: (String) -> Unit, +): List = + buildList { + jwts.forEachIndexed { index, jwt -> + val tab = + if (jwt.source.equals("Authorization", ignoreCase = true)) { + InspectorDetailTab.REQUEST + } else { + InspectorDetailTab.RESPONSE + } + val prefix = if (jwts.size > 1) "Decoded · JWT (${jwt.source})" else "Decoded · JWT" + if (jwt.timestamps.isNotEmpty()) { + val claimEntries = + jwt.timestamps.map { claim -> + val color = if (claim.isExpired) colors.error else colors.signal + InspectorKeyValue(claim.claim, "${claim.humanTime} (${claim.relativeStatus})", color) + } + add( + InspectorDetailSectionSpec( + key = "decoded-jwt-claims-$index", + label = "$prefix claims", + body = InspectorDetailSectionBody.KeyValues(claimEntries), + copyDescription = "Copy decoded JWT claims", + onCopy = keyValuesCopyAction(claimEntries, copyText), + tab = tab, + ), + ) + } + val headerLines = jwt.headerJson.lines().map { it.toRedactionAwareCodeLine(colors) } + add( + InspectorDetailSectionSpec( + key = "decoded-jwt-header-$index", + label = "$prefix header", + body = InspectorDetailSectionBody.Code(headerLines), + copyDescription = "Copy decoded JWT header", + onCopy = { copyText(jwt.headerJson) }, + tab = tab, + ), + ) + val payloadLines = jwt.payloadJson.lines().map { it.toRedactionAwareCodeLine(colors) } + add( + InspectorDetailSectionSpec( + key = "decoded-jwt-payload-$index", + label = "$prefix payload", + body = InspectorDetailSectionBody.Code(payloadLines), + copyDescription = "Copy decoded JWT payload", + onCopy = { copyText(jwt.payloadJson) }, + tab = tab, + ), + ) + } + } + +private fun netDecodedFormSection( + formFields: List?, + colors: DevConsoleColors, + copyText: (String) -> Unit, +): InspectorDetailSectionSpec? { + val fields = formFields?.takeIf { it.isNotEmpty() } ?: return null + val entries = + fields.map { field -> + InspectorKeyValue( + key = field.key, + value = field.value, + valueColor = if (field.value.looksRedacted()) colors.warn else null, + ) + } + return InspectorDetailSectionSpec( + key = "decoded-form", + label = "Decoded · Form", + body = InspectorDetailSectionBody.KeyValues(entries), + copyDescription = "Copy decoded form fields", + onCopy = keyValuesCopyAction(entries, copyText), + tab = InspectorDetailTab.REQUEST, + ) +} + +private fun netDecodedGraphQlSections( + graphQl: DecodedGraphQlRequest?, + colors: DevConsoleColors, + copyText: (String) -> Unit, +): List { + if (graphQl == null) return emptyList() + val metaEntries = + buildList { + add(InspectorKeyValue("type", graphQl.operationType)) + graphQl.operationName?.let { add(InspectorKeyValue("operationName", it)) } + } + val queryLines = graphQl.query.lines().map { it.toRedactionAwareCodeLine(colors) } + return buildList { + add( + InspectorDetailSectionSpec( + key = "decoded-graphql", + label = "Decoded · GraphQL", + body = InspectorDetailSectionBody.KeyValues(metaEntries), + copyDescription = "Copy GraphQL operation info", + onCopy = keyValuesCopyAction(metaEntries, copyText), + tab = InspectorDetailTab.REQUEST, + ), + ) + add( + InspectorDetailSectionSpec( + key = "decoded-graphql-query", + label = "Decoded · GraphQL query", + body = InspectorDetailSectionBody.Code(queryLines), + copyDescription = "Copy GraphQL query", + onCopy = { copyText(graphQl.query) }, + tab = InspectorDetailTab.REQUEST, + ), + ) + graphQl.variablesJson?.let { variablesJson -> + val variableLines = variablesJson.lines().map { it.toRedactionAwareCodeLine(colors) } + add( + InspectorDetailSectionSpec( + key = "decoded-graphql-variables", + label = "Decoded · GraphQL variables", + body = InspectorDetailSectionBody.Code(variableLines), + copyDescription = "Copy GraphQL variables", + onCopy = { copyText(variablesJson) }, + tab = InspectorDetailTab.REQUEST, + ), + ) + } + } +} + +private fun netDecodedSections( + decoded: DecodedTransactionContent, + colors: DevConsoleColors, + copyText: (String) -> Unit, +): List = + buildList { + addAll(netDecodedJwtSections(decoded.jwts, colors, copyText)) + netDecodedFormSection(decoded.formFields, colors, copyText)?.let(::add) + addAll(netDecodedGraphQlSections(decoded.graphQl, colors, copyText)) + } + private fun netSections( transaction: InspectorTransactionUi, colors: DevConsoleColors, @@ -213,49 +355,123 @@ private fun netSections( copyText: (String) -> Unit, mockDiff: JsonMockDiffResult?, ): List { + val decoded = decodeTransactionStructuredContent(transaction) val generalEntries = netGeneralEntries(transaction, colors, statusColor, mockDiff) val (requestSection, responseSection) = netBodySections(transaction, colors, copyText, mockDiff) val requestHeadersBody = headerRowsBody(transaction.requestHeaders, colors) val responseHeadersBody = headerRowsBody(transaction.responseHeaders, colors) - return listOf( - responseSection, - InspectorDetailSectionSpec( - InspectorExchangeSection.SECONDARY_HEADERS.key, - InspectorExchangeSection.SECONDARY_HEADERS.networkLabel, - responseHeadersBody, - copyDescription = "Copy response headers", - onCopy = keyValuesCopyAction(responseHeadersBody.entries, copyText), - tab = InspectorDetailTab.RESPONSE, - ), - requestSection, - InspectorDetailSectionSpec( - InspectorExchangeSection.PRIMARY_HEADERS.key, - InspectorExchangeSection.PRIMARY_HEADERS.networkLabel, - requestHeadersBody, - copyDescription = "Copy request headers", - onCopy = keyValuesCopyAction(requestHeadersBody.entries, copyText), - tab = InspectorDetailTab.REQUEST, - ), - InspectorDetailSectionSpec( - "general", - "General", - InspectorDetailSectionBody.KeyValues(generalEntries), - copyDescription = "Copy general info", - onCopy = { copyText(generalEntries.toCopyText()) }, - ), - netRedactionsSection(transaction, colors, copyText), - netTimingSection(transaction, colors, copyText), + val decodedSections = netDecodedSections(decoded, colors, copyText) + val responseDecoded = decodedSections.filter { it.tab == InspectorDetailTab.RESPONSE } + val requestDecoded = decodedSections.filter { it.tab == InspectorDetailTab.REQUEST } + return buildList { + add(responseSection) + addAll(responseDecoded) + add( + InspectorDetailSectionSpec( + InspectorExchangeSection.SECONDARY_HEADERS.key, + InspectorExchangeSection.SECONDARY_HEADERS.networkLabel, + responseHeadersBody, + copyDescription = "Copy response headers", + onCopy = keyValuesCopyAction(responseHeadersBody.entries, copyText), + tab = InspectorDetailTab.RESPONSE, + ), + ) + add(requestSection) + addAll(requestDecoded) + add( + InspectorDetailSectionSpec( + InspectorExchangeSection.PRIMARY_HEADERS.key, + InspectorExchangeSection.PRIMARY_HEADERS.networkLabel, + requestHeadersBody, + copyDescription = "Copy request headers", + onCopy = keyValuesCopyAction(requestHeadersBody.entries, copyText), + tab = InspectorDetailTab.REQUEST, + ), + ) + add( + InspectorDetailSectionSpec( + "general", + "General", + InspectorDetailSectionBody.KeyValues(generalEntries), + copyDescription = "Copy general info", + onCopy = { copyText(generalEntries.toCopyText()) }, + ), + ) + add(netRedactionsSection(transaction, colors, copyText)) + add(netTimingSection(transaction, colors, copyText)) + } +} + +/** + * The detail's resend affordances. Non-null only for a live capture: a retained past run cannot be + * replayed (its host allow-list and capability state belong to a process that is no longer running). + * [disabledReason] explains why both actions are demoted instead of silently vanishing. + */ +internal data class NetResendActions( + val enabled: Boolean, + val disabledReason: String?, + val onResend: () -> Unit, + val onEditResend: () -> Unit, +) + +/** + * Builds [NetResendActions] from a capture's body state: a binary or truncated request body has no + * faithful text to send, and request execution off means the composer would reject the dispatch the + * ViewModel already gates. Either reason demotes both actions rather than offering a dead tap. + */ +internal fun netResendActions( + transaction: InspectorTransactionUi, + requestExecutionEnabled: Boolean, + onResend: () -> Unit, + onEditResend: () -> Unit, +): NetResendActions { + val bodyUsable = transaction.requestBodyKind != InspectorBodyKind.BINARY && !transaction.requestBodyTruncated + val disabledReason = + when { + !bodyUsable -> "Request body not captured as text" + !requestExecutionEnabled -> "Request execution is off" + else -> null + } + return NetResendActions( + enabled = disabledReason == null, + disabledReason = disabledReason, + onResend = onResend, + onEditResend = onEditResend, ) } -/** Mock/unmock and cURL retain their callbacks in the detail action panel. */ +/** Mock/unmock, resend and cURL retain their callbacks in the detail action panel. */ private fun netFooterActions( transaction: InspectorTransactionUi, colors: DevConsoleColors, onMockAction: (() -> Unit)?, copyText: (String) -> Unit, + resendActions: NetResendActions?, ): List = buildList { + if (resendActions != null) { + add( + InspectorFooterAction( + label = "Resend", + onClick = resendActions.onResend, + weight = 1f, + enabled = resendActions.enabled, + supportingText = resendActions.disabledReason, + containerColor = colors.surface3, + contentColor = colors.ink, + ), + ) + add( + InspectorFooterAction( + label = "Edit & resend", + onClick = resendActions.onEditResend, + weight = 1f, + enabled = resendActions.enabled, + containerColor = colors.surface3, + contentColor = colors.ink, + ), + ) + } if (onMockAction != null) { add( InspectorFooterAction( @@ -303,6 +519,7 @@ internal fun netDetailContent( onMockThisResponse: () -> Unit, onUnmockThisResponse: (String) -> Unit, mockDiff: JsonMockDiffResult? = null, + resendActions: NetResendActions? = null, ): ObserveDetailContent { // Prefilling a *new* mock rule from a response that's already mocked is pointless, so a mocked // transaction gets an "Unmock" action (disables the serving rule) instead -- unless its rule id @@ -332,6 +549,8 @@ internal fun netDetailContent( } if (redactedCount > 0) add("$redactedCount header fields masked on device") } + val sections = netSections(transaction, colors, statusColor, copyText, mockDiff) + val decodedKeys = sections.mapNotNullTo(mutableSetOf()) { spec -> spec.key.takeIf { it.startsWith("decoded-") } } return ObserveDetailContent( header = InspectorObserveDetailHeaderSpec( @@ -346,12 +565,13 @@ internal fun netDetailContent( actions = netHeaderActions(transaction, colors, shareText, isFlagged, onToggleFlag), notices = notices, ), - sections = netSections(transaction, colors, statusColor, copyText, mockDiff), + sections = sections, // Both bodies stay expanded when moving between Response and Request. initiallyOpenSectionKeys = InspectorExchangeSection.keysOf(InspectorExchangeSection.defaultSearchScope) + - setOf("general", "timing"), - footerActions = netFooterActions(transaction, colors, onMockAction, copyText), + setOf("general", "timing") + + decodedKeys, + footerActions = netFooterActions(transaction, colors, onMockAction, copyText, resendActions), searchOptions = NetworkDetailSearchOptions, ) } 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 index c407547..8456809 100644 --- 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 @@ -7,7 +7,9 @@ package io.devconsole.ui.compose +import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth @@ -17,13 +19,15 @@ import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text +import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.testTag import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp -import java.util.Locale /** * Remote Config tab: every provider's currently resolved keys, read-only. @@ -49,7 +53,7 @@ internal fun RemoteConfigTabContent( ObserveTabEmptyState("No Remote Config provider is registered for this session.", EmptySpot.RemoteConfig) return } - val query = ui.remoteConfigSearch.trim().lowercase(Locale.US) + val query = ui.remoteConfigSearch.trim() LazyColumn( modifier = Modifier.fillMaxSize(), contentPadding = PaddingValues(top = 12.dp, bottom = 24.dp), @@ -73,7 +77,14 @@ internal fun RemoteConfigTabContent( } } state.remoteConfig.forEach { provider -> - item(key = "rc-head-${provider.id}") { RemoteConfigHeader(provider, colors) } + item(key = "rc-head-${provider.id}") { + RemoteConfigHeader( + provider = provider, + colors = colors, + editable = state.remoteConfigOverridesEditable, + onClearAll = actions.onRequestClearAllRemoteConfigOverrides, + ) + } val shown = provider.entries.filter { it.matches(query) } when { provider.unavailableReason != null -> @@ -87,10 +98,13 @@ internal fun RemoteConfigTabContent( else -> itemsIndexed(shown, key = { _, entry -> "rc-${provider.id}-${entry.key}" }) { index, entry -> RemoteConfigRow( - entry, - colors, - Modifier.groupedPanelItem(GroupPosition.of(index, shown.size)), - ) { actions.onOpenRemoteConfigDetail(provider.id, entry.key) } + entry = entry, + colors = colors, + editable = state.remoteConfigOverridesEditable, + modifier = Modifier.groupedPanelItem(GroupPosition.of(index, shown.size)), + onClick = { actions.onOpenRemoteConfigDetail(provider.id, entry.key) }, + onEdit = { actions.onOpenRemoteConfigOverride(provider.id, entry.key) }, + ) } } item(key = "rc-space-${provider.id}") { Spacer(Modifier.height(16.dp)) } @@ -107,14 +121,30 @@ internal fun RemoteConfigTabContent( private fun RemoteConfigHeader( provider: InspectorRemoteConfigUi, colors: DevConsoleColors, + editable: Boolean, + onClearAll: () -> Unit, ) { GroupLabel("Remote Config · ${provider.id}") - Text( - text = remoteConfigFetchLine(provider), - modifier = Modifier.padding(start = 16.dp, end = 16.dp, bottom = 8.dp), - color = colors.muted, - fontSize = 12.5.sp, - ) + Row( + modifier = Modifier.fillMaxWidth().padding(start = 16.dp, end = 16.dp, bottom = 8.dp), + horizontalArrangement = Arrangement.spacedBy(8.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Text( + text = remoteConfigFetchLine(provider), + modifier = Modifier.weight(1f), + color = colors.muted, + fontSize = 12.5.sp, + ) + if (editable && provider.entries.any { it.overridden }) { + TextButton( + onClick = onClearAll, + modifier = Modifier.testTag("remoteConfigClearAll"), + ) { + Text("Clear all overrides", color = colors.signal, fontSize = 13.sp) + } + } + } } /** @@ -146,21 +176,24 @@ private fun RemoteConfigNoMatchNote() { InspectorEmptyState(EmptySpot.Search, "No key matches the current search.", spotSize = 64.dp) } +/** + * The override affordance and badge exist only when the adapter supports overrides; otherwise the + * row stays exactly the read-only row it has always been. The row's own click still opens the + * detail, so the edit control is a separate actionable node ([TonalListRow] must not merge them). + */ @Composable private fun RemoteConfigRow( entry: InspectorRemoteConfigEntryUi, colors: DevConsoleColors, + editable: Boolean, modifier: Modifier = Modifier, onClick: () -> Unit, + onEdit: () -> 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") - } + val sub = remoteConfigRowSubtitle(entry) TonalListRow( leadText = entry.source, leadColor = colors.muted, @@ -181,5 +214,30 @@ private fun RemoteConfigRow( trailValueColor = colors.muted, modifier = modifier, onClick = onClick, + mergeDescendants = !editable, + trailContent = + if (editable) { + { + TextButton( + onClick = onEdit, + modifier = Modifier.testTag("remoteConfigEdit-${entry.key}"), + ) { + Text("Edit", color = colors.signal, fontSize = 13.sp) + } + } + } else { + null + }, ) } + +/** + * The row's value line. A DevConsole override also names the provider's own value, so the masked + * value stays visible without opening the editor; a redacted entry never shows either value. + */ +internal fun remoteConfigRowSubtitle(entry: InspectorRemoteConfigEntryUi): String = + buildString { + append(if (entry.redacted) "" else entry.value) + if (entry.truncated) append(" · truncated") + if (entry.overridden && !entry.redacted) append(" · provider: ${entry.providerValue ?: ""}") + } 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 567b843..066af75 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 @@ -7,6 +7,7 @@ package io.devconsole.ui.compose import android.content.Context +import androidx.activity.compose.BackHandler import androidx.compose.animation.AnimatedContent import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeOut @@ -20,11 +21,13 @@ import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material3.AlertDialog +import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.DropdownMenu import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.SnackbarHost import androidx.compose.material3.SnackbarHostState import androidx.compose.material3.Text +import androidx.compose.material3.TextButton import androidx.compose.material3.minimumInteractiveComponentSize import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect @@ -33,6 +36,7 @@ import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.rememberUpdatedState import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment @@ -41,6 +45,7 @@ import androidx.compose.ui.platform.ClipboardManager import androidx.compose.ui.platform.LocalClipboardManager import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.platform.testTag import androidx.compose.ui.semantics.Role import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.semantics.semantics @@ -53,7 +58,10 @@ import androidx.lifecycle.compose.LifecycleStartEffect import androidx.lifecycle.compose.LocalLifecycleOwner import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.compose.currentStateAsState +import androidx.lifecycle.repeatOnLifecycle import androidx.lifecycle.viewmodel.compose.viewModel +import kotlinx.coroutines.delay +import kotlinx.coroutines.isActive import kotlinx.coroutines.launch /** Which capture the full-screen detail overlay is currently showing, and how to find it in [InspectorState]. */ @@ -109,12 +117,20 @@ internal data class ObserveUiState( val logsSearch: String = "", val crashesSearch: String = "", val remoteConfigSearch: String = "", + /** Non-null while the Remote Config override editor is open for one key. */ + val remoteConfigEditTarget: RemoteConfigOverrideEditTarget? = null, + /** True while the Clear all overrides confirmation is showing. */ + val clearAllRemoteConfigOverridesPending: Boolean = false, val flaggedTransactionIds: Set = emptySet(), val bookmarkedLogIds: Set = emptySet(), val flaggedCrashIds: Set = emptySet(), val detailTarget: ObserveDetailTarget? = null, /** Non-null while the net detail's "Mock this response" action has a create sheet open. */ val mockDraft: MockRuleEditorTarget.New? = null, + /** Non-null while the net detail's edit-and-resend sheet is open. */ + val resendDraft: InspectorResendDraft? = null, + /** Non-null while a completed resend's response sheet is open. */ + val resendResult: InspectorResendResult? = null, /** True while the Traffic tab's "clear captures" confirmation is showing. */ val clearTransactionsPending: Boolean = false, /** Hero collapse is hoisted per tab, independent of every other tab's. */ @@ -125,6 +141,10 @@ internal data class ObserveUiState( val crashesHeroCollapsed: Boolean = true, val searchOpen: Boolean = false, val trafficFiltersOpen: Boolean = false, + /** Whether Observe polls the capture store while it is on screen. */ + val liveMode: Boolean = true, + /** False until the first snapshot settles; the unavailable notice waits for it. */ + val snapshotLoaded: Boolean = true, ) // One callback per distinct Observe interaction; bundling further would just hide the count. @@ -145,6 +165,16 @@ internal data class ObserveActions( val onOpenCrashDetail: (String) -> Unit, val onRemoteConfigSearchChange: (String) -> Unit, val onOpenRemoteConfigDetail: (String, String) -> Unit, + /** Opens the local override editor for one Remote Config key. */ + val onOpenRemoteConfigOverride: (String, String) -> Unit = { _, _ -> }, + val onSetRemoteConfigOverride: (String, String, String) -> Unit = { _, _, _ -> }, + val onClearRemoteConfigOverride: (String, String) -> Unit = { _, _ -> }, + val onDismissRemoteConfigOverride: () -> Unit = {}, + val onRequestClearAllRemoteConfigOverrides: () -> Unit = {}, + val onConfirmClearAllRemoteConfigOverrides: () -> Unit = {}, + val onCancelClearAllRemoteConfigOverrides: () -> Unit = {}, + /** Sends one frame over [connectionId]; only a successful result clears the composer. */ + val onSendSocketFrame: (String, String, String?, Int, Boolean) -> Unit = { _, _, _, _, _ -> }, val onToggleCrashFlag: (String) -> Unit, val onToggleCrashesHero: () -> Unit, /** The previous-run-crashed banner's action: opens that session's crash on the Crashes tab. */ @@ -181,6 +211,26 @@ internal data class ObserveActions( val onToggleSocketsHero: () -> Unit, val onTogglePushHero: () -> Unit, val onToggleLogsHero: () -> Unit, + val onToggleLiveMode: () -> Unit = {}, + /** Leaves a selected past run and goes back to the live session. */ + val onReturnToLiveSession: () -> Unit = {}, + /** The paused-capture banner's action: resumes live capture. */ + val onResumeCapture: () -> Unit = {}, + val onSetSessionPinned: (id: String, pinned: Boolean) -> Unit = { _, _ -> }, + val onDeleteSession: (id: String) -> Unit = {}, + /** Traffic header's status-class chips: re-reads the capture store with the new bucket. */ + val onTrafficStatusClassClick: (TrafficStatusClass) -> Unit = {}, + /** Traffic header's host dropdown: null shows every host. */ + val onTrafficHostClick: (String?) -> Unit = {}, + /** The net detail's "Resend": replays the captured request through the composer. */ + val onResendTransaction: (InspectorTransactionUi) -> Unit = {}, + /** The net detail's "Edit & resend": opens the prefilled sheet. */ + val onEditResendTransaction: (InspectorTransactionUi) -> Unit = {}, + val onSendResendDraft: (InspectorResendDraft) -> Unit = {}, + val onCancelResendDraft: () -> Unit = {}, + /** Copies the response sheet's body and confirms it in a snackbar. */ + val onCopyResendBody: (String) -> Unit = {}, + val onDismissResendResult: () -> Unit = {}, ) /** @@ -192,10 +242,8 @@ internal data class ObserveActions( * by caller-supplied `rememberSaveable`-backed [MutableState]s too, so search text and hero-collapse * survive a configuration change such as rotation or a multi-window resize instead of resetting: a * config change is not process death, so there's no reason for these to behave as if it were. - * [detailTarget] and [bookmarkedIds] stay plain `mutableStateOf`: transaction/log ids aren't - * Bundle-friendly without a custom Saver (see [MockRuleEditorNewSaver] for what that would take), and - * losing an open detail overlay or the bookmark set across a rotation is a narrower, acceptable - * tradeoff for this debug-only inspector surface. + * [detailTarget] is saved through [ObserveDetailTargetSaver] so rotation keeps the open detail; + * [bookmarkedIds] stays plain `mutableStateOf`, a narrower loss for this debug-only surface. */ @Suppress("LongParameterList") // One rememberSaveable-backed MutableState per saved field; see doc above. private class ObserveRouteState( @@ -212,6 +260,8 @@ private class ObserveRouteState( pushHeroCollapsedState: MutableState, logsHeroCollapsedState: MutableState, crashesHeroCollapsedState: MutableState, + detailTargetState: MutableState, + liveModeState: MutableState, ) { var trafficSearch by trafficSearchState var trafficChip by trafficChipState @@ -220,10 +270,26 @@ private class ObserveRouteState( var logsSearch by logsSearchState var crashesSearch by crashesSearchState var remoteConfigSearch by remoteConfigSearchState + var remoteConfigEditTarget by mutableStateOf(null) + + /** A plain state: losing an open confirmation across rotation safely re-arms nothing. */ + var clearAllRemoteConfigOverridesPending by mutableStateOf(false) var bookmarkedIds by mutableStateOf(emptySet()) - var detailTarget by mutableStateOf(null) + var detailTarget by detailTargetState + + /** Live tail on/off for the Observe poll (see [ObserveLivePoll]); saved across rotation. */ + var liveMode by liveModeState var mockDraft by mockDraftState + /** Plain state like [clearTransactionsPending]: a half-edited request need not survive rotation. */ + var resendDraft by mutableStateOf(null) + + /** True between dispatching a resend and its command result arriving. */ + var awaitingResend by mutableStateOf(false) + + /** The response sheet's result, set only for an actual HTTP response rather than a flash message. */ + var resendResult by mutableStateOf(null) + /** * Plain `mutableStateOf`, not `rememberSaveable`: losing an open confirmation across a rotation * is the safe direction to fail for a destructive action -- the operator re-taps rather than @@ -260,6 +326,9 @@ private fun rememberObserveRouteState(mockDraftState: MutableState(null) } + val liveModeState = rememberSaveable { mutableStateOf(true) } return remember { ObserveRouteState( mockDraftState = mockDraftState, @@ -275,6 +344,8 @@ private fun rememberObserveRouteState(mockDraftState: MutableState(null) } val routeState = rememberObserveRouteState(mockDraftState) - val ui = routeState.toUiState(rememberAppIdentitySubtitle(), state.flaggedTransactionIds, state.flaggedCrashIds) + val snapshotLoaded by viewModel.snapshotLoaded.collectAsStateWithLifecycle() + val ui = + routeState + .toUiState(rememberAppIdentitySubtitle(), state.flaggedTransactionIds, state.flaggedCrashIds) + .copy(snapshotLoaded = snapshotLoaded) val actions = rememberObserveActions( viewModel, @@ -346,15 +426,38 @@ internal fun ObserveRoute( viewModel.dispatch(InspectorAction.Refresh) onStopOrDispose { } } - LaunchedEffect(ui.detailTarget, ui.mockDraft) { - onDetailOverlayOpen(ui.detailTarget != null || ui.mockDraft != null) + ObserveLivePoll(enabled = ui.canLivePoll(state)) { viewModel.dispatch(InspectorAction.Refresh) } + LaunchedEffect(ui.detailTarget, ui.mockDraft, ui.resendDraft, ui.resendResult) { + onDetailOverlayOpen( + ui.detailTarget != null || + ui.mockDraft != null || + ui.resendDraft != null || + ui.resendResult != null, + ) } // Same toast+dismiss consumer ControlRoute/MoreRoute already have -- previously missing here // entirely, so a mock-rule save's rejection (or the mocks capability being off) vanished // silently and the stale result leaked its toast onto whichever screen the operator opened next. LaunchedEffect(state.lastCommandResult) { state.lastCommandResult?.let { result -> - showMessage(result.toFlashMessage()) + val pendingDraft = routeState.resendDraft?.takeIf { it.sending } + if (routeState.awaitingResend || pendingDraft != null) { + routeState.awaitingResend = false + val resendResult = resendResultFrom(result) + when { + resendResult != null -> { + routeState.resendDraft = null + routeState.resendResult = resendResult + } + // A snackbar would sit under the open edit sheet; keep the operator's edits and + // show the rejection there so a typo or a blocked host is fixed in place. + pendingDraft != null -> + routeState.resendDraft = pendingDraft.copy(sending = false, error = result.toFlashMessage()) + else -> showMessage(result.toFlashMessage()) + } + } else { + showMessage(result.toFlashMessage()) + } if (routeState.mockDraft != null && result is InspectorCommandResult.Success) { routeState.mockDraft = null } @@ -407,6 +510,27 @@ private fun rememberObserveActions( onOpenRemoteConfigDetail = { providerId, key -> routeState.detailTarget = ObserveDetailTarget.RemoteConfigKey(providerId, key) }, + onOpenRemoteConfigOverride = { providerId, key -> + routeState.remoteConfigEditTarget = RemoteConfigOverrideEditTarget(providerId, key) + }, + onSetRemoteConfigOverride = { providerId, key, value -> + routeState.remoteConfigEditTarget = null + viewModel.dispatch(InspectorAction.SetRemoteConfigOverride(providerId, key, value)) + }, + onClearRemoteConfigOverride = { providerId, key -> + routeState.remoteConfigEditTarget = null + viewModel.dispatch(InspectorAction.ClearRemoteConfigOverride(providerId, key)) + }, + onDismissRemoteConfigOverride = { routeState.remoteConfigEditTarget = null }, + onRequestClearAllRemoteConfigOverrides = { routeState.clearAllRemoteConfigOverridesPending = true }, + onConfirmClearAllRemoteConfigOverrides = { + routeState.clearAllRemoteConfigOverridesPending = false + viewModel.dispatch(InspectorAction.ClearAllRemoteConfigOverrides) + }, + onCancelClearAllRemoteConfigOverrides = { routeState.clearAllRemoteConfigOverridesPending = false }, + onSendSocketFrame = { connectionId, text, topic, qos, retained -> + viewModel.dispatch(InspectorAction.SendSocketFrame(connectionId, text, topic, qos, retained)) + }, // 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. @@ -450,6 +574,29 @@ private fun rememberObserveActions( onToggleSocketsHero = { routeState.socketsHeroCollapsed = !routeState.socketsHeroCollapsed }, onTogglePushHero = { routeState.pushHeroCollapsed = !routeState.pushHeroCollapsed }, onToggleLogsHero = { routeState.logsHeroCollapsed = !routeState.logsHeroCollapsed }, + onToggleLiveMode = { routeState.liveMode = !routeState.liveMode }, + onReturnToLiveSession = { viewModel.dispatch(InspectorAction.SelectSession(null)) }, + onResumeCapture = { viewModel.dispatch(InspectorAction.SetCapturePaused(false)) }, + onSetSessionPinned = { id, pinned -> viewModel.dispatch(InspectorAction.SetSessionPinned(id, pinned)) }, + onDeleteSession = { id -> viewModel.dispatch(InspectorAction.DeleteSession(id)) }, + onTrafficStatusClassClick = { statusClass -> + viewModel.dispatch(InspectorAction.SelectTrafficStatusClass(statusClass)) + }, + onTrafficHostClick = { host -> viewModel.dispatch(InspectorAction.SelectTrafficHost(host)) }, + // Resend reuses the existing composer path (capability gate + host allow-list), so its + // success/rejection toast arrives through lastCommandResult like every other command. + onResendTransaction = { transaction -> + routeState.awaitingResend = true + viewModel.dispatch(InspectorAction.ExecuteComposer(transaction.toComposerRequest())) + }, + onEditResendTransaction = { transaction -> routeState.resendDraft = resendDraftFromTransaction(transaction) }, + onSendResendDraft = { draft -> + routeState.resendDraft = draft.copy(sending = true, error = null) + viewModel.dispatch(InspectorAction.ExecuteComposer(draft.toComposerRequest())) + }, + onCancelResendDraft = { routeState.resendDraft = null }, + onCopyResendBody = { body -> clipboard.setText(AnnotatedString(body)) }, + onDismissResendResult = { routeState.resendResult = null }, ) private fun toggleBookmark( @@ -592,74 +739,32 @@ internal fun ObserveScreen( var filtersOpen by rememberSaveable { mutableStateOf(false) } var moreOpen by remember { mutableStateOf(false) } val tabUi = ui.copy(searchOpen = searchOpen, trafficFiltersOpen = filtersOpen) + // Composed before the tab content and the detail overlay, so their own BackHandlers win first. + ObserveSearchBackHandler( + searchOpen = searchOpen, + filtersOpen = filtersOpen, + onCloseSearch = { + clearObserveSearch(state.observeTab, actions) + searchOpenTabs = searchOpenTabs - state.observeTab.name + }, + onCloseFilters = { filtersOpen = false }, + ) Box(modifier = modifier.background(colors.ground)) { Column(Modifier.fillMaxSize()) { - InspectorTopArea( - subLine = "", - title = state.observeTab.title(), - actions = - buildList { - add( - InspectorTopAction( - contentDescription = "Search", - onClick = { - if (searchOpen) clearObserveSearch(state.observeTab, actions) - searchOpenTabs = - if (searchOpen) { - searchOpenTabs - state.observeTab.name - } else { - searchOpenTabs + state.observeTab.name - } - }, - icon = { InspectorGlyphIcon(InspectorGlyph.Search, null, tint = colors.muted) }, - ), - ) - if (state.observeTab == ObserveTab.TRAFFIC) { - add( - InspectorTopAction( - contentDescription = "Filter", - onClick = { filtersOpen = !filtersOpen }, - icon = { - ObserveGlyphIcon( - ObserveGlyph.Filter, - null, - tint = - if (filtersOpen || - ui.trafficChip != "all" - ) { - colors.signal - } else { - colors.muted - }, - ) - }, - ), - ) - } - add( - InspectorTopAction( - contentDescription = "More options", - onClick = { moreOpen = true }, - icon = { - Box { - DevConsoleIcon( - R.drawable.devconsole_ic_more_horizontal, - contentDescription = null, - modifier = Modifier, - tint = colors.muted, - size = 20.dp, - ) - ObserveOverflowMenu(state, ui, actions, moreOpen) { moreOpen = false } - } - }, - ), - ) - }, + ObserveTopArea( + state = state, + ui = ui, + actions = actions, + filtersOpen = filtersOpen, + moreOpen = moreOpen, + onToggleSearch = { searchOpenTabs = toggledObserveSearch(state, actions, searchOpen, searchOpenTabs) }, + onToggleFilters = { filtersOpen = !filtersOpen }, + onOpenMore = { moreOpen = true }, + onCloseMore = { moreOpen = false }, ) - previousCrashedSession(state.sessions)?.let { session -> - PreviousRunCrashedBanner(session = session, onViewCrash = { actions.onViewPreviousCrash(session.id) }) - } - val visibleTabs = ObserveTab.entries.toList() + ObserveRunBanners(state, actions) + val visibleTabs = + remember(state.captureCategories, state.remoteConfig.isNotEmpty()) { state.visibleObserveTabs() } InspectorTabRow( tabs = visibleTabs.map { tab -> @@ -668,7 +773,7 @@ internal fun ObserveScreen( ) Box(Modifier.weight(1f)) { when { - !state.available -> ObserveUnavailableNotice() + !state.available -> if (ui.snapshotLoaded) ObserveUnavailableNotice() else ObserveLoadingNotice() else -> ObserveTabPager(state.observeTab, visibleTabs, state, tabUi, actions) } } @@ -688,9 +793,180 @@ internal fun ObserveScreen( onCancel = actions.onCancelMockDraft, ) } + ui.resendDraft?.let { draft -> + InspectorResendSheet( + draft = draft, + onSend = actions.onSendResendDraft, + onDismiss = actions.onCancelResendDraft, + ) + } + ui.resendResult?.let { result -> + InspectorResendResultSheet( + result = result, + onCopyBody = actions.onCopyResendBody, + onDismiss = actions.onDismissResendResult, + ) + } + ObserveRemoteConfigDialogs(state, ui, actions, started = lifecycleState.isAtLeast(Lifecycle.State.STARTED)) } } +/** + * The Remote Config override editor and its clear-all confirmation; both exist only while the data + * source reports overrides as editable. [started] keeps the confirmation from reappearing over a + * backgrounded inspector. + */ +@Composable +private fun ObserveRemoteConfigDialogs( + state: InspectorState, + ui: ObserveUiState, + actions: ObserveActions, + started: Boolean, +) { + if (state.remoteConfigOverridesEditable) { + remoteConfigEditEntry(state, ui)?.let { (target, entry) -> + RemoteConfigOverrideDialog( + entry = entry, + onOverride = { value -> actions.onSetRemoteConfigOverride(target.providerId, target.key, value) }, + onClear = { actions.onClearRemoteConfigOverride(target.providerId, target.key) }, + onDismiss = actions.onDismissRemoteConfigOverride, + ) + } + } + if (state.remoteConfigOverridesEditable && + ui.clearAllRemoteConfigOverridesPending && + started + ) { + ClearAllRemoteConfigOverridesConfirmDialog( + onConfirm = actions.onConfirmClearAllRemoteConfigOverrides, + onDismiss = actions.onCancelClearAllRemoteConfigOverrides, + ) + } +} + +/** One Remote Config key the override editor is open for. */ +internal data class RemoteConfigOverrideEditTarget( + val providerId: String, + val key: String, +) + +/** The open override editor's provider entry, or null once the snapshot no longer carries it. */ +private fun remoteConfigEditEntry( + state: InspectorState, + ui: ObserveUiState, +): Pair? = + ui.remoteConfigEditTarget?.let { target -> + state.remoteConfig + .firstOrNull { it.id == target.providerId } + ?.entries + ?.firstOrNull { it.key == target.key } + ?.let { entry -> target to entry } + } + +/** Confirms removing every local override before the ViewModel is asked to. */ +@Composable +private fun ClearAllRemoteConfigOverridesConfirmDialog( + onConfirm: () -> Unit, + onDismiss: () -> Unit, +) { + AlertDialog( + onDismissRequest = onDismiss, + title = { Text("Clear all overrides?") }, + text = { Text("Every key goes back to the value its provider fetched.") }, + confirmButton = { + TextButton( + onClick = onConfirm, + modifier = Modifier.testTag("remoteConfigClearAllConfirm"), + ) { + Text("Clear all") + } + }, + dismissButton = { + TextButton(onClick = onDismiss) { Text("Cancel") } + }, + ) +} + +/** The Observe title, live pill and top actions, split out of [ObserveScreen] to keep it simple. */ +@Composable +private fun ObserveTopArea( + state: InspectorState, + ui: ObserveUiState, + actions: ObserveActions, + filtersOpen: Boolean, + moreOpen: Boolean, + onToggleSearch: () -> Unit, + onToggleFilters: () -> Unit, + onOpenMore: () -> Unit, + onCloseMore: () -> Unit, +) { + val colors = DevConsoleTheme.colors + val live = ObserveLivePill.of(state, ui, actions) + InspectorTopArea( + subLine = "", + title = state.observeTab.title(), + liveLabel = live.label, + liveActive = live.active, + onLiveClick = live.onClick, + liveDescription = live.description, + actions = + buildList { + add( + InspectorTopAction( + contentDescription = "Search", + onClick = onToggleSearch, + icon = { InspectorGlyphIcon(InspectorGlyph.Search, null, tint = colors.muted) }, + ), + ) + if (state.observeTab == ObserveTab.TRAFFIC) { + add( + InspectorTopAction( + contentDescription = "Filter", + onClick = onToggleFilters, + icon = { + ObserveGlyphIcon( + ObserveGlyph.Filter, + null, + tint = if (filtersOpen || ui.trafficChip != "all") colors.signal else colors.muted, + ) + }, + ), + ) + } + add( + InspectorTopAction( + contentDescription = "More options", + onClick = onOpenMore, + icon = { + Box { + DevConsoleIcon( + R.drawable.devconsole_ic_more_horizontal, + contentDescription = null, + modifier = Modifier, + tint = colors.muted, + size = 20.dp, + ) + ObserveOverflowMenu(state, ui, actions, moreOpen, onCloseMore) + } + }, + ), + ) + }, + ) +} + +/** Toggles the current tab's search open state, clearing its text on close. */ +private fun toggledObserveSearch( + state: InspectorState, + actions: ObserveActions, + searchOpen: Boolean, + openTabs: List, +): List { + if (searchOpen) clearObserveSearch(state.observeTab, actions) + val tabName = state.observeTab.name + return if (searchOpen) openTabs - tabName else openTabs + tabName +} + private fun clearObserveSearch( tab: ObserveTab, actions: ObserveActions, @@ -818,6 +1094,144 @@ private fun previousCrashedSession(sessions: List): Inspecto * already know to check the Crashes tab. Tapping it jumps straight to that session's crash via * [ObserveActions.onViewPreviousCrash]. */ +private const val LIVE_REFRESH_INTERVAL_MS = 2_000L + +/** Polls while the screen is at least STARTED and [enabled]; stops as soon as either goes away. */ +@Composable +private fun ObserveLivePoll( + enabled: Boolean, + onTick: () -> Unit, +) { + val lifecycleOwner = LocalLifecycleOwner.current + val currentOnTick by rememberUpdatedState(onTick) + LaunchedEffect(enabled, lifecycleOwner) { + if (enabled) { + lifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) { + while (isActive) { + delay(LIVE_REFRESH_INTERVAL_MS) + currentOnTick() + } + } + } + } +} + +/** No polling over a past run or while a detail, mock sheet or clear confirmation is open. */ +private fun ObserveUiState.canLivePoll(state: InspectorState): Boolean { + val sheetOpen = mockDraft != null || resendDraft != null || resendResult != null + val overlayOpen = detailTarget != null || sheetOpen || clearTransactionsPending + return liveMode && state.selectedSessionId == null && !overlayOpen +} + +/** The Observe title's live pill: toggles the poll, or returns to live while a past run is shown. */ +private data class ObserveLivePill( + val label: String, + val description: String, + val active: Boolean, + val onClick: () -> Unit, +) { + companion object { + fun of( + state: InspectorState, + ui: ObserveUiState, + actions: ObserveActions, + ): ObserveLivePill = + when { + state.selectedSessionId != null -> + ObserveLivePill( + "Past run", + "Viewing a past run. Back to live", + false, + actions.onReturnToLiveSession, + ) + // Capture pause outranks the refresh toggle: with nothing being recorded, "Live" would + // claim a liveness the inspector does not have. Tapping it resumes capture. + state.capturePaused -> + ObserveLivePill("Not capturing", "Capture paused. Resume capture", false, actions.onResumeCapture) + ui.liveMode -> ObserveLivePill("Live", "Live updates on. Pause", true, actions.onToggleLiveMode) + else -> ObserveLivePill("Paused", "Live updates paused. Resume", false, actions.onToggleLiveMode) + } + } +} + +/** System Back closes an open search first, then the traffic filters panel. */ +@Composable +private fun ObserveSearchBackHandler( + searchOpen: Boolean, + filtersOpen: Boolean, + onCloseSearch: () -> Unit, + onCloseFilters: () -> Unit, +) { + BackHandler(enabled = searchOpen || filtersOpen) { + if (searchOpen) onCloseSearch() else onCloseFilters() + } +} + +/** Previous-run-crashed and viewing-a-past-run banners above the tab row. */ +@Composable +private fun ObserveRunBanners( + state: InspectorState, + actions: ObserveActions, +) { + if (state.capturePaused) { + CapturePausedBanner(onResume = actions.onResumeCapture) + } + // Hidden while a past run is open: its "View" would only re-select what is already on screen. + previousCrashedSession(state.sessions)?.takeIf { state.selectedSessionId == null }?.let { session -> + PreviousRunCrashedBanner(session = session, onViewCrash = { actions.onViewPreviousCrash(session.id) }) + } + state.sessions.firstOrNull { it.id == state.selectedSessionId }?.let { session -> + PastRunBanner( + session = session, + onReturnToLive = actions.onReturnToLiveSession, + onSetPinned = { pinned -> actions.onSetSessionPinned(session.id, pinned) }, + onDelete = { actions.onDeleteSession(session.id) }, + ) + } +} + +/** The capture [target] points at, looked up cheaply so the detail can be memoized on it. */ +private fun detailSubject( + target: ObserveDetailTarget, + state: InspectorState, + recentFrames: List>, +): Any? = + when (target) { + is ObserveDetailTarget.Net -> state.transactions.find { it.id == target.transactionId } to state.mockRules + is ObserveDetailTarget.Frame -> + recentFrames.firstOrNull { (socket, frame) -> + socket.id == target.socketId && frame.timestampEpochMs == target.timestampEpochMs + } + is ObserveDetailTarget.Push -> + state.pushEvents.firstOrNull { + it.provider == target.provider && it.receivedAtEpochMs == target.receivedAtEpochMs + } + is ObserveDetailTarget.Log -> state.logs.find { it.id == target.logId } + is ObserveDetailTarget.Crash -> state.crashes.find { it.id == target.crashId } + is ObserveDetailTarget.RemoteConfigKey -> state.remoteConfig.firstOrNull { it.id == target.providerId } + } + +/** + * Shown while live capture is paused, so an empty list is never mistaken for a quiet app. Shaped + * like [PastRunBanner]: a tagged panel row whose trailing action is the way back. + */ +@Composable +private fun CapturePausedBanner(onResume: () -> Unit) { + val colors = DevConsoleTheme.colors + TonalListRow( + leadText = "PAUSED", + leadColor = colors.ink, + leadContainerColor = colors.panel, + title = "Capture paused", + subtitle = "New requests, sockets, logs and push are not recorded", + trailValue = "Resume", + trailValueColor = colors.signal, + containerColor = colors.panel, + modifier = Modifier.padding(start = 16.dp, top = 4.dp, end = 16.dp, bottom = 8.dp), + onClick = onResume, + ) +} + @Composable private fun PreviousRunCrashedBanner( session: InspectorSessionUi, @@ -825,7 +1239,7 @@ private fun PreviousRunCrashedBanner( ) { val colors = DevConsoleTheme.colors TonalListRow( - leadText = "CRA", + leadText = "CRASH", leadColor = colors.error, leadContainerColor = colors.errorSoft, title = "Previous run crashed", @@ -838,6 +1252,16 @@ private fun PreviousRunCrashedBanner( ) } +@Composable +private fun ObserveLoadingNotice() { + Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { + CircularProgressIndicator( + modifier = Modifier.semantics { contentDescription = "Loading captures" }, + color = DevConsoleTheme.colors.signal, + ) + } +} + @Composable private fun ObserveUnavailableNotice() { val colors = DevConsoleTheme.colors @@ -920,6 +1344,19 @@ private fun resolveObserveDetail( }, onUnmockThisResponse = actions.onUnmockTransaction, mockDiff = netMockDiff, + // A retained past run is browsed, not driven: only a live capture can be + // replayed through the composer. Disabled reasons are shown on the buttons. + resendActions = + if (state.selectedSessionId == null) { + netResendActions( + transaction = transaction, + requestExecutionEnabled = state.capabilities.requestExecution, + onResend = { actions.onResendTransaction(transaction) }, + onEditResend = { actions.onEditResendTransaction(transaction) }, + ) + } else { + null + }, ) target.transactionId to content } @@ -1002,7 +1439,24 @@ private fun ObserveDetailOverlay( val colors = DevConsoleTheme.colors val recentFrames = rememberRecentFrames(state.sockets) val netMockDiff = rememberNetMockDiff(target, state) - val resolved = resolveObserveDetail(target, state, ui, actions, colors, recentFrames, netMockDiff) + // Keyed on the resolved capture itself (data-class equality), not the whole snapshot: a live + // refresh that leaves this capture unchanged must not re-format its bodies. + val subject = detailSubject(target, state, recentFrames) + val resolved = + remember( + target, + subject, + ui.flaggedTransactionIds, + ui.flaggedCrashIds, + ui.bookmarkedLogIds, + colors, + netMockDiff, + // Resend availability is derived from these two, not from the capture itself. + state.selectedSessionId, + state.capabilities.requestExecution, + ) { + resolveObserveDetail(target, state, ui, actions, colors, recentFrames, netMockDiff) + } if (resolved == null) { // The capture aged out of the snapshot while its detail was open. Close explicitly: // rendering nothing while `detailTarget` stays set would drop BackHandler from the @@ -1013,16 +1467,54 @@ private fun ObserveDetailOverlay( } } else { val (resetKey, content) = resolved - ObserveDetailFromContent(resetKey, content, actions.onCloseDetail) + val composerHost = frameComposerHost(target, state, recentFrames, actions) + ObserveDetailFromContent(resetKey, content, actions.onCloseDetail, composerHost) } } +/** + * The send composer for an open socket frame's connection, or null when that connection has no + * write protocol (or the target is not a socket frame). The Sockets tab is a flat frame list with no + * single-connection selection, so the frame detail is where one connection is in view. + */ +private fun frameComposerHost( + target: ObserveDetailTarget, + state: InspectorState, + recentFrames: List>, + actions: ObserveActions, +): SocketComposerHost? = + (target as? ObserveDetailTarget.Frame)?.let { frameTarget -> + recentFrames + .firstOrNull { (socket, frame) -> + socket.id == frameTarget.socketId && frame.timestampEpochMs == frameTarget.timestampEpochMs + }?.let { (socket, frame) -> + state.socketSendProtocols[socket.id]?.let { protocol -> + SocketComposerHost( + connectionId = socket.id, + protocol = protocol, + initialTopic = frame.topic, + lastResult = state.lastCommandResult, + onSend = { text, topic, qos, retained -> + actions.onSendSocketFrame(socket.id, text, topic, qos, retained) + }, + ) + } + } + } + @Composable private fun ObserveDetailFromContent( resetKey: Any, content: ObserveDetailContent, onBack: () -> Unit, + socketComposer: SocketComposerHost? = null, ) { + val composerContent: (@Composable () -> Unit)? = + if (socketComposer != null) { + { SocketSendComposer(socketComposer) } + } else { + null + } InspectorObserveDetailScreen( resetKey = resetKey, header = content.header, @@ -1032,6 +1524,7 @@ private fun ObserveDetailFromContent( onBack = onBack, searchPlaceholder = content.searchPlaceholder, searchOptions = content.searchOptions, + trailingContent = composerContent, ) } diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveSignals.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveSignals.kt index 9580e78..0c5dee6 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveSignals.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveSignals.kt @@ -52,18 +52,19 @@ internal fun SocketsTabContent( } val searchedIndices = remember(recentFrames, ui.socketsSearch) { - val query = ui.socketsSearch.trim().lowercase(Locale.US) + val query = ui.socketsSearch.trim() recentFrames.indices.filter { index -> if (query.isEmpty()) { true } else { val (socket, frame) = recentFrames[index] - socket.url.lowercase(Locale.US).contains(query) || - frame.preview?.lowercase(Locale.US)?.contains(query) == true + socket.url.contains(query, ignoreCase = true) || + frame.preview?.contains(query, ignoreCase = true) == true } } } - val arrivals = rememberArrivals(searchedIndices.map { frameKeys[it] }) + val arrivalKeys = remember(searchedIndices, frameKeys) { searchedIndices.map { frameKeys[it] } } + val arrivals = rememberArrivals(arrivalKeys) LazyColumn( modifier = Modifier.fillMaxSize(), @@ -121,7 +122,7 @@ private fun SocketsHero( buildString { if (loudest != null && loudest.receivedCount > 0) { val path = loudest.url.removePrefix("wss://").removePrefix("ws://") - append("$path is the loudest at ${loudest.receivedCount} frames received.") + append("$path is the loudest at ${countLabel(loudest.receivedCount, "frame")} received.") } else { append("No frames received yet.") } @@ -208,19 +209,20 @@ internal fun PushTabContent( } val searchedIndices = remember(state.pushEvents, ui.pushSearch) { - val query = ui.pushSearch.trim().lowercase(Locale.US) + val query = ui.pushSearch.trim() state.pushEvents.indices.filter { index -> if (query.isEmpty()) { true } else { val push = state.pushEvents[index] - push.provider.lowercase(Locale.US).contains(query) || - push.messageId?.lowercase(Locale.US)?.contains(query) == true || - push.dataPreview.values.any { it.lowercase(Locale.US).contains(query) } + push.provider.contains(query, ignoreCase = true) || + push.messageId?.contains(query, ignoreCase = true) == true || + push.dataPreview.values.any { it.contains(query, ignoreCase = true) } } } } - val arrivals = rememberArrivals(searchedIndices.map { pushKeys[it] }) + val arrivalKeys = remember(searchedIndices, pushKeys) { searchedIndices.map { pushKeys[it] } } + val arrivals = rememberArrivals(arrivalKeys) LazyColumn( modifier = Modifier.fillMaxSize(), @@ -325,21 +327,26 @@ internal fun LogsTabContent( ObserveTabEmptyState("No logs captured yet.", EmptySpot.Logs) return } - val searched = + val rowsNewestFirst = remember(state.logs, ui.logsSearch) { - val query = ui.logsSearch.trim().lowercase(Locale.US) - if (query.isEmpty()) { - state.logs - } else { - state.logs.filter { log -> - log.summary.lowercase(Locale.US).contains(query) || - log.source.lowercase(Locale.US).contains(query) || - log.detail?.lowercase(Locale.US)?.contains(query) == true + val query = ui.logsSearch.trim() + val filtered = + if (query.isEmpty()) { + state.logs + } else { + state.logs.filter { log -> + log.summary.contains(query, ignoreCase = true) || + log.source.contains(query, ignoreCase = true) || + log.detail?.contains(query, ignoreCase = true) == true + } } - } + filtered.sortedWith( + compareByDescending { it.timestampEpochMs } + .thenByDescending { it.id }, + ) } - val rowsNewestFirst = searched.asReversed() - val arrivals = rememberArrivals(rowsNewestFirst.map { it.id }) + val arrivalIds = remember(rowsNewestFirst) { rowsNewestFirst.map { it.id } } + val arrivals = rememberArrivals(arrivalIds) LazyColumn( modifier = Modifier.fillMaxSize(), @@ -383,7 +390,7 @@ private fun LogsHero( if (ui.logsHeroCollapsed) { HeroBar( value = flagged.size.toString(), - label = "of ${logs.size} events need attention", + label = "of ${countLabel(logs.size, "event")} ${if (flagged.size == 1) "needs" else "need"} attention", onExpand = actions.onToggleLogsHero, valueColor = colors.warn, labelColor = colors.warn, diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveTrafficTab.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveTrafficTab.kt index 3945770..d00fef7 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveTrafficTab.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveTrafficTab.kt @@ -27,11 +27,16 @@ import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.selection.toggleable import androidx.compose.foundation.shape.CircleShape +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.material3.minimumInteractiveComponentSize import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip @@ -42,11 +47,35 @@ import androidx.compose.ui.semantics.semantics import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp -import java.util.Locale private const val TRAFFIC_HTTP_CLIENT_ERROR_START = 400 private const val TRAFFIC_HTTP_CLIENT_ERROR_END = 499 private const val TRAFFIC_HTTP_SERVER_ERROR_START = 500 +private const val TRAFFIC_HOST_LIMIT = 8 + +/** Status-class chips in the traffic header, in HTTP bucket order. */ +private val TRAFFIC_STATUS_CLASS_LABELS = + listOf( + TrafficStatusClass.ALL to "All", + TrafficStatusClass.SUCCESS to "2xx", + TrafficStatusClass.REDIRECT to "3xx", + TrafficStatusClass.CLIENT_ERROR to "4xx", + TrafficStatusClass.SERVER_ERROR to "5xx", + TrafficStatusClass.FAILED to "Failed", + ) + +/** + * Hosts worth offering in the traffic header's dropdown: the [TRAFFIC_HOST_LIMIT] most captured + * hosts first, ties alphabetical so the list does not reshuffle between identical counts. + */ +internal fun topTrafficHosts(transactions: List): List = + transactions + .groupingBy { it.host } + .eachCount() + .entries + .sortedWith(compareByDescending> { it.value }.thenBy { it.key }) + .take(TRAFFIC_HOST_LIMIT) + .map { it.key } /** Search+chip-filtered view over [InspectorState.transactions], plus the counts the hero/chips need. */ private data class TrafficStats( @@ -61,11 +90,11 @@ private data class TrafficStats( private fun List.matchesTrafficSearch(search: String): List { if (search.isEmpty()) return this return filter { tx -> - tx.path.lowercase(Locale.US).contains(search) || - tx.queryString().lowercase(Locale.US).contains(search) || - tx.host.lowercase(Locale.US).contains(search) || - tx.requestPreview?.lowercase(Locale.US)?.contains(search) == true || - tx.responsePreview?.lowercase(Locale.US)?.contains(search) == true + tx.path.contains(search, ignoreCase = true) || + tx.queryString().contains(search, ignoreCase = true) || + tx.host.contains(search, ignoreCase = true) || + tx.requestPreview?.contains(search, ignoreCase = true) == true || + tx.responsePreview?.contains(search, ignoreCase = true) == true } } @@ -81,7 +110,7 @@ private fun rememberTrafficStats( chip: String, ): TrafficStats = remember(transactions, search, chip) { - val searched = transactions.matchesTrafficSearch(search.trim().lowercase(Locale.US)) + val searched = transactions.matchesTrafficSearch(search.trim()) val chipFiltered = when (chip) { "failing" -> searched.filter { it.isFailing() } @@ -108,7 +137,9 @@ internal fun TrafficTabContent( ui: ObserveUiState, actions: ObserveActions, ) { - if (state.transactions.isEmpty() && !ui.searchOpen && !ui.trafficFiltersOpen) { + val trafficFilterActive = state.trafficStatusClass != TrafficStatusClass.ALL || state.trafficHost != null + val headerControlsOpen = ui.searchOpen || ui.trafficFiltersOpen + if (state.transactions.isEmpty() && !headerControlsOpen && !trafficFilterActive) { TrafficEmptyState() return } @@ -121,7 +152,7 @@ internal fun TrafficTabContent( val selectionModeActive = state.selectedTransactionIds.isNotEmpty() BackHandler(enabled = selectionModeActive, onBack = actions.onClearTransactionSelection) - TrafficList(stats, ui, actions, colors, TrafficSelection(state.selectedTransactionIds, selectionModeActive)) + TrafficList(state, stats, ui, actions, colors, TrafficSelection(state.selectedTransactionIds, selectionModeActive)) } /** The traffic tab's selection state, bundled so [TrafficList] doesn't grow a parameter per field. */ @@ -132,13 +163,15 @@ private data class TrafficSelection( @Composable private fun TrafficList( + state: InspectorState, stats: TrafficStats, ui: ObserveUiState, actions: ObserveActions, colors: DevConsoleColors, selection: TrafficSelection, ) { - val arrivals = rememberArrivals(stats.rowsNewestFirst.map { it.id }) + val arrivalIds = remember(stats.rowsNewestFirst) { stats.rowsNewestFirst.map { it.id } } + val arrivals = rememberArrivals(arrivalIds) LazyColumn( modifier = Modifier.fillMaxSize(), contentPadding = PaddingValues(top = 12.dp, bottom = 24.dp), @@ -173,6 +206,20 @@ private fun TrafficList( } } } + // Keep the filter row reachable even when the filters match nothing, so a narrowing + // selection is never a dead end. + val filterActive = state.trafficStatusClass != TrafficStatusClass.ALL || state.trafficHost != null + if (state.transactions.isNotEmpty() || filterActive) { + item { + TrafficStatusFilterRow( + selectedClass = state.trafficStatusClass, + selectedHost = state.trafficHost, + transactions = state.transactions, + actions = actions, + ) + } + item { Spacer(Modifier.height(12.dp)) } + } if (stats.failCount > 0) { item { TrafficHero(stats, ui, colors, actions) } item { Spacer(Modifier.height(12.dp)) } @@ -291,6 +338,79 @@ private fun ExportPillIcon(colors: DevConsoleColors) { ObserveGlyphIcon(ObserveGlyph.Download, contentDescription = null, tint = colors.ground, size = 13.dp) } +/** + * The traffic header's server-side filters: a status-class chip row plus a host dropdown. Both + * dispatch to the ViewModel, which re-reads the capture store with an [InspectorTrafficQuery] -- + * unlike the search/method chips below, these narrow the page itself rather than the loaded rows. + */ +@Composable +private fun TrafficStatusFilterRow( + selectedClass: TrafficStatusClass, + selectedHost: String?, + transactions: List, + actions: ObserveActions, +) { + Column(Modifier.padding(top = 8.dp)) { + FilterChipRow( + chips = + TRAFFIC_STATUS_CLASS_LABELS.map { (statusClass, label) -> + InspectorFilterChip(statusClass.name, label, statusClass == selectedClass) + }, + onChipClick = { chip -> actions.onTrafficStatusClassClick(TrafficStatusClass.valueOf(chip.id)) }, + contentPadding = PaddingValues(horizontal = 16.dp, vertical = 0.dp), + ) + TrafficHostMenu(selectedHost, transactions, actions) + } +} + +@Composable +private fun TrafficHostMenu( + selectedHost: String?, + transactions: List, + actions: ObserveActions, +) { + var expanded by remember { mutableStateOf(false) } + // Once a host is picked the page only holds that host's rows, so the menu keeps offering the + // hosts seen while unfiltered -- switching hosts must not require a detour through "All hosts". + val unfilteredHosts = remember { mutableListOf() } + val hosts = + remember(transactions, selectedHost) { + if (selectedHost == null) { + topTrafficHosts(transactions).also { + unfilteredHosts.clear() + unfilteredHosts.addAll(it) + } + } else { + (unfilteredHosts + selectedHost).distinct() + } + } + Box { + FilterChipRow( + chips = listOf(InspectorFilterChip("host", "${selectedHost ?: "All hosts"} ▾", selectedHost != null)), + onChipClick = { expanded = true }, + contentPadding = PaddingValues(horizontal = 16.dp, vertical = 4.dp), + ) + DropdownMenu(expanded = expanded, onDismissRequest = { expanded = false }) { + DropdownMenuItem( + text = { Text("All hosts") }, + onClick = { + expanded = false + actions.onTrafficHostClick(null) + }, + ) + hosts.forEach { host -> + DropdownMenuItem( + text = { Text(host) }, + onClick = { + expanded = false + actions.onTrafficHostClick(host) + }, + ) + } + } + } +} + @Composable private fun TrafficChips( stats: TrafficStats, @@ -321,7 +441,7 @@ private fun TrafficHero( if (ui.trafficHeroCollapsed) { HeroBar( value = stats.failCount.toString(), - label = "requests failing", + label = if (stats.failCount == 1) "request failing" else "requests failing", onExpand = actions.onToggleTrafficHero, valueColor = if (failing) colors.error else colors.ink, labelColor = if (failing) colors.error else colors.text3, diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorPastRunBanner.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorPastRunBanner.kt new file mode 100644 index 0000000..30a402d --- /dev/null +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorPastRunBanner.kt @@ -0,0 +1,92 @@ +/** + * @author Shakib + * @since 03/11/26 + */ +@file:Suppress("FunctionNaming") + +package io.devconsole.ui.compose + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp + +/** Shown while a retained past run is selected: back to live, pin against retention, or delete. */ +@Composable +internal fun PastRunBanner( + session: InspectorSessionUi, + onReturnToLive: () -> Unit, + onSetPinned: (Boolean) -> Unit, + onDelete: () -> Unit, +) { + val colors = DevConsoleTheme.colors + var confirmDelete by rememberSaveable(session.id) { mutableStateOf(false) } + Column(modifier = Modifier.padding(start = 16.dp, top = 4.dp, end = 16.dp)) { + TonalListRow( + leadText = "RUN", + leadColor = colors.ink, + leadContainerColor = colors.panel, + title = "Viewing past run", + // "Pinned" leads the subtitle: appended to the title it was the first thing ellipsized away. + subtitle = + (if (session.pinned) "Pinned · " else "") + + "${session.label} · ${formatCaptureClockTime(session.startedAtEpochMs)}", + trailValue = "Back to live", + trailValueColor = colors.signal, + containerColor = colors.panel, + onClick = onReturnToLive, + ) + Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) { + TextButton(onClick = { onSetPinned(!session.pinned) }) { + Text(if (session.pinned) "Unpin" else "Pin", color = colors.ink, fontSize = 14.sp) + } + TextButton(onClick = { confirmDelete = true }) { + Text("Delete run", color = colors.error, fontSize = 14.sp) + } + } + } + if (confirmDelete) { + DeleteRunDialog( + onConfirm = { + confirmDelete = false + onDelete() + }, + onDismiss = { confirmDelete = false }, + ) + } +} + +@Composable +private fun DeleteRunDialog( + onConfirm: () -> Unit, + onDismiss: () -> Unit, +) { + val colors = DevConsoleTheme.colors + AlertDialog( + onDismissRequest = onDismiss, + title = { Text("Delete this run?") }, + text = { + Text( + "Its captures, logs, crashes and attachments are removed from the device. This cannot be undone.", + ) + }, + confirmButton = { + TextButton(onClick = onConfirm) { Text("Delete", color = colors.error) } + }, + dismissButton = { + TextButton(onClick = onDismiss) { Text("Cancel", color = colors.ink) } + }, + ) +} 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 be5600c..6698746 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 @@ -56,8 +56,8 @@ internal fun remoteConfigFetchLine(provider: InspectorRemoteConfigUi): String = /** 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)) + key.contains(query, ignoreCase = true) || + (!redacted && value.contains(query, ignoreCase = true)) /** Hand-built fixture shared by the Observe preview and the detail preview. */ internal fun remoteConfigPreviewProviders(): List = diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorRemoteConfigOverrideDialog.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorRemoteConfigOverrideDialog.kt new file mode 100644 index 0000000..c0cd9f6 --- /dev/null +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorRemoteConfigOverrideDialog.kt @@ -0,0 +1,105 @@ +/** + * @author Shakib + * @since 04/11/26 + */ +@file:Suppress("FunctionNaming", "MagicNumber") + +package io.devconsole.ui.compose + +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp + +/** + * The "Provider value: ()" line the editor shows while an override is active, or + * null for a key still serving the provider's own value. Returns the line rather than painting it + * so the same text can be asserted without a Compose test. + */ +internal fun remoteConfigProviderValueLabel(entry: InspectorRemoteConfigEntryUi): String? = + if (!entry.overridden) { + null + } else { + val value = entry.providerValue ?: UNKNOWN_PROVIDER_VALUE + "Provider value: $value (${entry.providerSource})" + } + +private const val UNKNOWN_PROVIDER_VALUE = "" +private const val REDACTED_VALUE = "" + +/** + * Local override editor for one Remote Config key. The text field is prefilled with the value the + * app currently resolves, so the operator edits from truth rather than retyping it; "Clear override" + * exists only while an override is actually masking the provider's value. + */ +@Composable +internal fun RemoteConfigOverrideDialog( + entry: InspectorRemoteConfigEntryUi, + onOverride: (String) -> Unit, + onClear: () -> Unit, + onDismiss: () -> Unit, +) { + val colors = DevConsoleTheme.colors + var value by rememberSaveable(entry.key) { mutableStateOf(if (entry.redacted) "" else entry.value) } + AlertDialog( + onDismissRequest = onDismiss, + title = { Text(entry.key) }, + text = { + Column { + Text( + "Current value: ${if (entry.redacted) REDACTED_VALUE else entry.value}", + color = colors.muted, + fontSize = 12.5.sp, + ) + remoteConfigProviderValueLabel(entry)?.let { label -> + Text(label, color = colors.muted, fontSize = 12.5.sp, modifier = Modifier.padding(top = 4.dp)) + } + OutlinedTextField( + value = value, + onValueChange = { value = it }, + label = { Text("Override value") }, + modifier = Modifier.fillMaxWidth().padding(top = 8.dp).testTag("remoteConfigOverrideValue"), + ) + } + }, + confirmButton = { + TextButton( + onClick = { onOverride(value) }, + modifier = Modifier.testTag("remoteConfigOverrideSet"), + ) { + Text("Override") + } + }, + dismissButton = { + Row { + if (entry.overridden) { + TextButton( + onClick = onClear, + modifier = Modifier.testTag("remoteConfigOverrideClear"), + ) { + Text("Clear override", color = colors.warn) + } + } + TextButton( + onClick = onDismiss, + modifier = Modifier.testTag("remoteConfigOverrideCancel"), + ) { + Text("Cancel", color = colors.muted) + } + } + }, + ) +} diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorResendSheet.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorResendSheet.kt new file mode 100644 index 0000000..b14ac2e --- /dev/null +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorResendSheet.kt @@ -0,0 +1,350 @@ +/** + * @author Shakib + * @since 03/11/26 + */ +@file:Suppress("FunctionNaming", "MagicNumber") +@file:OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class) + +package io.devconsole.ui.compose + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.imePadding +import androidx.compose.foundation.layout.navigationBarsPadding +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.ModalBottomSheet +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.rememberModalBottomSheetState +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.semantics.LiveRegionMode +import androidx.compose.ui.semantics.liveRegion +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import kotlinx.coroutines.delay + +/** Methods offerable from the resend sheet's dropdown. */ +private val RESEND_METHODS = listOf("GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS") + +/** A completed resend, as the response sheet shows it. */ +internal data class InspectorResendResult( + val summary: String, + val statusCode: Int, + val body: String?, +) + +/** + * Narrows a composer result to what the resend sheet can actually show. Only a [InspectorCommandResult.Success] + * that carries an HTTP status is a resend -- an export's or an enable/disable's Success has no response + * to display and must keep its plain snackbar. + */ +internal fun resendResultFrom(result: InspectorCommandResult): InspectorResendResult? = + (result as? InspectorCommandResult.Success)?.let { success -> + success.statusCode?.let { statusCode -> + // The sheet shows the status large on its own, so drop the composer's "-> 200" echo. + InspectorResendResult(success.summary.replace(" -> $statusCode", ""), statusCode, success.body) + } + } + +/** The editable shape of a captured request, as the resend sheet holds it. */ +internal data class InspectorResendDraft( + val method: String, + val url: String, + /** One `Name: value` per line, the same shape the mock-rule editor uses for headers. */ + val headerLines: String, + val body: String, + /** True from Send until the composer answers; the sheet stays open (and Send disabled) meanwhile. */ + val sending: Boolean = false, + /** Why the last Send was rejected, shown in the sheet so the operator can fix the request in place. */ + val error: String? = null, +) + +/** Seeds the sheet from an already-redacted capture, reusing the same URL fallback the snippets use. */ +internal fun resendDraftFromTransaction(transaction: InspectorTransactionUi): InspectorResendDraft = + InspectorResendDraft( + method = transaction.method, + url = transaction.url.ifBlank { "https://${transaction.host}${transaction.pathWithQuery()}" }, + headerLines = formatResendHeaderLines(transaction.requestHeaders), + body = transaction.requestPreview.orEmpty(), + ) + +internal fun formatResendHeaderLines(headers: Map): String = + headers.entries.joinToString("\n") { (name, value) -> "$name: $value" } + +/** + * Parses `Name: value` lines into a header map. Blank lines and lines without a name are skipped + * rather than rejected, so a stray newline never blocks sending the rest of the request. + */ +internal fun parseResendHeaderLines(text: String): Map = + text + .lineSequence() + .map(String::trim) + .filter(String::isNotEmpty) + .mapNotNull { line -> + val separator = line.indexOf(':') + if (separator <= 0) { + null + } else { + line + .substring(0, separator) + .trim() + .takeIf(String::isNotEmpty) + ?.let { name -> name to line.substring(separator + 1).trim() } + } + }.toMap() + +/** Turns the edited draft back into the composer request the ViewModel executes. */ +internal fun InspectorResendDraft.toComposerRequest(): InspectorComposerRequest = + InspectorComposerRequest( + method = method.trim().uppercase(), + url = url.trim(), + headers = parseResendHeaderLines(headerLines), + body = body.takeIf(String::isNotEmpty), + ) + +/** Edit-and-resend modal: method dropdown, URL, header lines and body, then Send/Cancel. */ +@Composable +internal fun InspectorResendSheet( + draft: InspectorResendDraft, + onSend: (InspectorResendDraft) -> Unit, + onDismiss: () -> Unit, +) { + val colors = DevConsoleTheme.colors + ModalBottomSheet( + onDismissRequest = onDismiss, + containerColor = colors.panel, + sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true), + ) { + InspectorResendSheetContent(draft, onSend, onDismiss) + } +} + +@Suppress("LongMethod") // One field per editable request component, in one reader-friendly column. +@Composable +private fun InspectorResendSheetContent( + draft: InspectorResendDraft, + onSend: (InspectorResendDraft) -> Unit, + onDismiss: () -> Unit, +) { + val colors = DevConsoleTheme.colors + var method by rememberSaveable { mutableStateOf(draft.method.uppercase()) } + var url by rememberSaveable { mutableStateOf(draft.url) } + var headerLines by rememberSaveable { mutableStateOf(draft.headerLines) } + var body by rememberSaveable { mutableStateOf(draft.body) } + val canSend = method.isNotBlank() && url.isNotBlank() + Column( + modifier = + Modifier + .fillMaxWidth() + .verticalScroll(rememberScrollState()) + .imePadding() + .navigationBarsPadding() + .padding(horizontal = 20.dp, vertical = 8.dp), + verticalArrangement = Arrangement.spacedBy(12.dp), + ) { + Text("Edit & resend", color = colors.ink, fontSize = 18.sp, fontWeight = FontWeight.Bold) + ResendMethodDropdown(method) { method = it } + OutlinedTextField( + value = url, + onValueChange = { url = it }, + label = { Text("URL") }, + singleLine = true, + modifier = Modifier.fillMaxWidth(), + ) + OutlinedTextField( + value = headerLines, + onValueChange = { headerLines = it }, + label = { Text("Headers (one Name: value per line)") }, + textStyle = TextStyle(fontFamily = FontFamily.Monospace, fontSize = 13.sp), + modifier = Modifier.fillMaxWidth().heightIn(min = 96.dp), + ) + OutlinedTextField( + value = body, + onValueChange = { body = it }, + label = { Text("Body") }, + textStyle = TextStyle(fontFamily = FontFamily.Monospace, fontSize = 13.sp), + modifier = Modifier.fillMaxWidth().heightIn(min = 96.dp), + ) + draft.error?.let { error -> + Text( + error, + color = colors.error, + fontSize = 13.sp, + modifier = Modifier.semantics { liveRegion = LiveRegionMode.Polite }, + ) + } + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(12.dp), + ) { + TextButton(onClick = onDismiss, modifier = Modifier.weight(1f)) { + Text("Cancel", color = colors.muted) + } + InspectorPillButton( + label = if (draft.sending) "Sending…" else "Send", + onClick = { + onSend( + InspectorResendDraft( + method = method.trim().uppercase(), + url = url.trim(), + headerLines = headerLines, + body = body, + ), + ) + }, + modifier = Modifier.weight(1f), + enabled = canSend && !draft.sending, + ) + } + } +} + +@Composable +private fun ResendMethodDropdown( + method: String, + onMethodChange: (String) -> Unit, +) { + var expanded by rememberSaveable { mutableStateOf(false) } + val colors = DevConsoleTheme.colors + Box { + InspectorPillButton( + label = method, + onClick = { expanded = true }, + containerColor = colors.surface3, + contentColor = colors.ink, + ) + DropdownMenu(expanded = expanded, onDismissRequest = { expanded = false }) { + RESEND_METHODS.forEach { option -> + DropdownMenuItem( + text = { Text(option) }, + onClick = { + expanded = false + onMethodChange(option) + }, + ) + } + } + } +} + +/** Ceiling on what the response sheet renders; the full body is still what Copy body copies. */ +private const val MAX_RESEND_RESULT_BODY_CHARS = 64_000 + +/** Bottom sheet showing what a resend actually returned: status, summary and response body. */ +@Composable +internal fun InspectorResendResultSheet( + result: InspectorResendResult, + onCopyBody: (String) -> Unit, + onDismiss: () -> Unit, +) { + val colors = DevConsoleTheme.colors + ModalBottomSheet( + onDismissRequest = onDismiss, + containerColor = colors.panel, + sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true), + ) { + InspectorResendResultContent(result, onCopyBody, onDismiss) + } +} + +@Composable +private fun InspectorResendResultContent( + result: InspectorResendResult, + onCopyBody: (String) -> Unit, + onDismiss: () -> Unit, +) { + val colors = DevConsoleTheme.colors + val bodyText = result.body?.takeIf(String::isNotBlank) + // A snackbar would render under this modal sheet, so the button itself confirms the copy. + var copied by remember(result) { mutableStateOf(false) } + LaunchedEffect(copied) { + if (copied) { + delay(COPIED_LABEL_MS) + copied = false + } + } + val statusColor = + when (result.statusCode) { + in 500..599 -> colors.error + in 400..499 -> colors.warn + else -> colors.ink + } + Column( + modifier = + Modifier + .fillMaxWidth() + .verticalScroll(rememberScrollState()) + .navigationBarsPadding() + .padding(horizontal = 20.dp, vertical = 8.dp), + verticalArrangement = Arrangement.spacedBy(12.dp), + ) { + Text("Response", color = colors.ink, fontSize = 18.sp, fontWeight = FontWeight.Bold) + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(12.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Text(result.statusCode.toString(), color = statusColor, fontSize = 20.sp, fontWeight = FontWeight.Bold) + Text(result.summary, color = colors.muted, fontSize = 13.sp) + } + Column( + modifier = + Modifier + .fillMaxWidth() + .heightIn(max = 360.dp) + .verticalScroll(rememberScrollState()), + ) { + Text( + text = bodyText?.let { prettyOrRaw(it.take(MAX_RESEND_RESULT_BODY_CHARS)) } ?: "(empty body)", + color = colors.ink, + fontFamily = FontFamily.Monospace, + fontSize = 13.sp, + ) + } + Text( + "Sent from the device; not shown in Traffic and not affected by mock rules.", + color = colors.muted, + fontSize = 12.sp, + ) + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(12.dp), + ) { + TextButton(onClick = onDismiss, modifier = Modifier.weight(1f)) { + Text("Close", color = colors.muted) + } + InspectorPillButton( + label = if (copied) "Copied" else "Copy body", + onClick = { + bodyText?.let(onCopyBody) + copied = bodyText != null + }, + modifier = Modifier.weight(1f), + enabled = bodyText != null, + ) + } + } +} + +private const val COPIED_LABEL_MS = 2_000L diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorSocketComposer.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorSocketComposer.kt new file mode 100644 index 0000000..6f76adc --- /dev/null +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorSocketComposer.kt @@ -0,0 +1,156 @@ +/** + * @author Shakib + * @since 04/11/26 + */ +@file:Suppress("FunctionNaming", "MagicNumber") + +package io.devconsole.ui.compose + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Switch +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp + +private const val MQTT_PROTOCOL = "mqtt" +private const val DEFAULT_QOS = 0 +private val qosOptions = listOf("0", "1", "2") +private const val COMPOSER_TEXT_MIN_LINES = 3 + +/** + * Everything the frame detail needs to show a send composer for one connection. Null [protocol] + * (a connection the data source cannot write to) means no composer at all. + */ +internal data class SocketComposerHost( + val connectionId: String, + val protocol: String, + val initialTopic: String?, + val lastResult: InspectorCommandResult?, + val onSend: (text: String, topic: String?, qos: Int, retained: Boolean) -> Unit, +) + +/** + * Whether Send may be tapped: a frame needs text, and an MQTT publish additionally needs a topic. + * A WebSocket frame ignores both topic and QoS, so only the text gate applies to it. + */ +internal fun socketComposerSendEnabled( + protocol: String, + text: String, + topic: String, +): Boolean = text.isNotEmpty() && (protocol != MQTT_PROTOCOL || topic.isNotBlank()) + +/** + * In-frame send composer, shown in the socket frame detail for a connection the adapter reports as + * writable. The draft is local to the open frame; only a [InspectorCommandResult.Success] clears + * the text, so a rejected frame stays editable while the shared result flash explains why. + */ +@Composable +internal fun SocketSendComposer( + host: SocketComposerHost, + modifier: Modifier = Modifier, +) { + val colors = DevConsoleTheme.colors + val isMqtt = host.protocol == MQTT_PROTOCOL + var text by rememberSaveable(host.connectionId) { mutableStateOf("") } + var topic by rememberSaveable(host.connectionId) { mutableStateOf(host.initialTopic.orEmpty()) } + var qos by rememberSaveable(host.connectionId) { mutableIntStateOf(DEFAULT_QOS) } + var retained by rememberSaveable(host.connectionId) { mutableStateOf(false) } + var awaitingResult by remember(host.connectionId) { mutableStateOf(false) } + + LaunchedEffect(host.lastResult) { + if (awaitingResult) { + if (host.lastResult is InspectorCommandResult.Success) text = "" + awaitingResult = false + } + } + + Column( + modifier = modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 12.dp), + verticalArrangement = Arrangement.spacedBy(10.dp), + ) { + Text("Send a frame", color = colors.ink, fontSize = 14.sp, fontWeight = FontWeight.SemiBold) + OutlinedTextField( + value = text, + onValueChange = { text = it }, + label = { Text("Frame text") }, + minLines = COMPOSER_TEXT_MIN_LINES, + modifier = Modifier.fillMaxWidth().testTag("socketComposerText"), + ) + if (isMqtt) { + TopicField(topic) { topic = it } + QosSelector(qos) { qos = it } + RetainedToggle(retained) { retained = it } + } + InspectorPillButton( + label = "Send", + onClick = { + awaitingResult = true + host.onSend(text, topic.takeIf { isMqtt }, qos, retained) + }, + modifier = Modifier.fillMaxWidth().testTag("socketComposerSend"), + enabled = socketComposerSendEnabled(host.protocol, text, topic), + ) + } +} + +@Composable +private fun TopicField( + topic: String, + onTopicChange: (String) -> Unit, +) { + OutlinedTextField( + value = topic, + onValueChange = onTopicChange, + label = { Text("Topic") }, + singleLine = true, + modifier = Modifier.fillMaxWidth().testTag("socketComposerTopic"), + ) +} + +@Composable +private fun QosSelector( + qos: Int, + onQosChange: (Int) -> Unit, +) { + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) { + Text("QoS", modifier = Modifier.weight(1f)) + InspectorSegmentedControl( + options = qosOptions, + selectedIndex = qos, + onSelect = onQosChange, + modifier = Modifier.testTag("socketComposerQos"), + ) + } +} + +@Composable +private fun RetainedToggle( + retained: Boolean, + onRetainedChange: (Boolean) -> Unit, +) { + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) { + Text("Retained", modifier = Modifier.weight(1f)) + Switch( + checked = retained, + onCheckedChange = onRetainedChange, + modifier = Modifier.testTag("socketComposerRetained"), + ) + } +} 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 e6549c4..13011fd 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 @@ -21,6 +21,10 @@ enum class ObserveTab { TRAFFIC, SOCKETS, PUSH, LOGS, CRASHES, REMOTE_CONFIG } data class InspectorState( val available: Boolean = false, val serverControlSupported: Boolean = false, + /** Whether the More screen should offer the Capture group (pause/resume and purge). */ + val captureControlSupported: Boolean = false, + /** Whether live capture is paused; re-read from the data source on every snapshot refresh. */ + val capturePaused: Boolean = false, val transactions: List = emptyList(), val capabilities: InspectorEditingUi = InspectorEditingUi(), val mocksEnabled: Boolean = false, @@ -41,10 +45,20 @@ data class InspectorState( val stateProviders: List = emptyList(), /** Remote Config providers, already redacted and STATE-gated by the data source. */ val remoteConfig: List = emptyList(), + /** True when the data source can apply local Remote Config overrides; gates the override editor. */ + val remoteConfigOverridesEditable: Boolean = false, + /** + * The write protocol ([InspectorDataSource.socketSendProtocol]) per live socket connection id, + * read on every snapshot load. A connection missing here cannot be written to, so the send + * composer is hidden for it. + */ + val socketSendProtocols: Map = emptyMap(), val preferenceFiles: List = emptyList(), val fileRoots: List = emptyList(), val fileListing: InspectorFileListingUi? = null, val filePreview: InspectorFilePreviewUi? = null, + /** The previewed file's name, so the preview card says what it is showing. */ + val filePreviewName: String? = null, /** One-shot: a resolved path awaiting the Share sheet; consumed by [InspectorAction.ConsumeShareFile]. */ val pendingShareFilePath: String? = null, val databases: List = emptyList(), @@ -73,6 +87,10 @@ data class InspectorState( val captureCategories: Set = CaptureCategory.all(), /** Mirrors [InspectorSnapshot.redactionEnabled]. */ val redactionEnabled: Boolean = false, + /** Status-class filter applied to the traffic snapshot; see [InspectorTrafficQuery.statusClass]. */ + val trafficStatusClass: TrafficStatusClass = TrafficStatusClass.ALL, + /** Exact host filter applied to the traffic snapshot; null means every host. */ + val trafficHost: String? = null, ) /** True when [category] is enabled for this session; the one-line building block every gate below composes. */ diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorStructuredDecoders.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorStructuredDecoders.kt new file mode 100644 index 0000000..e52db90 --- /dev/null +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorStructuredDecoders.kt @@ -0,0 +1,422 @@ +/** + * @author Shakib + * @since 03/11/26 + */ +@file:Suppress("TooManyFunctions") + +package io.devconsole.ui.compose + +import java.net.URLDecoder +import java.text.SimpleDateFormat +import java.util.Base64 +import java.util.Date +import java.util.Locale +import java.util.TimeZone + +private const val JWT_SEGMENT_COUNT = 3 +private const val MS_PER_SECOND_LONG = 1000L +private const val SECONDS_PER_MINUTE_LONG = 60L +private const val JWT_TIMESTAMP_PATTERN = "yyyy-MM-dd HH:mm:ss 'UTC'" +private const val FORM_URLENCODED_MEDIA_TYPE = "application/x-www-form-urlencoded" +private const val BEARER_PREFIX = "Bearer " +private const val GRAPHQL_PATH_SUFFIX = "/graphql" + +private val RESPONSE_JWT_FIELD_NAMES = setOf("access_token", "id_token", "token") +private val FORM_LOOKALIKE_REGEX = Regex("^[A-Za-z0-9_.~%+\\-]+=[^&\\s]*(&[A-Za-z0-9_.~%+\\-]+=[^&\\s]*)*$") +private val GRAPHQL_OPERATION_REGEX = + Regex("^(query|mutation|subscription)\\b(?:\\s+([_A-Za-z][_0-9A-Za-z]*))?") + +/** A decoded numeric timestamp claim (`exp`, `iat`, `nbf`) from a JWT payload. */ +internal data class DecodedJwtTimestampClaim( + val claim: String, + val epochSeconds: Long, + val humanTime: String, + val relativeStatus: String, + val isExpired: Boolean = false, +) + +/** One decoded JWT discovered in a network transaction's request or response. */ +internal data class DecodedJwt( + val source: String, + val headerJson: String, + val payloadJson: String, + val headerRoot: JsonValue.Obj, + val payloadRoot: JsonValue.Obj, + val timestamps: List = emptyList(), +) + +/** One URL-decoded key/value pair from an `application/x-www-form-urlencoded` request body. */ +internal data class DecodedFormField( + val key: String, + val value: String, +) + +/** Decoded GraphQL operation details extracted from a network request. */ +internal data class DecodedGraphQlRequest( + val operationType: String, + val operationName: String?, + val query: String, + val variablesJson: String?, + val variablesRoot: JsonValue? = null, +) + +/** Structured representations decoded from an [InspectorTransactionUi]. */ +internal data class DecodedTransactionContent( + val jwts: List = emptyList(), + val formFields: List? = null, + val graphQl: DecodedGraphQlRequest? = null, +) { + val hasAny: Boolean + get() = jwts.isNotEmpty() || !formFields.isNullOrEmpty() || graphQl != null +} + +/** + * True when [this] carries a redaction replacement marker (`` or `***`) and therefore + * must never be decoded. + */ +internal fun String.isRedactedValue(): Boolean = contains("", ignoreCase = true) || contains("***") + +/** + * Decodes all structured payloads (JWTs, form-urlencoded fields, GraphQL operation) applicable to + * [transaction], using [nowEpochMs] to evaluate relative JWT claim validity. + */ +internal fun decodeTransactionStructuredContent( + transaction: InspectorTransactionUi, + nowEpochMs: Long = System.currentTimeMillis(), +): DecodedTransactionContent { + val requestBinary = transaction.requestBodyKind == InspectorBodyKind.BINARY + val requestBody = transaction.requestPreview?.takeUnless { requestBinary } + val jwts = extractTransactionJwts(transaction, nowEpochMs) + val formFields = + if (isFormUrlEncodedRequest(transaction.requestHeaders, requestBody)) { + requestBody?.let(::parseFormUrlEncoded)?.takeIf { it.isNotEmpty() } + } else { + null + } + val graphQl = detectGraphQlRequest(transaction.method, transaction.url, transaction.path, requestBody) + return DecodedTransactionContent( + jwts = jwts, + formFields = formFields, + graphQl = graphQl, + ) +} + +/** + * Extracts and decodes JWT tokens from [transaction]'s request `Authorization` header (`Bearer `, + * case-insensitive) and from any `access_token`, `id_token`, or `token` fields in a JSON response + * preview. + */ +internal fun extractTransactionJwts( + transaction: InspectorTransactionUi, + nowEpochMs: Long = System.currentTimeMillis(), +): List = + buildList { + transaction.requestHeaders.entries + .firstOrNull { it.key.equals("Authorization", ignoreCase = true) } + ?.value + ?.let { authHeader -> extractBearerToken(authHeader) } + ?.let { token -> decodeJwt(token, nowEpochMs = nowEpochMs, source = "Authorization") } + ?.let(::add) + + val responsePreview = transaction.responsePreview + if (!responsePreview.isNullOrBlank() && sniffBodyFormat(responsePreview) == SniffedBodyFormat.JSON) { + val root = runCatching { MinimalJsonParser(responsePreview).parseDocument() }.getOrNull() + if (root != null) { + val candidates = mutableListOf>() + collectResponseJwtCandidates(root, candidates) + candidates.forEach { (fieldName, rawToken) -> + decodeJwt(rawToken, nowEpochMs = nowEpochMs, source = "response.$fieldName")?.let(::add) + } + } + } + } + +private fun extractBearerToken(headerValue: String): String? = + headerValue + .trim() + .takeIf { !it.isRedactedValue() && it.startsWith(BEARER_PREFIX, ignoreCase = true) } + ?.substring(BEARER_PREFIX.length) + ?.trim() + ?.takeIf { it.isNotEmpty() && !it.isRedactedValue() } + +private fun collectResponseJwtCandidates( + node: JsonValue, + out: MutableList>, +) { + when (node) { + is JsonValue.Obj -> + node.entries.forEach { (key, value) -> + if (key.lowercase(Locale.US) in RESPONSE_JWT_FIELD_NAMES && value is JsonValue.Str) { + out += key to value.value + } else { + collectResponseJwtCandidates(value, out) + } + } + is JsonValue.Arr -> node.items.forEach { item -> collectResponseJwtCandidates(item, out) } + else -> Unit + } +} + +/** + * Decodes a single [rawToken] as a 3-segment base64url JWT whose first two segments parse as JSON + * objects. Returns `null` when [rawToken] is redacted, does not have 3 segments, fails base64url + * decoding, or has non-object JSON in its header or payload. + */ +@Suppress("ReturnCount") +internal fun decodeJwt( + rawToken: String, + nowEpochMs: Long = System.currentTimeMillis(), + source: String = "JWT", +): DecodedJwt? { + val trimmed = rawToken.trim().removeSurrounding("\"") + val token = + if (trimmed.startsWith(BEARER_PREFIX, ignoreCase = true)) { + trimmed.substring(BEARER_PREFIX.length).trim() + } else { + trimmed + } + if (token.isEmpty() || token.isRedactedValue()) return null + val segments = token.split('.') + if (segments.size != JWT_SEGMENT_COUNT || segments.any { it.isEmpty() }) return null + + val headerText = decodeBase64UrlUtf8(segments[0]) ?: return null + val payloadText = decodeBase64UrlUtf8(segments[1]) ?: return null + if (headerText.isRedactedValue() || payloadText.isRedactedValue()) return null + + val headerObj = + runCatching { MinimalJsonParser(headerText).parseDocument() }.getOrNull() as? JsonValue.Obj + ?: return null + val payloadObj = + runCatching { MinimalJsonParser(payloadText).parseDocument() }.getOrNull() as? JsonValue.Obj + ?: return null + + return DecodedJwt( + source = source, + headerJson = headerObj.prettyPrint(), + payloadJson = payloadObj.prettyPrint(), + headerRoot = headerObj, + payloadRoot = payloadObj, + timestamps = extractJwtTimestamps(payloadObj, nowEpochMs), + ) +} + +private fun decodeBase64UrlUtf8(segment: String): String? = + runCatching { + // Base64url drops '=' padding; the JDK decoder accepts unpadded input, and rejects a + // length that is 1 mod 4 (never valid base64) by throwing, which runCatching maps to null. + String(Base64.getUrlDecoder().decode(segment), Charsets.UTF_8) + }.getOrNull() + +private fun extractJwtTimestamps( + payload: JsonValue.Obj, + nowEpochMs: Long, +): List { + val claimNames = listOf("exp", "iat", "nbf") + val nowSeconds = nowEpochMs / MS_PER_SECOND_LONG + return claimNames.mapNotNull { claim -> + val rawNum = + payload.entries + .firstOrNull { (key, _) -> key == claim } + ?.second as? JsonValue.Num + ?: return@mapNotNull null + val epochSeconds = rawNum.raw.toLongOrNull() ?: rawNum.raw.toDoubleOrNull()?.toLong() ?: return@mapNotNull null + val humanTime = formatJwtUtcTimestamp(epochSeconds * MS_PER_SECOND_LONG) + val (relativeStatus, isExpired) = formatJwtRelativeStatus(claim, epochSeconds, nowSeconds) + DecodedJwtTimestampClaim( + claim = claim, + epochSeconds = epochSeconds, + humanTime = humanTime, + relativeStatus = relativeStatus, + isExpired = isExpired, + ) + } +} + +private fun formatJwtUtcTimestamp(epochMs: Long): String = + SimpleDateFormat(JWT_TIMESTAMP_PATTERN, Locale.US) + .apply { timeZone = TimeZone.getTimeZone("UTC") } + .format(Date(epochMs)) + +private fun formatJwtRelativeStatus( + claim: String, + claimSeconds: Long, + nowSeconds: Long, +): Pair { + val span = formatJwtSpan(kotlin.math.abs(claimSeconds - nowSeconds)) + val inPast = claimSeconds <= nowSeconds + return when (claim) { + "exp" -> if (inPast) "expired $span ago" to true else "valid for $span" to false + "nbf" -> if (inPast) "active since $span ago" to false else "not valid yet, starts in $span" to false + else -> if (inPast) "issued $span ago" to false else "issued $span in the future (clock skew?)" to false + } +} + +/** + * A claim distance at the coarsest unit that still reads precisely: `45 s`, `15 min`, `2 h 5 min`, + * `3 days`, `about 5 months`, `about 3 years` -- never `1662228 min`. Partial minutes round up so a + * token with 30 s left never reads as `0 min`. + */ +internal fun formatJwtSpan(seconds: Long): String { + val minutes = (seconds + SECONDS_PER_MINUTE_LONG - 1) / SECONDS_PER_MINUTE_LONG + val hours = minutes / MINUTES_PER_HOUR + val days = hours / HOURS_PER_DAY + return when { + seconds < SECONDS_PER_MINUTE_LONG -> "$seconds s" + minutes < MINUTES_PER_HOUR -> "$minutes min" + hours < HOURS_PER_DAY -> + "$hours h" + (minutes % MINUTES_PER_HOUR).let { rest -> if (rest > 0) " $rest min" else "" } + days < DAYS_PER_MONTH * 2 -> "$days day${if (days == 1L) "" else "s"}" + days < DAYS_PER_YEAR -> "about ${days / DAYS_PER_MONTH} months" + else -> (days / DAYS_PER_YEAR).let { years -> "about $years year${if (years == 1L) "" else "s"}" } + } +} + +private const val MINUTES_PER_HOUR = 60L +private const val HOURS_PER_DAY = 24L +private const val DAYS_PER_MONTH = 30L +private const val DAYS_PER_YEAR = 365L + +/** + * True when [headers] declare `Content-Type: application/x-www-form-urlencoded` (ignoring parameters + * like `; charset=utf-8` and case) or when that content-type is present and [body] looks like + * `k=v&k2=v2`. + */ +internal fun isFormUrlEncodedRequest( + headers: Map, + body: String?, +): Boolean { + if (body.isNullOrBlank() || body.trim().isRedactedValue()) return false + val contentType = + headers.entries + .firstOrNull { it.key.equals("Content-Type", ignoreCase = true) } + ?.value + ?.substringBefore(';') + ?.trim() + val hasFormContentType = contentType.equals(FORM_URLENCODED_MEDIA_TYPE, ignoreCase = true) + return hasFormContentType || (contentType == null && FORM_LOOKALIKE_REGEX.matches(body.trim())) +} + +/** + * Parses an `application/x-www-form-urlencoded` payload into ordered key/value pairs, preserving + * repeated keys and empty values while URL-decoding keys and values using UTF-8. + */ +internal fun parseFormUrlEncoded(body: String): List { + val trimmed = body.trim() + if (trimmed.isEmpty() || trimmed.isRedactedValue()) return emptyList() + return trimmed + .split('&') + .filter { it.isNotEmpty() } + .map { part -> + val eqIndex = part.indexOf('=') + val rawKey = if (eqIndex >= 0) part.substring(0, eqIndex) else part + val rawValue = if (eqIndex >= 0) part.substring(eqIndex + 1) else "" + DecodedFormField( + key = urlDecodeFormComponent(rawKey), + value = urlDecodeFormComponent(rawValue), + ) + } +} + +private fun urlDecodeFormComponent(value: String): String = + runCatching { URLDecoder.decode(value, Charsets.UTF_8.name()) }.getOrDefault(value) + +/** + * Detects and parses a GraphQL request when the request is `POST` with a JSON body containing a + * string `"query"` field (and optional `"operationName"` / `"variables"`), or when the URL path + * ends with `/graphql`. + */ +@Suppress("ReturnCount", "CyclomaticComplexMethod") +internal fun detectGraphQlRequest( + method: String, + url: String, + path: String, + body: String?, +): DecodedGraphQlRequest? { + val rawBody = body?.trim().orEmpty() + if (rawBody.isEmpty() || rawBody.isRedactedValue()) return null + + val isPost = method.equals("POST", ignoreCase = true) + val isGraphQlPath = hasGraphQlPath(url, path) + if (!isPost && !isGraphQlPath) return null + + if (sniffBodyFormat(rawBody) == SniffedBodyFormat.JSON) { + val obj = + runCatching { MinimalJsonParser(rawBody).parseDocument() }.getOrNull() as? JsonValue.Obj + ?: return null + val queryValue = + (obj.entries.firstOrNull { (k, _) -> k == "query" }?.second as? JsonValue.Str) + ?.value + ?.takeIf { it.isNotBlank() && !it.isRedactedValue() } + ?: return null + val explicitOperationName = + (obj.entries.firstOrNull { (k, _) -> k == "operationName" }?.second as? JsonValue.Str) + ?.value + ?.trim() + ?.takeIf { it.isNotEmpty() && !it.isRedactedValue() } + val variablesNode = + obj.entries + .firstOrNull { (k, _) -> k == "variables" } + ?.second + ?.takeUnless { it is JsonValue.Null } + val variablesJson = + when (variablesNode) { + null -> null + is JsonValue.Str -> + runCatching { MinimalJsonParser(variablesNode.value).parseDocument().prettyPrint() } + .getOrDefault(variablesNode.value) + else -> variablesNode.prettyPrint() + } + val (parsedType, parsedName) = parseGraphQlOperationHeader(queryValue) + return DecodedGraphQlRequest( + operationType = parsedType, + operationName = explicitOperationName ?: parsedName, + query = queryValue, + variablesJson = variablesJson, + variablesRoot = variablesNode, + ) + } + + if (isGraphQlPath) { + val (parsedType, parsedName) = parseGraphQlOperationHeader(rawBody) + return DecodedGraphQlRequest( + operationType = parsedType, + operationName = parsedName, + query = rawBody, + variablesJson = null, + ) + } + + return null +} + +private fun hasGraphQlPath( + url: String, + path: String, +): Boolean { + val cleanPath = path.substringBefore('?').trimEnd('/') + if (cleanPath.endsWith(GRAPHQL_PATH_SUFFIX, ignoreCase = true)) return true + val cleanUrlPath = url.substringBefore('?').trimEnd('/') + return cleanUrlPath.endsWith(GRAPHQL_PATH_SUFFIX, ignoreCase = true) +} + +/** + * Extracts `(operationType, operationName)` from a GraphQL document string. Shorthand selection + * sets (`{ viewer { id } }`) report `"query"` with a `null` operation name. + */ +internal fun parseGraphQlOperationHeader(query: String): Pair { + val stripped = + query + .lineSequence() + .map { line -> line.substringBefore('#').trim() } + .filter { it.isNotEmpty() } + .joinToString(" ") + .trim() + val match = GRAPHQL_OPERATION_REGEX.find(stripped) + return if (match != null) { + val type = match.groupValues[1].lowercase(Locale.US) + val name = match.groupValues.getOrNull(2)?.takeIf { it.isNotEmpty() } + type to name + } else { + "query" to null + } +} diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorUrlCard.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorUrlCard.kt index de81e6f..2ce15a1 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorUrlCard.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorUrlCard.kt @@ -13,7 +13,6 @@ import androidx.compose.animation.core.infiniteRepeatable import androidx.compose.animation.core.rememberInfiniteTransition import androidx.compose.animation.core.tween import androidx.compose.foundation.background -import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column @@ -21,7 +20,6 @@ import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size -import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.CircleShape import androidx.compose.material3.IconButton import androidx.compose.material3.Text @@ -86,11 +84,13 @@ internal fun InspectorUrlCard( Row(verticalAlignment = Alignment.CenterVertically) { Text( url, - modifier = Modifier.weight(1f).horizontalScroll(rememberScrollState()), + // Wraps rather than scrolling sideways: a one-line scroller clipped the tail with no + // cue, so `:8080` read as `:80` -- the wrong port for anyone typing it by hand. + modifier = Modifier.weight(1f), color = urlColor, fontFamily = FontFamily.Monospace, fontSize = 14.sp, - maxLines = 1, + maxLines = 3, ) actions.forEach { action -> IconButton( 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 46c536b..2b6b65d 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 @@ -7,6 +7,7 @@ package io.devconsole.ui.compose import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import io.devconsole.api.ScreenshotResult +import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job @@ -19,6 +20,7 @@ import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch +import java.util.concurrent.atomic.AtomicLong private const val MAX_VISIBLE_TRANSACTIONS = 200 private const val OBSERVE_TAB_SWITCH_DEBOUNCE_MS = 300L @@ -58,6 +60,10 @@ class InspectorViewModel private val mutableServerStartPermission = MutableStateFlow(null) internal val serverStartPermission: StateFlow = mutableServerStartPermission.asStateFlow() + /** False until the first snapshot attempt settles, so screens show loading, not "unavailable". */ + private val mutableSnapshotLoaded = MutableStateFlow(false) + internal val snapshotLoaded: StateFlow = mutableSnapshotLoaded.asStateFlow() + /** * Tracks the in-flight snapshot fetch so a newer refresh (filter change, mutation, * explicit [InspectorAction.Refresh]) always requests cancellation of an older one still @@ -69,6 +75,16 @@ class InspectorViewModel * snapshot for a stale filter. */ private var snapshotJob: Job? = null + private val snapshotJobLock = Any() + private val snapshotGeneration = AtomicLong() + + /** + * The traffic filter the next read is made with. Owned here rather than in the Compose + * route because [InspectorDataSource.snapshot] takes it: a selection change has to re-read + * the store with the new filter, not just re-filter an already-loaded page. + */ + @Volatile + private var trafficQuery = InspectorTrafficQuery() init { viewModelScope.launch(dispatcher) { @@ -79,7 +95,7 @@ class InspectorViewModel // One branch per MVI action; a when-based dispatcher is the clearest shape for this even as // action count grows, so complexity is accepted here rather than split across dispatchers. - @Suppress("CyclomaticComplexMethod") + @Suppress("CyclomaticComplexMethod", "LongMethod") fun dispatch(action: InspectorAction) { when (action) { InspectorAction.Refresh -> refreshSnapshot() @@ -94,6 +110,10 @@ class InspectorViewModel is InspectorAction.SelectTransactions -> selectTransactions(action.ids) InspectorAction.ClearTransactionSelection -> clearTransactionSelection() is InspectorAction.SelectSession -> selectSession(action.id) + is InspectorAction.SelectTrafficStatusClass -> selectTrafficStatusClass(action.statusClass) + is InspectorAction.SelectTrafficHost -> selectTrafficHost(action.host) + is InspectorAction.SetSessionPinned -> setSessionPinned(action.id, action.pinned) + is InspectorAction.DeleteSession -> deleteSession(action.id) is InspectorAction.ToggleTransactionFlag -> toggleTransactionFlag(action.id) is InspectorAction.ToggleCrashFlag -> toggleCrashFlag(action.id) is InspectorAction.ExecuteComposer -> executeComposer(action.request) @@ -123,14 +143,26 @@ class InspectorViewModel InspectorAction.ExportSessionZip -> exportSessionZip() is InspectorAction.RevokePrincipal -> revokePrincipal(action.id) is InspectorAction.SetServerRunning -> setServerRunning(action.running) + is InspectorAction.SetCapturePaused -> setCapturePaused(action.paused) + InspectorAction.PurgeCapturedData -> purgeCapturedData() + is InspectorAction.SendSocketFrame -> + sendSocketFrame(action.connectionId, action.text, action.topic, action.qos, action.retained) + is InspectorAction.SetRemoteConfigOverride -> + setRemoteConfigOverride(action.providerId, action.key, action.value) + is InspectorAction.ClearRemoteConfigOverride -> + clearRemoteConfigOverride(action.providerId, action.key) + InspectorAction.ClearAllRemoteConfigOverrides -> clearAllRemoteConfigOverrides() InspectorAction.CaptureScreenshot -> captureScreenshot() InspectorAction.DismissScreenshotResult -> dismissScreenshotResult() } } private fun refreshSnapshot() { - snapshotJob?.cancel() - snapshotJob = viewModelScope.launch(dispatcher) { loadSnapshot() } + val generation = snapshotGeneration.incrementAndGet() + synchronized(snapshotJobLock) { + snapshotJob?.cancel() + snapshotJob = viewModelScope.launch(dispatcher) { loadSnapshot(generation) } + } } /** @@ -140,12 +172,15 @@ class InspectorViewModel * alone is not sufficient to stop it. */ private fun refreshSnapshotDebounced() { - snapshotJob?.cancel() - snapshotJob = - viewModelScope.launch(dispatcher) { - delay(OBSERVE_TAB_SWITCH_DEBOUNCE_MS) - loadSnapshot() - } + val generation = snapshotGeneration.incrementAndGet() + synchronized(snapshotJobLock) { + snapshotJob?.cancel() + snapshotJob = + viewModelScope.launch(dispatcher) { + delay(OBSERVE_TAB_SWITCH_DEBOUNCE_MS) + loadSnapshot(generation) + } + } } /** @@ -155,17 +190,30 @@ class InspectorViewModel * cancelled, so this throws instead of reaching [applySnapshot] once a newer job has taken * over. */ - private suspend fun loadSnapshot() { - val snapshot = dataSource.snapshot() + private suspend fun loadSnapshot(generation: Long = snapshotGeneration.incrementAndGet()) { + val result = runCatching { dataSource.snapshot(trafficQuery) } + val snapshot = + result.getOrElse { error -> + if (error is CancellationException) throw error + currentCoroutineContext().ensureActive() + if (generation == snapshotGeneration.get()) mutableState.update { it.copy(available = false) } + mutableSnapshotLoaded.value = true + return + } currentCoroutineContext().ensureActive() + if (generation != snapshotGeneration.get()) return applySnapshot(snapshot) + mutableSnapshotLoaded.value = true // Evidence flags are a separate durable read (Room, not the in-memory snapshot above) -- // refreshed alongside every snapshot load so a flag made from the dashboard shows up here // on the next poll, not just after a flag/unflag made on this device. Crash flags follow // the same selectedSessionId guard as `crashes`/`logs` in applySnapshot: a live refresh // must not clobber a past session's flag set while it stays selected. refreshFlaggedTransactionIds() - if (mutableState.value.selectedSessionId == null) refreshFlaggedCrashIds(null) + currentCoroutineContext().ensureActive() + val shouldRefreshCurrentSession = + generation == snapshotGeneration.get() && mutableState.value.selectedSessionId == null + if (shouldRefreshCurrentSession) refreshFlaggedCrashIds(null) } private suspend fun refreshFlaggedTransactionIds() { @@ -216,60 +264,9 @@ class InspectorViewModel private fun applySnapshot(snapshot: InspectorSnapshot) { val boundedTransactions = snapshot.transactions.takeLast(MAX_VISIBLE_TRANSACTIONS) + val sendProtocols = socketSendProtocols(snapshot.sockets) mutableState.update { current -> - val next = - current.copy( - available = snapshot.available, - serverControlSupported = dataSource.supportsServerControl(), - transactions = boundedTransactions, - // selectedTransactionIds backs the Observe traffic tab's selection-mode UI and - // InspectorAction.ExportHar/ExportPostman's scope; prune whatever aged out of the - // bounded page (capacity eviction), same as every other list below. - selectedTransactionIds = - current.selectedTransactionIds.filterTo(mutableSetOf()) { id -> - boundedTransactions.any { it.id == id } - }, - capabilities = snapshot.capabilities, - keepAlivePromptNeeded = snapshot.keepAlivePromptNeeded, - mocksEnabled = snapshot.mocksEnabled, - mockRules = snapshot.mockRules, - captureRules = snapshot.captureRules, - sockets = snapshot.sockets.take(MAX_VISIBLE_TRANSACTIONS), - pushEvents = snapshot.pushEvents.take(MAX_VISIBLE_TRANSACTIONS), - // While a past session is selected, `logs`/`crashes` hold that session's retained - // capture (loaded by selectSession below), not the live one -- a periodic/tab-switch - // refresh landing in between must not silently snap them back to the live session's - // data. See selectSession's own doc for why this matters for the Crashes tab's - // previous-run banner in particular. - logs = - if (current.selectedSessionId != null) { - current.logs - } else { - snapshot.logs.take(MAX_VISIBLE_TRANSACTIONS) - }, - crashes = - if (current.selectedSessionId != null) { - current.crashes - } else { - snapshot.crashes.take(MAX_VISIBLE_TRANSACTIONS) - }, - featureFlags = snapshot.featureFlags, - stateProviders = snapshot.stateProviders, - remoteConfig = snapshot.remoteConfig, - preferenceFiles = snapshot.preferenceFiles, - fileRoots = snapshot.fileRoots, - databases = snapshot.databases, - sessions = snapshot.sessions, - selectedSessionId = - current.selectedSessionId?.takeIf { id -> - snapshot.sessions.any { it.id == id } - }, - health = snapshot.health, - browser = snapshot.browser, - retention = snapshot.retention, - captureCategories = snapshot.captureCategories, - redactionEnabled = snapshot.redactionEnabled, - ) + val next = current.withSnapshot(snapshot, boundedTransactions, dataSource, sendProtocols) // A category disabled mid-session (or a filter change while a now-hidden tab stayed // selected) must not strand the Observe tab row on a tab [visibleObserveTabs] no // longer lists -- snap to the first still-visible one. [visibleObserveTabs] always @@ -287,6 +284,76 @@ class InspectorViewModel } } + /** + * Asks the data source which live connections accept a frame. Only non-null answers make it + * into the map; a connection the adapter cannot write to therefore has no composer. + */ + private fun socketSendProtocols(sockets: List): Map = + sockets + .mapNotNull { socket -> + dataSource.socketSendProtocol(socket.id)?.let { protocol -> socket.id to protocol } + }.toMap() + + private fun InspectorState.withSnapshot( + snapshot: InspectorSnapshot, + boundedTransactions: List, + dataSource: InspectorDataSource, + sendProtocols: Map, + ): InspectorState { + val current = this + // While a past run is selected, its retained captures (loaded by selectSession) stay on + // screen: a periodic or tab-switch refresh must not snap them back to the live run. + val pastRunSelected = + current.selectedSessionId != null && snapshot.sessions.any { it.id == current.selectedSessionId } + val shownTransactions = if (pastRunSelected) current.transactions else boundedTransactions + return copy( + available = snapshot.available, + serverControlSupported = dataSource.supportsServerControl(), + captureControlSupported = dataSource.supportsCaptureControl(), + // Re-read on every snapshot refresh, so a pause toggled on the More screen (or from + // the dashboard) reaches the Observe banner on its next poll without new plumbing. + capturePaused = dataSource.isCapturePaused(), + transactions = shownTransactions, + // selectedTransactionIds backs the Observe traffic tab's selection-mode UI and + // InspectorAction.ExportHar/ExportPostman's scope; prune whatever aged out of the + // bounded page (capacity eviction), same as every other list below. + selectedTransactionIds = + current.selectedTransactionIds.filterTo(mutableSetOf()) { id -> + shownTransactions.any { it.id == id } + }, + capabilities = snapshot.capabilities, + keepAlivePromptNeeded = snapshot.keepAlivePromptNeeded, + mocksEnabled = snapshot.mocksEnabled, + mockRules = snapshot.mockRules, + captureRules = snapshot.captureRules, + sockets = if (pastRunSelected) current.sockets else snapshot.sockets.take(MAX_VISIBLE_TRANSACTIONS), + // A retained run's connections are long closed; only the live run can be written to. + socketSendProtocols = if (pastRunSelected) emptyMap() else sendProtocols, + pushEvents = + if (pastRunSelected) current.pushEvents else snapshot.pushEvents.take(MAX_VISIBLE_TRANSACTIONS), + featureFlags = snapshot.featureFlags, + stateProviders = snapshot.stateProviders, + remoteConfig = snapshot.remoteConfig, + remoteConfigOverridesEditable = dataSource.supportsRemoteConfigOverrides(), + preferenceFiles = snapshot.preferenceFiles, + fileRoots = snapshot.fileRoots, + databases = snapshot.databases, + sessions = snapshot.sessions, + selectedSessionId = + current.selectedSessionId?.takeIf { id -> + snapshot.sessions.any { it.id == id } + }, + // Same past-run guard; see selectSession for why the Crashes banner depends on it. + logs = if (pastRunSelected) current.logs else snapshot.logs.take(MAX_VISIBLE_TRANSACTIONS), + crashes = if (pastRunSelected) current.crashes else snapshot.crashes.take(MAX_VISIBLE_TRANSACTIONS), + health = snapshot.health, + browser = snapshot.browser, + retention = snapshot.retention, + captureCategories = snapshot.captureCategories, + redactionEnabled = snapshot.redactionEnabled, + ) + } + private fun selectObserveTab(tab: ObserveTab) { mutableState.update { it.copy(observeTab = tab) } // Observe is a live tail: every tab switch re-reads the capture store so the screen @@ -315,26 +382,43 @@ class InspectorViewModel } /** - * Loads both the retained logs and crashes for [id] (or the live session's, when `null`) -- + * Loads the retained logs, crashes and traffic (network/socket/push) for [id] (or the live + * session's, when `null`) -- * the Crashes tab is a session-scoped read exactly like Logs, so the More screen's Retained * runs row and the Crashes tab's previous-run-crashed banner both go through this one path. * [applySnapshot]'s own guard keeps a later live-snapshot refresh from clobbering either list * while [id] stays selected. */ - private fun selectSession(id: String?) { + private fun selectSession(requestedId: String?) { + // The current run is always browsed live; selecting it from a list means "back to live". + val id = + requestedId?.takeUnless { candidate -> + mutableState.value.sessions.any { + it.id == candidate && + it.isCurrent + } + } mutableState.update { it.copy(selectedSessionId = id, sessionLogsLoading = id != null) } viewModelScope.launch(dispatcher) { val logs = runCatching { dataSource.logsForSession(id) }.getOrDefault(emptyList()) val crashes = runCatching { dataSource.crashesForSession(id) }.getOrDefault(emptyList()) val flaggedCrashIds = runCatching { dataSource.flaggedCrashIds(id) }.getOrDefault(emptySet()) + val captures = + runCatching { + dataSource.capturesForSession( + id, + ) + }.getOrDefault(InspectorSessionCaptures()) mutableState.update { state -> - if (state.selectedSessionId == - id - ) { + if (state.selectedSessionId == id) { state.copy( logs = logs.take(MAX_VISIBLE_TRANSACTIONS), crashes = crashes.take(MAX_VISIBLE_TRANSACTIONS), flaggedCrashIds = flaggedCrashIds, + transactions = captures.transactions.takeLast(MAX_VISIBLE_TRANSACTIONS), + sockets = captures.sockets.take(MAX_VISIBLE_TRANSACTIONS), + pushEvents = captures.pushEvents.take(MAX_VISIBLE_TRANSACTIONS), + selectedTransactionIds = emptySet(), sessionLogsLoading = false, ) } else { @@ -344,15 +428,48 @@ class InspectorViewModel } } + /** + * Re-reads the capture store with a new status-class filter. The state field is written + * before the reload so the chip selection paints immediately, in step with the refresh. + */ + private fun selectTrafficStatusClass(statusClass: TrafficStatusClass) { + trafficQuery = trafficQuery.copy(statusClass = statusClass) + mutableState.update { it.copy(trafficStatusClass = statusClass) } + refreshSnapshot() + } + + /** Host counterpart of [selectTrafficStatusClass]; null shows every host. */ + private fun selectTrafficHost(host: String?) { + val normalized = host?.trim()?.takeIf(String::isNotEmpty) + trafficQuery = trafficQuery.copy(host = normalized) + mutableState.update { it.copy(trafficHost = normalized) } + refreshSnapshot() + } + + private fun setSessionPinned( + id: String, + pinned: Boolean, + ) { + runCommandThenReload { dataSource.setSessionPinned(id, pinned) } + } + + private fun deleteSession(id: String) { + viewModelScope.launch(dispatcher) { + val result = dataSource.deleteSession(id) + showComposerResult(result) + if (result is InspectorCommandResult.Success && mutableState.value.selectedSessionId == id) { + selectSession(null) + } + loadSnapshot() + } + } + private fun executeComposer(request: InspectorComposerRequest) { if (!mutableState.value.capabilities.requestExecution) { showComposerResult(InspectorCommandResult.Disabled(CAPABILITY_REQUEST_EXECUTION)) return } - viewModelScope.launch(dispatcher) { - showComposerResult(dataSource.execute(request)) - loadSnapshot() - } + runCommandThenReload { dataSource.execute(request) } } private fun setMocksEnabled(enabled: Boolean) { @@ -360,10 +477,7 @@ class InspectorViewModel showComposerResult(InspectorCommandResult.Disabled(CAPABILITY_MOCKS)) return } - viewModelScope.launch(dispatcher) { - showComposerResult(dataSource.setMocksEnabled(enabled)) - loadSnapshot() - } + runCommandThenReload { dataSource.setMocksEnabled(enabled) } } /** @@ -436,10 +550,7 @@ class InspectorViewModel showComposerResult(InspectorCommandResult.Disabled(CAPABILITY_FEATURE_FLAGS)) return } - viewModelScope.launch(dispatcher) { - showComposerResult(dataSource.setFeatureFlag(key, value)) - loadSnapshot() - } + runCommandThenReload { dataSource.setFeatureFlag(key, value) } } private fun setPreference( @@ -452,10 +563,7 @@ class InspectorViewModel showComposerResult(InspectorCommandResult.Disabled(CAPABILITY_PREFERENCES)) return } - viewModelScope.launch(dispatcher) { - showComposerResult(dataSource.setPreference(file, key, value, type)) - loadSnapshot() - } + runCommandThenReload { dataSource.setPreference(file, key, value, type) } } private fun removePreference( @@ -466,10 +574,7 @@ class InspectorViewModel showComposerResult(InspectorCommandResult.Disabled(CAPABILITY_PREFERENCES)) return } - viewModelScope.launch(dispatcher) { - showComposerResult(dataSource.removePreference(file, key)) - loadSnapshot() - } + runCommandThenReload { dataSource.removePreference(file, key) } } private fun openFilePath( @@ -488,7 +593,9 @@ class InspectorViewModel ) { viewModelScope.launch(dispatcher) { val preview = dataSource.previewFile(root, relativePath) - mutableState.update { it.copy(filePreview = preview) } + mutableState.update { + it.copy(filePreview = preview, filePreviewName = relativePath.substringAfterLast('/')) + } } } @@ -604,10 +711,7 @@ class InspectorViewModel * disappears from [InspectorState.browser] immediately. */ private fun revokePrincipal(id: String) { - viewModelScope.launch(dispatcher) { - showComposerResult(dataSource.revokePrincipal(id)) - loadSnapshot() - } + runCommandThenReload { dataSource.revokePrincipal(id) } } /** Ungated, like the exports above: starting/stopping is a device-owner action, not a data capability. */ @@ -630,6 +734,58 @@ class InspectorViewModel } } + /** Ungated like the capture commands: pausing only touches the SDK's own live capture gate. */ + private fun setCapturePaused(paused: Boolean) { + viewModelScope.launch(dispatcher) { + showComposerResult(dataSource.setCapturePaused(paused)) + // The snapshot carries the authoritative flag, so the switch and the Observe banner + // both reflect what the runtime actually applied rather than the requested value. + loadSnapshot() + } + } + + /** Ungated: purging empties the SDK's own capture buffers and old unpinned runs only. */ + private fun purgeCapturedData() { + viewModelScope.launch(dispatcher) { + showComposerResult(dataSource.purgeCapturedData()) + mutableState.update { it.copy(selectedTransactionIds = emptySet()) } + loadSnapshot() + } + } + + /** Ungated, like the capture commands: sending only writes to a connection the adapter offered. */ + private fun sendSocketFrame( + connectionId: String, + text: String, + topic: String?, + qos: Int, + retained: Boolean, + ) { + runCommandThenReload { dataSource.sendSocketFrame(connectionId, text, topic, qos, retained) } + } + + /** Ungated: an override only touches the SDK's own local Remote Config layer. */ + private fun setRemoteConfigOverride( + providerId: String, + key: String, + value: String, + ) { + runCommandThenReload { dataSource.setRemoteConfigOverride(providerId, key, value) } + } + + /** Ungated counterpart of [setRemoteConfigOverride]; the provider's own value returns. */ + private fun clearRemoteConfigOverride( + providerId: String, + key: String, + ) { + runCommandThenReload { dataSource.clearRemoteConfigOverride(providerId, key) } + } + + /** Ungated counterpart of [setRemoteConfigOverride], clearing every provider's overrides. */ + private fun clearAllRemoteConfigOverrides() { + runCommandThenReload { dataSource.clearAllRemoteConfigOverrides() } + } + /** * Continues a preflighted start. Local-network access is required for the requested LAN * bind, whereas notification permission only affects foreground-notification visibility; @@ -675,12 +831,21 @@ class InspectorViewModel mutableState.update { it.copy(lastScreenshotResult = null) } } + /** Runs one data-source command off the main thread, flashes its result, then reloads the snapshot. */ + private fun runCommandThenReload(command: suspend () -> InspectorCommandResult) { + viewModelScope.launch(dispatcher) { + showComposerResult(command()) + loadSnapshot() + } + } + /** * A successful export's [InspectorCommandResult.Success.sharePath] also opens the system * Share sheet, exactly like a Files-screen [InspectorAction.ShareFile] would -- see the * `LaunchedEffect` in `DevConsoleWorkspace`'s `WorkspaceContent`, which is what actually * consumes [InspectorState.pendingShareFilePath]. */ + private fun showComposerResult(result: InspectorCommandResult) { val sharePath = (result as? InspectorCommandResult.Success)?.sharePath mutableState.update { diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/ObserveDetailTargetSaver.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/ObserveDetailTargetSaver.kt new file mode 100644 index 0000000..a2f9165 --- /dev/null +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/ObserveDetailTargetSaver.kt @@ -0,0 +1,46 @@ +/** + * @author Shakib + * @since 03/11/26 + */ +package io.devconsole.ui.compose + +import androidx.compose.runtime.saveable.Saver +import androidx.compose.runtime.saveable.listSaver + +private const val TAG_NONE = "none" +private const val TAG_NET = "net" +private const val TAG_FRAME = "frame" +private const val TAG_PUSH = "push" +private const val TAG_LOG = "log" +private const val TAG_CRASH = "crash" +private const val TAG_REMOTE_CONFIG = "rc" +private const val PUSH_RECEIVED_AT_INDEX = 3 + +/** Keeps an open capture detail across rotation: a type tag plus its Bundle-friendly identity fields. */ +internal val ObserveDetailTargetSaver: Saver = + listSaver( + save = { target -> target.toSavedFields() }, + restore = { saved -> saved.toDetailTarget() }, + ) + +private fun ObserveDetailTarget?.toSavedFields(): List = + when (this) { + null -> listOf(TAG_NONE) + is ObserveDetailTarget.Net -> listOf(TAG_NET, transactionId) + is ObserveDetailTarget.Frame -> listOf(TAG_FRAME, socketId, timestampEpochMs) + is ObserveDetailTarget.Push -> listOf(TAG_PUSH, provider, messageId, receivedAtEpochMs) + is ObserveDetailTarget.Log -> listOf(TAG_LOG, logId) + is ObserveDetailTarget.Crash -> listOf(TAG_CRASH, crashId) + is ObserveDetailTarget.RemoteConfigKey -> listOf(TAG_REMOTE_CONFIG, providerId, key) + } + +private fun List.toDetailTarget(): ObserveDetailTarget? = + when (firstOrNull()) { + TAG_NET -> ObserveDetailTarget.Net(get(1) as String) + TAG_FRAME -> ObserveDetailTarget.Frame(get(1) as String, get(2) as Long) + TAG_PUSH -> ObserveDetailTarget.Push(get(1) as String, get(2) as String?, get(PUSH_RECEIVED_AT_INDEX) as Long) + TAG_LOG -> ObserveDetailTarget.Log(get(1) as String) + TAG_CRASH -> ObserveDetailTarget.Crash(get(1) as String) + TAG_REMOTE_CONFIG -> ObserveDetailTarget.RemoteConfigKey(get(1) as String, get(2) as String) + else -> null + } diff --git a/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorCountLabelTest.kt b/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorCountLabelTest.kt new file mode 100644 index 0000000..fda8418 --- /dev/null +++ b/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorCountLabelTest.kt @@ -0,0 +1,19 @@ +/** + * @author Shakib + * @since 03/11/26 + */ +package io.devconsole.ui.compose + +import org.junit.Assert.assertEquals +import org.junit.Test + +class InspectorCountLabelTest { + @Test + fun countLabelUsesSingularOnlyForOne() { + assertEquals("0 files", countLabel(0, "file")) + assertEquals("1 file", countLabel(1, "file")) + assertEquals("2 files", countLabel(2, "file")) + assertEquals("1 entry", countLabel(1, "entry", "entries")) + assertEquals("4 entries", countLabel(4, "entry", "entries")) + } +} diff --git a/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorCrashGroupingTest.kt b/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorCrashGroupingTest.kt new file mode 100644 index 0000000..b1b5799 --- /dev/null +++ b/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorCrashGroupingTest.kt @@ -0,0 +1,180 @@ +/** + * @author Shakib + * @since 03/11/26 + */ +package io.devconsole.ui.compose + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +class InspectorCrashGroupingTest { + @Test + fun `same crash at different line numbers produces the same fingerprint`() { + val first = + InspectorCrashUi( + id = "crash-1", + kind = "UNCAUGHT", + summary = "IllegalStateException: Order 101 missing", + thread = "main", + timestampEpochMs = 1_000L, + stackTrace = + """ + java.lang.IllegalStateException: Order 101 missing + at java.util.Objects.requireNonNull(Objects.java:208) + at kotlin.PreconditionsKt.checkNotNull(Preconditions.kt:32) + at com.acmeship.checkout.OrderRepository.getOrder(OrderRepository.kt:42) + at com.acmeship.checkout.CheckoutViewModel.load(CheckoutViewModel.kt:88) + """.trimIndent(), + ) + val secondMovedLine = + InspectorCrashUi( + id = "crash-2", + kind = "UNCAUGHT", + summary = "IllegalStateException: Order 202 missing", + thread = "main", + timestampEpochMs = 2_000L, + stackTrace = + """ + java.lang.IllegalStateException: Order 202 missing + at java.util.Objects.requireNonNull(Objects.java:208) + at kotlin.PreconditionsKt.checkNotNull(Preconditions.kt:32) + at com.acmeship.checkout.OrderRepository.getOrder(OrderRepository.kt:195) + at com.acmeship.checkout.CheckoutViewModel.load(CheckoutViewModel.kt:120) + """.trimIndent(), + ) + + val fp1 = crashFingerprint(first) + val fp2 = crashFingerprint(secondMovedLine) + + assertEquals(fp1, fp2) + assertTrue(fp1.contains("java.lang.IllegalStateException")) + assertTrue(fp1.contains("com.acmeship.checkout.OrderRepository.getOrder")) + assertFalse(fp1.contains("42")) + assertFalse(fp1.contains("195")) + } + + @Test + fun `framework-only frames fall back to the first stack frame`() { + val crash = + InspectorCrashUi( + id = "crash-framework-only", + kind = "ANR", + summary = "Main thread unresponsive", + thread = "main", + timestampEpochMs = 3_000L, + stackTrace = + """ + "main" + at android.os.MessageQueue.nativePollOnce(Native Method) + at android.os.MessageQueue.next(MessageQueue.java:335) + at android.os.Looper.loop(Looper.java:183) + at com.android.internal.os.RuntimeInit.main(RuntimeInit.java:392) + """.trimIndent(), + ) + + val fingerprint = crashFingerprint(crash) + + assertTrue(fingerprint.contains("Main thread unresponsive")) + assertTrue(fingerprint.contains("android.os.MessageQueue.nativePollOnce")) + } + + @Test + fun `different app methods with same exception class produce distinct fingerprints`() { + val crashA = + InspectorCrashUi( + id = "a", + kind = "UNCAUGHT", + summary = "NullPointerException: boom", + thread = "main", + timestampEpochMs = 1_000L, + stackTrace = + """ + java.lang.NullPointerException: boom + at com.acmeship.CartManager.add(CartManager.kt:10) + """.trimIndent(), + ) + val crashB = + InspectorCrashUi( + id = "b", + kind = "UNCAUGHT", + summary = "NullPointerException: boom", + thread = "main", + timestampEpochMs = 2_000L, + stackTrace = + """ + java.lang.NullPointerException: boom + at com.acmeship.CartManager.remove(CartManager.kt:20) + """.trimIndent(), + ) + + assertNotEquals(crashFingerprint(crashA), crashFingerprint(crashB)) + } + + @Test + fun `groups crashes by fingerprint with newest group first and newest crash per group`() { + val npeOld = + InspectorCrashUi( + id = "npe-1", + kind = "UNCAUGHT", + summary = "NullPointerException: first", + thread = "main", + timestampEpochMs = 1_000L, + stackTrace = + "java.lang.NullPointerException: first\n" + + "\tat com.acmeship.Cart.checkout(Cart.kt:10)", + ) + val iseMiddle = + InspectorCrashUi( + id = "ise-1", + kind = "UNCAUGHT", + summary = "IllegalStateException: middle", + thread = "worker", + timestampEpochMs = 3_000L, + stackTrace = + "java.lang.IllegalStateException: middle\n" + + "\tat com.acmeship.SyncWorker.run(SyncWorker.kt:50)", + ) + val npeNewest = + InspectorCrashUi( + id = "npe-2", + kind = "UNCAUGHT", + summary = "NullPointerException: latest", + thread = "main", + timestampEpochMs = 5_000L, + stackTrace = + "java.lang.NullPointerException: latest\n" + + "\tat com.acmeship.Cart.checkout(Cart.kt:77)", + ) + val npeMiddle = + InspectorCrashUi( + id = "npe-3", + kind = "UNCAUGHT", + summary = "NullPointerException: mid", + thread = "main", + timestampEpochMs = 2_000L, + stackTrace = + "java.lang.NullPointerException: mid\n" + + "\tat com.acmeship.Cart.checkout(Cart.kt:44)", + ) + + val crashes = listOf(npeOld, iseMiddle, npeNewest, npeMiddle) + assertTrue(hasDuplicateCrashFingerprints(crashes)) + assertFalse(hasDuplicateCrashFingerprints(listOf(npeOld, iseMiddle))) + + val groups = groupCrashes(crashes) + + assertEquals(2, groups.size) + // Newest group first (npe group has lastSeen = 5000, ise group has lastSeen = 3000) + assertEquals("npe-2", groups[0].newest.id) + assertEquals("NullPointerException: latest", groups[0].newest.summary) + assertEquals(3, groups[0].count) + assertEquals(5_000L, groups[0].lastSeenEpochMs) + + assertEquals("ise-1", groups[1].newest.id) + assertEquals(1, groups[1].count) + assertEquals(3_000L, groups[1].lastSeenEpochMs) + } +} diff --git a/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorFlagEditDialogsTest.kt b/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorFlagEditDialogsTest.kt new file mode 100644 index 0000000..c96b197 --- /dev/null +++ b/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorFlagEditDialogsTest.kt @@ -0,0 +1,35 @@ +/** + * @author Shakib + * @since 03/11/26 + */ +package io.devconsole.ui.compose + +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class InspectorFlagEditDialogsTest { + @Test + fun `boolean flags only accept true or false`() { + assertTrue(isValidFeatureFlagValue("BOOLEAN", "true")) + assertTrue(isValidFeatureFlagValue("BOOLEAN", " FALSE ")) + assertFalse(isValidFeatureFlagValue("BOOLEAN", "yes")) + assertFalse(isValidFeatureFlagValue("BOOLEAN", "")) + } + + @Test + fun `numeric flags must parse and use a numeric keyboard`() { + assertTrue(flagValueUsesNumericKeyboard("INT")) + assertTrue(flagValueUsesNumericKeyboard("double")) + assertFalse(flagValueUsesNumericKeyboard("STRING")) + assertTrue(isValidFeatureFlagValue("INT", "42")) + assertTrue(isValidFeatureFlagValue("DOUBLE", "-1.5")) + assertFalse(isValidFeatureFlagValue("INT", "forty-two")) + } + + @Test + fun `free-form string flags accept any non-blank text`() { + assertTrue(isValidFeatureFlagValue("STRING", "staging")) + assertFalse(isValidFeatureFlagValue("STRING", " ")) + } +} diff --git a/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorLogDetailTest.kt b/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorLogDetailTest.kt new file mode 100644 index 0000000..d2dec33 --- /dev/null +++ b/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorLogDetailTest.kt @@ -0,0 +1,31 @@ +/** + * @author Shakib + * @since 03/11/26 + */ +package io.devconsole.ui.compose + +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class InspectorLogDetailTest { + @Test + fun recordedThrowableIsDetectedAsStackTrace() { + val trace = + """ + java.lang.IllegalStateException: Card issuer returned 402 + at io.devconsole.sample.compose.MainActivity.writeSampleLogs(MainActivity.kt:120) + at androidx.compose.foundation.ClickableNode.onClick(Clickable.kt:42) + """.trimIndent() + + assertTrue(trace.looksLikeStackTrace()) + } + + @Test + fun plainContextIsNotAStackTrace() { + assertFalse(null.looksLikeStackTrace()) + assertFalse("""{"orderId": 42}""".looksLikeStackTrace()) + assertFalse("at the start of the line only".looksLikeStackTrace()) + assertFalse("first line\nsecond line mentions at once".looksLikeStackTrace()) + } +} diff --git a/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorMockRuleEditorTest.kt b/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorMockRuleEditorTest.kt index 96b98c5..fcf057a 100644 --- a/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorMockRuleEditorTest.kt +++ b/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorMockRuleEditorTest.kt @@ -12,6 +12,7 @@ class InspectorMockRuleEditorTest { responsePreview: String?, responseHeaders: Map = emptyMap(), statusCode: Int? = 200, + responseBodyTruncated: Boolean = false, ) = InspectorTransactionUi( id = "tx-1", method = "GET", @@ -21,6 +22,7 @@ class InspectorMockRuleEditorTest { durationMs = 42, responsePreview = responsePreview, responseHeaders = responseHeaders, + responseBodyTruncated = responseBodyTruncated, ) @Test @@ -66,6 +68,13 @@ class InspectorMockRuleEditorTest { assertFalse(target.prefillNote.orEmpty().contains("binary")) } + @Test + fun `truncated capture preview is identified on the editable draft`() { + val target = mockRuleDraftFromTransaction(transaction("partial", responseBodyTruncated = true)) + assertEquals("partial", target.draft.body) + assertTrue(target.draft.responseBodyTruncated) + } + @Test fun `existing rule ids are threaded through to avoid an id collision`() { val base = suggestMockRuleId("GET", "/v1/cart") @@ -101,9 +110,9 @@ class InspectorMockRuleEditorTest { // The sheet's open state must survive a configuration change like rotation, not just its // individual field values -- verifies MockRuleEditorNewSaver round-trips a draft, and null, intact. @Test - fun `MockRuleEditorNewSaver round-trips a draft and null`() { + fun `MockRuleEditorNewSaver round-trips a truncated draft and null`() { val scope = SaverScope { true } - val original = mockRuleDraftFromTransaction(transaction("""{"ok":true}""")) + val original = mockRuleDraftFromTransaction(transaction("""{"ok":true}""", responseBodyTruncated = true)) val saved = with(MockRuleEditorNewSaver) { scope.save(original) } assertEquals(original, saved?.let(MockRuleEditorNewSaver::restore)) diff --git a/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorMockRuleFormTest.kt b/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorMockRuleFormTest.kt index 0161571..8ee41d1 100644 --- a/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorMockRuleFormTest.kt +++ b/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorMockRuleFormTest.kt @@ -83,18 +83,120 @@ class InspectorMockRuleFormTest { } @Test - fun `a static response or delayed static response rule is editable on device`() { - assertTrue(InspectorMockRuleUi(id = "r", actionLabel = "Static response (200)").isEditableOnDevice()) - assertTrue(InspectorMockRuleUi(id = "r", actionLabel = "Delay (500ms)").isEditableOnDevice()) + fun `every action type except other is editable on device`() { + InspectorMockActionType.entries.filter { it != InspectorMockActionType.OTHER }.forEach { type -> + assertTrue(type.name, InspectorMockRuleUi(id = "r", actionType = type).isEditableOnDevice()) + } + assertFalse( + InspectorMockRuleUi(id = "r", actionType = InspectorMockActionType.OTHER).isEditableOnDevice(), + ) } @Test - fun `fault-injection and template rules are not editable on device`() { - assertFalse(InspectorMockRuleUi(id = "r", actionLabel = "Connection failure").isEditableOnDevice()) - assertFalse(InspectorMockRuleUi(id = "r", actionLabel = "Timeout (500ms)").isEditableOnDevice()) - assertFalse(InspectorMockRuleUi(id = "r", actionLabel = "Template response (200)").isEditableOnDevice()) - assertFalse(InspectorMockRuleUi(id = "r", actionLabel = "Status override (200)").isEditableOnDevice()) - assertFalse(InspectorMockRuleUi(id = "r", actionLabel = "Body replacement").isEditableOnDevice()) - assertFalse(InspectorMockRuleUi(id = "r", actionLabel = "Passthrough").isEditableOnDevice()) + fun `action label fallback recognises the editable labels but not templates or sequences`() { + assertTrue(isEditableMockActionLabel("Static response (200)")) + assertTrue(isEditableMockActionLabel("Delay (500ms) → Static response (200)")) + assertTrue(isEditableMockActionLabel("Connection failure")) + assertTrue(isEditableMockActionLabel("Timeout (500ms)")) + assertTrue(isEditableMockActionLabel("Status override (200)")) + assertTrue(isEditableMockActionLabel("Body replacement")) + assertTrue(isEditableMockActionLabel("Throttle (1024 B/s) → Passthrough")) + assertTrue(isEditableMockActionLabel("Throttle 64 KB/s · +1500 ms")) + assertTrue(isEditableMockActionLabel("Map remote (https:example.test)")) + assertFalse(isEditableMockActionLabel("Delay (500ms) → Template response (200)")) + assertFalse(isEditableMockActionLabel("Delay (500ms) → Connection failure")) + assertFalse(isEditableMockActionLabel("Template response (200)")) + assertFalse(isEditableMockActionLabel("Sequence (2 steps)")) + assertFalse(isEditableMockActionLabel("Passthrough")) + } + + @Test + fun `timeout error requires a number inside the engine range`() { + assertNull(mockRuleTimeoutError("1000", 1_000)) + assertNull(mockRuleTimeoutError("0", 0)) + assertNull(mockRuleTimeoutError("30000", 30_000)) + assertNotNull(mockRuleTimeoutError("", null)) + assertNotNull(mockRuleTimeoutError("abc", null)) + assertNotNull(mockRuleTimeoutError("30001", 30_001)) + } + + @Test + fun `throttle rate error validates against the engine byte range`() { + assertNull(mockRuleThrottleRateError("64", 65_536)) + assertNull(mockRuleThrottleRateError("1", 1_024)) + assertNotNull(mockRuleThrottleRateError("", null)) + assertNotNull(mockRuleThrottleRateError("0", 0)) + assertNotNull(mockRuleThrottleRateError("999999", 102_400L * 1_024 + 1_024)) + } + + @Test + fun `throttle latency is optional and bounded like a delay`() { + assertNull(mockRuleThrottleLatencyError("", null)) + assertNull(mockRuleThrottleLatencyError("0", 0)) + assertNull(mockRuleThrottleLatencyError("30000", 30_000)) + assertNotNull(mockRuleThrottleLatencyError("abc", null)) + assertNotNull(mockRuleThrottleLatencyError("30001", 30_001)) + } + + @Test + fun `map remote validation mirrors the engine constraints`() { + assertNotNull(mockRuleMapRemoteError(hasAnyField = false)) + assertNull(mockRuleMapRemoteError(hasAnyField = true)) + assertNull(mockRuleRemoteSchemeError("https")) + assertNull(mockRuleRemoteSchemeError("")) + assertNotNull(mockRuleRemoteSchemeError("ftp")) + assertNull(mockRuleRemoteHostError("staging.example.test")) + assertNotNull(mockRuleRemoteHostError("bad/host")) + assertNull(mockRuleRemotePathError("/v2/orders")) + assertNull(mockRuleRemotePathError("")) + assertNotNull(mockRuleRemotePathError("v2/orders")) + assertNull(mockRuleRemotePortError("", null)) + assertNull(mockRuleRemotePortError("443", 443)) + assertNotNull(mockRuleRemotePortError("0", 0)) + assertNotNull(mockRuleRemotePortError("70000", 70_000)) + assertNotNull(mockRuleRemotePortError("abc", null)) + } + + @Test + fun `predicate lines parse key=value and skip malformed lines`() { + val result = parseMockRulePredicateLines("page=1\nnot-a-predicate\nX-Trace=abc\n\n") + + assertEquals(mapOf("page" to "1", "X-Trace" to "abc"), result.predicates) + assertEquals(1, result.skippedLines) + } + + @Test + fun `predicate map round-trips through toMockRulePredicateLines`() { + val predicates = linkedMapOf("page" to "1", "X-Trace" to "abc") + + val roundTripped = parseMockRulePredicateLines(predicates.toMockRulePredicateLines()).predicates + + assertEquals(predicates, roundTripped) + } + + @Test + fun `mock delay reads as ms under a second and trimmed seconds above`() { + assertEquals("800 ms", formatMockDelay(800)) + assertEquals("1.2 s", formatMockDelay(1_200)) + assertEquals("1.05 s", formatMockDelay(1_050)) + assertEquals("3 s", formatMockDelay(3_000)) + } + + @Test + fun `condition hint names the first predicate and counts the rest`() { + val base = InspectorMockRuleUi(id = "r", method = "GET", pathPattern = "/x", actionLabel = "Passthrough") + assertNull(mockRuleConditionHint(base)) + assertEquals("if debug=1", mockRuleConditionHint(base.copy(queryPredicates = mapOf("debug" to "1")))) + assertEquals( + "if debug=1 +2", + mockRuleConditionHint( + base.copy( + queryPredicates = mapOf("debug" to "1"), + headerPredicates = mapOf("X-Env" to "qa"), + bodyPredicate = ".*paid.*", + ), + ), + ) + assertEquals("if body matches", mockRuleConditionHint(base.copy(bodyPredicate = ".*"))) } } diff --git a/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorNetworkSnippetsTest.kt b/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorNetworkSnippetsTest.kt index fcc785a..8513a35 100644 --- a/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorNetworkSnippetsTest.kt +++ b/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorNetworkSnippetsTest.kt @@ -102,4 +102,21 @@ class InspectorNetworkSnippetsTest { val headers = parse(snippet).field("responseHeaders") as JsonValue.Obj assertEquals(JsonValue.Str("""W/"53-hfEnume"""), headers.entries.single().second) } + + @Test + fun `a resend drops headers whose captured value was redacted instead of sending the marker`() { + val request = + InspectorTransactionUi( + id = "tx-3", + method = "GET", + host = "api.example.test", + path = "/me", + statusCode = 401, + durationMs = 12, + url = "https://api.example.test/me", + requestHeaders = mapOf("Authorization" to "", "Accept" to "application/json"), + ).toComposerRequest() + + assertEquals(mapOf("Accept" to "application/json"), request.headers) + } } diff --git a/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorRemoteConfigOverrideTest.kt b/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorRemoteConfigOverrideTest.kt new file mode 100644 index 0000000..96736ed --- /dev/null +++ b/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorRemoteConfigOverrideTest.kt @@ -0,0 +1,75 @@ +/** + * @author Shakib + * @since 04/11/26 + */ +package io.devconsole.ui.compose + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +class InspectorRemoteConfigOverrideTest { + @Test + fun `an entry without an override has no provider value line`() { + val entry = InspectorRemoteConfigEntryUi(key = "checkout_v2", value = "on", source = "remote") + + assertNull(remoteConfigProviderValueLabel(entry)) + } + + @Test + fun `an overridden entry names the provider value and its source`() { + val entry = + InspectorRemoteConfigEntryUi( + key = "checkout_v2", + value = "on", + source = "override", + providerValue = "off", + providerSource = "remote", + ) + + assertEquals("Provider value: off (remote)", remoteConfigProviderValueLabel(entry)) + } + + @Test + fun `an overridden entry with no provider value falls back to an unknown marker`() { + val entry = + InspectorRemoteConfigEntryUi( + key = "checkout_v2", + value = "on", + source = "override", + providerSource = "default", + ) + + assertEquals("Provider value: (default)", remoteConfigProviderValueLabel(entry)) + } + + @Test + fun `the row value line names the provider value only while overridden`() { + val plain = InspectorRemoteConfigEntryUi(key = "promo", value = "Free delivery", source = "remote") + val overridden = + plain.copy( + value = "Set locally", + source = "override", + providerValue = "Free delivery", + providerSource = "remote", + ) + + assertEquals("Free delivery", remoteConfigRowSubtitle(plain)) + assertEquals("Set locally · provider: Free delivery", remoteConfigRowSubtitle(overridden)) + } + + @Test + fun `a redacted overridden row never shows either value`() { + val entry = + InspectorRemoteConfigEntryUi( + key = "api_key", + value = "secret", + source = "override", + redacted = true, + providerValue = "older-secret", + providerSource = "remote", + ) + + assertEquals("", remoteConfigRowSubtitle(entry)) + } +} diff --git a/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorResendResultTest.kt b/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorResendResultTest.kt new file mode 100644 index 0000000..d1a9a0f --- /dev/null +++ b/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorResendResultTest.kt @@ -0,0 +1,39 @@ +/** + * @author Shakib + * @since 03/11/26 + */ +package io.devconsole.ui.compose + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +class InspectorResendResultTest { + @Test + fun `success with a status maps summary status and body`() { + val mapped = + resendResultFrom( + InspectorCommandResult.Success( + summary = "GET https://api.example.test/todos/1 -> 200", + statusCode = 200, + body = "{\"id\":1}", + ), + ) ?: error("expected a resend result") + + assertEquals("GET https://api.example.test/todos/1", mapped.summary) + assertEquals(200, mapped.statusCode) + assertEquals("{\"id\":1}", mapped.body) + } + + @Test + fun `success without a status is not a resend result`() { + assertNull(resendResultFrom(InspectorCommandResult.Success(summary = "Mocks enabled"))) + } + + @Test + fun `invalid failed and disabled results are not resend results`() { + assertNull(resendResultFrom(InspectorCommandResult.Invalid("Destination host is not allowed"))) + assertNull(resendResultFrom(InspectorCommandResult.Failed("connection reset"))) + assertNull(resendResultFrom(InspectorCommandResult.Disabled("requestExecution"))) + } +} diff --git a/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorResendSheetTest.kt b/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorResendSheetTest.kt new file mode 100644 index 0000000..4b8403b --- /dev/null +++ b/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorResendSheetTest.kt @@ -0,0 +1,80 @@ +/** + * @author Shakib + * @since 03/11/26 + */ +package io.devconsole.ui.compose + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +class InspectorResendSheetTest { + @Test + fun `draft seeds url headers and body from the capture`() { + val transaction = + InspectorTransactionUi( + id = "tx-1", + method = "POST", + host = "api.example.test", + path = "/orders", + statusCode = 201, + durationMs = null, + url = "https://api.example.test/orders?status=open", + requestHeaders = mapOf("Content-Type" to "application/json", "X-Id" to "7"), + requestPreview = "{\"id\":7}", + requestBodyKind = InspectorBodyKind.TEXT, + ) + + val draft = resendDraftFromTransaction(transaction) + + assertEquals("POST", draft.method) + assertEquals("https://api.example.test/orders?status=open", draft.url) + assertEquals("Content-Type: application/json\nX-Id: 7", draft.headerLines) + assertEquals("{\"id\":7}", draft.body) + } + + @Test + fun `draft composes a url when the adapter predates the url field`() { + val transaction = + InspectorTransactionUi( + id = "tx-1", + method = "GET", + host = "api.example.test", + path = "/orders", + statusCode = 200, + durationMs = null, + ) + + assertEquals("https://api.example.test/orders", resendDraftFromTransaction(transaction).url) + } + + @Test + fun `header lines parse trims whitespace and skips malformed lines`() { + val parsed = parseResendHeaderLines(" Content-Type: application/json \n\nX-Id:7\nnot-a-header\n: value\n") + + assertEquals(mapOf("Content-Type" to "application/json", "X-Id" to "7"), parsed) + } + + @Test + fun `a draft becomes the composer request the view model executes`() { + val request = + InspectorResendDraft( + method = " post ", + url = " https://api.example.test/orders ", + headerLines = "Content-Type: application/json", + body = "{\"id\":1}", + ).toComposerRequest() + + assertEquals("POST", request.method) + assertEquals("https://api.example.test/orders", request.url) + assertEquals(mapOf("Content-Type" to "application/json"), request.headers) + assertEquals("{\"id\":1}", request.body) + } + + @Test + fun `an empty body is sent as no body`() { + val request = InspectorResendDraft("GET", "https://api.example.test", "", "").toComposerRequest() + + assertNull(request.body) + } +} diff --git a/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorSocketComposerTest.kt b/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorSocketComposerTest.kt new file mode 100644 index 0000000..dbdf871 --- /dev/null +++ b/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorSocketComposerTest.kt @@ -0,0 +1,29 @@ +/** + * @author Shakib + * @since 04/11/26 + */ +package io.devconsole.ui.compose + +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class InspectorSocketComposerTest { + @Test + fun `an empty frame never enables send`() { + assertFalse(socketComposerSendEnabled("websocket", text = "", topic = "")) + assertFalse(socketComposerSendEnabled("mqtt", text = "", topic = "orders")) + } + + @Test + fun `a websocket frame needs only text`() { + assertTrue(socketComposerSendEnabled("websocket", text = "ping", topic = "")) + } + + @Test + fun `an mqtt publish needs both text and topic`() { + assertFalse(socketComposerSendEnabled("mqtt", text = "on", topic = "")) + assertFalse(socketComposerSendEnabled("mqtt", text = "on", topic = " ")) + assertTrue(socketComposerSendEnabled("mqtt", text = "on", topic = "orders")) + } +} diff --git a/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorStructuredDecodersTest.kt b/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorStructuredDecodersTest.kt new file mode 100644 index 0000000..eaa18f4 --- /dev/null +++ b/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorStructuredDecodersTest.kt @@ -0,0 +1,269 @@ +/** + * @author Shakib + * @since 03/11/26 + */ +package io.devconsole.ui.compose + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test +import java.util.Base64 + +class InspectorStructuredDecodersTest { + private fun base64Url(text: String): String = + Base64.getUrlEncoder().withoutPadding().encodeToString(text.toByteArray(Charsets.UTF_8)) + + private fun sampleJwt( + headerJson: String = """{"alg":"HS256","typ":"JWT"}""", + payloadJson: String, + signature: String = "sig123", + ): String = "${base64Url(headerJson)}.${base64Url(payloadJson)}.$signature" + + // --- JWT decode ---------------------------------------------------------------------------- + + @Test + fun `decodes valid jwt from authorization header and formats header, payload and valid exp`() { + val nowEpochMs = 1_700_000_000_000L // 1700000000s + val expSeconds = 1_700_000_900L // +15 min + val iatSeconds = 1_699_999_700L // -5 min + val token = + sampleJwt( + payloadJson = """{"sub":"user-42","exp":$expSeconds,"iat":$iatSeconds}""", + ) + val transaction = + InspectorTransactionUi( + id = "tx-jwt-valid", + method = "GET", + host = "api.example.test", + path = "/v1/profile", + statusCode = 200, + durationMs = 42, + requestHeaders = mapOf("authorization" to "Bearer $token"), + ) + + val jwts = extractTransactionJwts(transaction, nowEpochMs = nowEpochMs) + + assertEquals(1, jwts.size) + val jwt = jwts.single() + assertEquals("Authorization", jwt.source) + assertEquals( + """ + { + "alg": "HS256", + "typ": "JWT" + } + """.trimIndent(), + jwt.headerJson, + ) + assertEquals( + """ + { + "sub": "user-42", + "exp": 1700000900, + "iat": 1699999700 + } + """.trimIndent(), + jwt.payloadJson, + ) + val expClaim = jwt.timestamps.firstOrNull { it.claim == "exp" } + assertNotNull(expClaim) + assertFalse(expClaim!!.isExpired) + assertEquals("valid for 15 min", expClaim.relativeStatus) + assertTrue(expClaim.humanTime.contains("2023-11-14")) + } + + @Test + fun `marks jwt as expired relative to injected clock and extracts response json token fields`() { + val nowEpochMs = 1_700_001_000_000L + val expSeconds = 1_700_000_000L // in the past relative to nowEpochMs + val accessToken = sampleJwt(payloadJson = """{"sub":"u-1","exp":$expSeconds}""") + val idToken = sampleJwt(payloadJson = """{"sub":"u-1","nbf":1700000400}""") + val transaction = + InspectorTransactionUi( + id = "tx-jwt-expired", + method = "POST", + host = "auth.example.test", + path = "/oauth/token", + statusCode = 200, + durationMs = 95, + responsePreview = + """{"access_token":"$accessToken","nested":{"id_token":"$idToken"},"token":"not-a-jwt"}""", + ) + + val jwts = extractTransactionJwts(transaction, nowEpochMs = nowEpochMs) + + assertEquals(2, jwts.size) + val decodedAccess = jwts.first { it.source == "response.access_token" } + val expClaim = decodedAccess.timestamps.single { it.claim == "exp" } + assertTrue(expClaim.isExpired) + assertEquals("expired 17 min ago", expClaim.relativeStatus) + assertTrue(expClaim.humanTime.endsWith("UTC")) + + val decodedId = jwts.first { it.source == "response.id_token" } + val nbfClaim = decodedId.timestamps.single { it.claim == "nbf" } + assertEquals("active since 10 min ago", nbfClaim.relativeStatus) + } + + @Test + fun `jwt spans read at the coarsest precise unit`() { + assertEquals("30 s", formatJwtSpan(30)) + assertEquals("1 min", formatJwtSpan(60)) + assertEquals("15 min", formatJwtSpan(900)) + assertEquals("2 h 5 min", formatJwtSpan(2 * 3_600 + 300)) + assertEquals("3 h", formatJwtSpan(3 * 3_600)) + assertEquals("1 day", formatJwtSpan(86_400)) + assertEquals("45 days", formatJwtSpan(45 * 86_400L)) + assertEquals("about 5 months", formatJwtSpan(150 * 86_400L)) + assertEquals("about 3 years", formatJwtSpan(1_154 * 86_400L)) + } + + @Test + fun `rejects malformed jwt tokens cleanly`() { + assertNull(decodeJwt("not.a")) + assertNull(decodeJwt("a.b.c.d")) + assertNull(decodeJwt("..")) + assertNull(decodeJwt("${base64Url("not-json")}.${base64Url("""{"sub":"1"}""")}.sig")) + assertNull(decodeJwt("${base64Url("[1,2,3]")}.${base64Url("""{"sub":"1"}""")}.sig")) + assertNull(decodeJwt("!!!invalid-base64!!!.${base64Url("""{"sub":"1"}""")}.sig")) + } + + @Test + fun `never decodes redacted jwt values in headers or response fields`() { + val validLookingJwtWithRedactedPayload = + sampleJwt(payloadJson = """{"sub":""}""") + assertNull(decodeJwt("")) + assertNull(decodeJwt("Bearer ")) + assertNull(decodeJwt("Bearer ***")) + assertNull(decodeJwt(validLookingJwtWithRedactedPayload)) + + val transaction = + InspectorTransactionUi( + id = "tx-jwt-redacted", + method = "POST", + host = "auth.example.test", + path = "/oauth/token", + statusCode = 200, + durationMs = 50, + requestHeaders = mapOf("Authorization" to "Bearer "), + responsePreview = + """ + {"access_token":"","id_token":"***","token":"$validLookingJwtWithRedactedPayload"} + """.trimIndent(), + ) + + assertTrue(extractTransactionJwts(transaction).isEmpty()) + } + + // --- Form-urlencoded parse ----------------------------------------------------------------- + + @Test + fun `parses urlencoded form fields with percent encoding, plus spaces, repeated keys and empty values`() { + val raw = "user%20name= Jane+Doe &tag=alpha&tag=beta&empty=&flag& filter%5B0%5D =a%26b%3Dc" + + val fields = parseFormUrlEncoded(raw) + + assertEquals( + listOf( + DecodedFormField("user name", " Jane Doe "), + DecodedFormField("tag", "alpha"), + DecodedFormField("tag", "beta"), + DecodedFormField("empty", ""), + DecodedFormField("flag", ""), + DecodedFormField(" filter[0] ", "a&b=c"), + ), + fields, + ) + } + + @Test + fun `detects form urlencoded requests from content type header or lookalike body`() { + val headersWithCharset = mapOf(" content-type " to "application/x-www-form-urlencoded; charset=UTF-8") + assertTrue(isFormUrlEncodedRequest(headersWithCharset.mapKeys { it.key.trim() }, "a=1&b=2")) + assertFalse(isFormUrlEncodedRequest(mapOf("Content-Type" to "application/json"), """{"a":1}""")) + assertFalse(isFormUrlEncodedRequest(mapOf("Content-Type" to "application/x-www-form-urlencoded"), "")) + } + + // --- GraphQL detection --------------------------------------------------------------------- + + @Test + @Suppress("ktlint:standard:max-line-length") // Single JSON fixture line; wrapping would change the body. + fun `detects graphql post with json query, operation name and pretty-printed variables`() { + val body = + """ + { + "query": "mutation CreateOrder(${'$'}input: OrderInput!) {\n createOrder(input: ${'$'}input) { id status }\n}", + "operationName": "CreateOrder", + "variables": {"input":{"sku":"ABC-1","qty":2}} + } + """.trimIndent() + + val decoded = + detectGraphQlRequest( + method = "POST", + url = "https://api.example.test/v1/query", + path = "/v1/query", + body = body, + ) + + assertNotNull(decoded) + assertEquals("mutation", decoded!!.operationType) + assertEquals("CreateOrder", decoded.operationName) + assertEquals( + "mutation CreateOrder(\$input: OrderInput!) {\n createOrder(input: \$input) { id status }\n}", + decoded.query, + ) + assertEquals( + """ + { + "input": { + "sku": "ABC-1", + "qty": 2 + } + } + """.trimIndent(), + decoded.variablesJson, + ) + } + + @Test + fun `parses operation type and name from query text when operationName field is absent`() { + val body = """{"query":"# comment\nsubscription OnOrderUpdated { orderUpdated { id } }"}""" + + val decoded = + detectGraphQlRequest( + method = "POST", + url = "https://api.example.test/graphql", + path = "/graphql", + body = body, + ) + + assertNotNull(decoded) + assertEquals("subscription", decoded!!.operationType) + assertEquals("OnOrderUpdated", decoded.operationName) + assertNull(decoded.variablesJson) + } + + @Test + fun `ignores non-graphql json bodies even on post requests`() { + val ordinaryJson = """{"userId":42,"action":"checkout"}""" + assertNull( + detectGraphQlRequest( + method = "POST", + url = "https://api.example.test/v1/checkout", + path = "/v1/checkout", + body = ordinaryJson, + ), + ) + assertNull( + detectGraphQlRequest( + method = "POST", + url = "https://api.example.test/graphql", + path = "/graphql", + body = ordinaryJson, + ), + ) + } +} diff --git a/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorTrafficFiltersTest.kt b/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorTrafficFiltersTest.kt new file mode 100644 index 0000000..b88a635 --- /dev/null +++ b/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorTrafficFiltersTest.kt @@ -0,0 +1,61 @@ +/** + * @author Shakib + * @since 03/11/26 + */ +package io.devconsole.ui.compose + +import org.junit.Assert.assertEquals +import org.junit.Test + +class InspectorTrafficFiltersTest { + private fun transaction( + id: String, + host: String, + ) = InspectorTransactionUi( + id = id, + method = "GET", + host = host, + path = "/orders", + statusCode = 200, + durationMs = null, + ) + + @Test + fun `hosts are ranked by capture count`() { + val transactions = + listOf( + transaction("1", "api.example.test"), + transaction("2", "api.example.test"), + transaction("3", "cdn.example.test"), + transaction("4", "img.example.test"), + transaction("5", "img.example.test"), + ) + + assertEquals( + listOf("api.example.test", "img.example.test", "cdn.example.test"), + topTrafficHosts(transactions), + ) + } + + @Test + fun `the host list is capped and ties stay alphabetical`() { + val transactions = (1..10).map { index -> transaction("tx-$index", "host-$index.example.test") } + + val hosts = topTrafficHosts(transactions) + + assertEquals(8, hosts.size) + assertEquals( + listOf( + "host-1.example.test", + "host-10.example.test", + "host-2.example.test", + "host-3.example.test", + "host-4.example.test", + "host-5.example.test", + "host-6.example.test", + "host-7.example.test", + ), + hosts, + ) + } +} 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 0f64fbb..0b73f9a 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 @@ -16,6 +16,19 @@ import org.junit.Test @Suppress("LargeClass") // Exhaustive per-action MVI coverage; mirrors FullInspectorDataSourceTest's justification. class InspectorViewModelTest { + @Test + fun `snapshot exception leaves view model in unavailable state`() = + runTest { + val dispatcher = StandardTestDispatcher(testScheduler) + val source = + RecordingInspectorDataSource(InspectorSnapshot(available = true)).apply { + snapshotFailure = IllegalStateException("failed") + } + val viewModel = InspectorViewModel(dataSource = source, dispatcher = dispatcher) + dispatcher.scheduler.advanceUntilIdle() + assertFalse(viewModel.state.value.available) + } + @Test fun `initial load populates state from snapshot`() = runTest { @@ -1146,6 +1159,61 @@ class InspectorViewModelTest { assertEquals(listOf(pastCrash), viewModel.state.value.crashes) } + @Test + fun `a past run's traffic replaces the live traffic and survives a live refresh`() = + runTest { + val dispatcher = StandardTestDispatcher(testScheduler) + val session = sampleSession() + val source = + RecordingInspectorDataSource( + InspectorSnapshot( + available = true, + sessions = listOf(session), + transactions = listOf(sampleTransaction("live-tx")), + ), + ) + val viewModel = InspectorViewModel(dataSource = source, dispatcher = dispatcher) + dispatcher.scheduler.advanceUntilIdle() + // Default capturesForSession reads the snapshot; point it at the past run's traffic. + source.snapshotToReturn = source.snapshotToReturn.copy(transactions = listOf(sampleTransaction("past-tx"))) + + viewModel.dispatch(InspectorAction.SelectSession(session.id)) + dispatcher.scheduler.advanceUntilIdle() + source.snapshotToReturn = source.snapshotToReturn.copy(transactions = listOf(sampleTransaction("live-2"))) + viewModel.dispatch(InspectorAction.Refresh) + dispatcher.scheduler.advanceUntilIdle() + + assertEquals( + listOf("past-tx"), + viewModel.state.value.transactions + .map { it.id }, + ) + + viewModel.dispatch(InspectorAction.SelectSession(null)) + dispatcher.scheduler.advanceUntilIdle() + + assertEquals( + listOf("live-2"), + viewModel.state.value.transactions + .map { it.id }, + ) + } + + @Test + fun `selecting the current run goes back to live instead of freezing it`() = + runTest { + val dispatcher = StandardTestDispatcher(testScheduler) + val current = sampleSession().copy(isCurrent = true) + val source = RecordingInspectorDataSource(InspectorSnapshot(available = true, sessions = listOf(current))) + val viewModel = InspectorViewModel(dataSource = source, dispatcher = dispatcher) + dispatcher.scheduler.advanceUntilIdle() + + viewModel.dispatch(InspectorAction.SelectSession(current.id)) + dispatcher.scheduler.advanceUntilIdle() + + assertNull(viewModel.state.value.selectedSessionId) + } + @Test fun `capturing a screenshot records the result and refreshes on success`() = runTest { @@ -1629,6 +1697,174 @@ class InspectorViewModelTest { assertEquals(ObserveTab.TRAFFIC, viewModel.state.value.observeTab) } + + @Test + fun `selecting a traffic status class re-reads the snapshot with that filter`() = + runTest { + val dispatcher = StandardTestDispatcher(testScheduler) + val source = RecordingInspectorDataSource(InspectorSnapshot(available = true)) + val viewModel = InspectorViewModel(dataSource = source, dispatcher = dispatcher) + dispatcher.scheduler.advanceUntilIdle() + + viewModel.dispatch(InspectorAction.SelectTrafficStatusClass(TrafficStatusClass.CLIENT_ERROR)) + dispatcher.scheduler.advanceUntilIdle() + + assertEquals(TrafficStatusClass.CLIENT_ERROR, source.lastTrafficQuery?.statusClass) + assertEquals(TrafficStatusClass.CLIENT_ERROR, viewModel.state.value.trafficStatusClass) + } + + @Test + fun `selecting a traffic host passes it in the traffic query and keeps the status class`() = + runTest { + val dispatcher = StandardTestDispatcher(testScheduler) + val source = RecordingInspectorDataSource(InspectorSnapshot(available = true)) + val viewModel = InspectorViewModel(dataSource = source, dispatcher = dispatcher) + dispatcher.scheduler.advanceUntilIdle() + + viewModel.dispatch(InspectorAction.SelectTrafficStatusClass(TrafficStatusClass.SERVER_ERROR)) + dispatcher.scheduler.advanceUntilIdle() + viewModel.dispatch(InspectorAction.SelectTrafficHost("api.example.test")) + dispatcher.scheduler.advanceUntilIdle() + + assertEquals("api.example.test", source.lastTrafficQuery?.host) + assertEquals(TrafficStatusClass.SERVER_ERROR, source.lastTrafficQuery?.statusClass) + assertEquals("api.example.test", viewModel.state.value.trafficHost) + } + + @Test + fun `clearing the traffic host reads every host again`() = + runTest { + val dispatcher = StandardTestDispatcher(testScheduler) + val source = RecordingInspectorDataSource(InspectorSnapshot(available = true)) + val viewModel = InspectorViewModel(dataSource = source, dispatcher = dispatcher) + dispatcher.scheduler.advanceUntilIdle() + + viewModel.dispatch(InspectorAction.SelectTrafficHost("api.example.test")) + dispatcher.scheduler.advanceUntilIdle() + viewModel.dispatch(InspectorAction.SelectTrafficHost(null)) + dispatcher.scheduler.advanceUntilIdle() + + assertNull(source.lastTrafficQuery?.host) + assertNull(viewModel.state.value.trafficHost) + } + + @Test + fun `resending a capture executes its request through the composer`() = + runTest { + val dispatcher = StandardTestDispatcher(testScheduler) + val transaction = + sampleTransaction().copy( + method = "POST", + url = "https://api.example.test/orders", + requestHeaders = mapOf("Content-Type" to "application/json"), + requestPreview = "{\"id\":1}", + requestBodyKind = InspectorBodyKind.TEXT, + ) + val source = + RecordingInspectorDataSource( + InspectorSnapshot( + available = true, + transactions = listOf(transaction), + capabilities = InspectorEditingUi(requestExecution = true), + ), + ) + val viewModel = InspectorViewModel(dataSource = source, dispatcher = dispatcher) + dispatcher.scheduler.advanceUntilIdle() + + viewModel.dispatch(InspectorAction.ExecuteComposer(transaction.toComposerRequest())) + dispatcher.scheduler.advanceUntilIdle() + + assertEquals(1, source.executeCallCount) + val executed = source.lastExecuteRequest + assertEquals("POST", executed?.method) + assertEquals("https://api.example.test/orders", executed?.url) + assertEquals(mapOf("Content-Type" to "application/json"), executed?.headers) + assertEquals("{\"id\":1}", executed?.body) + } + + @Test + fun `the snapshot exposes a write protocol only for connections the source can send on`() = + runTest { + val dispatcher = StandardTestDispatcher(testScheduler) + val snapshot = InspectorSnapshot(available = true, sockets = listOf(sampleSocket())) + val source = RecordingInspectorDataSource(snapshot) + source.socketSendProtocolToReturn = "mqtt" + val viewModel = InspectorViewModel(dataSource = source, dispatcher = dispatcher) + dispatcher.scheduler.advanceUntilIdle() + + assertEquals(mapOf("socket-1" to "mqtt"), viewModel.state.value.socketSendProtocols) + } + + @Test + fun `a connection the source cannot write to has no send protocol in state`() = + runTest { + val dispatcher = StandardTestDispatcher(testScheduler) + val snapshot = InspectorSnapshot(available = true, sockets = listOf(sampleSocket())) + val source = RecordingInspectorDataSource(snapshot) + val viewModel = InspectorViewModel(dataSource = source, dispatcher = dispatcher) + dispatcher.scheduler.advanceUntilIdle() + + assertTrue( + viewModel.state.value.socketSendProtocols + .isEmpty(), + ) + } + + @Test + fun `the snapshot reports whether remote config overrides are editable`() = + runTest { + val dispatcher = StandardTestDispatcher(testScheduler) + val source = RecordingInspectorDataSource(InspectorSnapshot(available = true)) + source.supportsRemoteConfigOverridesToReturn = true + val viewModel = InspectorViewModel(dataSource = source, dispatcher = dispatcher) + dispatcher.scheduler.advanceUntilIdle() + + assertTrue(viewModel.state.value.remoteConfigOverridesEditable) + } + + @Test + fun `sending a socket frame calls through and stores the result`() = + runTest { + val dispatcher = StandardTestDispatcher(testScheduler) + val source = RecordingInspectorDataSource(InspectorSnapshot(available = true)) + val viewModel = InspectorViewModel(dataSource = source, dispatcher = dispatcher) + dispatcher.scheduler.advanceUntilIdle() + + viewModel.dispatch(InspectorAction.SendSocketFrame("socket-1", "{\"ping\":true}", "orders", 1, true)) + dispatcher.scheduler.advanceUntilIdle() + + assertEquals(1, source.sendSocketFrameCallCount) + assertEquals("socket-1", source.lastSocketSendConnectionId) + assertEquals("{\"ping\":true}", source.lastSocketSendText) + assertEquals("orders", source.lastSocketSendTopic) + assertEquals(1, source.lastSocketSendQos) + assertEquals(true, source.lastSocketSendRetained) + assertEquals(source.sendSocketFrameResult, viewModel.state.value.lastCommandResult) + } + + @Test + fun `remote config override actions call through and store the result`() = + runTest { + val dispatcher = StandardTestDispatcher(testScheduler) + val source = RecordingInspectorDataSource(InspectorSnapshot(available = true)) + val viewModel = InspectorViewModel(dataSource = source, dispatcher = dispatcher) + dispatcher.scheduler.advanceUntilIdle() + + viewModel.dispatch(InspectorAction.SetRemoteConfigOverride("firebase", "checkout_v2", "on")) + dispatcher.scheduler.advanceUntilIdle() + assertEquals(1, source.setRemoteConfigOverrideCallCount) + assertEquals(Triple("firebase", "checkout_v2", "on"), source.lastRemoteConfigOverride) + + viewModel.dispatch(InspectorAction.ClearRemoteConfigOverride("firebase", "checkout_v2")) + dispatcher.scheduler.advanceUntilIdle() + assertEquals(1, source.clearRemoteConfigOverrideCallCount) + assertEquals("firebase" to "checkout_v2", source.lastClearedRemoteConfigOverride) + + viewModel.dispatch(InspectorAction.ClearAllRemoteConfigOverrides) + dispatcher.scheduler.advanceUntilIdle() + assertEquals(1, source.clearAllRemoteConfigOverridesCallCount) + assertEquals(source.clearAllRemoteConfigOverridesResult, viewModel.state.value.lastCommandResult) + } } private fun sampleTransaction(id: String = "tx-1") = @@ -1742,6 +1978,9 @@ private open class RecordingInspectorDataSource( initialSnapshot: InspectorSnapshot = InspectorSnapshot(), ) : InspectorDataSource { var snapshotToReturn: InspectorSnapshot = initialSnapshot + var snapshotFailure: Throwable? = null + var lastTrafficQuery: InspectorTrafficQuery? = null + private set var executeResult: InspectorCommandResult = InspectorCommandResult.Success(summary = "OK") var setMocksResult: InspectorCommandResult = InspectorCommandResult.Success(summary = "Mocks updated") var upsertMockRuleResult: InspectorCommandResult = InspectorCommandResult.Success(summary = "Mock rule saved") @@ -1766,6 +2005,15 @@ private open class RecordingInspectorDataSource( var exportSessionZipResult: InspectorCommandResult = InspectorCommandResult.Success(summary = "Saved to zip") var revokePrincipalResult: InspectorCommandResult = InspectorCommandResult.Success(summary = "Browser revoked") var captureScreenshotResult: ScreenshotResult = ScreenshotResult.Failed("not configured") + var socketSendProtocolToReturn: String? = null + var sendSocketFrameResult: InspectorCommandResult = InspectorCommandResult.Success(summary = "Frame sent") + var supportsRemoteConfigOverridesToReturn = false + var setRemoteConfigOverrideResult: InspectorCommandResult = + InspectorCommandResult.Success(summary = "Override set") + var clearRemoteConfigOverrideResult: InspectorCommandResult = + InspectorCommandResult.Success(summary = "Override cleared") + var clearAllRemoteConfigOverridesResult: InspectorCommandResult = + InspectorCommandResult.Success(summary = "Overrides cleared") /** Stands in for the durable EvidenceStore's own read -- what "something else" (e.g. the dashboard) wrote. */ var flaggedTransactionIdsToReturn: Set = emptySet() @@ -1860,8 +2108,35 @@ private open class RecordingInspectorDataSource( private set var flaggedCrashIdsCallSessionIds = mutableListOf() private set + var sendSocketFrameCallCount = 0 + private set + var lastSocketSendConnectionId: String? = null + private set + var lastSocketSendText: String? = null + private set + var lastSocketSendTopic: String? = null + private set + var lastSocketSendQos: Int? = null + private set + var lastSocketSendRetained: Boolean? = null + private set + var setRemoteConfigOverrideCallCount = 0 + private set + var lastRemoteConfigOverride: Triple? = null + private set + var clearRemoteConfigOverrideCallCount = 0 + private set + var lastClearedRemoteConfigOverride: Pair? = null + private set + var clearAllRemoteConfigOverridesCallCount = 0 + private set + + override fun snapshot(): InspectorSnapshot = snapshotFailure?.let { throw it } ?: snapshotToReturn - override fun snapshot(): InspectorSnapshot = snapshotToReturn + override fun snapshot(trafficQuery: InspectorTrafficQuery): InspectorSnapshot { + lastTrafficQuery = trafficQuery + return snapshot() + } override fun setServerRunning(running: Boolean): InspectorCommandResult { setServerRunningCallCount++ @@ -2064,6 +2339,50 @@ private open class RecordingInspectorDataSource( captureScreenshotCallCount++ return captureScreenshotResult } + + override fun socketSendProtocol(connectionId: String): String? = socketSendProtocolToReturn + + override fun sendSocketFrame( + connectionId: String, + text: String, + topic: String?, + qos: Int, + retained: Boolean, + ): InspectorCommandResult { + sendSocketFrameCallCount++ + lastSocketSendConnectionId = connectionId + lastSocketSendText = text + lastSocketSendTopic = topic + lastSocketSendQos = qos + lastSocketSendRetained = retained + return sendSocketFrameResult + } + + override fun supportsRemoteConfigOverrides(): Boolean = supportsRemoteConfigOverridesToReturn + + override fun setRemoteConfigOverride( + providerId: String, + key: String, + value: String, + ): InspectorCommandResult { + setRemoteConfigOverrideCallCount++ + lastRemoteConfigOverride = Triple(providerId, key, value) + return setRemoteConfigOverrideResult + } + + override fun clearRemoteConfigOverride( + providerId: String, + key: String, + ): InspectorCommandResult { + clearRemoteConfigOverrideCallCount++ + lastClearedRemoteConfigOverride = providerId to key + return clearRemoteConfigOverrideResult + } + + override fun clearAllRemoteConfigOverrides(): InspectorCommandResult { + clearAllRemoteConfigOverridesCallCount++ + return clearAllRemoteConfigOverridesResult + } } private class PermissionRecordingInspectorDataSource( diff --git a/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/ObserveDetailTargetSaverTest.kt b/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/ObserveDetailTargetSaverTest.kt new file mode 100644 index 0000000..f2ce3e5 --- /dev/null +++ b/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/ObserveDetailTargetSaverTest.kt @@ -0,0 +1,38 @@ +/** + * @author Shakib + * @since 03/11/26 + */ +package io.devconsole.ui.compose + +import androidx.compose.runtime.saveable.SaverScope +import org.junit.Assert.assertEquals +import org.junit.Test + +class ObserveDetailTargetSaverTest { + private val scope = SaverScope { true } + + private fun roundTrip(target: ObserveDetailTarget?): ObserveDetailTarget? { + val saved = with(ObserveDetailTargetSaver) { scope.save(target) } + return saved?.let(ObserveDetailTargetSaver::restore) + } + + @Test + fun `every detail target survives a save and restore`() { + val targets = + listOf( + ObserveDetailTarget.Net("tx-1"), + ObserveDetailTarget.Frame("socket-1", 1_700_000_000_123L), + ObserveDetailTarget.Push("fcm", "message-1", 42L), + ObserveDetailTarget.Push("fcm", null, 43L), + ObserveDetailTarget.Log("log-1"), + ObserveDetailTarget.Crash("crash-1"), + ObserveDetailTarget.RemoteConfigKey("firebase", "checkout|flag"), + ) + targets.forEach { target -> assertEquals(target, roundTrip(target)) } + } + + @Test + fun `no open detail restores as none`() { + assertEquals(null, roundTrip(null)) + } +} diff --git a/sdk/ui-views/build.gradle.kts b/sdk/ui-views/build.gradle.kts index eec5186..bcf74c1 100644 --- a/sdk/ui-views/build.gradle.kts +++ b/sdk/ui-views/build.gradle.kts @@ -4,7 +4,10 @@ plugins { id("devconsole.publishing") } -android { namespace = "io.devconsole.ui.views" } +android { + namespace = "io.devconsole.ui.views" + defaultConfig { consumerProguardFiles("consumer-rules.pro") } +} dependencies { api(project(":sdk:api")) diff --git a/sdk/ui-views/consumer-rules.pro b/sdk/ui-views/consumer-rules.pro new file mode 100644 index 0000000..03747a9 --- /dev/null +++ b/sdk/ui-views/consumer-rules.pro @@ -0,0 +1 @@ +-keep class io.devconsole.internal.enabled.UiViewsCaptureMarker { *; } diff --git a/sdk/ui-views/src/main/kotlin/io/devconsole/internal/enabled/UiViewsCaptureMarker.kt b/sdk/ui-views/src/main/kotlin/io/devconsole/internal/enabled/UiViewsCaptureMarker.kt new file mode 100644 index 0000000..f6e4dfa --- /dev/null +++ b/sdk/ui-views/src/main/kotlin/io/devconsole/internal/enabled/UiViewsCaptureMarker.kt @@ -0,0 +1,9 @@ +/** + * @author Shakib + * @since 04/11/26 + */ +package io.devconsole.internal.enabled + +internal object UiViewsCaptureMarker { + const val SIGNATURE = "DEVCONSOLE_ENABLED_UI_VIEWS_V1" +} diff --git a/settings.gradle.kts b/settings.gradle.kts index 7d0257b..c21c8da 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -30,6 +30,7 @@ include(":sdk:server-api") include(":sdk:server-ktor") include(":sdk:timeline") include(":sdk:logs") +include(":sdk:logs-timber") include(":sdk:network") include(":sdk:network-okhttp") include(":sdk:network-okhttp-noop")