Sentry to Server / Electron / Android(untested)

This commit is contained in:
loucass003 committed 2026-09-29 23:35:39 +02:00
1 parent 87c9190354
commit a0c90f2355
75 files changed
+1964 -289

No files matched your search

@@ -9,6 +9,7 @@ import dev.slimevr.networkprofile.NetworkProfileManager
import dev.slimevr.provisioning.ProvisioningManager
import dev.slimevr.resets.ResetsManager
import dev.slimevr.routing.BoneRoutingManager
import dev.slimevr.sentry.ErrorReportingManager
import dev.slimevr.serial.SerialServer
import dev.slimevr.skeleton.Skeleton
import dev.slimevr.solarxr.rpc.ServerInfos
@@ -24,12 +25,14 @@ interface Phase1ContextProvider {
val server: VRServer
val config: AppConfig
val serialServer: SerialServer
val errorReporting: ErrorReportingManager
}
data class Phase1Context(
override val server: VRServer,
override val config: AppConfig,
override val serialServer: SerialServer,
override val errorReporting: ErrorReportingManager,
) : Phase1ContextProvider
interface AppContextProvider : Phase1ContextProvider {
@@ -59,6 +62,7 @@ class AppContext(
override val server: VRServer,
override val config: AppConfig,
override val serialServer: SerialServer,
override val errorReporting: ErrorReportingManager,
override val serverInfos: ServerInfos,
override val featureFlags: FeatureFlags,
override val keybindManager: KeybindManager,
@@ -9,19 +9,44 @@ import kotlinx.serialization.json.decodeFromJsonElement
import kotlinx.serialization.json.intOrNull
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import solarxr_protocol.rpc.ErrorReportingConsent
import java.util.UUID
private const val GLOBAL_CONFIG_VERSION = 1
private const val CURRENT_CONSENT_VERSION = 2
@Serializable
data class ErrorReportingConfig(
val consent: ErrorReportingConsent = ErrorReportingConsent.UNDECIDED,
/** Version of the consent text the user answered. So we can change the version and ask for consent again */
val consentVersion: Int = CURRENT_CONSENT_VERSION,
val userId: String = UUID.randomUUID().toString(),
)
fun effectiveConsent(config: ErrorReportingConfig): ErrorReportingConsent {
if (config.consent == ErrorReportingConsent.ALLOWED && config.consentVersion < CURRENT_CONSENT_VERSION) {
return ErrorReportingConsent.UNDECIDED
}
return config.consent
}
fun changeConsent(config: ErrorReportingConfig, consent: ErrorReportingConsent): ErrorReportingConfig {
val version = if (consent == ErrorReportingConsent.UNDECIDED) 0 else CURRENT_CONSENT_VERSION
return config.copy(consent = consent, consentVersion = version)
}
@Serializable
data class GlobalConfigState(
val selectedUserProfile: String = "default",
val selectedSettingsProfile: String = "default",
val errorReporting: ErrorReportingConfig = ErrorReportingConfig(),
val version: Int = GLOBAL_CONFIG_VERSION,
)
sealed interface GlobalConfigActions {
data class SetUserProfile(val name: String) : GlobalConfigActions
data class SetSettingsProfile(val name: String) : GlobalConfigActions
data class SetErrorReporting(val config: ErrorReportingConfig) : GlobalConfigActions
}
typealias GlobalConfigContext = Context<GlobalConfigState, GlobalConfigActions>
@@ -45,6 +70,8 @@ class GlobalConfig(
)
val globalConfig = GlobalConfig(context)
globalConfig.startObserving()
// Persists defaults filled on load (the generated userId), autosave skips the initial state
storage.write("global.json", jsonConfig.encodeToString(initialState))
launchAutosave(
scope = scope,
state = context.state,
@@ -85,6 +112,15 @@ class AppConfig(
settings.swap(name)
}
fun reset() {
settings.context.dispatch(SettingsActions.Update { SettingsConfigState() })
userConfig.context.dispatch(UserConfigActions.Update { UserConfigData() })
val errorReporting = globalConfig.context.state.value.errorReporting
globalConfig.context.dispatch(
GlobalConfigActions.SetErrorReporting(changeConsent(errorReporting, ErrorReportingConsent.UNDECIDED)),
)
}
companion object {
suspend fun create(scope: CoroutineScope, storage: ConfigStorage): AppConfig {
val globalConfig = GlobalConfig.create(scope, storage)
@@ -3,4 +3,5 @@ package dev.slimevr.config
fun reduce(state: GlobalConfigState, action: GlobalConfigActions): GlobalConfigState = when (action) {
is GlobalConfigActions.SetUserProfile -> state.copy(selectedUserProfile = action.name)
is GlobalConfigActions.SetSettingsProfile -> state.copy(selectedSettingsProfile = action.name)
is GlobalConfigActions.SetErrorReporting -> state.copy(errorReporting = action.config)
}
@@ -7,6 +7,8 @@ import dev.slimevr.VRServer
import dev.slimevr.config.UserConfig
import dev.slimevr.context.Behaviour
import dev.slimevr.context.Context
import dev.slimevr.sentry.ErrorReportingManager
import dev.slimevr.skeleton.reportProportionsMethodUsage
import io.github.axisangles.ktmath.Quaternion
import io.github.axisangles.ktmath.Vector3
import kotlinx.coroutines.CoroutineScope
@@ -47,6 +49,7 @@ class HeightCalibrationManager(
val context: HeightCalibrationContext,
val serverContext: VRServer,
private val userConfig: UserConfig,
private val errorReporting: ErrorReportingManager,
) {
fun startObserving() = context.observeAll(this)
@@ -89,7 +92,12 @@ class HeightCalibrationManager(
fun start() {
sessionJob?.cancel()
sessionJob = context.scope.launch { runCalibrationSession(context, userConfig, headUpdates, controllerUpdates) }
sessionJob = context.scope.launch {
runCalibrationSession(context, userConfig, headUpdates, controllerUpdates)
if (context.state.value.status == UserHeightCalibrationStatus.DONE) {
reportProportionsMethodUsage(errorReporting, "scaled", calibration = "auto")
}
}
}
fun cancel() {
@@ -110,7 +118,12 @@ class HeightCalibrationManager(
behaviours = listOf(BaseCalibrationBehaviour()),
name = "HeightCalibration",
)
return HeightCalibrationManager(context = context, serverContext = ctx.server, userConfig = ctx.config.userConfig)
return HeightCalibrationManager(
context = context,
serverContext = ctx.server,
userConfig = ctx.config.userConfig,
errorReporting = ctx.errorReporting,
)
}
}
}
@@ -1,11 +1,13 @@
package dev.slimevr.logging
import dev.slimevr.sentry.reportLog
import io.klogging.Level
import io.klogging.config.SinkConfiguration
import io.klogging.config.loggingConfiguration
import io.klogging.logger
import io.klogging.noCoLogger
import io.klogging.rendering.RENDER_SIMPLE
import io.klogging.sending.EventSender
import java.nio.file.Path
object AppLogger {
@@ -45,6 +47,11 @@ object AppLogger {
private const val CONSOLE_SINK = "console"
private const val FILE_SINK = "file"
private const val ERROR_REPORTS_SINK = "error-reports"
private val errorReportsSender = EventSender { batch ->
batch.forEach { reportLog(it.logger, it.level, it.message, it.stackTrace) }
}
suspend fun configureLogging(consoleSink: SinkConfiguration, logDirectory: Path?, minLevel: Level = Level.INFO) {
val fileSender = logDirectory?.let { runCatching { LogFileSender(it) } }
@@ -52,11 +59,13 @@ suspend fun configureLogging(consoleSink: SinkConfiguration, logDirectory: Path?
loggingConfiguration {
sink(CONSOLE_SINK, consoleSink)
fileSender?.getOrNull()?.let { sink(FILE_SINK, RENDER_SIMPLE, it) }
sink(ERROR_REPORTS_SINK, SinkConfiguration(eventSender = errorReportsSender))
logging {
fromMinLevel(minLevel) {
toSink(CONSOLE_SINK)
if (fileSender?.isSuccess == true) toSink(FILE_SINK)
}
fromMinLevel(Level.WARN) { toSink(ERROR_REPORTS_SINK) }
}
}
@@ -9,6 +9,7 @@ import dev.slimevr.config.SettingsActions
import dev.slimevr.context.Behaviour
import dev.slimevr.context.Context
import dev.slimevr.logging.AppLogger
import dev.slimevr.sentry.ErrorReportingManager
import dev.slimevr.skeleton.Skeleton
import dev.slimevr.skeleton.SkeletonActions
import dev.slimevr.tracker.Tracker
@@ -52,7 +53,13 @@ sealed interface ResetsActions {
typealias ResetsContext = Context<ResetsState, ResetsActions>
typealias ResetsBehaviour = Behaviour<ResetsManager>
class ResetsManager(val context: ResetsContext, val server: VRServer, val settings: Settings, val skeleton: Skeleton) {
class ResetsManager(
val context: ResetsContext,
val server: VRServer,
val settings: Settings,
val skeleton: Skeleton,
private val errorReporting: ErrorReportingManager,
) {
fun startObserving() = context.observeAll(this)
private var resetJob: Job = Job()
@@ -64,6 +71,18 @@ class ResetsManager(val context: ResetsContext, val server: VRServer, val settin
* If bodyParts is null, resets all trackers.
*/
suspend fun scheduleReset(resetSourceName: String, resetType: ResetType, delay: Float = 0f, bodyParts: List<BodyPart>? = null) {
errorReporting.reportUsage(
"reset",
mapOf(
"resetType" to resetType.name,
// SolarXR sources are named per connection "SolarXR[3]"
"source" to resetSourceName.substringBefore('['),
"bodyParts" to (bodyParts?.map { it.name }?.sorted()?.joinToString(",") ?: "all"),
),
)
if (resetType == ResetType.POSE_MOUNTING) {
errorReporting.reportUsageOncePerSession("mounting_method_used", mapOf("method" to "auto"))
}
resetJob.cancelAndJoin()
resetJob = context.scope.launch {
val delayMs = (delay * 1000).toInt()
@@ -276,7 +295,7 @@ class ResetsManager(val context: ResetsContext, val server: VRServer, val settin
behaviours = listOf(ResetsMountingTimeoutBehaviour()),
name = "ResetsManager",
)
return ResetsManager(context, ctx.server, ctx.config.settings, skeleton)
return ResetsManager(context, ctx.server, ctx.config.settings, skeleton, ctx.errorReporting)
}
}
}
@@ -0,0 +1,33 @@
package dev.slimevr.sentry
import dev.slimevr.config.GlobalConfig
import dev.slimevr.config.effectiveConsent
import io.sentry.Sentry
import io.sentry.protocol.User
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.onEach
class ErrorReportingConsentSyncBehaviour(private val globalConfig: GlobalConfig) : ErrorReportingBehaviour {
override fun observe(receiver: ErrorReportingManager) {
globalConfig.context.state
.map { effectiveConsent(it.errorReporting) to it.errorReporting.userId }
.distinctUntilChanged()
.onEach { (consent, userId) -> receiver.context.dispatch(ErrorReportingActions.SetConsent(consent, userId)) }
.launchIn(receiver.context.scope)
}
}
class ErrorReportingSentryBehaviour : ErrorReportingBehaviour {
override fun observe(receiver: ErrorReportingManager) {
receiver.context.state
.map { it.consent to it.userId }
.distinctUntilChanged()
.onEach { (consent, userId) ->
Sentry.setUser(User().apply { id = userId })
receiver.gate.apply(consent)
}
.launchIn(receiver.context.scope)
}
}
@@ -0,0 +1,119 @@
package dev.slimevr.sentry
import dev.slimevr.config.GlobalConfig
import dev.slimevr.config.effectiveConsent
import dev.slimevr.context.Behaviour
import dev.slimevr.context.Context
import io.sentry.AsyncHttpTransportFactory
import io.sentry.Hint
import io.sentry.Sentry
import io.sentry.SentryAttributeType
import io.sentry.SentryEnvelope
import io.sentry.SentryLogEventAttributeValue
import io.sentry.SentryOptions
import io.sentry.metrics.SentryMetricsParameters
import io.sentry.transport.ITransport
import kotlinx.coroutines.CoroutineScope
import solarxr_protocol.rpc.ErrorReportingConsent
import java.util.UUID
private const val HELD_LIMIT = 500
data class ReportedUsage(
val name: String,
val attributes: Map<String, Any?>,
)
data class ErrorReportingState(
val sessionId: String,
val consent: ErrorReportingConsent,
val userId: String,
val reportedUsages: Set<ReportedUsage>,
)
sealed interface ErrorReportingActions {
data class SetConsent(val consent: ErrorReportingConsent, val userId: String) : ErrorReportingActions
data class MarkUsageReported(val usage: ReportedUsage) : ErrorReportingActions
}
typealias ErrorReportingContext = Context<ErrorReportingState, ErrorReportingActions>
typealias ErrorReportingBehaviour = Behaviour<ErrorReportingManager>
internal class HeldEnvelope(val envelope: SentryEnvelope, val hint: Hint, val transport: ITransport)
class ErrorReportingManager(
val context: ErrorReportingContext,
) {
internal val gate = ConsentGate<HeldEnvelope>(HELD_LIMIT) { it.transport.send(it.envelope, it.hint) }
fun startObserving() = context.observeAll(this)
@Suppress("UnstableApiUsage")
fun init(
dsn: String,
release: String,
environment: String,
tags: Map<String, String>,
initSentry: (configure: (SentryOptions) -> Unit) -> Unit = { configure -> Sentry.init { configure(it) } },
) {
if (dsn.isBlank() || release.isBlank()) return
val sessionId = context.state.value.sessionId
initSentry { options ->
options.dsn = dsn
options.release = release
options.environment = environment
options.setTransportFactory { transportOptions, requestDetails ->
val inner = AsyncHttpTransportFactory().create(transportOptions, requestDetails)
object : ITransport {
override fun send(envelope: SentryEnvelope, hint: Hint) = gate.offer(HeldEnvelope(envelope, hint, inner))
override fun isHealthy() = inner.isHealthy
override fun flush(timeoutMillis: Long) = inner.flush(timeoutMillis)
override fun getRateLimiter() = inner.rateLimiter
override fun close(isRestarting: Boolean) = inner.close(isRestarting)
override fun close() = inner.close()
}
}
options.isEnableUncaughtExceptionHandler = false
options.isSendDefaultPii = false
options.logs.isEnabled = true
options.logs.beforeSend = SentryOptions.Logs.BeforeSendLogCallback { log ->
log.setAttribute("session_id", SentryLogEventAttributeValue(SentryAttributeType.STRING, sessionId))
log
}
}
tags.forEach { (key, value) -> Sentry.setTag(key, value) }
Sentry.setTag("session_id", sessionId)
}
fun reportUsage(name: String, attributes: Map<String, Any?> = emptyMap()) {
val present = attributes.mapNotNull { (key, value) -> value?.let { key to it } }.toMap()
Sentry.metrics().count(name, 1.0, null, SentryMetricsParameters.create(present))
}
fun reportUsageOncePerSession(name: String, attributes: Map<String, Any?> = emptyMap()) {
val usage = ReportedUsage(name, attributes)
if (usage in context.state.value.reportedUsages) return
context.dispatch(ErrorReportingActions.MarkUsageReported(usage))
reportUsage(name, attributes)
}
companion object {
fun create(scope: CoroutineScope, globalConfig: GlobalConfig): ErrorReportingManager {
val stored = globalConfig.context.state.value.errorReporting
val context = Context.create(
initialState = ErrorReportingState(
sessionId = UUID.randomUUID().toString(),
consent = effectiveConsent(stored),
userId = stored.userId,
reportedUsages = emptySet(),
),
scope = scope,
reducer = ::reduce,
behaviours = listOf(ErrorReportingConsentSyncBehaviour(globalConfig), ErrorReportingSentryBehaviour()),
name = "ErrorReportingManager",
)
return ErrorReportingManager(context)
}
}
}
@@ -0,0 +1,6 @@
package dev.slimevr.sentry
fun reduce(state: ErrorReportingState, action: ErrorReportingActions): ErrorReportingState = when (action) {
is ErrorReportingActions.SetConsent -> state.copy(consent = action.consent, userId = action.userId)
is ErrorReportingActions.MarkUsageReported -> state.copy(reportedUsages = state.reportedUsages + action.usage)
}
@@ -0,0 +1,71 @@
package dev.slimevr.sentry
import io.klogging.Level
import io.sentry.Breadcrumb
import io.sentry.Sentry
import io.sentry.SentryAttributes
import io.sentry.SentryLevel
import io.sentry.SentryLogLevel
import io.sentry.logger.SentryLogParameters
import solarxr_protocol.rpc.ErrorReportingConsent
internal class ConsentGate<T>(
private val capacity: Int,
private val forward: (T) -> Unit,
) {
private val lock = Any()
private var consent = ErrorReportingConsent.UNDECIDED
private val held = ArrayDeque<T>()
fun offer(item: T) {
val send = synchronized(lock) {
if (consent == ErrorReportingConsent.UNDECIDED) {
if (held.size >= capacity) held.removeFirst()
held.addLast(item)
}
consent == ErrorReportingConsent.ALLOWED
}
if (send) forward(item)
}
fun apply(newConsent: ErrorReportingConsent) {
val toSend = synchronized(lock) {
consent = newConsent
val toSend = if (newConsent == ErrorReportingConsent.ALLOWED) held.toList() else emptyList()
if (newConsent != ErrorReportingConsent.UNDECIDED) held.clear()
toSend
}
toSend.forEach(forward)
}
}
private fun toSentryLevel(level: Level): SentryLevel = when (level) {
Level.FATAL -> SentryLevel.FATAL
Level.ERROR -> SentryLevel.ERROR
Level.WARN -> SentryLevel.WARNING
Level.INFO -> SentryLevel.INFO
else -> SentryLevel.DEBUG
}
fun reportError(throwable: Throwable, tags: Map<String, String> = emptyMap()) {
Sentry.captureException(throwable) { scope -> tags.forEach { (key, value) -> scope.setTag(key, value) } }
}
fun reportLog(logger: String, level: Level, message: String, stackTrace: String?) {
Sentry.addBreadcrumb(
Breadcrumb().apply {
category = logger
this.level = toSentryLevel(level)
this.message = message
},
)
val attributes = buildMap<String, Any> {
put("logger", logger)
stackTrace?.let { put("stack_trace", it) }
}
Sentry.logger().log(SentryLogLevel.valueOf(level.name), SentryLogParameters.create(SentryAttributes.fromMap(attributes)), message)
}
fun flushErrorReports(timeoutMillis: Long) = Sentry.flush(timeoutMillis)
fun closeErrorReporting() = Sentry.close()
@@ -0,0 +1,69 @@
package dev.slimevr.sentry
import dev.slimevr.AppContextProvider
import io.sentry.EventProcessor
import io.sentry.Hint
import io.sentry.Sentry
import io.sentry.SentryEvent
fun registerErrorReportSnapshots(appContext: AppContextProvider) {
addReportSnapshot("trackers") {
val trackers = appContext.server.context.state.value.trackers.values.map { tracker ->
val state = tracker.context.state.value
mapOf(
"id" to state.id,
"deviceId" to state.deviceId,
"origin" to state.origin.name,
"driverName" to state.driverName,
"imuType" to state.imuType?.name,
"bodyPart" to state.bodyPart?.name,
)
}
mapOf("count" to trackers.size, "trackers" to trackers)
}
addReportSnapshot("devices") {
val devices = appContext.server.context.state.value.devices.values.map { device ->
val state = device.context.state.value
mapOf(
"id" to state.id,
"origin" to state.origin.name,
"boardType" to state.boardType.name,
"mcuType" to state.mcuType.name,
"firmwareVersion" to state.firmwareVersion,
"protocolVersion" to state.protocolVersion,
"status" to state.status.name,
)
}
mapOf("count" to devices.size, "devices" to devices)
}
addReportSnapshot("skeleton") {
val user = appContext.config.userConfig.context.state.value.data
mapOf("userHeight" to user.userHeight, "proportions" to user.proportions)
}
addReportSnapshot("features") {
val flags = appContext.featureFlags
mapOf(
"steam" to flags.steam,
"supportsDriver" to flags.supportsDriver,
"keybindSupport" to flags.keybindSupport.name,
"solarxrConnections" to appContext.server.context.state.value.solarxr.size,
"dongles" to appContext.server.context.state.value.dongles.size,
)
}
}
private fun addReportSnapshot(key: String, provider: () -> Map<String, Any?>) {
Sentry.configureScope { scope ->
scope.addEventProcessor(
object : EventProcessor {
override fun process(event: SentryEvent, hint: Hint): SentryEvent {
event.contexts.put(key, provider())
return event
}
},
)
}
}
@@ -1,5 +1,6 @@
package dev.slimevr.skeleton
import dev.slimevr.sentry.ErrorReportingManager
import dev.slimevr.vrchat.EYE_HEIGHT_TO_HEIGHT_RATIO
import io.github.axisangles.ktmath.Vector3
import io.github.axisangles.ktmath.times
@@ -433,3 +434,7 @@ private fun getToeHeadOffsets(footLength: Float): Map<BodyPart, Vector3> = build
put(toe.segments.second, Vector3(-k.x * footLength, k.y * footLength, k.z * footLength))
}
}
fun reportProportionsMethodUsage(errorReporting: ErrorReportingManager, method: String, calibration: String? = null) {
errorReporting.reportUsageOncePerSession("proportions_method_used", mapOf("method" to method, "calibration" to calibration))
}
@@ -16,6 +16,7 @@ import dev.slimevr.solarxr.rpc.BoneRoutingBehaviour
import dev.slimevr.solarxr.rpc.BvhBehaviour
import dev.slimevr.solarxr.rpc.DongleSettingsBehaviour
import dev.slimevr.solarxr.rpc.DriverSettingsBehaviour
import dev.slimevr.solarxr.rpc.ErrorReportingSettingsBehaviour
import dev.slimevr.solarxr.rpc.FirmwareBehaviour
import dev.slimevr.solarxr.rpc.HIDSettingsBehaviour
import dev.slimevr.solarxr.rpc.HeightCalibrationBehaviour
@@ -28,6 +29,7 @@ import dev.slimevr.solarxr.rpc.ResetsBehaviour
import dev.slimevr.solarxr.rpc.SerialBehaviour
import dev.slimevr.solarxr.rpc.ServerInfosBehaviour
import dev.slimevr.solarxr.rpc.SessionCalibrationBehaviour
import dev.slimevr.solarxr.rpc.SettingsResetBehaviour
import dev.slimevr.solarxr.rpc.SkeletonProportionsBehaviour
import dev.slimevr.solarxr.rpc.SkeletonSettingsBehaviour
import dev.slimevr.solarxr.rpc.StayAlignedBehaviour
@@ -191,10 +193,12 @@ class SolarXRBridge(
add(BoneRoutingBehaviour(appContext))
add(DriverSettingsBehaviour(appContext))
add(HIDSettingsBehaviour(appContext.config.settings))
add(ErrorReportingSettingsBehaviour(appContext.config.globalConfig, appContext.errorReporting))
add(SettingsResetBehaviour(appContext.config))
add(SkeletonSettingsBehaviour(appContext.config.settings))
add(SkeletonProportionsBehaviour(appContext.config.userConfig, appContext.skeleton))
add(TrackingChecklistBehaviour(appContext.trackingChecklist, appContext.config.settings))
add(AssignTrackerBehaviour(appContext.server))
add(SkeletonProportionsBehaviour(appContext.config.userConfig, appContext.skeleton, appContext.errorReporting))
add(TrackingChecklistBehaviour(appContext.trackingChecklist, appContext.config.settings, appContext.errorReporting))
add(AssignTrackerBehaviour(appContext.server, appContext.errorReporting))
add(DongleSettingsBehaviour(appContext.server))
add(TelemetryBehaviour(appContext.server))
add(DriverHandshakeBehaviour(appContext))
@@ -0,0 +1,46 @@
package dev.slimevr.solarxr.rpc
import dev.slimevr.config.GlobalConfig
import dev.slimevr.config.GlobalConfigActions
import dev.slimevr.config.changeConsent
import dev.slimevr.sentry.ErrorReportingManager
import dev.slimevr.sentry.ErrorReportingState
import dev.slimevr.solarxr.SolarXRBridge
import dev.slimevr.solarxr.SolarXRBridgeBehaviour
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.drop
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.onEach
import solarxr_protocol.rpc.ChangeErrorReportingSettingsRequest
import solarxr_protocol.rpc.ErrorReportingSettingsRequest
import solarxr_protocol.rpc.ErrorReportingSettingsResponse
private fun buildResponse(state: ErrorReportingState) = ErrorReportingSettingsResponse(
consent = state.consent,
userId = state.userId,
sessionId = state.sessionId,
)
class ErrorReportingSettingsBehaviour(
private val globalConfig: GlobalConfig,
private val errorReporting: ErrorReportingManager,
) : SolarXRBridgeBehaviour {
override fun observe(receiver: SolarXRBridge) {
receiver.rpcDispatcher.on<ErrorReportingSettingsRequest> {
receiver.sendRpc(buildResponse(errorReporting.context.state.value))
}.launchIn(receiver.context.scope)
errorReporting.context.state
.drop(1)
.map(::buildResponse)
.distinctUntilChanged()
.onEach(receiver::sendRpc)
.launchIn(receiver.context.scope)
receiver.rpcDispatcher.on<ChangeErrorReportingSettingsRequest> { req ->
val current = globalConfig.context.state.value.errorReporting
globalConfig.context.dispatch(GlobalConfigActions.SetErrorReporting(changeConsent(current, req.consent)))
}.launchIn(receiver.context.scope)
}
}
@@ -0,0 +1,14 @@
package dev.slimevr.solarxr.rpc
import dev.slimevr.config.AppConfig
import dev.slimevr.solarxr.SolarXRBridge
import dev.slimevr.solarxr.SolarXRBridgeBehaviour
import solarxr_protocol.rpc.SettingsResetRequest
class SettingsResetBehaviour(
private val config: AppConfig,
) : SolarXRBridgeBehaviour {
override fun observe(receiver: SolarXRBridge) {
receiver.rpcDispatcher.on<SettingsResetRequest> { config.reset() }.launchIn(receiver.context.scope)
}
}
@@ -2,6 +2,7 @@ package dev.slimevr.solarxr.rpc
import dev.slimevr.config.UserConfig
import dev.slimevr.config.UserConfigActions
import dev.slimevr.sentry.ErrorReportingManager
import dev.slimevr.skeleton.ALL_BODY_PARTS
import dev.slimevr.skeleton.BONE_SPECS
import dev.slimevr.skeleton.BodyPartMap
@@ -11,6 +12,7 @@ import dev.slimevr.skeleton.clampBoneValue
import dev.slimevr.skeleton.computeAllDefaultProportionsByBone
import dev.slimevr.skeleton.computeDefaultProportionsByBone
import dev.slimevr.skeleton.height
import dev.slimevr.skeleton.reportProportionsMethodUsage
import dev.slimevr.skeleton.toBoneValues
import dev.slimevr.solarxr.SolarXRBridge
import dev.slimevr.solarxr.SolarXRBridgeBehaviour
@@ -32,6 +34,7 @@ private const val MIN_HEIGHT = 0.9f
class SkeletonProportionsBehaviour(
private val userConfig: UserConfig,
private val skeleton: Skeleton,
private val errorReporting: ErrorReportingManager,
) : SolarXRBridgeBehaviour {
private fun buildConfigResponse(boneInputs: InputSkeleton): SkeletonProportionsResponse {
val tailOffsets = BodyPartMap(boneInputs.mapValues { it.value.offset })
@@ -73,6 +76,7 @@ class SkeletonProportionsBehaviour(
copy(userHeight = height, proportions = computeDefaultProportionsByBone(height))
},
)
reportProportionsMethodUsage(errorReporting, "scaled", calibration = "manual")
}
}.launchIn(receiver.context.scope)
@@ -90,6 +94,7 @@ class SkeletonProportionsBehaviour(
val value = clampBoneValue(bone, req.value)
userConfig.context.dispatch(UserConfigActions.Update { copy(proportions = proportions + (bone.name to value)) })
reportProportionsMethodUsage(errorReporting, "manual")
}.launchIn(receiver.context.scope)
}
}
@@ -1,6 +1,7 @@
package dev.slimevr.solarxr.rpc
import dev.slimevr.VRServer
import dev.slimevr.sentry.ErrorReportingManager
import dev.slimevr.skeleton.bodyPartMap
import dev.slimevr.solarxr.SolarXRBridge
import dev.slimevr.solarxr.SolarXRBridgeBehaviour
@@ -15,6 +16,7 @@ import solarxr_protocol.rpc.UpdateTrackerRequest
class AssignTrackerBehaviour(
private val server: VRServer,
private val errorReporting: ErrorReportingManager,
) : SolarXRBridgeBehaviour {
override fun observe(receiver: SolarXRBridge) {
receiver.rpcDispatcher.on<UpdateTrackerRequest> { req ->
@@ -53,9 +55,14 @@ class AssignTrackerBehaviour(
// Override default mounting orientation set from changing the bodyPart
val mountingOrientation = req.mountingOrientation?.let { Quaternion(it.w, it.x, it.y, it.z) }
if (mountingOrientation != null) {
val current = tracker.context.state.value.mountingOrientation
tracker.context.dispatch(
TrackerActions.SetMountingOrientation(mountingOrientation),
)
// Assignment re-sends the current orientation. So we make sure it didnt change
if (current.angleToR(mountingOrientation) > 0.1f) {
errorReporting.reportUsageOncePerSession("mounting_method_used", mapOf("method" to "manual"))
}
}
}.launchIn(receiver.context.scope)
@@ -2,6 +2,7 @@ package dev.slimevr.solarxr.rpc
import dev.slimevr.config.Settings
import dev.slimevr.config.SettingsActions
import dev.slimevr.sentry.ErrorReportingManager
import dev.slimevr.solarxr.SolarXRBridge
import dev.slimevr.solarxr.SolarXRBridgeBehaviour
import dev.slimevr.trackingchecklist.TrackingChecklist
@@ -39,6 +40,7 @@ private fun stepOrder(id: TrackingChecklistStepId): Int {
class TrackingChecklistBehaviour(
private val checklist: TrackingChecklist,
private val settings: Settings,
private val errorReporting: ErrorReportingManager,
) : SolarXRBridgeBehaviour {
private fun parseMutedSteps(): Set<TrackingChecklistStepId> = settings.context.state.value.data.mutedChecklistSteps
@@ -71,6 +73,10 @@ class TrackingChecklistBehaviour(
val stepId = req.stepId
if (stepId == TrackingChecklistStepId.UNKNOWN) return@on
val name = stepId.name
errorReporting.reportUsage(
if (req.ignore) "mute_checklist_step" else "unmute_checklist_step",
mapOf("step" to name, "session" to false),
)
settings.context.dispatch(
SettingsActions.Update {
copy(mutedChecklistSteps = if (req.ignore) mutedChecklistSteps + name else mutedChecklistSteps - name)
@@ -1,43 +1,33 @@
package dev.slimevr.util
import dev.slimevr.logging.AppLogger
import dev.slimevr.sentry.flushErrorReports
import dev.slimevr.sentry.reportError
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.CoroutineName
import kotlin.coroutines.CoroutineContext
private const val UNCAUGHT_FLUSH_TIMEOUT_MS = 2000L
/**
* Reports every coroutine failure that nothing else handled.
*
* Install it in the context of the application's root scope. A [CoroutineExceptionHandler] is
* looked up in the context of the coroutine that *finishes* the exception, and coroutine context
* is inherited, so a single handler at the root is found by everything underneath it.
*
* It fires for coroutines that finish an exception themselves: a root coroutine, or a direct
* child of a `SupervisorJob` -- which is what every [dev.slimevr.context.Context] scope is, so
* every behaviour listener lands here.
*
* Cancellation is never reported: coroutines cancelled as a *consequence* of another failure
* carry a [kotlinx.coroutines.CancellationException] and are not passed to a handler at all.
* Reports coroutine failures nothing else handled. Install it in the root scope's context: every
* [dev.slimevr.context.Context] scope is a `SupervisorJob` child, so behaviour failures land here.
*/
val appCoroutineExceptionHandler = CoroutineExceptionHandler { context, throwable ->
AppLogger.coroutines.error(throwable, "Unhandled exception in coroutine (scope: ${context.scopeName})")
reportError(throwable, mapOf("scope" to context.scopeName))
}
private val CoroutineContext.scopeName: String
get() = this[CoroutineName]?.name ?: "unnamed"
/**
* Routes failures on threads that coroutines do not own -- JNA callbacks, JmDNS, serial reader
* threads -- into the same log, instead of the JVM dumping them on stderr where nothing collects
* them.
*
* Chains to any previously installed handler. The JVM installs none by default, so normally this
* replaces the stderr dump rather than adding to it.
*/
/** Reports failures on threads coroutines don't own (JNA callbacks, JmDNS, serial readers) */
fun installUncaughtExceptionReporting() {
val previous = Thread.getDefaultUncaughtExceptionHandler()
Thread.setDefaultUncaughtExceptionHandler { thread, throwable ->
AppLogger.coroutines.error(throwable, "Unhandled exception on thread ${thread.name}")
reportError(throwable, mapOf("thread" to thread.name))
flushErrorReports(UNCAUGHT_FLUSH_TIMEOUT_MS)
previous?.uncaughtException(thread, throwable)
}
}