-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSession.js
255 lines (238 loc) · 8.97 KB
/
Session.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
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
const axios = require('axios');
const Utils = require('./Utils');
const utils = new Utils();
/**
*
* Session
* Constructs the session object for the Amp instance.
*
* @constructor
* @param {Object} options
*
* Options:
* amp - amp instance
* userId - id to identify the user. If id is not passed, a random userId will be auto generated.
* sessionId - id to identify the session. If sessionId is not passed, a random sessionId will be auto generated.
* timeOutMilliseconds - request timeOut in milliSeconds will override the default 10 seconds from amp instance.
* sessionLifeTimeSeconds - session life time in Seconds will override the default 30 minutes from amp instance.
*
*/
module.exports = class Session {
constructor(options = {}) {
if(utils.isEmpty(options.amp))
throw new Error('Please pass valid amp instance.');
this.amp = options.amp;
this.userId = options.userId || utils.generateRandomAlphaNumericString();
this.sessionId = options.sessionId || utils.generateRandomAlphaNumericString();
this.ampToken = options.ampToken;
this.timeOut = options.timeOutMilliseconds || this.amp.timeOut;
this.sessionLifeTime = options.sessionLifeTimeSeconds || this.amp.sessionLifeTime;
this.index = 1;
const selectedAmpAgent = this.amp.ampAgents[Math.abs(utils.hashCode(this.userId) % this.amp.ampAgents.length)];
this.decideContextUrl = `${selectedAmpAgent}/${this.amp.apiPath}/${this.amp.key}/decideWithContextV2`;
this.decideUrl = `${selectedAmpAgent}/${this.amp.apiPath}/${this.amp.key}/decideV2`;
this.observeUrl = `${selectedAmpAgent}/${this.amp.apiPath}/${this.amp.key}/observeV2`;
}
/**
* decideWithContext
* Decision to determine action for the provided context name and properties
*
* @param {string} contextName - name of the context
* @param {object} context - properties to observe
* @param {string} decisionName - name of the event
* @param {object} candidates - variations to choose from
* @param {int} timeout - request timeout in milliseconds will override the value from session or amp
*
* @return {Promise<decideResponse>} decideResponse promise object is returned.
* decisionResponse object
* decision - decision outcome
* fallback - true means server errored out, so that a default decision is returned.
* - false means a valid decision is returned.
* ampToken - valid token is returned in case of success amp call otherwise custom or empty token is returned.
* failureReason - will capture the server error message if any.
*
*/
decideWithContext(contextName, context={},
decisionName, candidates, timeout) {
if(utils.isEmpty(contextName)) {
throw new Error('Context name cannot be empty');
}
if(utils.isEmpty(decisionName)){
throw new Error('Decision name cannot be empty');
}
if(!utils.isObject(candidates)){
throw new Error('Candidates strictly has to be object of key being string and value being Array');
}
if(utils.isEmpty(timeout) || timeout <= 0){
timeout = this.timeOut;
}
const specificFields = {
decisionName,
name: contextName,
properties: context,
decision:{
candidates:[candidates],
limit:1
}
};
const reqJSON = JSON.stringify(Object.assign(this._getBaseFields(), specificFields));
const count = this._getCandidateCombinationCount(candidates);
return this._asDecideResponse(
this.decideContextUrl,
reqJSON,
() => this._getCandidatesAtIndex(candidates,0),
count,
timeout
);
}
/**
*
* @param {string} contextName - name of the context
* @param {object} context - properties to observe
* @param {int} timeout - request timeout in milliseconds will override the value from session or amp
* @return {Promise<observeResponse>}
* observeResponse object
* success - false means server errored out.
* - true means server accepted the observe outcome event.
* ampToken - valid token is returned in case of success amp call otherwise custom or empty token is returned.
* failureReason - will capture the server error message if any.
*/
observe(contextName, context, timeout) {
if(utils.isEmpty(contextName)){
throw new Error('Context name cannot be empty');
}
if(utils.isEmpty(timeout)){
timeout = this.timeOut;
}
const specificFields = {
name: contextName,
properties: context
};
const reqJSON = JSON.stringify(Object.assign(this._getBaseFields(), specificFields));
return this._asObserveResponse(this.observeUrl, reqJSON, timeout);
}
/**
* decide
* Decision to determine action to take
*
* @param {string} decisionName - name of the event
* @param {object} candidates - variations to choose from
* @param {int} timeout - request timeout in milliseconds will override the value from session or amp
*
* @return {Promise<decideResponse>} decideResponse promise object is returned.
* decisionResponse object
* decision - decision outcome
* fallback - true means server errored out, so that a default decision is returned.
* - false means a valid decision is returned.
* ampToken - valid token is returned in case of success amp call otherwise custom or empty token is returned.
* failureReason - will capture the server error message if any.
*/
decide(decisionName, candidates, timeout) {
if(utils.isEmpty(decisionName)){
throw new Error('Decision name cannot be empty');
}
if(!utils.isObject(candidates)){
throw new Error('Candidates strictly has to be object of key being string and value being Array');
}
if(utils.isEmpty(timeout) || timeout <= 0){
timeout = this.timeOut;
}
const specificFields = {
decisionName,
decision:{
candidates:[candidates],
limit:1
}
};
const reqJSON = JSON.stringify(Object.assign(this._getBaseFields(), specificFields));
const count = this._getCandidateCombinationCount(candidates);
return this._asDecideResponse(
this.decideUrl,
reqJSON, () => this._getCandidatesAtIndex(candidates,0),
count,
timeout
);
}
async _asDecideResponse(url, reqJson, decisionFn, candidatesCount, timeout){
const decideResponse = {
decision: decisionFn(),
fallback: true,
ampToken: this.ampToken
};
try {
if(candidatesCount > 50) {
decideResponse.failureReason = 'Cant have more than 50 candidates';
return decideResponse;
}
const response = await axios.post(url, reqJson, {timeout});
if(response.status === 200) {
const { decision, ampToken, fallback, failureReason } = response.data;
this.ampToken = this.amp.dontUseTokens
? this.amp.customToken
: ampToken;
decideResponse.ampToken = this.ampToken;
if(fallback && !utils.isEmpty(failureReason)){
decideResponse.fallback = true;
decideResponse.failureReason = `amp-agent error: ${failureReason}`;
}else if(!fallback && !utils.isEmpty(decision)){
decideResponse.decision = decision;
decideResponse.fallback = false;
}
}else {
decideResponse.failureReason = `bad status code from server ${response.code} with reason: ${response.statusText}`;
}
}catch(error) {
const { response } = error;
decideResponse.failureReason = response
? `bad status code from server ${response.status} with reason: ${response.statusText}`
: error.message;
}
return decideResponse;
}
async _asObserveResponse(url, reqJson, timeout){
const observeResponse = {
ampToken: this.ampToken,
success:false,
failureReason: ''
};
try {
const response = await axios.post(url, reqJson, {timeout});
if(response.status === 200){
const { ampToken } = response.data;
this.ampToken = this.amp.dontUseTokens
? this.amp.customToken
: ampToken;
observeResponse.ampToken = this.ampToken;
observeResponse.success = true;
}
}catch(error){
const { response } = error;
observeResponse.failureReason = response
? `bad status code from server ${response.status} with reason: ${response.statusText}`
: error.message;
}
return observeResponse;
}
_getBaseFields(){
return {
userId: this.userId,
sessionId: this.sessionId,
index: this.index++,
ts: Date.now(),
ampToken: this.ampToken,
sessionLifetime: this.sessionLifeTime
};
}
_getCandidatesAtIndex(candidates, index) {
let partial = index;
return Object.keys(candidates).sort((a,b) => a < b).reduce((results, key) => {
const values = candidates[key];
results[key] = values[ partial % values.length];
partial = Math.floor(partial / values.length);
return results;
}, {});
}
_getCandidateCombinationCount(candidates) {
return Object.keys(candidates).reduce((count, key) => { return candidates[key].length * count; }, 1);
}
};