/
timestamp.js
229 lines (197 loc) · 5.84 KB
/
timestamp.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
(function(root, factory) {
if (typeof exports === 'object') {
module.exports = factory(require('murmurhash'));
} else {
let { Timestamp, MutableTimestamp } = factory(root.murmur);
root.Timestamp = Timestamp;
root.MutableTimestamp = MutableTimestamp;
}
})(this, function(murmurhash) {
var config = {
// Maximum physical clock drift allowed, in ms
maxDrift: 60000
};
class Timestamp {
constructor(millis, counter, node) {
this._state = {
millis: millis,
counter: counter,
node: node
};
}
valueOf() {
return this.toString();
}
toString() {
return [
new Date(this.millis()).toISOString(),
(
'0000' +
this.counter()
.toString(16)
.toUpperCase()
).slice(-4),
('0000000000000000' + this.node()).slice(-16)
].join('-');
}
millis() {
return this._state.millis;
}
counter() {
return this._state.counter;
}
node() {
return this._state.node;
}
hash() {
return murmurhash.v3(this.toString());
}
}
class MutableTimestamp extends Timestamp {
setMillis(n) {
this._state.millis = n;
}
setCounter(n) {
this._state.counter = n;
}
setNode(n) {
this._state.node = n;
}
}
MutableTimestamp.from = timestamp => {
return new MutableTimestamp(
timestamp.millis(),
timestamp.counter(),
timestamp.node()
);
};
// Timestamp generator initialization
// * sets the node ID to an arbitrary value
// * useful for mocking/unit testing
Timestamp.init = function(options = {}) {
if (options.maxDrift) {
config.maxDrift = options.maxDrift;
}
};
/**
* Timestamp send. Generates a unique, monotonic timestamp suitable
* for transmission to another system in string format
*/
Timestamp.send = function(clock) {
// Retrieve the local wall time
var phys = Date.now();
// Unpack the clock.timestamp logical time and counter
var lOld = clock.timestamp.millis();
var cOld = clock.timestamp.counter();
// Calculate the next logical time and counter
// * ensure that the logical time never goes backward
// * increment the counter if phys time does not advance
var lNew = Math.max(lOld, phys);
var cNew = lOld === lNew ? cOld + 1 : 0;
// Check the result for drift and counter overflow
if (lNew - phys > config.maxDrift) {
throw new Timestamp.ClockDriftError(lNew, phys, config.maxDrift);
}
if (cNew > 65535) {
throw new Timestamp.OverflowError();
}
// Repack the logical time/counter
clock.timestamp.setMillis(lNew);
clock.timestamp.setCounter(cNew);
return new Timestamp(
clock.timestamp.millis(),
clock.timestamp.counter(),
clock.timestamp.node()
);
};
// Timestamp receive. Parses and merges a timestamp from a remote
// system with the local timeglobal uniqueness and monotonicity are
// preserved
Timestamp.recv = function(clock, msg) {
var phys = Date.now();
// Unpack the message wall time/counter
var lMsg = msg.millis();
var cMsg = msg.counter();
// Assert the node id and remote clock drift
if (msg.node() === clock.timestamp.node()) {
throw new Timestamp.DuplicateNodeError(clock.timestamp.node());
}
if (lMsg - phys > config.maxDrift) {
throw new Timestamp.ClockDriftError();
}
// Unpack the clock.timestamp logical time and counter
var lOld = clock.timestamp.millis();
var cOld = clock.timestamp.counter();
// Calculate the next logical time and counter.
// Ensure that the logical time never goes backward;
// * if all logical clocks are equal, increment the max counter,
// * if max = old > message, increment local counter,
// * if max = messsage > old, increment message counter,
// * otherwise, clocks are monotonic, reset counter
var lNew = Math.max(Math.max(lOld, phys), lMsg);
var cNew =
lNew === lOld && lNew === lMsg
? Math.max(cOld, cMsg) + 1
: lNew === lOld
? cOld + 1
: lNew === lMsg
? cMsg + 1
: 0;
// Check the result for drift and counter overflow
if (lNew - phys > config.maxDrift) {
throw new Timestamp.ClockDriftError();
}
if (cNew > 65535) {
throw new Timestamp.OverflowError();
}
// Repack the logical time/counter
clock.timestamp.setMillis(lNew);
clock.timestamp.setCounter(cNew);
return new Timestamp(
clock.timestamp.millis(),
clock.timestamp.counter(),
clock.timestamp.node()
);
};
/**
* Converts a fixed-length string timestamp to the structured value
*/
Timestamp.parse = function(timestamp) {
if (typeof timestamp === 'string') {
var parts = timestamp.split('-');
if (parts && parts.length === 5) {
var millis = Date.parse(parts.slice(0, 3).join('-')).valueOf();
var counter = parseInt(parts[3], 16);
var node = parts[4];
if (!isNaN(millis) && !isNaN(counter))
return new Timestamp(millis, counter, node);
}
}
return null;
};
Timestamp.since = isoString => {
return isoString + '-0000-0000000000000000';
};
Timestamp.DuplicateNodeError = class extends Error {
constructor(node) {
super();
this.type = 'DuplicateNodeError';
this.message = 'duplicate node identifier ' + node;
}
};
Timestamp.ClockDriftError = class extends Error {
constructor(...args) {
super();
this.type = 'ClockDriftError';
this.message = ['maximum clock drift exceeded'].concat(args).join(' ');
}
};
Timestamp.OverflowError = class extends Error {
constructor() {
super();
this.type = 'OverflowError';
this.message = 'timestamp counter overflow';
}
};
return { Timestamp, MutableTimestamp };
});