-
-
Notifications
You must be signed in to change notification settings - Fork 39
/
Copy pathfarmLog2.js
313 lines (292 loc) · 9.95 KB
/
farmLog2.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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
/* eslint-disable no-param-reassign */
import { uniq, zipObj, without } from 'ramda';
import defaultResources from '../core/store/defaultResources';
const data = Symbol('data');
const changed = Symbol('changed');
const conflicts = Symbol('conflicts');
const lastSync = Symbol('lastSync');
function createSymbolRegistry(logTypes) {
const uniqueFields = uniq(Object.values(logTypes)
.flatMap(({ fields }) => Object.keys(fields)));
const fieldSymbols = zipObj(
uniqueFields,
uniqueFields.map(f => Symbol(f)),
);
return {
name: Symbol('name'),
timestamp: Symbol('timestamp'),
done: Symbol('done'),
...fieldSymbols,
// NB: We don't need to register properties that don't change once set,
// like id, type, and localID.
};
}
function updateSymbolRegistry(registry, newLogTypes) {
const uniqueFields = uniq(Object.values(newLogTypes)
.flatMap(({ fields }) => Object.keys(fields)));
uniqueFields.forEach((f) => {
if (!registry[f]) {
registry[f] = Symbol(f);
}
});
}
function makeDefault(schema) {
if (schema === null) {
return null;
}
if (Array.isArray(schema)) {
return [];
}
if (typeof schema === 'object') {
const entries = Object.entries(schema)
.map(([key, val]) => ([key, makeDefault(val)]));
return Object.fromEntries(entries);
}
return schema;
}
function setOnce(obj, key, value) {
const writable = value === undefined;
Object.defineProperty(obj, key, {
value,
writable,
configurable: true,
enumerable: true,
});
}
function farmLog(_logTypes) {
let logTypes = _logTypes;
const symbolRegistry = createSymbolRegistry(logTypes);
function createProperty(obj, key, val, _changed, _conflicts) {
const sym = symbolRegistry[key];
Object.defineProperty(obj, sym, {
enumerable: false,
value: {
[data]: val,
[changed]: _changed || Math.floor(Date.now() / 1000),
[conflicts]: _conflicts || [],
},
});
Object.defineProperty(obj, key, {
enumerable: true,
configurable: true,
get: function symbolGetter() {
return this[sym][data];
},
set: function symbolSetter(value) {
this[sym][changed] = Math.floor(Date.now() / 1000);
this[sym][data] = value;
},
});
}
// The type determines what other properites are included, so it requires
// a special setter. Also, it can only be changed before it is synced with the
// server, so it doesn't need metadata.
function createTypeProperty(obj, val) {
Object.defineProperty(obj, 'type', {
enumerable: true,
configurable: true,
get: function typeGetter() {
return val;
},
set: function typeSetter(newType) {
const oldType = val;
const oldSchemaKeys = Object.keys(logTypes[oldType].fields);
const newSchemaKeys = Object.keys(logTypes[newType].fields);
const keysToBeAdded = without(oldSchemaKeys, newSchemaKeys);
const keysToBeRemoved = without(newSchemaKeys, oldSchemaKeys);
keysToBeAdded.forEach((key) => {
const value = makeDefault(logTypes[newType].fields[key].data_schema);
createProperty(this, key, value);
});
keysToBeRemoved.forEach((key) => {
const sym = symbolRegistry[key];
delete this[sym];
delete this[key];
});
val = newType;
},
});
}
return {
setLogTypes(newTypes) {
logTypes = newTypes;
updateSymbolRegistry(symbolRegistry, newTypes);
},
createLog(props = {}, _lastSync = 0) {
if (!props.localID) {
throw new Error('A localID must be provided when creating a new log.');
}
// Set a common timestamp to be used for the latest change on all properties.
const _changed = props.changed || Math.floor(Date.now() / 1000);
const log = {};
// Set properties for what farmOS considers "properties" (vs "fields").
createProperty(log, 'name', (props.name || ''), _changed);
createProperty(log, 'timestamp', (props.timestamp || _changed), _changed);
createProperty(log, 'done', (props.done || false), _changed);
// If the log is coming from the server, freeze its type; otherwise, use
// the special createTypeProperty function.
const type = props.type || 'farm_activity';
if (props.id) {
setOnce(log, 'type', type);
} else {
createTypeProperty(log, type);
}
// Set properties for "fields".
const schema = logTypes[type]?.fields;
Object.entries(schema).forEach(([key, { data_schema: dataSchema }]) => {
const val = props[key] !== undefined ? props[key] : makeDefault(dataSchema);
createProperty(log, key, val);
});
// Add enumerable props directly for identifying logs; since these can't
// be changed once set, they need no metadata, and should only be set once.
setOnce(log, 'localID', props.localID);
setOnce(log, 'id', props.id);
setOnce(log, 'url', props.url);
// Record metadata for the last time the log was synced (defaults to 0).
Object.defineProperty(log, lastSync, {
enumerable: false,
value: _lastSync,
});
// Once an id has been assigned by the server, freeze the type and prevent
// the object from being extended. Otherwise, keep the type writable and
// allow properties to be changed depending on type.
if (log.id) {
setOnce(log, 'type', type);
Object.preventExtensions(log);
} else {
createTypeProperty(log, type);
}
return log;
},
formatLogForServer(log) {
const serverLog = { ...log };
delete serverLog.localID;
return serverLog;
},
mergeLogFromServer(localLog, _serverLog) {
// Clean up the server response by coercing strings to numbers, numbers
// to bools.
const serverLog = {
..._serverLog,
changed: +_serverLog.changed,
timestamp: +_serverLog.timestamp,
done: !!+_serverLog.done,
};
// Main logic for merging log properties between the server and local device.
function mergeProps(key) {
const sym = symbolRegistry[key];
// If the server log changed more recently than the local log, and
// the local log was synced more recently than it changed,
// use the server log's value.
if (serverLog.changed > localLog[sym][changed]
&& localLog[lastSync] > localLog[sym][changed]) {
localLog[sym][changed] = serverLog.changed;
localLog[sym][data] = serverLog[key];
return;
}
// If the local log changed more recently than server log, or
// the local log was synced more recently than it changed,
// keep the local log's value (ie, do nothing).
if (serverLog.changed < localLog[sym][changed]
|| localLog[lastSync] > localLog[sym][changed]) {
return;
}
// Otherwise, the server log changed since the last sync, while
// the local log has outstanding changes, so we have a conflict.
localLog[sym][conflicts].push({
[changed]: serverLog.changed,
[data]: serverLog[key],
});
}
// Iterate over all fields for the given log type and merge the properties.
Object.entries(logTypes[localLog.type].fields).forEach(([key, { type }]) => {
// Due to a bug on the server, notes and other text_long fields sometimes
// come from the server with value of [], which gets rejected if sent back
// to the server, so we need to reset it to null to correct the error.
if (type === 'text_long' && Array.isArray(serverLog[key])) {
serverLog[key] = null;
}
mergeProps(key);
});
if (localLog.id === undefined) {
localLog.id = serverLog.id;
localLog.url = serverLog.url;
}
localLog[lastSync] = Math.floor(Date.now() / 1000);
},
serializeLog(log) {
const newLog = Object.keys(log).reduce((obj, key) => {
const sym = symbolRegistry[key];
// B/c some props, like id, aren't in the symbolRegistry and don't have metadata.
if (!sym) {
return { ...obj, [key]: log[key] };
}
return {
...obj,
[key]: {
data: log[sym][data],
changed: log[sym][changed],
conflicts: log[sym][conflicts],
},
};
}, {});
newLog.lastSync = log[lastSync];
return newLog;
},
deserializeLog(log) {
const newLog = {};
Object.entries(log).forEach(([key, val]) => {
const sym = symbolRegistry[key];
// First handle the special cases of the lastSync & type props.
if (key === 'lastSync') {
newLog[lastSync] = val;
} else if (key === 'type') {
createTypeProperty(newLog, val);
// Then any props that aren't in the symbol reg, like url & localID.
} else if (!sym) {
setOnce(newLog, key, val);
// The rest should be regular props with metadata.
} else {
createProperty(newLog, key, val);
}
});
return newLog;
},
getLastChange(log, key) {
const sym = symbolRegistry[key];
return log[sym][changed];
},
getLastSync(log) {
return log[lastSync];
},
getConflicts(log) {
return Object.entries(symbolRegistry).reduce((_conflicts, [key, sym]) => {
if (log[sym][conflicts].length > 0) {
return {
..._conflicts,
[key]: log[sym][conflicts],
};
}
return _conflicts;
}, {});
},
resolveConflict(log, key, val) {
const sym = symbolRegistry[key];
log[sym][data] = val;
log[sym][changed] = Math.floor(Date.now() / 1000);
log[sym][conflicts] = [];
},
};
}
export const {
setLogTypes,
createLog,
formatLogForServer,
mergeLogFromServer,
serializeLog,
deserializeLog,
getLastChange,
getLastSync,
getConflicts,
resolveConflict,
} = farmLog(defaultResources.log);