Skip to content
Open
Show file tree
Hide file tree
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
170 changes: 59 additions & 111 deletions packages/plugins/plugin-amplitudeSession/src/AmplitudeSessionPlugin.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ 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';
Expand All @@ -28,25 +27,9 @@ export class AmplitudeSessionPlugin extends EventPlugin {
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
)
);
}
}
private _previousAppState: string = AppState.currentState ?? 'unknown';
private _sessionTransition: Promise<void> | null = null;

get lastEventTime() {
return this._lastEventTime;
Expand All @@ -68,14 +51,6 @@ export class AmplitudeSessionPlugin extends EventPlugin {
}
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> => {
Expand All @@ -96,7 +71,7 @@ export class AmplitudeSessionPlugin extends EventPlugin {
return event;
}

if (this.sessionId === -1 || this.lastEventTime === -1) {
if (this._sessionId === -1 || this._lastEventTime === -1) {
await this.loadSessionData();
}
await this.startNewSessionIfNecessary();
Expand All @@ -120,7 +95,6 @@ export class AmplitudeSessionPlugin extends EventPlugin {
}

this.lastEventTime = Date.now();
//await this.saveSessionData();
return result;
}

Expand All @@ -131,26 +105,25 @@ export class AmplitudeSessionPlugin extends EventPlugin {
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);
const ampIntegration = event.integrations?.[this.key];
const existingSessionId =
ampIntegration !== undefined &&
typeof ampIntegration === 'object' &&
ampIntegration !== null &&
'session_id' in ampIntegration
? (ampIntegration as { session_id: number }).session_id
: this._sessionId;
return {
...event,
integrations: {
...integrations,
[this.key]: { session_id: this.eventSessionId },
[this.key]: { session_id: existingSessionId },
},
};
}
Expand All @@ -175,10 +148,15 @@ export class AmplitudeSessionPlugin extends EventPlugin {
}

async reset() {
this.sessionId = -1;
this.eventSessionId = -1;
this.lastEventTime = -1;
await AsyncStorage.removeItem(SESSION_ID_KEY);
const oldSessionId = this._sessionId;
if (oldSessionId >= 0) {
this.analytics?.track(AMP_SESSION_END_EVENT, {
integrations: { [this.key]: { session_id: oldSessionId } },
});
}
this._sessionId = -1;
this._lastEventTime = -1;
await AsyncStorage.multiRemove([SESSION_ID_KEY, LAST_EVENT_TIME_KEY]);
}

private insertSession = (event: SegmentEvent) => {
Expand All @@ -197,7 +175,7 @@ export class AmplitudeSessionPlugin extends EventPlugin {
...event,
integrations: {
...integrations,
[this.key]: { session_id: this.sessionId },
[this.key]: { session_id: this._sessionId },
},
};
};
Expand All @@ -206,97 +184,60 @@ export class AmplitudeSessionPlugin extends EventPlugin {
this.lastEventTime = Date.now();
};

private onForeground = () => {
this.startNewSessionIfNecessary();
private onForeground = async () => {
await this.startNewSessionIfNecessary();
};

private async startNewSessionIfNecessary() {
if (this.eventSessionId === -1) {
this.eventSessionId = this.sessionId;
}

if (this.resetPending) {
if (this._sessionTransition !== null) {
await this._sessionTransition;
return;
}

const current = Date.now();
const withinSessionLimit = this.withinMinSessionTime(current);

const isSessionExpired =
this.sessionId === -1 || this.lastEventTime === -1 || !withinSessionLimit;
const isExpired =
this._sessionId === -1 ||
this._lastEventTime === -1 ||
!this.withinMinSessionTime(Date.now());

if (this.sessionId >= 0 && !isSessionExpired) {
if (!isExpired) {
return;
}

// End old session and start a new one
await this.startNewSession();
this._sessionTransition = this.performSessionTransition().finally(() => {
this._sessionTransition = null;
});
await this._sessionTransition;
}

/**
* 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;
private async performSessionTransition() {
const oldSessionId = this._sessionId;
if (oldSessionId >= 0) {
await this.endSession(oldSessionId);
this.analytics?.track(AMP_SESSION_END_EVENT, {
integrations: { [this.key]: { session_id: oldSessionId } },
});
}

const newSessionId = Date.now();
this.sessionId = newSessionId;
this.eventSessionId =
this.eventSessionId === -1 ? newSessionId : this.eventSessionId;
this.lastEventTime = newSessionId;
this._sessionId = newSessionId;
this._lastEventTime = newSessionId;

console.log(`[AmplitudeSession] startNewSession -> ${newSessionId}`);
await AsyncStorage.multiSet([
[SESSION_ID_KEY, newSessionId.toString()],
[LAST_EVENT_TIME_KEY, newSessionId.toString()],
]);

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 },
},
integrations: { [this.key]: { session_id: newSessionId } },
});
}

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 =
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
Expand All @@ -313,15 +254,22 @@ export class AmplitudeSessionPlugin extends EventPlugin {
}

private withinMinSessionTime(timestamp: number): boolean {
const timeDelta = timestamp - this.lastEventTime;
const timeDelta = timestamp - this._lastEventTime;
return timeDelta < MAX_SESSION_TIME_IN_MS;
}

private handleAppStateChange = (nextAppState: string) => {
if (nextAppState === 'active') {
if (
['inactive', 'background'].includes(this._previousAppState) &&
nextAppState === 'active'
) {
this.onForeground();
} else if (nextAppState === 'background') {
} else if (
this._previousAppState === 'active' &&
['inactive', 'background'].includes(nextAppState)
) {
this.onBackground();
}
this._previousAppState = nextAppState;
};
}
Loading
Loading