-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
variant.js
141 lines (127 loc) · 4.9 KB
/
variant.js
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
/**
* Copyright 2016 The AMP HTML Authors. All Rights Reserved.
*
* 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
*
* http://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 {isObject} from '../../../src/types';
import {dev, user} from '../../../src/log';
import {cidForDoc} from '../../../src/services';
import {viewerForDoc} from '../../../src/services';
import {userNotificationManagerFor} from '../../../src/services';
import {cryptoFor} from '../../../src/crypto';
const ATTR_PREFIX = 'amp-x-';
const nameValidator = /^[\w-]+$/;
/**
* Allocates the current page view to an experiment variant based on the given
* experiment config.
* @param {!../../../src/service/ampdoc-impl.AmpDoc} ampdoc
* @param {string} experimentName
* @param {!JsonObject} config
* @return {!Promise<?string>}
*/
export function allocateVariant(ampdoc, experimentName, config) {
assertName(experimentName);
validateConfig(config);
// Variant can be overridden from URL fragment.
const viewer = viewerForDoc(ampdoc);
const override = viewer.getParam(ATTR_PREFIX + experimentName);
if (override && config['variants'].hasOwnProperty(override)) {
return Promise.resolve(/** @type {?string} */ (override));
}
const sticky = config['sticky'] !== false;
const cidScope = config['cidScope'] || 'amp-experiment';
let hasConsentPromise = Promise.resolve(true);
if (sticky && config['consentNotificationId']) {
hasConsentPromise = userNotificationManagerFor(ampdoc.win)
.then(manager => manager.getNotification(
config['consentNotificationId']))
.then(userNotification => {
user().assert(userNotification,
`Notification not found: ${config['consentNotificationId']}`);
return userNotification.isDismissed();
});
}
return hasConsentPromise.then(hasConsent => {
if (!hasConsent) {
return null;
}
const group = config['group'] || experimentName;
return getBucketTicket(ampdoc, group, sticky ? cidScope : null)
.then(ticket => {
let upperBound = 0;
// Loop through keys in a specific order since the default object key
// enumeration is implementation (browser) dependent.
const variantNames = Object.keys(config['variants']).sort();
for (let i = 0; i < variantNames.length; i++) {
upperBound += config['variants'][variantNames[i]];
if (ticket < upperBound) {
return variantNames[i];
}
}
return null;
});
});
}
/**
* Validates an experiment config.
* @param {!JsonObject} config
* @throws {!Error}
*/
function validateConfig(config) {
const variants = config['variants'];
user().assert(isObject(variants) && Object.keys(variants).length > 0,
'Missing experiment variants config.');
if (config['group']) {
assertName(config['group']);
}
let totalPercentage = 0;
for (const variantName in variants) {
if (variants.hasOwnProperty(variantName)) {
assertName(variantName);
const percentage = variants[variantName];
user().assert(
typeof percentage === 'number' && percentage > 0 && percentage < 100,
'Invalid percentage %s:%s.'
+ ' Has to be greater than 0 and less than 100',
variantName, percentage);
totalPercentage += percentage;
}
}
user().assert(totalPercentage./*avoid float precision*/toFixed(6) <= 100,
'Total percentage is bigger than 100: ' + totalPercentage);
}
/**
* Returns a float number (bucket ticket) in the range of [0, 100). The number
* is hashed from the CID of the given scope (opt_cidScope). If the
* scope is not provided, a random number is used.
* @param {!../../../src/service/ampdoc-impl.AmpDoc} ampdoc
* @param {string} group
* @param {string=} opt_cidScope
* @return {!Promise<!number>} a float number in the range of [0, 100)
*/
function getBucketTicket(ampdoc, group, opt_cidScope) {
if (!opt_cidScope) {
return Promise.resolve(ampdoc.win.Math.random() * 100);
}
const cidPromise = cidForDoc(ampdoc).then(cidService => cidService.get({
scope: dev().assertString(opt_cidScope),
createCookieIfNotPresent: true,
}, Promise.resolve()));
return Promise.all([cidPromise, cryptoFor(ampdoc.win)])
.then(results => results[1].uniform(group + ':' + results[0]))
.then(hash => hash * 100);
}
function assertName(name) {
user().assert(nameValidator.test(name),
`Invalid name ${name}: %s. Allowed chars are [a-zA-Z0-9-_].`);
}