File size: 4,012 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import * as ExperimentAssignments from './experiment-assignments';
import localStorage from './local-storage';
import { monotonicNow } from './timing';
import { validateExperimentAssignment, isObject } from './validations';
import type { Config, ExperimentAssignment } from '../types';

interface FetchExperimentAssignmentResponse {
	variations: Record< string, unknown >;
	ttl: number;
}

/**
 * Exported for testing only.
 * @param response The response data
 */
export function isFetchExperimentAssignmentResponse(
	response: unknown
): response is FetchExperimentAssignmentResponse {
	return (
		isObject( response ) &&
		isObject( response.variations ) &&
		typeof response.ttl === 'number' &&
		0 < response.ttl
	);
}

function validateFetchExperimentAssignmentResponse(
	response: unknown
): FetchExperimentAssignmentResponse {
	if ( isFetchExperimentAssignmentResponse( response ) ) {
		return response;
	}
	throw new Error( 'Invalid FetchExperimentAssignmentResponse' );
}

// We cache the anonId and add it to requests to ensure users that have recently
// crossed the logged-out/logged-in boundry have a consistent assignment.
//
// There can be issues otherwise as matching anonId to userId is only eventually
// consistent.
const localStorageLastAnonIdKey = 'explat-last-anon-id';
const localStorageLastAnonIdRetrievalTimeKey = 'explat-last-anon-id-retrieval-time';
const lastAnonIdExpiryTimeMs = 24 * 60 * 60 * 1000; // 24 hours
/**
 * INTERNAL USE ONLY
 *
 * Runs the getAnonId provided cached by LocalStorage:
 * - Returns the result of getAnonId if it can
 * - Otherwise, within the expiry time, returns the cached anonId
 *
 * Exported for testing.
 * @param getAnonId The getAnonId function
 */
export const localStorageCachedGetAnonId = async ( getAnonId: Config[ 'getAnonId' ] ) => {
	const anonId = await getAnonId();
	if ( anonId ) {
		localStorage.setItem( localStorageLastAnonIdKey, anonId );
		localStorage.setItem( localStorageLastAnonIdRetrievalTimeKey, String( monotonicNow() ) );
		return anonId;
	}

	const maybeStoredAnonId = localStorage.getItem( localStorageLastAnonIdKey );
	const maybeStoredRetrievalTime = localStorage.getItem( localStorageLastAnonIdRetrievalTimeKey );
	if (
		maybeStoredAnonId &&
		maybeStoredRetrievalTime &&
		monotonicNow() - parseInt( maybeStoredRetrievalTime, 10 ) < lastAnonIdExpiryTimeMs
	) {
		return maybeStoredAnonId;
	}

	return null;
};

/**
 * Fetch an ExperimentAssignment
 * @param config The config object providing dependecy injection.
 * @param experimentName The experiment name to fetch
 */
export async function fetchExperimentAssignment(
	config: Config,
	experimentName: string
): Promise< ExperimentAssignment > {
	const retrievedTimestamp = monotonicNow();

	const { variations, ttl: responseTtl } = validateFetchExperimentAssignmentResponse(
		await config.fetchExperimentAssignment( {
			anonId: await localStorageCachedGetAnonId( config.getAnonId ),
			experimentName,
		} )
	);

	const ttl = Math.max( ExperimentAssignments.minimumTtl, responseTtl );

	const fetchedExperimentAssignments = Object.entries( variations )
		.map( ( [ experimentName, variationName ] ) => ( {
			experimentName,
			variationName,
			retrievedTimestamp,
			ttl,
		} ) )
		.map( validateExperimentAssignment );

	if ( fetchedExperimentAssignments.length > 1 ) {
		throw new Error(
			'Received multiple experiment assignments while trying to fetch exactly one.'
		);
	}

	if ( fetchedExperimentAssignments.length === 0 ) {
		return ExperimentAssignments.createFallbackExperimentAssignment( experimentName, ttl );
	}

	const fetchedExperimentAssignment = fetchedExperimentAssignments[ 0 ];

	if ( fetchedExperimentAssignment.experimentName !== experimentName ) {
		throw new Error(
			"Newly fetched ExperimentAssignment's experiment name does not match request."
		);
	}

	if ( ! ExperimentAssignments.isAlive( fetchedExperimentAssignment ) ) {
		throw new Error( "Newly fetched experiment isn't alive." );
	}

	return fetchedExperimentAssignment;
}