-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathat-core-state.html
296 lines (241 loc) · 10.3 KB
/
at-core-state.html
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
<link rel="import" href="../tangere/tangere.html" />
<link rel="import" href="../at-core-activity-queue/at-core-activity-queue.html">
<link rel="import" href="../at-core-signals/at-core-signals.html">
<dom-module id="at-core-state">
<template>
<style>
:host {
display: block;
box-sizing: border-box;
}
</style>
<at-core-signals id="coreSignals" on-state-request="_handleStateRequest" on-state-push="_handleStatePush" on-state-poll="_handleStatePoll"></at-core-signals>
<at-core-activity-queue id="activityQueue" on-response="_handleActivityResponse" on-error="_handleActivityError"></at-core-activity-queue>
</template>
</dom-module>
<script>
Polymer({
is: "at-core-state",
properties: {
},
created: function () {
//
// cached data should hold responses for named requests
//
if (this._state == undefined) {
this._state = {};
window._state = this._state;
}
},
ready: function () {
},
_clearStateFromCache: function (stateName) {
//console.log("clear from cache: " + stateName);
if (this._stateExists(stateName)) {
delete this._state[stateName];
}
},
_stateExists: function (stateName) {
var existing = this._state[stateName];
if (existing) {
return true;
} else {
return false;
}
},
_signalUpdate: function (stateName) {
var state = this._state[stateName];
// console.log("_signalUpdate " + stateName);
if (!state.data || !state.data.name) debugger;
// state-update should have only name, version and response
var stateUpdate = {
name: state.data.name,
version: state.version,
response: state.data.response
}
if (this._isOfflineCache(stateName)) {
if (!!state.data.response.ErrorCode) {
// when response contains error do not cache and invalidate last cached item
localStorage.removeItem(this._offlineCacheKey(stateName));
} else {
// save state in offline cache
try {
var oldState = localStorage.getItem(this._offlineCacheKey(stateName));
if (oldState) {
oldState = JSON.parse(oldState);
if (oldState.response.Data._ts > stateUpdate.response.Data._ts) {
// console.log(this._offlineCacheKey(stateRequest.name) + " discard update");
stateUpdate = oldState; // discard 'updates' older then current state
}
}
localStorage.setItem(this._offlineCacheKey(stateName), JSON.stringify(stateUpdate));
} catch (err) {
// remove cached item when serialization fails
console.error(err);
localStorage.removeItem(this._offlineCacheKey(stateName));
}
}
}
// console.log("state-update state answer async " + stateName);
Polymer.signalAsync('state-update', stateName, stateUpdate);
//}
},
_requestQueueAndCache: function (stateRequest) {
//console.log("_requestQueueAndCache");
// cache state request
if (!this._stateExists(stateRequest.name)) {
this._state[stateRequest.name] = stateRequest;
} else {
// deduplicate already existing request
if (this._state[stateRequest.name].answerPending) return;
}
if (stateRequest.name.indexOf("state://") < 0) { // state:// requests are just in memory and not requested from a server
this.$.activityQueue.addRequest(stateRequest);
}
this._state[stateRequest.name].answerPending = true;
},
_handleStatePoll: function (event) {
var statePoll = event.detail;
statePoll.name = statePoll.url;
this._requestQueueAndCache(statePoll);
},
_handleStateRequest: function (event) {
var stateRequest = event.detail;
stateRequest.name = stateRequest.url;
console.log("state request " + stateRequest.name);
// default cache duration in milliseconds
var cacheDuration = 10000;
if (this._isOfflineCache(stateRequest.name)) cacheDuration = 60 * 60 * 1000; // when offline cache is used cache 1hr in memory
// If maxAge is 0 -> always clear old state from cache if existing, cache and send a new one
if (stateRequest.maxAge === 0) {
if (this._stateExists(stateRequest.name)) {
var existing = this._state[stateRequest.name];
if (existing.answerPending == true) return;
this._clearStateFromCache(stateRequest.name);
}
this._requestQueueAndCache(stateRequest);
return;
}
// If maxAge is false -> always return cached state if existing. Otherwise, cache and send a new one
if (stateRequest.maxAge === false) {
if (this._stateExists(stateRequest.name)) {
var existing = this._state[stateRequest.name];
if (!existing.answerPending == true) {
this._signalUpdate(stateRequest.name);
return;
}
}
this._requestQueueAndCache(stateRequest);
return;
}
// If maxAge == undefined, use default cacheDuration
if (stateRequest.maxAge !== 0 && stateRequest.maxAge !== false && stateRequest.maxAge !== undefined) {
cacheDuration = stateRequest.maxAge * 1000;
}
var cachedState = this._state[stateRequest.name];
var currentTimeStamp = Date.now();
var milliSecondsPassed = 0;
// If the request is cached and answered -> calculate milliSecondsPassed
if (cachedState != undefined && cachedState.answerPending == false) {
milliSecondsPassed = currentTimeStamp - cachedState.cacheTimeStamp;;
}
// If the request is not cached -> send a new request, add it to cache and set request.answerPending to "true" (equal to "SENT")
if (cachedState == undefined) {
console.log("state-request cache check " + stateRequest.name);
var delayRequest = false;
if (this._isOfflineCache(stateRequest.name)) {
// start with offline data but still request fresh data
var state = localStorage.getItem(this._offlineCacheKey(stateRequest.name));
//console.log(this._offlineCacheKey(stateRequest.name) + " cached: " + !!state);
if (state) {
var stateUpdate = JSON.parse(state);
//console.log(this._offlineCacheKey(stateRequest.name) + " hash: " + stateUpdate.response.Data._hash, " ts: " + stateUpdate.response.Data._ts);
Polymer.signalAsync('state-update');
delayRequest = true; // we have cached data, so postpone first request for faster inital load
} else {
// new request
}
}
this.async(function () {
this._requestQueueAndCache(stateRequest);
}, delayRequest ? 500 : 10);
return;
}
// If the request is cached and unanswered -> do not send a new request, wait for answser
if (cachedState.answerPending == true) {
return;
}
if (cachedState.answerPending != false) debugger;
// If the request is cached and requested within last cacheDurtion -> return cached response
if (milliSecondsPassed <= cacheDuration) {
this._signalUpdate(stateRequest.name);
return;
} else {
// If the request cache is expired -> clear cache and send a new request
this._clearStateFromCache(stateRequest.name);
this._requestQueueAndCache(stateRequest);
return;
}
},
_handleStatePush: function (event) {
var statePush = event.detail;
if (statePush.url != undefined) {
statePush.name = statePush.url;
}
if (!statePush.response.Data._ts) statePush.response.Data._ts = (new Date()).toJSON(); // set current time if server didn't provide time stamp
if (this._stateExists(statePush.name)) {
var existing = this._state[statePush.name];
// ignore/deduplicate responses/states with same hash
if (existing.answerPending == false && typeof statePush.response.Data._hash != "undefined") {
if (statePush.response.Data._ts && existing.data.response.Data._ts) {
if (statePush.response.Data._ts <= existing.data.response.Data._ts) {
console.log("ignored older data " + statePush.name + " " + statePush.response.Data._ts + " " + existing.data.response.Data._ts);
return; // ignore older data
}
}
if (statePush.response.Data._hash == existing.data.response.Data._hash) {
this._state[statePush.name].cacheTimeStamp = Math.floor(Date.now()); // just update cache age
return;
} else {
console.log("_hash change " + statePush.name + " " + statePush.response.Data._hash + " " + existing.data.response.Data._hash);
}
}
}
//console.log("state push " + statePush.name);
// Set version -> set data -> set answerPending to false -> set timestamp
// Setting the answerPending to false mimics the requests that have been answered
this._state[statePush.name] = {
version: Math.floor(Date.now()),
data: statePush,
answerPending: false,
cacheTimeStamp: Math.floor(Date.now())
};
this._signalUpdate(statePush.name);
},
// handle activity error should send state-update signal with error
_handleActivityError: function (e) {
//console.log("Handle activity error.");
var existing = this._state[e.detail.name];
e.detail.response.handler.handled = true;
// disableErrorCodeHandler is true -> cache a response and signal update
if (existing != undefined && existing.disableErrorCodeHandler == true) {
this._handleStatePush(e);
} else {
// disabledErrorCodeHandler is false -> do not cache and do not signal an update
return;
}
},
_handleActivityResponse: function (event) {
//console.log("Handle activity response.");
this._handleStatePush(event);
},
_isOfflineCache: function (service) {
// check if service should be cached
// for now just hardcoded type
return service.indexOf("service://cardData") == 0 || service.indexOf("state://briefing") == 0;
},
_offlineCacheKey: function (service) {
return (Tangere.session.user.UserCacheKey || Tangere.session.user.UserName) + "." + service;
}
});
</script>