|
| 1 | +// deno-lint-ignore-file no-explicit-any |
| 2 | +import type { MessageQueue, MessageQueueEnqueueOptions } from "@fedify/fedify"; |
| 3 | +import type { Redis, RedisKey } from "ioredis"; |
| 4 | +import { type Codec, JsonCodec } from "./codec.ts"; |
| 5 | + |
| 6 | +/** |
| 7 | + * Options for {@link RedisMessageQueue} class. |
| 8 | + */ |
| 9 | +export interface RedisMessageQueueOptions { |
| 10 | + /** |
| 11 | + * The unique identifier for the worker that is processing messages from the |
| 12 | + * queue. If this is not specified, a random identifier will be generated. |
| 13 | + * This is used to prevent multiple workers from processing the same message, |
| 14 | + * so it should be unique for each worker. |
| 15 | + */ |
| 16 | + workerId?: string; |
| 17 | + |
| 18 | + /** |
| 19 | + * The Pub/Sub channel key to use for the message queue. `"fedify_channel"` |
| 20 | + * by default. |
| 21 | + */ |
| 22 | + channelKey?: RedisKey; |
| 23 | + |
| 24 | + /** |
| 25 | + * The Sorted Set key to use for the delayed message queue. `"fedify_queue"` |
| 26 | + * by default. |
| 27 | + */ |
| 28 | + queueKey?: RedisKey; |
| 29 | + |
| 30 | + /** |
| 31 | + * The key to use for locking the message queue. `"fedify_lock"` by default. |
| 32 | + */ |
| 33 | + lockKey?: RedisKey; |
| 34 | + |
| 35 | + /** |
| 36 | + * The codec to use for encoding and decoding messages in the key-value store. |
| 37 | + * Defaults to {@link JsonCodec}. |
| 38 | + */ |
| 39 | + codec?: Codec; |
| 40 | + |
| 41 | + /** |
| 42 | + * The interval at which to poll the message queue for delayed messages. |
| 43 | + * If this interval is too short, it may cause excessive load on the Redis |
| 44 | + * server. If it is too long, it may cause messages to be delayed longer |
| 45 | + * than expected. |
| 46 | + * |
| 47 | + * 5 seconds by default. |
| 48 | + */ |
| 49 | + loopInterval?: Temporal.DurationLike; |
| 50 | +} |
| 51 | + |
| 52 | +/** |
| 53 | + * A message queue that uses Redis as the underlying storage. |
| 54 | + */ |
| 55 | +export class RedisMessageQueue implements MessageQueue, Disposable { |
| 56 | + #redis: Redis; |
| 57 | + #subRedis: Redis; |
| 58 | + #workerId: string; |
| 59 | + #channelKey: RedisKey; |
| 60 | + #queueKey: RedisKey; |
| 61 | + #lockKey: RedisKey; |
| 62 | + #codec: Codec; |
| 63 | + #loopInterval: Temporal.Duration; |
| 64 | + #loopHandle?: ReturnType<typeof setInterval>; |
| 65 | + |
| 66 | + /** |
| 67 | + * Creates a new Redis message queue. |
| 68 | + * @param redis The Redis client factory. |
| 69 | + * @param options The options for the message queue. |
| 70 | + */ |
| 71 | + constructor(redis: () => Redis, options: RedisMessageQueueOptions = {}) { |
| 72 | + this.#redis = redis(); |
| 73 | + this.#subRedis = redis(); |
| 74 | + this.#workerId = options.workerId ?? crypto.randomUUID(); |
| 75 | + this.#channelKey = options.channelKey ?? "fedify_channel"; |
| 76 | + this.#queueKey = options.queueKey ?? "fedify_queue"; |
| 77 | + this.#lockKey = options.lockKey ?? "fedify_lock"; |
| 78 | + this.#codec = options.codec ?? new JsonCodec(); |
| 79 | + this.#loopInterval = Temporal.Duration.from( |
| 80 | + options.loopInterval ?? { seconds: 5 }, |
| 81 | + ); |
| 82 | + } |
| 83 | + |
| 84 | + async enqueue( |
| 85 | + message: any, |
| 86 | + options?: MessageQueueEnqueueOptions, |
| 87 | + ): Promise<void> { |
| 88 | + const ts = options?.delay == null |
| 89 | + ? 0 |
| 90 | + : Temporal.Now.instant().add(options.delay).epochMilliseconds; |
| 91 | + const encodedMessage = this.#codec.encode(message); |
| 92 | + await this.#redis.zadd(this.#queueKey, ts, encodedMessage); |
| 93 | + if (ts < 1) this.#redis.publish(this.#channelKey, ""); |
| 94 | + } |
| 95 | + |
| 96 | + async #poll(): Promise<any | undefined> { |
| 97 | + const result = await this.#redis.setnx(this.#lockKey, this.#workerId); |
| 98 | + if (result < 1) return; |
| 99 | + await this.#redis.expire( |
| 100 | + this.#lockKey, |
| 101 | + this.#loopInterval.total({ unit: "seconds" }) * 2, |
| 102 | + ); |
| 103 | + const messages = await this.#redis.zrangebyscoreBuffer( |
| 104 | + this.#queueKey, |
| 105 | + 0, |
| 106 | + Temporal.Now.instant().epochMilliseconds, |
| 107 | + ); |
| 108 | + try { |
| 109 | + if (messages.length < 1) return; |
| 110 | + const message = messages[0]; |
| 111 | + await this.#redis.zrem(this.#queueKey, message); |
| 112 | + return this.#codec.decode(message); |
| 113 | + } finally { |
| 114 | + await this.#redis.del(this.#lockKey); |
| 115 | + } |
| 116 | + } |
| 117 | + |
| 118 | + listen(handler: (message: any) => void | Promise<void>): void { |
| 119 | + if (this.#loopHandle != null) { |
| 120 | + throw new Error("Already listening"); |
| 121 | + } |
| 122 | + this.#loopHandle = setInterval(async () => { |
| 123 | + const message = await this.#poll(); |
| 124 | + if (message === undefined) return; |
| 125 | + await handler(message); |
| 126 | + }, this.#loopInterval.total({ unit: "milliseconds" })); |
| 127 | + this.#subRedis.subscribe(this.#channelKey, () => { |
| 128 | + this.#subRedis.on("message", async () => { |
| 129 | + const message = await this.#poll(); |
| 130 | + if (message === undefined) return; |
| 131 | + await handler(message); |
| 132 | + }); |
| 133 | + }); |
| 134 | + } |
| 135 | + |
| 136 | + [Symbol.dispose](): void { |
| 137 | + clearInterval(this.#loopHandle); |
| 138 | + this.#redis.disconnect(); |
| 139 | + this.#subRedis.disconnect(); |
| 140 | + } |
| 141 | +} |
0 commit comments