-
Notifications
You must be signed in to change notification settings - Fork 58
Expand file tree
/
Copy pathobjects_helper.js
More file actions
419 lines (353 loc) · 10.6 KB
/
objects_helper.js
File metadata and controls
419 lines (353 loc) · 10.6 KB
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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
'use strict';
/**
* Helper class to create pre-determined objects tree on channels and create object messages.
*/
define(['ably', 'shared_helper', 'objects'], function (Ably, Helper, ObjectsPlugin) {
const createPM = Ably.makeProtocolMessageFromDeserialized({ ObjectsPlugin });
const ACTIONS = {
MAP_CREATE: 0,
MAP_SET: 1,
MAP_REMOVE: 2,
COUNTER_CREATE: 3,
COUNTER_INC: 4,
OBJECT_DELETE: 5,
};
const ACTION_STRINGS = {
MAP_CREATE: 'MAP_CREATE',
MAP_SET: 'MAP_SET',
MAP_REMOVE: 'MAP_REMOVE',
COUNTER_CREATE: 'COUNTER_CREATE',
COUNTER_INC: 'COUNTER_INC',
OBJECT_DELETE: 'OBJECT_DELETE',
};
function nonce() {
return Helper.randomString();
}
class ObjectsHelper {
constructor(helper) {
this._helper = helper;
this._rest = helper.AblyRest({ useBinaryProtocol: false });
}
static ACTIONS = ACTIONS;
static fixtureRootKeys() {
return ['emptyCounter', 'initialValueCounter', 'referencedCounter', 'emptyMap', 'referencedMap', 'valuesMap'];
}
/**
* Sends Objects REST API requests to create objects tree on a provided channel:
*
* root "emptyMap" -> Map#1 {} -- empty map
* root "referencedMap" -> Map#2 { "counterKey": <object id Counter#3> }
* root "valuesMap" -> Map#3 { "stringKey": "stringValue", "emptyStringKey": "", "bytesKey": <byte array for "{"productId": "001", "productName": "car"}", encoded in base64>, "emptyBytesKey": <empty byte array>, "numberKey": 1, "zeroKey": 0, "trueKey": true, "falseKey": false, "mapKey": <objectId of Map#2> }
* root "emptyCounter" -> Counter#1 -- no initial value counter, should be 0
* root "initialValueCounter" -> Counter#2 count=10
* root "referencedCounter" -> Counter#3 count=20
*/
async initForChannel(channelName) {
const emptyCounter = await this.createAndSetOnMap(channelName, {
mapObjectId: 'root',
key: 'emptyCounter',
createOp: this.counterCreateRestOp(),
});
const initialValueCounter = await this.createAndSetOnMap(channelName, {
mapObjectId: 'root',
key: 'initialValueCounter',
createOp: this.counterCreateRestOp({ number: 10 }),
});
const referencedCounter = await this.createAndSetOnMap(channelName, {
mapObjectId: 'root',
key: 'referencedCounter',
createOp: this.counterCreateRestOp({ number: 20 }),
});
const emptyMap = await this.createAndSetOnMap(channelName, {
mapObjectId: 'root',
key: 'emptyMap',
createOp: this.mapCreateRestOp(),
});
const referencedMap = await this.createAndSetOnMap(channelName, {
mapObjectId: 'root',
key: 'referencedMap',
createOp: this.mapCreateRestOp({ data: { counterKey: { objectId: referencedCounter.objectId } } }),
});
const valuesMap = await this.createAndSetOnMap(channelName, {
mapObjectId: 'root',
key: 'valuesMap',
createOp: this.mapCreateRestOp({
data: {
stringKey: { string: 'stringValue' },
emptyStringKey: { string: '' },
bytesKey: { bytes: 'eyJwcm9kdWN0SWQiOiAiMDAxIiwgInByb2R1Y3ROYW1lIjogImNhciJ9' },
emptyBytesKey: { bytes: '' },
numberKey: { number: 1 },
zeroKey: { number: 0 },
trueKey: { boolean: true },
falseKey: { boolean: false },
mapKey: { objectId: referencedMap.objectId },
},
}),
});
}
// #region Wire Object Messages
mapCreateOp(opts) {
const { objectId, entries } = opts ?? {};
const op = {
operation: {
action: ACTIONS.MAP_CREATE,
nonce: nonce(),
objectId,
map: {
semantics: 0,
},
},
};
if (entries) {
op.operation.map = {
...op.operation.map,
entries,
};
}
return op;
}
mapSetOp(opts) {
const { objectId, key, data } = opts ?? {};
const op = {
operation: {
action: ACTIONS.MAP_SET,
objectId,
mapOp: {
key,
data,
},
},
};
return op;
}
mapRemoveOp(opts) {
const { objectId, key } = opts ?? {};
const op = {
operation: {
action: ACTIONS.MAP_REMOVE,
objectId,
mapOp: {
key,
},
},
};
return op;
}
counterCreateOp(opts) {
const { objectId, count } = opts ?? {};
const op = {
operation: {
action: ACTIONS.COUNTER_CREATE,
nonce: nonce(),
objectId,
},
};
if (count != null) {
op.operation.counter = { count };
}
return op;
}
counterIncOp(opts) {
const { objectId, amount } = opts ?? {};
const op = {
operation: {
action: ACTIONS.COUNTER_INC,
objectId,
counterOp: {
amount,
},
},
};
return op;
}
objectDeleteOp(opts) {
const { objectId } = opts ?? {};
const op = {
operation: {
action: ACTIONS.OBJECT_DELETE,
objectId,
},
};
return op;
}
mapObject(opts) {
const { objectId, siteTimeserials, initialEntries, materialisedEntries, tombstone } = opts;
const obj = {
object: {
objectId,
siteTimeserials,
tombstone: tombstone === true,
map: {
semantics: 0,
entries: materialisedEntries,
},
},
};
if (initialEntries) {
obj.object.createOp = this.mapCreateOp({ objectId, entries: initialEntries }).operation;
}
return obj;
}
counterObject(opts) {
const { objectId, siteTimeserials, initialCount, materialisedCount, tombstone } = opts;
const obj = {
object: {
objectId,
siteTimeserials,
tombstone: tombstone === true,
counter: {
count: materialisedCount,
},
},
};
if (initialCount != null) {
obj.object.createOp = this.counterCreateOp({ objectId, count: initialCount }).operation;
}
return obj;
}
objectOperationMessage(opts) {
const { channelName, serial, siteCode, state } = opts;
state?.forEach((objectMessage, i) => {
objectMessage.serial = serial;
objectMessage.siteCode = siteCode;
});
return {
action: 19, // OBJECT
channel: channelName,
channelSerial: serial,
state: state ?? [],
};
}
objectStateMessage(opts) {
const { channelName, syncSerial, state } = opts;
return {
action: 20, // OBJECT_SYNC
channel: channelName,
channelSerial: syncSerial,
state: state ?? [],
};
}
async processObjectOperationMessageOnChannel(opts) {
const { channel, ...rest } = opts;
this._helper.recordPrivateApi('call.channel.processMessage');
this._helper.recordPrivateApi('call.makeProtocolMessageFromDeserialized');
await channel.processMessage(
createPM(
this.objectOperationMessage({
...rest,
channelName: channel.name,
}),
),
);
}
async processObjectStateMessageOnChannel(opts) {
const { channel, ...rest } = opts;
this._helper.recordPrivateApi('call.channel.processMessage');
this._helper.recordPrivateApi('call.makeProtocolMessageFromDeserialized');
await channel.processMessage(
createPM(
this.objectStateMessage({
...rest,
channelName: channel.name,
}),
),
);
}
// #endregion
// #region REST API Operations
async createAndSetOnMap(channelName, opts) {
const { mapObjectId, key, createOp } = opts;
const createResult = await this.operationRequest(channelName, createOp);
const objectId = createResult.objectId;
await this.operationRequest(channelName, this.mapSetRestOp({ objectId: mapObjectId, key, value: { objectId } }));
return createResult;
}
mapCreateRestOp(opts) {
const { objectId, nonce, data } = opts ?? {};
const opBody = {
operation: ACTION_STRINGS.MAP_CREATE,
};
if (data) {
opBody.data = data;
}
if (objectId != null) {
opBody.objectId = objectId;
opBody.nonce = nonce;
}
return opBody;
}
mapSetRestOp(opts) {
const { objectId, key, value } = opts ?? {};
const opBody = {
operation: ACTION_STRINGS.MAP_SET,
objectId,
data: {
key,
value,
},
};
return opBody;
}
mapRemoveRestOp(opts) {
const { objectId, key } = opts ?? {};
const opBody = {
operation: ACTION_STRINGS.MAP_REMOVE,
objectId,
data: {
key,
},
};
return opBody;
}
counterCreateRestOp(opts) {
const { objectId, nonce, number } = opts ?? {};
const opBody = {
operation: ACTION_STRINGS.COUNTER_CREATE,
};
if (number != null) {
opBody.data = { number };
}
if (objectId != null) {
opBody.objectId = objectId;
opBody.nonce = nonce;
}
return opBody;
}
counterIncRestOp(opts) {
const { objectId, number } = opts ?? {};
const opBody = {
operation: ACTION_STRINGS.COUNTER_INC,
objectId,
data: { number },
};
return opBody;
}
async operationRequest(channelName, opBody) {
if (Array.isArray(opBody)) {
throw new Error(`Only single object operation requests are supported`);
}
const method = 'post';
const path = `/channels/${channelName}/objects`;
const response = await this._rest.request(method, path, 3, null, opBody, null);
if (response.success) {
// only one operation in the request, so need only the first item.
const result = response.items[0];
// extract objectId if present
result.objectId = result.objectIds?.[0];
return result;
}
throw new Error(
`${method}: ${path} FAILED; http code = ${response.statusCode}, error code = ${response.errorCode}, message = ${response.errorMessage}; operation = ${JSON.stringify(opBody)}`,
);
}
// #endregion
fakeMapObjectId() {
return `map:${Helper.randomString()}@${Date.now()}`;
}
fakeCounterObjectId() {
return `counter:${Helper.randomString()}@${Date.now()}`;
}
}
return (module.exports = ObjectsHelper);
});