-
Notifications
You must be signed in to change notification settings - Fork 8
/
Locks.test.ts
468 lines (412 loc) · 15.7 KB
/
Locks.test.ts
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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
import { it, describe, expect, vi, beforeEach } from 'vitest';
import { PresenceMessage, Realtime, RealtimeClient, RealtimePresence } from 'ably';
import Space from './Space.js';
import type { SpaceMember, LockStatus } from './types.js';
import { createPresenceMessage } from './utilities/test/fakes.js';
interface SpaceTestContext {
client: RealtimeClient;
space: Space;
presence: RealtimePresence;
presenceMap: Map<string, PresenceMessage>;
}
vi.mock('ably');
describe('Locks', () => {
beforeEach<SpaceTestContext>((context) => {
const client = new Realtime({});
const presence = client.channels.get('').presence;
const presenceMap = new Map();
// support entering the space, which requires presence.get() to return a
// presenceMap including an entry for the client's connectionId, and also
// include some members with connectionIds which sort before and after for
// testing lock invalidation
vi.spyOn(presence, 'get').mockImplementation(async () => {
return Array.from(presenceMap.values());
});
presenceMap.set('1', createPresenceMessage('enter', { connectionId: '1' }));
presenceMap.set('0', createPresenceMessage('enter', { connectionId: '0' }));
presenceMap.set('2', createPresenceMessage('enter', { connectionId: '2' }));
context.client = client;
context.space = new Space('test', client);
context.presence = presence;
context.presenceMap = presenceMap;
});
describe('acquire', () => {
it<SpaceTestContext>('errors if acquiring before entering the space', ({ space, presence }) => {
// override presence.get() so the current member is not in presence
vi.spyOn(presence, 'get').mockImplementation(async () => []);
expect(space.locks.acquire('test')).rejects.toThrowError();
});
it<SpaceTestContext>('enters presence with a PENDING lock request for the current member', async ({
space,
presence,
}) => {
const presenceUpdate = vi.spyOn(presence, 'update');
const lockID = 'test';
const req = await space.locks.acquire(lockID);
expect(req.status).toBe('pending');
const presenceMessage = expect.objectContaining({
extras: {
locks: [
expect.objectContaining({
id: lockID,
status: 'pending',
}),
],
},
});
expect(presenceUpdate).toHaveBeenCalledWith(presenceMessage);
});
it<SpaceTestContext>('includes attributes in the lock request when provided', async ({ space, presence }) => {
const presenceUpdate = vi.spyOn(presence, 'update');
const lockID = 'test';
const attributes = { key1: 'foo', key2: 'bar' };
const req = await space.locks.acquire(lockID, { attributes });
expect(req.attributes).toBe(attributes);
const presenceMessage = expect.objectContaining({
extras: {
locks: [expect.objectContaining({ attributes })],
},
});
expect(presenceUpdate).toHaveBeenCalledWith(presenceMessage);
});
it<SpaceTestContext>('errors if a PENDING request already exists', async ({ space }) => {
const lockID = 'test';
await space.locks.acquire(lockID);
expect(space.locks.acquire(lockID)).rejects.toThrowError();
});
});
describe('processPresenceMessage', () => {
const lockID = 'test';
const lockEvent = (member: SpaceMember, status: LockStatus) =>
expect.objectContaining({
member: member,
id: lockID,
status,
});
it<SpaceTestContext>('sets a PENDING request to LOCKED', async ({ space }) => {
const member = (await space.members.getSelf())!;
const emitSpy = vi.spyOn(space.locks, 'emit');
const msg = Realtime.PresenceMessage.fromValues({
action: 'update',
connectionId: member.connectionId,
extras: {
locks: [
{
id: lockID,
status: 'pending',
timestamp: Date.now(),
},
],
},
});
await space.locks.processPresenceMessage(msg);
const lock = space.locks.getLock(lockID, member.connectionId)!;
expect(lock.status).toBe('locked');
expect(emitSpy).toHaveBeenCalledWith('update', lockEvent(member, 'locked'));
});
// use table driven tests to check whether a PENDING request for "self"
// (i.e. the current member) transitions to LOCKED or UNLOCKED when the
// referenced lock is already held by some other member with timestamp
// and/or connectionId before/after the current member's request.
const now = Date.now();
describe.each([
{
name: 'when the other member has the lock with an earlier timestamp',
desc: 'assigns the lock to the other member',
otherConnId: '0',
otherTimestamp: now - 100,
expectedSelfStatus: undefined,
expectedOtherStatus: 'locked',
},
{
name: 'when the other member has the lock with the same timestamp but a lower connectionId',
desc: 'assigns the lock to the other member',
otherConnId: '0',
otherTimestamp: now,
expectedSelfStatus: undefined,
expectedOtherStatus: 'locked',
},
{
name: 'when the other member has the lock with the same timestamp but a higher connectionId',
desc: 'assigns the lock to self',
otherConnId: '2',
otherTimestamp: now,
expectedSelfStatus: 'locked',
expectedOtherStatus: undefined,
},
{
name: 'when the other member has the lock with a later timestamp',
desc: 'assigns the lock to self',
otherConnId: '0',
otherTimestamp: now + 100,
expectedSelfStatus: 'locked',
expectedOtherStatus: undefined,
},
])('$name', ({ desc, otherConnId, otherTimestamp, expectedSelfStatus, expectedOtherStatus }) => {
it<SpaceTestContext>(desc, async ({ client, space }) => {
// process a PENDING request for the other member, which should
// transition to LOCKED
let msg = Realtime.PresenceMessage.fromValues({
action: 'update',
connectionId: otherConnId,
extras: {
locks: [
{
id: lockID,
status: 'pending',
timestamp: otherTimestamp,
},
],
},
});
await space.locks.processPresenceMessage(msg);
const lock = space.locks.get(lockID)!;
expect(lock.member.connectionId).toBe(otherConnId);
// process a PENDING request for the current member and check the
// result matches what is expected
const emitSpy = vi.spyOn(space.locks, 'emit');
msg = Realtime.PresenceMessage.fromValues({
action: 'update',
connectionId: client.connection.id,
extras: {
locks: [
{
id: lockID,
status: 'pending',
timestamp: now,
},
],
},
});
await space.locks.processPresenceMessage(msg);
const selfMember = (await space.members.getByConnectionId(client.connection.id!))!;
const selfLock = space.locks.getLock(lockID, selfMember.connectionId)!;
expect(selfLock?.status).toBe(expectedSelfStatus);
const otherMember = (await space.members.getByConnectionId(otherConnId))!;
const otherLock = space.locks.getLock(lockID, otherMember.connectionId)!;
expect(otherLock?.status).toBe(expectedOtherStatus);
if (!expectedSelfStatus) {
expect(emitSpy).toHaveBeenCalledTimes(1);
expect(emitSpy).toHaveBeenNthCalledWith(1, 'update', lockEvent(selfMember, 'unlocked'));
} else {
expect(emitSpy).toHaveBeenCalledTimes(2);
expect(emitSpy).toHaveBeenNthCalledWith(1, 'update', lockEvent(otherMember, 'unlocked'));
expect(emitSpy).toHaveBeenNthCalledWith(2, 'update', lockEvent(selfMember, 'locked'));
}
});
});
it<SpaceTestContext>('sets a released request to UNLOCKED', async ({ space }) => {
const member = (await space.members.getSelf())!;
let msg = Realtime.PresenceMessage.fromValues({
action: 'update',
connectionId: member.connectionId,
extras: {
locks: [
{
id: lockID,
status: 'pending',
timestamp: Date.now(),
},
],
},
});
await space.locks.processPresenceMessage(msg);
const emitSpy = vi.spyOn(space.locks, 'emit');
msg = Realtime.PresenceMessage.fromValues({
action: 'update',
connectionId: member.connectionId,
extras: undefined,
});
await space.locks.processPresenceMessage(msg);
const lock = space.locks.getLock(lockID, member.connectionId);
expect(lock).not.toBeDefined();
expect(emitSpy).toHaveBeenCalledWith('update', lockEvent(member, 'unlocked'));
});
it<SpaceTestContext>('sets all locks to UNLOCKED when a member leaves', async ({ space }) => {
const member = (await space.members.getSelf())!;
let msg = Realtime.PresenceMessage.fromValues({
action: 'update',
connectionId: member.connectionId,
extras: {
locks: [
{
id: 'lock1',
status: 'pending',
timestamp: Date.now(),
},
{
id: 'lock2',
status: 'pending',
timestamp: Date.now(),
},
],
},
});
await space.locks.processPresenceMessage(msg);
let lock1 = space.locks.get('lock1');
expect(lock1).toBeDefined();
expect(lock1!.member).toEqual(member);
let lock2 = space.locks.get('lock2');
expect(lock2).toBeDefined();
expect(lock2!.member).toEqual(member);
msg.action = 'leave';
await space.locks.processPresenceMessage(msg);
lock1 = space.locks.get('lock1');
expect(lock1).not.toBeDefined();
lock2 = space.locks.get('lock2');
expect(lock2).not.toBeDefined();
});
});
describe('release', () => {
it<SpaceTestContext>('errors if releasing before entering the space', ({ space, presence }) => {
// override presence.get() so the current member is not in presence
vi.spyOn(presence, 'get').mockImplementation(async () => []);
expect(space.locks.release('test')).rejects.toThrowError();
});
it<SpaceTestContext>('removes the identified lock request from presence extras', async ({ space, presence }) => {
const member = (await space.members.getSelf())!;
const lockID = 'test';
const timestamp = Date.now();
const msg = Realtime.PresenceMessage.fromValues({
connectionId: member.connectionId,
extras: {
locks: [
{
id: lockID,
status: 'pending',
timestamp,
},
],
},
});
await space.locks.processPresenceMessage(msg);
expect(space.locks.get(lockID)).toBeDefined();
const presenceUpdate = vi.spyOn(presence, 'update');
await space.locks.release(lockID);
expect(presenceUpdate).toHaveBeenCalledTimes(1);
const updateMsg = presenceUpdate.mock.calls[0][0];
expect(updateMsg.extras).toEqual({ locks: [{ id: lockID, member, timestamp, status: 'unlocked' }] });
});
});
describe('get*', () => {
beforeEach<SpaceTestContext>(async ({ space }) => {
await space.locks.processPresenceMessage(
Realtime.PresenceMessage.fromValues({
action: 'update',
connectionId: '1',
extras: {
locks: [
{
id: 'lock1',
status: 'pending',
timestamp: Date.now(),
},
{
id: 'lock2',
status: 'pending',
timestamp: Date.now(),
},
],
},
}),
);
await space.locks.processPresenceMessage(
Realtime.PresenceMessage.fromValues({
action: 'update',
connectionId: '2',
extras: {
locks: [
{
id: 'lock3',
status: 'pending',
timestamp: Date.now(),
},
],
},
}),
);
});
it<SpaceTestContext>('correctly sets up locks', ({ space }) => {
const lock1 = space.locks.get('lock1');
expect(lock1).toBeDefined();
const lock2 = space.locks.get('lock2');
expect(lock2).toBeDefined();
const lock3 = space.locks.get('lock3');
expect(lock3).toBeDefined();
});
it<SpaceTestContext>('returns the lock by value, not reference', ({ space }) => {
const lockGet1 = space.locks.get('lock1');
const lockGet2 = space.locks.get('lock1');
expect(lockGet1).toEqual(expect.objectContaining({ status: 'locked' }));
// Note we are using toBe here on purpose, to check the reference, not value
expect(lockGet1).not.toBe(lockGet2);
});
it<SpaceTestContext>('returns locks by value, not reference', async ({ space }) => {
const lockGetAll1 = await space.locks.getAll();
const lockGetAll2 = await space.locks.getAll();
expect(lockGetAll1).toEqual(expect.arrayContaining([expect.objectContaining({ status: 'locked' })]));
// Note we are using toBe here on purpose, to check the reference, not value
expect(lockGetAll1[0]).not.toBe(lockGetAll2[0]);
});
describe('getSelf', () => {
it<SpaceTestContext>('returns all locks in the LOCKED state that belong to self', async ({ space }) => {
const member1 = await space.members.getByConnectionId('1')!;
const locks = await space.locks.getSelf();
expect(locks.length).toEqual(2);
for (const lock of locks) {
switch (lock.id) {
case 'lock1':
case 'lock2':
expect(lock.member).toEqual(member1);
break;
default:
throw new Error(`unexpected lock id: ${lock.id}`);
}
}
});
it<SpaceTestContext>('returns locks by value not reference', async ({ space }) => {
const locksGetSelf1 = await space.locks.getSelf();
const locksGetSelf2 = await space.locks.getSelf();
// Note we are using toBe here on purpose, to check the reference, not value
expect(locksGetSelf1[0]).not.toBe(locksGetSelf2[0]);
});
});
describe('getOthers', () => {
it<SpaceTestContext>('returns all locks in the LOCKED state for every member but self', async ({ space }) => {
const member2 = await space.members.getByConnectionId('2')!;
const locks = await space.locks.getOthers();
expect(locks.length).toEqual(1);
for (const lock of locks) {
switch (lock.id) {
case 'lock3':
expect(lock.member).toEqual(member2);
break;
default:
throw new Error(`unexpected lock id: ${lock.id}`);
}
}
});
});
describe('getAll', () => {
it<SpaceTestContext>('returns all locks in the LOCKED state', async ({ space }) => {
const member1 = await space.members.getByConnectionId('1')!;
const member2 = await space.members.getByConnectionId('2')!;
const locks = await space.locks.getAll();
expect(locks.length).toEqual(3);
for (const lock of locks) {
switch (lock.id) {
case 'lock1':
case 'lock2':
expect(lock.member).toEqual(member1);
break;
case 'lock3':
expect(lock.member).toEqual(member2);
break;
default:
throw new Error(`unexpected lock id: ${lock.id}`);
}
}
});
});
});
});