-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathsession.ts
206 lines (177 loc) · 6.25 KB
/
session.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
/**
*
* 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 { SpanProcessor, WebTracerProvider } from '@opentelemetry/sdk-trace-web'
import { InternalEventTarget } from '../EventTarget'
import { generateId } from '../utils'
import { parseCookieToSessionState, renewCookieTimeout } from './cookie-session'
import { SessionState, SessionId } from './types'
import { getSessionStateFromLocalStorage, setSessionStateToLocalStorage } from './local-storage-session'
import { SESSION_INACTIVITY_TIMEOUT_MS } from './constants'
/*
The basic idea is to let the browser expire cookies for us "naturally" once
IntactivityTimeout is reached. Activity (including any page load)
extends the session. The true startTime of the session is set in the cookie value
and if an extension would ever exceed MaxAge it doesn't happen.
We use a background periodic timer to check for expired cookies and initialize new ones.
Session state is stored in the cookie as uriencoded json and is of the form
{
id: 'sessionIdAsHex',
startTime: startTimeAsNewDate_getTime
}
Future work can add more fields though note that the fact that the value doesn't change
once created makes this very robust when used in multiple tabs/windows - tabs don't compete/
race to do anything but set the max-age.
Finally, if SplunkRumNative exists, use its session ID exclusively and don't bother
with setting cookies, checking for inactivity, etc.
*/
let recentActivity = false
let cookieDomain: string
let eventTarget: InternalEventTarget | undefined
export function markActivity(): void {
recentActivity = true
}
function createSessionState(): SessionState {
return {
expiresAt: Date.now() + SESSION_INACTIVITY_TIMEOUT_MS,
id: generateId(128),
startTime: Date.now(),
}
}
export function getCurrentSessionState({ useLocalStorage = false, forceStoreRead = false }): SessionState | undefined {
return useLocalStorage
? getSessionStateFromLocalStorage({ forceStoreRead })
: parseCookieToSessionState({ forceStoreRead })
}
// This is called periodically and has two purposes:
// 1) Check if the cookie has been expired by the browser; if so, create a new one
// 2) If activity has occurred since the last periodic invocation, renew the cookie timeout
// (Only exported for testing purposes.)
export function getOrCreateSessionIdAndUpdateExpirationIfNecessary(
{
forceStore,
useLocalStorage,
forceActivity,
}: {
forceActivity?: boolean
forceStore: boolean
useLocalStorage: boolean
},
level = 0,
): string {
if (hasNativeSessionId()) {
return window['SplunkRumNative'].getNativeSessionId()
}
let sessionState = getCurrentSessionState({ useLocalStorage, forceStoreRead: forceStore })
let shouldForceWrite = false
if (!sessionState) {
// Check if another tab has created a new session
sessionState = getCurrentSessionState({ useLocalStorage, forceStoreRead: true })
if (!sessionState) {
sessionState = createSessionState()
recentActivity = true // force write of new cookie
shouldForceWrite = true
}
}
eventTarget?.emit('session-changed', { sessionId: sessionState.id })
if (recentActivity || forceActivity) {
sessionState.expiresAt = Date.now() + SESSION_INACTIVITY_TIMEOUT_MS
if (useLocalStorage) {
setSessionStateToLocalStorage(sessionState, { forceStoreWrite: shouldForceWrite || forceStore })
} else {
renewCookieTimeout(sessionState, cookieDomain, { forceStoreWrite: shouldForceWrite || forceStore })
}
}
recentActivity = false
// New session created, check if another tab has created a new session at the same time
if (shouldForceWrite && level < 1) {
return getOrCreateSessionIdAndUpdateExpirationIfNecessary(
{
forceStore: true,
useLocalStorage,
},
level + 1,
)
}
return sessionState.id
}
export function getCurrentSessionId({
forceStore,
useLocalStorage,
}: {
forceStore: boolean
useLocalStorage: boolean
}): string | undefined {
return getCurrentSessionState({ useLocalStorage, forceStoreRead: forceStore })?.id
}
function hasNativeSessionId(): boolean {
return typeof window !== 'undefined' && window['SplunkRumNative'] && window['SplunkRumNative'].getNativeSessionId
}
class SessionSpanProcessor implements SpanProcessor {
constructor(
private readonly options: {
allSpansAreActivity: boolean
useLocalStorage: boolean
},
) {}
forceFlush(): Promise<void> {
return Promise.resolve()
}
onEnd(): void {}
onStart(): void {
if (this.options.allSpansAreActivity) {
markActivity()
}
}
shutdown(): Promise<void> {
return Promise.resolve()
}
}
const ACTIVITY_EVENTS = ['click', 'scroll', 'mousedown', 'keydown', 'touchend', 'visibilitychange']
export function initSessionTracking(
provider: WebTracerProvider,
newEventTarget: InternalEventTarget,
domain?: string,
allSpansAreActivity = false,
useLocalStorage = false,
): { deinit: () => void } {
if (hasNativeSessionId()) {
// short-circuit and bail out - don't create cookie, watch for inactivity, or anything
return {
deinit: () => {},
}
}
if (domain) {
cookieDomain = domain
}
recentActivity = true // document loaded implies activity
eventTarget = newEventTarget
ACTIVITY_EVENTS.forEach((type) => document.addEventListener(type, markActivity, { capture: true, passive: true }))
provider.addSpanProcessor(new SessionSpanProcessor({ allSpansAreActivity, useLocalStorage }))
return {
deinit: () => {
ACTIVITY_EVENTS.forEach((type) => document.removeEventListener(type, markActivity))
eventTarget = undefined
},
}
}
export function getRumSessionId({ useLocalStorage }: { useLocalStorage: boolean }): SessionId | undefined {
if (hasNativeSessionId()) {
return window['SplunkRumNative'].getNativeSessionId()
}
return getCurrentSessionId({ useLocalStorage, forceStore: true })
}