forked from dominictarr/crdt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
doc.js
287 lines (234 loc) · 7.27 KB
/
doc.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
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
var inherits = require('util').inherits
var Row = require('./row')
var between = require('between')
var Set = require('./set')
var Seq = require('./seq')
var Scuttlebutt = require('scuttlebutt')
var EventEmitter = require('events').EventEmitter
var createId = require('scuttlebutt/util').createId
inherits(Doc, Scuttlebutt)
function merge(to, from) {
for(var k in from)
to[k] = from[k]
return to
}
module.exports = Doc
//doc
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/*
idea: instead of using a tombstone for deletes,
use a anti-tombstone to show something is alive.
breathing: count. -- updated by an authority.
set breathing to 0 to kill something.
if a node has rows that have been garbage collected on the server,
it will be obvious from the value of breathing.
node disconnects... makes changes...
other nodes delete some things, which get garbage collected.
node reconnects.
server updates the node, but only increments _breathing for some rows.
clearly, the nodes that do not have an upto date _breathing are either
dead, or where created by the node while it was offline.
would breathing need to be a vector clock?
if the disconneded node is still updating the rows,
maybe it shouldn't be deleted, that is, undeleted.
may be on to something here... but this needs more thinking.
will depend on how much churn something has...
*/
function order (a, b) {
return between.strord(a[1], b[1]) || between.strord(a[2], b[2])
}
function Doc (id) {
if (!(this instanceof Doc)) return new Doc(id)
//the id of the doc refers to the instance.
//that is, to the node.
//it's used to identify a node
// this.id = id || '#' + Math.round(Math.random()*1000)
this.rows = {}
this.hist = {}
this.sets = new EventEmitter() //for tracking membership of sets.
this.setMaxListeners(Infinity)
this.sets.setMaxListeners(Infinity)
Scuttlebutt.call(this, id)
}
Doc.prototype.add = function (initial) {
var id = initial.id === undefined ? createId() : initial.id
if(id === '__proto__')
throw new Error('__proto__ is illegial id')
var r = this._add(id, 'local')
r._set(initial, 'local')
return r
}
Doc.prototype._add = function (id, source, change) {
var doc = this
if(id === '__proto__')
throw new Error('__proto__ is illegial id')
if(this.rows[id])
return this.rows[id]
var r = id instanceof Row ? id : new Row(id)
this.rows[r.id] = r
function track (changes, source) {
//console.log(changes, source)
doc.localUpdate([r.id, changes])
}
r.on('preupdate', track)
r.on('remove', function () {
r.removeAllListeners('preupdate')
})
r._new = true
return r
}
Doc.prototype.timeUpdated = function (row, key) {
var h = this.hist[row.id]
if(!h) return
return h[key][2]
}
Doc.prototype.set = function (id, change) {
if(id === '__proto__')
throw new Error('__proto__ is illegial id')
var r = this._add(id, 'local', change)
return r.set(change)
}
Doc.prototype.rm = function (id) {
this.set(id, null)
}
/*
histroy for each row is indexed by key.
key -> update that set that key.
so applying a change is as simple
as iterating over the keys in the rows hist
checking if the new update is more recent
than the hist update
if so, replace that keys hist.
*/
Doc.prototype.applyUpdate = function (update, source) {
//apply an update to a row.
//take into account histroy.
//and insert the change into the correct place.
if(!(Array.isArray(update[0])
&& 'string' === typeof update[0][0]
)) return this.emit('invalid', new Error('invalid update'))
var id = update[0][0]
var changes = update[0][1]
var timestamp = update[1]
var from = update[2]
if(id === '__proto__')
return this.emit('invalid', new Error('__proto__ is illegial id'))
var changed = {}
var row = this._add(id, source)
var hist = this.hist[id] = this.hist[id] || {}
var emit = false, oldnews = false
//remember the most recent update from each node.
//now handled my scuttlebutt.
// if(!row.validate(changes)) return
if (changes === null) {
// clean up the history
for(var key in row.state) {
if(row.state.hasOwnProperty(key)) {
if(!hist[key] || order(hist[key], update) < 0) {
if(hist[key]) this.emit('_remove', hist[key])
hist[key] = [ null, update[1], update[2]]
emit = true
}
}
}
// remove from all sets that contain row
for (var setId in this.sets) {
var isSet = setId.indexOf(':') > 0
var set = this.sets[setId]
var setContainsRow = isSet && set && set.get(row.id)
if (setContainsRow) set.rm(row)
}
// delete from the doc rows
delete this.rows[id]
row.emit('removed')
this.emit('remove', row)
}
else {
var maybe = []
for(var key in changes) {
if(changes.hasOwnProperty(key)) {
var value = changes[key]
if(!hist[key] || order(hist[key], update) < 0) {
if(hist[key] && !~maybe.indexOf(hist[key]))
maybe.push(hist[key])
hist[key] = update
changed[key] = value
emit = true
}
}
}
var h = this.history()
var self = this
maybe.forEach(function (e) {
if(!~h.indexOf(e))
self.emit('_remove', e)
})
}
// probably, there may be mulitple sets that listen to the same key,
// but activate on different values...
//
// hang on, in the mean time, I will probably only be managing n < 10 sets.
// at once,
merge(row.state, changed)
for(var k in changed)
this.sets.emit(k, row, changed)
if(!emit) return
if(row._new) {
this.emit('add', row)
this.emit('create', row) //alias
row._new = false
}
this.emit('_update', update)
row.emit('update', update, changed)
row.emit('changes', changes, changed)
row.emit('change', changed) //installing this in paralel, so tests still pass.
//will depreciate the old way later.
this.emit('update', update, source) //rename this event to 'data' or 'diff'?
this.emit('row_update', row) //rename this event to 'update'
}
Doc.prototype.history = function (sources) {
var h = []
for (var id in this.hist) {
var hist = this.hist[id]
for (var k in hist) {
if(!~h.indexOf(hist[k]) && Scuttlebutt.filter(hist[k], sources))
h.push(hist[k])
}
}
return h.sort(order)
}
function _set(self, key, val, type) {
var id = typeof key === 'string' && key + ':' + val
if(id && self.sets[id]) {
return self.sets[id]
}
var set = new type(self, key, val)
if (id) {
self.sets[id] = set
}
return set
}
Doc.prototype.createSet = function (key, val) {
if(key === '__proto__')
throw new Error('__proto__ is invalid key')
return _set(this, key, val, Set)
}
Doc.prototype.createSeq = function (key, val) {
if(key === '__proto__')
throw new Error('__proto__ is invalid key')
return _set(this, key, val, Seq)
}
Doc.prototype.toJSON = function () {
var j = {}
for (var k in this.rows) {
if(this.rows.hasOwnProperty(k))
j[k] = this.rows[k].state
}
return j
}
//retrive a reference to a row.
//if the row is not created yet, create
Doc.prototype.get = function (id) {
if(id === '__proto__') throw new Error('__proto__ is illegal id')
return this.rows[id] = this.rows[id] || this._add(new Row(id), 'local')
}