Support time discretization in scripts

This can be used to ensure parameter refresh times are aligned (as
opposed to using Date.now() - X). It also allows for possible future
optimizations by exploiting the fact that the value of Date.now(X)
remains static for a given amount of time.

The variance value can be used to shift the discretization threshold
points based on the hash of the device ID for load distribution.

The djb2 hashing algorithm has been replaced with MD5 for better
distribution.
This commit is contained in:
Zaid Abdulla committed 2017-11-10 14:34:24 -08:00
1 parent ed873cdd4a
commit 6a9c62b639
6 files changed
+121 -47

No files matched your search

+29 -4
View File
@@ -26,6 +26,7 @@ const common = require("./common");
const device = require("./device");
const extensions = require("./extensions");
const logger = require("./logger");
const scheduling = require("./scheduling");
// Used for throwing to exit user script and commit
@@ -40,15 +41,39 @@ let state;
class SandboxDate {
constructor(arg) {
constructor() {
if (arguments.length)
return new (Function.prototype.bind.apply(Date, arguments));
return new Date(...arguments);
return new Date(state.sessionContext.timestamp);
}
static now() {
return state.sessionContext.timestamp;
static now(intervalOrCron, variance) {
let t = state.sessionContext.timestamp;
if (typeof intervalOrCron === "number") {
if (variance == null)
variance = intervalOrCron;
let offset = 0;
if (variance)
offset = scheduling.variance(state.sessionContext.deviceId, variance);
t = scheduling.interval(t, intervalOrCron, offset);
}
else if (typeof intervalOrCron === "string") {
let offset = 0;
if (variance)
offset = scheduling.variance(state.sessionContext.deviceId, variance);
let cron = scheduling.parseCron(intervalOrCron);
t = scheduling.cron(t, cron, offset)[0];
}
else if (intervalOrCron) {
throw new Error("Invalid Date.now() argument");
}
return t;
}
};