Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: user tracking #949

Draft
wants to merge 9 commits into
base: main
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion packages/session-recorder/src/index.ts
Original file line number Diff line number Diff line change
@@ -196,10 +196,16 @@ const SplunkRumRecorder = {
debug,
headers,
getResourceAttributes() {
return {
const newAttributes = {
...resource.attributes,
'splunk.rumSessionId': SplunkRum.getSessionId(),
}
const anonymousId = SplunkRum.getAnonymousId()
if (anonymousId) {
newAttributes['user.anonymousId'] = anonymousId
}

return newAttributes
},
})
const processor = new BatchLogProcessor(exporter, {})
11 changes: 11 additions & 0 deletions packages/web/src/SplunkSpanAttributesProcessor.ts
Original file line number Diff line number Diff line change
@@ -19,13 +19,16 @@
import { Attributes } from '@opentelemetry/api'
import { Span, SpanProcessor } from '@opentelemetry/sdk-trace-base'
import { getRumSessionId } from './session'
import { forgetAnonymousId, getOrCreateAnonymousId } from './user-tracking'
import { SplunkOtelWebConfig } from './types/config'

export class SplunkSpanAttributesProcessor implements SpanProcessor {
private readonly _globalAttributes: Attributes

constructor(
globalAttributes: Attributes,
private useLocalStorageForSessionMetadata: boolean,
private getUserTracking: () => SplunkOtelWebConfig['user']['trackingMode'],
) {
this._globalAttributes = globalAttributes ?? {}
}
@@ -49,6 +52,13 @@ export class SplunkSpanAttributesProcessor implements SpanProcessor {
'splunk.rumSessionId',
getRumSessionId({ useLocalStorage: this.useLocalStorageForSessionMetadata }),
)
if (this.getUserTracking() === 'anonymousTracking') {
span.setAttribute(
'user.anonymousId',
getOrCreateAnonymousId({ useLocalStorage: this.useLocalStorageForSessionMetadata }),
)
}

span.setAttribute('browser.instance.visibility_state', document.visibilityState)
}

@@ -63,6 +73,7 @@ export class SplunkSpanAttributesProcessor implements SpanProcessor {
}

shutdown(): Promise<void> {
forgetAnonymousId()
return Promise.resolve()
}
}
19 changes: 19 additions & 0 deletions packages/web/src/index.ts
Original file line number Diff line number Diff line change
@@ -66,6 +66,7 @@ import { registerGlobal, unregisterGlobal } from './global-utils'
import { BrowserInstanceService } from './services/BrowserInstanceService'
import { SessionId } from './session'
import { SplunkOtelWebConfig, SplunkOtelWebExporterOptions, SplunkOtelWebOptionsInstrumentations } from './types'
import { forgetAnonymousId, getOrCreateAnonymousId } from './user-tracking'
import { isBot } from './utils/is-bot'

