Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

9.0 KB
Raw Blame
import RE2 from "re2";

import { applyJitter } from "@app/lib/dates";
import { delay as delayMs } from "@app/lib/delay";
import { Lock } from "@app/lib/red-lock";

import { TKeyStoreFactory } from "./keystore";

export const inMemoryKeyStore = (): TKeyStoreFactory => {
  const store: Record<string, string | number | Buffer> = {};
  const listStore: Record<string, string[]> = {};
  const hashStore: Record<string, Record<string, string>> = {};
  const sortedSetStore: Record<string, Record<string, number>> = {};
  // Exact membership rather than a HyperLogLog
  const distinctStore: Record<string, Set<string>> = {};
  const getRegex = (pattern: string) =>
    new RE2(`^${pattern.replace(/[-[\]/{}()+?.\\^$|]/g, "\\$&").replace(/\*/g, ".*")}$`);

  return {
    setItem: async (key, value) => {
      store[key] = value;
      return "OK";
    },
    setExpiry: async () => 0,
    ttl: async () => -1,
    setItemWithExpiry: async (key, _expiryInSeconds, value) => {
      store[key] = value;
      return "OK";
    },
    setItemWithExpiryNX: async (key, _expiryInSeconds, value) => {
      if (store[key] !== undefined) return null;
      store[key] = value;
      return "OK";
    },
    deleteItem: async (key) => {
      delete store[key];
      delete hashStore[key];
      return 1;
    },
    deleteItems: async ({ pattern, batchSize = 500, delay = 1500, jitter = 200 }) => {
      const regex = getRegex(pattern);
      let totalDeleted = 0;
      const keys = Object.keys(store);

      for (let i = 0; i < keys.length; i += batchSize) {
        const batch = keys.slice(i, i + batchSize);

        for (const key of batch) {
          if (regex.test(key)) {
            delete store[key];
            totalDeleted += 1;
          }
        }

        // eslint-disable-next-line no-await-in-loop
        await delayMs(Math.max(0, applyJitter(delay, jitter)));
      }

      return totalDeleted;
    },
    getItem: async (key) => {
      const value = store[key];
      if (typeof value === "string") {
        return value;
      }
      return null;
    },
    // Redis stores values as bytes, so a string written by setItem reads back as its utf8 bytes here.
    getItemBuffer: async (key) => {
      const value = store[key];
      if (Buffer.isBuffer(value)) return value;
      if (typeof value === "string") return Buffer.from(value, "utf8");
      return null;
    },
    getItemPrimary: async (key) => {
      const value = store[key];
      if (typeof value === "string") {
        return value;
      }
      return null;
    },
    pgGetIntItem: async (key) => {
      const value = store[key];
      if (typeof value === "number") {
        return Number(value);
      }
    },
    hashSet: async (key, field, value) => {
      if (!hashStore[key]) hashStore[key] = {};
      hashStore[key][field] = value;
      return 1;
    },
    hashGet: async (key, field) => {
      return hashStore[key]?.[field] ?? null;
    },
    setIndexedItemWithExpiry: async ({ indexKey, member, itemKey, value, expiryInSeconds, indexed }) => {
      store[itemKey] = value;
      if (!sortedSetStore[indexKey]) sortedSetStore[indexKey] = {};
      if (indexed) {
        sortedSetStore[indexKey][member] = Date.now() + expiryInSeconds * 1000;
      } else {
        delete sortedSetStore[indexKey][member];
      }
    },
    deleteIndexedItems: async ({ indexKey, members, itemKeys }) => {
      itemKeys.forEach((key) => delete store[key]);
      members.forEach((member) => delete sortedSetStore[indexKey]?.[member]);
    },
    sortedSetRangeByScore: async (key, min, max) => {
      const lower = min === "-inf" ? -Infinity : Number(min);
      const upper = max === "+inf" ? Infinity : Number(max);
      return Object.entries(sortedSetStore[key] ?? {})
        .filter(([, score]) => score >= lower && score <= upper)
        .sort(([, a], [, b]) => a - b)
        .map(([member]) => member);
    },
    sortedSetMembersPrimary: async (key) => {
      return Object.entries(sortedSetStore[key] ?? {})
        .sort(([, a], [, b]) => a - b)
        .map(([member]) => member);
    },
    pgIncrementBy: async () => {
      return 1;
    },
    incrementBy: async (key, value) => {
      const current = typeof store[key] === "string" ? parseInt(store[key] as string, 10) : 0;
      const next = current + value;
      store[key] = String(next);
      return next;
    },
    // Enforces the limit rather than always admitting. The stub used to return 1 unconditionally,
    // which silently disabled any cap built on it for whoever wired this store in next.
    incrementByAndRefreshExpiryIfUnderLimit: async (key, limit) => {
      const current = typeof store[key] === "string" ? parseInt(store[key] as string, 10) : 0;
      const next = current + 1;
      if (next > limit) return -1;
      store[key] = String(next);
      return next;
    },
    incrementByIfUnderLimitWithFixedExpiry: async (key, value, limit) => {
      const current = typeof store[key] === "string" ? parseInt(store[key] as string, 10) : 0;
      if (current + value > limit) return -1;
      store[key] = String(current + value);
      return current + value;
    },
    claimLeastLoaded: async (keys, baseOccupancies) => {
      if (keys.length === 0) return 0;
      if (keys.length !== baseOccupancies.length) {
        throw new Error("claimLeastLoaded: baseOccupancies must have one entry per key");
      }
      let bestIdx = 0;
      let bestTotal: number | null = null;
      keys.forEach((key, i) => {
        const reserved = typeof store[key] === "string" ? parseInt(store[key] as string, 10) : 0;
        const total = baseOccupancies[i] + reserved;
        if (bestTotal === null || total < bestTotal) {
          bestTotal = total;
          bestIdx = i + 1;
        }
      });
      const chosen = keys[bestIdx - 1];
      const current = typeof store[chosen] === "string" ? parseInt(store[chosen] as string, 10) : 0;
      store[chosen] = String(current + 1);
      return bestIdx;
    },
    decrementIfExists: async (key) => {
      if (typeof store[key] !== "string") {
        return null;
      }
      const next = parseInt(store[key] as string, 10) - 1;
      store[key] = String(next);
      return next;
    },
    decrementByOrDelete: async (key) => {
      const current = typeof store[key] === "string" ? parseInt(store[key] as string, 10) : 0;
      const next = current - 1;
      if (next <= 0) {
        delete store[key];
        return 0;
      }
      store[key] = String(next);
      return next;
    },
    incrementByWithExpiry: async (key, value) => {
      const current = typeof store[key] === "string" ? parseInt(store[key] as string, 10) : 0;
      const next = current + value;
      store[key] = String(next);
      return next;
    },
    probeDistinctMember: async (key, member) => {
      if (!distinctStore[key]) distinctStore[key] = new Set<string>();
      const members = distinctStore[key];
      if (members.has(member)) return false;
      members.add(member);
      return true;
    },
    incrementSeededWithExpiry: async (key, seed) => {
      const existing = store[key];
      if (existing === undefined) {
        const seeded = 1 + seed;
        store[key] = String(seeded);
        return seeded;
      }
      const next = (typeof existing === "string" ? parseInt(existing, 10) : 0) + 1;
      store[key] = String(next);
      return next;
    },
    acquireLock: () => {
      return Promise.resolve({
        release: () => {}
      }) as Promise<Lock>;
    },
    waitTillReady: async () => {},
    getKeysByPattern: async (pattern) => {
      const regex = getRegex(pattern);
      const keys = Object.keys(store);
      return keys.filter((key) => regex.test(key));
    },
    deleteItemsByKeyIn: async (keys) => {
      for (const key of keys) {
        delete store[key];
      }
      return keys.length;
    },
    getItemsPrimary: async (keys) => {
      return keys.map((key) => {
        const value = store[key];
        return typeof value === "string" ? value : null;
      });
    },
    getItems: async (keys) => {
      const values = keys.map((key) => {
        const value = store[key];
        if (typeof value === "string") {
          return value;
        }
        return null;
      });
      return values;
    },
    listPush: async (key, value) => {
      if (!listStore[key]) listStore[key] = [];
      listStore[key].push(value);
      return listStore[key].length;
    },
    listRange: async (key, start, stop) => {
      if (!listStore[key]) return [];
      const list = listStore[key];
      const end = stop === -1 ? list.length : stop + 1;
      return list.slice(start, end);
    },
    listRemove: async (key, _count, value) => {
      if (!listStore[key]) return 0;
      const originalLength = listStore[key].length;
      listStore[key] = listStore[key].filter((v) => v !== value);
      return originalLength - listStore[key].length;
    },
    listLength: async (key) => {
      return listStore[key]?.length ?? 0;
    },
    streamAdd: async () => null,
    streamLength: async () => 0,
    streamRange: async () => [],
    streamTrim: async () => 0,
    streamCollect: async () => ({ entries: [], lastId: null })
  };
};