-
Notifications
You must be signed in to change notification settings - Fork 204
Expand file tree
/
Copy pathAmplitudeSessionPlugin.tsx
More file actions
327 lines (280 loc) · 8.32 KB
/
AmplitudeSessionPlugin.tsx
File metadata and controls
327 lines (280 loc) · 8.32 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
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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
import {
EventPlugin,
EventType,
IdentifyEventType,
PluginType,
SegmentAPISettings,
SegmentEvent,
TrackEventType,
ScreenEventType,
GroupEventType,
UpdateType,
AliasEventType,
SegmentClient,
} from '@segment/analytics-react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { AppState } from 'react-native';
const MAX_SESSION_TIME_IN_MS = 300000;
const SESSION_ID_KEY = 'previous_session_id';
const EVENT_SESSION_ID_KEY = 'event_session_id';
const LAST_EVENT_TIME_KEY = 'last_event_time';
const AMP_SESSION_START_EVENT = 'session_start';
const AMP_SESSION_END_EVENT = 'session_end';
export class AmplitudeSessionPlugin extends EventPlugin {
type = PluginType.enrichment;
key = 'Actions Amplitude';
active = false;
private _sessionId = -1;
private _eventSessionId = -1;
private _lastEventTime = -1;
resetPending = false;
get eventSessionId() {
return this._eventSessionId;
}
set eventSessionId(value: number) {
this._eventSessionId = value;
if (value !== -1) {
AsyncStorage.setItem(EVENT_SESSION_ID_KEY, value.toString()).catch(
(err) =>
console.warn(
'[AmplitudeSessionPlugin] Failed to persist eventSessionId:',
err
)
);
}
}
get lastEventTime() {
return this._lastEventTime;
}
set lastEventTime(value: number) {
this._lastEventTime = value;
if (value !== -1) {
AsyncStorage.setItem(LAST_EVENT_TIME_KEY, value.toString()).catch((err) =>
console.warn(
'[AmplitudeSessionPlugin] Failed to persist lastEventTime:',
err
)
);
}
}
get sessionId() {
return this._sessionId;
}
set sessionId(value: number) {
this._sessionId = value;
if (value !== -1) {
AsyncStorage.setItem(SESSION_ID_KEY, value.toString()).catch((err) =>
console.warn(
'[AmplitudeSessionPlugin] Failed to persist sessionId:',
err
)
);
}
}
configure = async (analytics: SegmentClient): Promise<void> => {
this.analytics = analytics;
await this.loadSessionData();
AppState.addEventListener('change', this.handleAppStateChange);
};
update(settings: SegmentAPISettings, type: UpdateType) {
if (type !== UpdateType.initial) {
return;
}
this.active = settings.integrations?.hasOwnProperty(this.key) ?? false;
}
async execute(event: SegmentEvent) {
if (!this.active) {
return event;
}
if (this.sessionId === -1 || this.lastEventTime === -1) {
await this.loadSessionData();
}
await this.startNewSessionIfNecessary();
let result = event;
switch (result.type) {
case EventType.IdentifyEvent:
result = this.identify(result);
break;
case EventType.TrackEvent:
result = this.track(result);
break;
case EventType.ScreenEvent:
result = this.screen(result);
break;
case EventType.AliasEvent:
result = this.alias(result);
break;
case EventType.GroupEvent:
result = this.group(result);
break;
}
this.lastEventTime = Date.now();
//await this.saveSessionData();
return result;
}
identify(event: IdentifyEventType) {
return this.insertSession(event) as IdentifyEventType;
}
track(event: TrackEventType) {
const eventName = event.event;
if (eventName === AMP_SESSION_START_EVENT) {
this.resetPending = false;
this.eventSessionId = this.sessionId;
}
if (eventName === AMP_SESSION_END_EVENT) {
console.log(`[AmplitudeSession] EndSession = ${this.eventSessionId}`);
}
if (
eventName.startsWith('Amplitude') ||
eventName === AMP_SESSION_START_EVENT ||
eventName === AMP_SESSION_END_EVENT
) {
const integrations = this.disableAllIntegrations(event.integrations);
return {
...event,
integrations: {
...integrations,
[this.key]: { session_id: this.eventSessionId },
},
};
}
return this.insertSession(event) as TrackEventType;
}
screen(event: ScreenEventType) {
event.properties = {
...event.properties,
name: event.name,
};
return this.insertSession(event) as ScreenEventType;
}
group(event: GroupEventType) {
return this.insertSession(event) as GroupEventType;
}
alias(event: AliasEventType) {
return this.insertSession(event) as AliasEventType;
}
async reset() {
this.sessionId = -1;
this.eventSessionId = -1;
this.lastEventTime = -1;
await AsyncStorage.removeItem(SESSION_ID_KEY);
}
private insertSession = (event: SegmentEvent) => {
const integrations = event.integrations || {};
const existingIntegration = integrations[this.key];
const hasSessionId =
typeof existingIntegration === 'object' &&
existingIntegration !== null &&
'session_id' in existingIntegration;
if (hasSessionId) {
return event;
}
return {
...event,
integrations: {
...integrations,
[this.key]: { session_id: this.sessionId },
},
};
};
private onBackground = () => {
this.lastEventTime = Date.now();
};
private onForeground = () => {
this.startNewSessionIfNecessary();
};
private async startNewSessionIfNecessary() {
if (this.eventSessionId === -1) {
this.eventSessionId = this.sessionId;
}
if (this.resetPending) {
return;
}
const current = Date.now();
const withinSessionLimit = this.withinMinSessionTime(current);
const isSessionExpired =
this.sessionId === -1 || this.lastEventTime === -1 || !withinSessionLimit;
if (this.sessionId >= 0 && !isSessionExpired) {
return;
}
// End old session and start a new one
await this.startNewSession();
}
/**
* Handles the entire process of starting a new session.
* Can be called directly or from startNewSessionIfNecessary()
*/
private async startNewSession() {
if (this.resetPending) {
return;
}
this.resetPending = true;
const oldSessionId = this.sessionId;
if (oldSessionId >= 0) {
await this.endSession(oldSessionId);
}
const newSessionId = Date.now();
this.sessionId = newSessionId;
this.eventSessionId =
this.eventSessionId === -1 ? newSessionId : this.eventSessionId;
this.lastEventTime = newSessionId;
console.log(`[AmplitudeSession] startNewSession -> ${newSessionId}`);
await this.trackSessionStart(newSessionId);
}
/**
* Extracted analytics tracking into its own method
*/
private async trackSessionStart(sessionId: number) {
this.analytics?.track(AMP_SESSION_START_EVENT, {
integrations: {
[this.key]: { session_id: sessionId },
},
});
}
private async endSession(sessionId: number) {
if (this.sessionId === -1) {
return;
}
console.log(`[AmplitudeSession] endSession -> ${this.sessionId}`);
this.analytics?.track(AMP_SESSION_END_EVENT, {
integrations: {
[this.key]: { session_id: sessionId },
},
});
}
private async loadSessionData() {
const storedSessionId = await AsyncStorage.getItem(SESSION_ID_KEY);
const storedLastEventTime = await AsyncStorage.getItem(LAST_EVENT_TIME_KEY);
const storedEventSessionId = await AsyncStorage.getItem(
EVENT_SESSION_ID_KEY
);
this.sessionId = storedSessionId != null ? Number(storedSessionId) : -1;
this.lastEventTime =
storedLastEventTime != null ? Number(storedLastEventTime) : -1;
this.eventSessionId =
storedEventSessionId != null ? Number(storedEventSessionId) : -1;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private disableAllIntegrations(integrations?: Record<string, any>) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const result: Record<string, any> = {};
if (!integrations) {
return result;
}
for (const key of Object.keys(integrations)) {
result[key] = false;
}
return result;
}
private withinMinSessionTime(timestamp: number): boolean {
const timeDelta = timestamp - this.lastEventTime;
return timeDelta < MAX_SESSION_TIME_IN_MS;
}
private handleAppStateChange = (nextAppState: string) => {
if (nextAppState === 'active') {
this.onForeground();
} else if (nextAppState === 'background') {
this.onBackground();
}
};
}