export { type SplunkExporterConfig } from './exporters/common'
@@ -220,6 +221,8 @@ export interface SplunkOtelWebType extends SplunkOtelWebEventTarget {

error: (...args: Array<any>) => void

getAnonymousId: () => string | undefined

/**
* This method provides access to computed, final value of global attributes, which are applied to all created spans.
*/
@@ -239,9 +242,12 @@ export interface SplunkOtelWebType extends SplunkOtelWebEventTarget {
readonly resource?: Resource

setGlobalAttributes: (attributes: Attributes) => void

setUserTrackingMode: (mode: SplunkOtelWebConfig['user']['trackingMode']) => void
}

let inited = false
let userTrackingMode: SplunkOtelWebConfig['user']['trackingMode'] = 'noTracking'
let _deregisterInstrumentations: () => void | undefined
let _deinitSessionTracking: () => void | undefined
let _errorInstrumentation: SplunkErrorInstrumentation | undefined
@@ -271,6 +277,7 @@ export const SplunkRum: SplunkOtelWebType = {
},

init: function (options) {
userTrackingMode = options.user?.trackingMode ?? 'noTracking'
// "env" based config still a bad idea for web
if (!('OTEL_TRACES_EXPORTER' in _globalThis)) {
_globalThis.OTEL_TRACES_EXPORTER = 'none'
@@ -426,6 +433,7 @@ export const SplunkRum: SplunkOtelWebType = {
...(processedOptions.globalAttributes || {}),
},
this._processedOptions.persistence === 'localStorage',
() => userTrackingMode,
)
provider.addSpanProcessor(this.attributesProcessor)

@@ -496,6 +504,7 @@ export const SplunkRum: SplunkOtelWebType = {
unregisterGlobal('splunk.rum')
unregisterGlobal('splunk.rum.version')

forgetAnonymousId()
inited = false
},

@@ -544,6 +553,16 @@ export const SplunkRum: SplunkOtelWebType = {
return this.removeEventListener(name, callback)
},

setUserTrackingMode(mode: SplunkOtelWebConfig['user']['trackingMode']) {
userTrackingMode = mode
},

getAnonymousId() {
if (userTrackingMode === 'anonymousTracking') {
return getOrCreateAnonymousId({ useLocalStorage: this._processedOptions.persistence === 'localStorage' })
}
},

getSessionId() {
if (!inited) {
return undefined
5 changes: 5 additions & 0 deletions packages/web/src/types/config.ts
Original file line number Diff line number Diff line change
@@ -172,6 +172,11 @@ export interface SplunkOtelWebConfig {
*/
tracer?: WebTracerConfig

user?: {
/** Sets tracking mode of user. Defaults to 'noTracking'. */
trackingMode?: 'noTracking' | 'anonymousTracking'
}

/**
* Sets a value for the 'app.version' attribute
*/
69 changes: 69 additions & 0 deletions packages/web/src/user-tracking/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
/**
*
* Copyright 2020-2025 Splunk Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
import { generateId } from '../utils'
import { safelyGetLocalStorage } from '../utils/storage'

const KEY = 'splunk.anonymousId'
let anonymousId: string | undefined

export const getOrCreateAnonymousId = ({ useLocalStorage }: { useLocalStorage: boolean }) => {
if (anonymousId) {
return anonymousId
}

const id = useLocalStorage ? getAnonymousIdFromLocalStorage() : getAnonymousIdFromCookie()
anonymousId = id
return id
}

export const forgetAnonymousId = () => {
anonymousId = undefined
}

const getAnonymousIdFromLocalStorage = () => {
const lsValue = safelyGetLocalStorage(KEY)
if (lsValue) {
return lsValue
}

const newId = generateAnonymousId()
localStorage.setItem(KEY, newId)
return newId
}

const getAnonymousIdFromCookie = () => {
const cookieValue = document.cookie
.split('; ')
.find((row) => row.startsWith(KEY + '='))
?.split('=')[1]

if (cookieValue) {
setCookie(cookieValue)
return cookieValue
}

const newId = generateAnonymousId()
setCookie(newId)
return newId
}

const generateAnonymousId = () => generateId(128)

const setCookie = (newId: string) => {
document.cookie = `${KEY}=${newId}; max-age=${60 * 60 * 24 * 400}`
}
2 changes: 2 additions & 0 deletions packages/web/tests/SplunkSpanAttributesProcessor.test.ts
Original file line number Diff line number Diff line change
@@ -27,6 +27,7 @@ describe('SplunkSpanAttributesProcessor', () => {
key1: 'value1',
},
false,
() => false,
)

expect(processor.getGlobalAttributes()).toStrictEqual({
@@ -41,6 +42,7 @@ describe('SplunkSpanAttributesProcessor', () => {
key2: 'value2',
},
false,
() => false,
)

processor.setGlobalAttributes({
102 changes: 102 additions & 0 deletions packages/web/tests/user-tracking.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
/**
*
* Copyright 2020-2025 Splunk Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/

import SplunkRum from '../src/index'
import * as tracing from '@opentelemetry/sdk-trace-base'
import { describe, it, expect, afterEach } from 'vitest'
import { deinit, initWithDefaultConfig, SpanCapturer } from './utils'

const createSpan = (tracer: tracing.Tracer) => {
const span = tracer.startSpan('testSpan')
span.end()
return span as tracing.Span
}

const getLocalStorage = () => localStorage.getItem('splunk.anonymousId')

const getCookie = () =>
document.cookie
.split('; ')
.find((row) => row.startsWith('splunk.anonymousId='))
?.split('=')[1]

describe('userTracking is reflected', () => {
const capturer = new SpanCapturer()

afterEach(() => {
deinit(true)
})

it('cookies/userTrackingMode is default, then anonymousTracking', () => {
initWithDefaultConfig(capturer)

const tracer = SplunkRum.provider.getTracer('test')
const spanWithoutAnonymousId = createSpan(tracer)
expect(spanWithoutAnonymousId.attributes['user.anonymousId'], 'Checking user.anonymousId').toBeUndefined()

SplunkRum.setUserTrackingMode('anonymousTracking')

const spanWithAnonymousId = createSpan(tracer)
const anonymousId = spanWithAnonymousId.attributes['user.anonymousId']
expect(anonymousId, 'Checking user.anonymousId').toBeDefined()
expect(getCookie(), 'Checking cookie value').equal(anonymousId)
})

it('cookies/userTrackingMode is anonymousTracking, then noTracking', () => {
initWithDefaultConfig(capturer, { user: { trackingMode: 'anonymousTracking' } })

const tracer = SplunkRum.provider.getTracer('test')
const spanWithAnonymousId = createSpan(tracer)
const anonymousId = spanWithAnonymousId.attributes['user.anonymousId']
expect(anonymousId, 'Checking user.anonymousId').toBeDefined()
expect(getCookie(), 'Checking cookie value').equal(anonymousId)

SplunkRum.setUserTrackingMode('noTracking')

const spanWithoutAnonymousId = createSpan(tracer)
expect(spanWithoutAnonymousId.attributes['user.anonymousId'], 'Checking user.anonymousId').toBeUndefined()
})

it('localStorage/userTrackingMode is anonymousTracking, then noTracking', () => {
initWithDefaultConfig(capturer, { user: { trackingMode: 'anonymousTracking' }, persistence: 'localStorage' })

const tracer = SplunkRum.provider.getTracer('test')
const spanWithAnonymousId = createSpan(tracer)
const anonymousId = spanWithAnonymousId.attributes['user.anonymousId']
expect(anonymousId, 'Checking user.anonymousId').toBe(getLocalStorage())

SplunkRum.setUserTrackingMode('noTracking')

const spanWithoutAnonymousId = createSpan(tracer)
expect(spanWithoutAnonymousId.attributes['user.anonymousId'], 'Checking user.anonymousId').toBeUndefined()
})

it('localStorage/userTrackingMode is default, then anonymousTracking', () => {
initWithDefaultConfig(capturer, { persistence: 'localStorage' })

const tracer = SplunkRum.provider.getTracer('test')
const spanWithoutAnonymousId = createSpan(tracer)
expect(spanWithoutAnonymousId.attributes['user.anonymousId'], 'Checking user.anonymousId').toBeUndefined()

SplunkRum.setUserTrackingMode('anonymousTracking')

const spanWithAnonymousId = createSpan(tracer)
const anonymousId = spanWithAnonymousId.attributes['user.anonymousId']
expect(anonymousId, 'Checking user.anonymousId').toBe(getLocalStorage())
})
})