Custom Metric for Activity Retry Attemps (Java)

Hi all,

I’m trying to emit a custom metric for a given activity’s attempt count via interceptors. I’ve written a small Kotlin interceptor, but I am unclear if this is “correct” implementation with respect to Temporal’s determinism constraints. Particularly, if I need to write the metrics scope within a Workflow.sideEffect(...).

Any feedback would be most appreciated!

class ActivityRetryCountInterceptor : WorkerInterceptorBase() {

    override fun interceptActivity(next: ActivityInboundCallsInterceptor): ActivityInboundCallsInterceptor {
        return RetryInterceptor(next)
    }
}


class RetryInterceptor(val next: ActivityInboundCallsInterceptor) : ActivityInboundCallsInterceptorBase(next) {

    companion object {
        private const val EVENT_TYPE = "temporal_activity_retry_count"
        private const val RUN_ID = "run_id"
        private const val WORKFLOW_ID = "workflow_id"
        private const val ACTIVITY_ID = "activity_id"
    }

    override fun init(context: ActivityExecutionContext?) {

        runCatching {
            val info = context?.info ?: return super.init(context)
            
            val attempts = info.attempt.toDouble()

            context.metricsScope?.tagged(info.extractTags())?.gauge(EVENT_TYPE)?.update(attempts)
        }

        super.init(context)
    }

    private fun ActivityInfo.extractTags(): Map<String, String> =
        mapOf(
            RUN_ID to this.runId,
            WORKFLOW_ID to this.workflowId,
            ACTIVITY_ID to this.activityId
        )
}