Skip to content

Commit d4837ce

Browse files
authored
fix: BinaryEncoding did not encode/decode the Clear message type (#38)
1 parent f63b4e7 commit d4837ce

File tree

2 files changed

+45
-2
lines changed

2 files changed

+45
-2
lines changed

packages/bentocache/src/bus/encoders/binary_encoder.ts

+14-2
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,18 @@ export class BinaryEncoder implements TransportEncoder {
3030
this.#busIdLength = busIdLength
3131
}
3232

33+
protected busMessageTypeToNum(type: CacheBusMessageType): number {
34+
if (type === CacheBusMessageType.Set) return 0x01
35+
if (type === CacheBusMessageType.Clear) return 0x02
36+
return 0x03
37+
}
38+
39+
protected numToBusMessageType(num: number): CacheBusMessageType {
40+
if (num === 0x01) return CacheBusMessageType.Set
41+
if (num === 0x02) return CacheBusMessageType.Clear
42+
return CacheBusMessageType.Delete
43+
}
44+
3345
/**
3446
* Encode the given message into a Buffer
3547
*/
@@ -59,7 +71,7 @@ export class BinaryEncoder implements TransportEncoder {
5971
/**
6072
* 2. write the message type. 0x01 for 'Set' message, and 0x02 for a 'Delete' message
6173
*/
62-
buffer.writeUInt8(payload.type === CacheBusMessageType.Set ? 0x01 : 0x02, this.#busIdLength)
74+
buffer.writeUInt8(this.busMessageTypeToNum(payload.type), this.#busIdLength)
6375

6476
/**
6577
* 3. Write the keys
@@ -100,7 +112,7 @@ export class BinaryEncoder implements TransportEncoder {
100112
* Then comes the message type as a single byte
101113
*/
102114
const typeValue = buffer.readUInt8(offset++)
103-
const type = typeValue === 0x01 ? CacheBusMessageType.Set : CacheBusMessageType.Delete
115+
const type = this.numToBusMessageType(typeValue)
104116

105117
/**
106118
* Finally, the keys

packages/bentocache/tests/bus/bus.spec.ts

+31
Original file line numberDiff line numberDiff line change
@@ -269,6 +269,37 @@ test.group('Bus synchronization', () => {
269269
})
270270
.waitForDone()
271271
.disableTimeout()
272+
273+
test('binary encoding/decoding using Clear should be fine', async ({ assert, cleanup }, done) => {
274+
const bus1 = redisBusDriver({ connection: REDIS_CREDENTIALS })
275+
.factory(null as any)
276+
.setId('foo')
277+
278+
const bus2 = redisBusDriver({ connection: REDIS_CREDENTIALS })
279+
.factory(null as any)
280+
.setId('bar')
281+
282+
cleanup(async () => {
283+
await bus1.disconnect()
284+
await bus2.disconnect()
285+
})
286+
287+
const data = {
288+
keys: [],
289+
type: CacheBusMessageType.Clear,
290+
}
291+
292+
bus1.subscribe('foo', (message: any) => {
293+
assert.deepInclude(message, data)
294+
done()
295+
})
296+
297+
await setTimeout(200)
298+
299+
await bus2.publish('foo', data)
300+
})
301+
.waitForDone()
302+
.disableTimeout()
272303

273304
test('works with utf8 characters', async ({ assert }, done) => {
274305
const bus1 = redisBusDriver({ connection: REDIS_CREDENTIALS })

0 commit comments

Comments
 (0)