Unverified Commit b88e3de1 authored by Hong Minhee's avatar Hong Minhee
Browse files

Refactor RedisKvStore.list() to use single loop

Extract pattern and exactKey before the conditional logic, then use
a unified scanning loop.

https://github.com/fedify-dev/fedify/pull/500#discussion_r2641826553



Co-Authored-By: default avatarClaude <noreply@anthropic.com>
parent 747db70c
Loading
Loading
Loading
Loading
+32 −48
Original line number Diff line number Diff line
@@ -126,48 +126,33 @@ export class RedisKvStore implements KvStore {
   * @since 1.10.0
   */
  async *list(prefix?: KvKey): AsyncIterable<KvStoreListEntry> {
    let pattern: string;
    let exactKey: string | Buffer | null = null;

    if (prefix == null || prefix.length === 0) {
      // Empty prefix: scan for all keys with the key prefix
      const pattern = `${this.#keyPrefixStr}*`;

      let cursor = "0";
      do {
        const [nextCursor, keys] = await this.#redis.scan(
          cursor,
          "MATCH",
          pattern,
          "COUNT",
          100,
        );
        cursor = nextCursor;

        for (const key of keys) {
          const encodedValue = await this.#redis.getBuffer(key);
          if (encodedValue == null) continue;
          yield {
            key: this.#deserializeKey(key),
            value: this.#codec.decode(encodedValue),
          };
        }
      } while (cursor !== "0");
      pattern = `${this.#keyPrefixStr}*`;
    } else {
      const prefixKey = this.#serializeKey(prefix);
      const prefixKeyFullStr = typeof prefixKey === "string"
        ? prefixKey
        : new TextDecoder().decode(new Uint8Array(prefixKey));
      exactKey = prefixKey;
      pattern = `${prefixKeyFullStr}::*`;
    }

    // First, check if the exact prefix key exists
      const exactValue = await this.#redis.getBuffer(prefixKey);
    if (exactKey != null) {
      const exactValue = await this.#redis.getBuffer(exactKey);
      if (exactValue != null) {
        yield {
          key: prefix,
          key: prefix!,
          value: this.#codec.decode(exactValue),
        };
      }
    }

      // Then scan for all keys starting with prefix::
      const pattern = `${prefixKeyFullStr}::*`;

    // Scan for all keys matching the pattern
    let cursor = "0";
    do {
      const [nextCursor, keys] = await this.#redis.scan(
@@ -190,4 +175,3 @@ export class RedisKvStore implements KvStore {
    } while (cursor !== "0");
  }
}
}