forked from snowplow/snowplow-javascript-tracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
127 lines (114 loc) · 4.41 KB
/
Copy pathindex.ts
File metadata and controls
127 lines (114 loc) · 4.41 KB
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
import { CorePluginConfiguration, PayloadBuilder } from '@snowplow/tracker-core';
import { v4 as uuidv4 } from 'uuid';
import { BACKGROUND_EVENT_SCHEMA, CLIENT_SESSION_ENTITY_SCHEMA, FOREGROUND_EVENT_SCHEMA } from '../../constants';
import { AsyncStorage, SessionConfiguration, SessionState, TrackerConfiguration } from '../../types';
import { getUsefulSchema } from '../../utils';
interface StoredSessionState {
userId: string;
sessionId: string;
sessionIndex: number;
}
interface SessionPlugin extends CorePluginConfiguration {
getSessionUserId: () => Promise<string | undefined>;
getSessionId: () => Promise<string | undefined>;
getSessionIndex: () => Promise<number | undefined>;
getSessionState: () => Promise<SessionState>;
startNewSession: () => Promise<void>;
}
async function storeSessionState(namespace: string, state: StoredSessionState, asyncStorage: AsyncStorage) {
const { userId, sessionId, sessionIndex } = state;
await asyncStorage.setItem(`snowplow_${namespace}_session`, JSON.stringify({ userId, sessionId, sessionIndex }));
}
async function resumeStoredSession(namespace: string, asyncStorage: AsyncStorage): Promise<SessionState> {
const storedState = await asyncStorage.getItem(`snowplow_${namespace}_session`);
if (storedState) {
const state = JSON.parse(storedState) as StoredSessionState;
return {
userId: state.userId,
sessionId: uuidv4(),
previousSessionId: state.sessionId,
sessionIndex: state.sessionIndex + 1,
storageMechanism: 'LOCAL_STORAGE',
};
} else {
return {
userId: uuidv4(),
sessionId: uuidv4(),
sessionIndex: 1,
storageMechanism: 'LOCAL_STORAGE',
};
}
}
/**
* Creates a new session plugin for tracking the session information.
* The plugin will add the session context to all events and start a new session if the current one has timed out.
*
* The session state is stored in the defined application storage.
* Each restart of the app or creation of a new tracker instance will trigger a new session with reference to the previous session.
*/
export async function newSessionPlugin({
asyncStorage,
namespace,
sessionContext = true,
foregroundSessionTimeout,
backgroundSessionTimeout,
}: TrackerConfiguration & SessionConfiguration & { asyncStorage: AsyncStorage }): Promise<SessionPlugin> {
let sessionState = await resumeStoredSession(namespace, asyncStorage);
await storeSessionState(namespace, sessionState, asyncStorage);
let inBackground = false;
let lastUpdateTs = new Date().getTime();
const startNewSession = async () => {
sessionState = {
userId: sessionState.userId,
storageMechanism: sessionState.storageMechanism,
sessionId: uuidv4(),
sessionIndex: sessionState.sessionIndex + 1,
previousSessionId: sessionState.sessionId,
};
};
const getTimeoutMs = () => {
return ((inBackground ? backgroundSessionTimeout : foregroundSessionTimeout) ?? 30 * 60) * 1000;
};
const beforeTrack = (payloadBuilder: PayloadBuilder) => {
// check if session has timed out and start a new one if necessary
const now = new Date();
const timeDiff = now.getTime() - lastUpdateTs;
if (timeDiff > getTimeoutMs()) {
startNewSession();
storeSessionState(namespace, sessionState, asyncStorage);
}
lastUpdateTs = now.getTime();
// update event properties
sessionState.eventIndex = (sessionState.eventIndex ?? 0) + 1;
if (sessionState.eventIndex === 1) {
sessionState.firstEventId = payloadBuilder.getPayload().eid as string;
sessionState.firstEventTimestamp = now.toISOString();
}
// update background state
if (payloadBuilder.getPayload().e === 'ue') {
const schema = getUsefulSchema(payloadBuilder);
if (schema === FOREGROUND_EVENT_SCHEMA) {
inBackground = false;
} else if (schema === BACKGROUND_EVENT_SCHEMA) {
inBackground = true;
}
}
// add session context to the payload
if (sessionContext) {
payloadBuilder.addContextEntity({
schema: CLIENT_SESSION_ENTITY_SCHEMA,
data: { ...sessionState },
});
}
};
return {
getSessionUserId: () => Promise.resolve(sessionState.userId),
getSessionId: () => Promise.resolve(sessionState.sessionId),
getSessionIndex: () => Promise.resolve(sessionState.sessionIndex),
getSessionState: () => Promise.resolve(sessionState),
startNewSession,
plugin: {
beforeTrack,
},
};
}