CoolFace
Apppublic

AK-21/Graphite-Industrial-Intelligence

sourceHugging Faceupdated 3mo agoView on Hugging Face
0likes
cache.cjs195 linesDownload Raw Back to upstash
1"use strict";2var __defProp = Object.defineProperty;3var __getOwnPropDesc = Object.getOwnPropertyDescriptor;4var __getOwnPropNames = Object.getOwnPropertyNames;5var __hasOwnProp = Object.prototype.hasOwnProperty;6var __export = (target, all) => {7  for (var name in all)8    __defProp(target, name, { get: all[name], enumerable: true });9};10var __copyProps = (to, from, except, desc) => {11  if (from && typeof from === "object" || typeof from === "function") {12    for (let key of __getOwnPropNames(from))13      if (!__hasOwnProp.call(to, key) && key !== except)14        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });15  }16  return to;17};18var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);19var cache_exports = {};20__export(cache_exports, {21  UpstashCache: () => UpstashCache,22  upstashCache: () => upstashCache23});24module.exports = __toCommonJS(cache_exports);25var import_redis = require("@upstash/redis");26var import_core = require("../core/index.cjs");27var import_entity = require("../../entity.cjs");28var import__ = require("../../index.cjs");29const getByTagScript = `30local tagsMapKey = KEYS[1] -- tags map key31local tag        = ARGV[1] -- tag32 33local compositeTableName = redis.call('HGET', tagsMapKey, tag)34if not compositeTableName then35  return nil36end37 38local value = redis.call('HGET', compositeTableName, tag)39return value40`;41const onMutateScript = `42local tagsMapKey = KEYS[1] -- tags map key43local tables     = {}      -- initialize tables array44local tags       = ARGV    -- tags array45 46for i = 2, #KEYS do47  tables[#tables + 1] = KEYS[i] -- add all keys except the first one to tables48end49 50if #tags > 0 then51  for _, tag in ipairs(tags) do52    if tag ~= nil and tag ~= '' then53      local compositeTableName = redis.call('HGET', tagsMapKey, tag)54      if compositeTableName then55        redis.call('HDEL', compositeTableName, tag)56      end57    end58  end59  redis.call('HDEL', tagsMapKey, unpack(tags))60end61 62local keysToDelete = {}63 64if #tables > 0 then65  local compositeTableNames = redis.call('SUNION', unpack(tables))66  for _, compositeTableName in ipairs(compositeTableNames) do67    keysToDelete[#keysToDelete + 1] = compositeTableName68  end69  for _, table in ipairs(tables) do70    keysToDelete[#keysToDelete + 1] = table71  end72  redis.call('DEL', unpack(keysToDelete))73end74`;75class UpstashCache extends import_core.Cache {76  constructor(redis, config, useGlobally) {77    super();78    this.redis = redis;79    this.useGlobally = useGlobally;80    this.internalConfig = this.toInternalConfig(config);81    this.luaScripts = {82      getByTagScript: this.redis.createScript(getByTagScript, { readonly: true }),83      onMutateScript: this.redis.createScript(onMutateScript)84    };85  }86  static [import_entity.entityKind] = "UpstashCache";87  /**88   * Prefix for sets which denote the composite table names for each unique table89   *90   * Example: In the composite table set of "table1", you may find91   * `${compositeTablePrefix}table1,table2` and `${compositeTablePrefix}table1,table3`92   */93  static compositeTableSetPrefix = "__CTS__";94  /**95   * Prefix for hashes which map hash or tags to cache values96   */97  static compositeTablePrefix = "__CT__";98  /**99   * Key which holds the mapping of tags to composite table names100   *101   * Using this tagsMapKey, you can find the composite table name for a given tag102   * and get the cache value for that tag:103   *104   * ```ts105   * const compositeTable = redis.hget(tagsMapKey, 'tag1')106   * console.log(compositeTable) // `${compositeTablePrefix}table1,table2`107   *108   * const cachevalue = redis.hget(compositeTable, 'tag1')109   */110  static tagsMapKey = "__tagsMap__";111  /**112   * Queries whose auto invalidation is false aren't stored in their respective113   * composite table hashes because those hashes are deleted when a mutation114   * occurs on related tables.115   *116   * Instead, they are stored in a separate hash with the prefix117   * `__nonAutoInvalidate__` to prevent them from being deleted when a mutation118   */119  static nonAutoInvalidateTablePrefix = "__nonAutoInvalidate__";120  luaScripts;121  internalConfig;122  strategy() {123    return this.useGlobally ? "all" : "explicit";124  }125  toInternalConfig(config) {126    return config ? {127      seconds: config.ex,128      hexOptions: config.hexOptions129    } : {130      seconds: 1131    };132  }133  async get(key, tables, isTag = false, isAutoInvalidate) {134    if (!isAutoInvalidate) {135      const result2 = await this.redis.hget(UpstashCache.nonAutoInvalidateTablePrefix, key);136      return result2 === null ? void 0 : result2;137    }138    if (isTag) {139      const result2 = await this.luaScripts.getByTagScript.exec([UpstashCache.tagsMapKey], [key]);140      return result2 === null ? void 0 : result2;141    }142    const compositeKey = this.getCompositeKey(tables);143    const result = (await this.redis.hget(compositeKey, key)) ?? void 0;144    return result === null ? void 0 : result;145  }146  async put(key, response, tables, isTag = false, config) {147    const isAutoInvalidate = tables.length !== 0;148    const pipeline = this.redis.pipeline();149    const ttlSeconds = config && config.ex ? config.ex : this.internalConfig.seconds;150    const hexOptions = config && config.hexOptions ? config.hexOptions : this.internalConfig?.hexOptions;151    if (!isAutoInvalidate) {152      if (isTag) {153        pipeline.hset(UpstashCache.tagsMapKey, { [key]: UpstashCache.nonAutoInvalidateTablePrefix });154        pipeline.hexpire(UpstashCache.tagsMapKey, key, ttlSeconds, hexOptions);155      }156      pipeline.hset(UpstashCache.nonAutoInvalidateTablePrefix, { [key]: response });157      pipeline.hexpire(UpstashCache.nonAutoInvalidateTablePrefix, key, ttlSeconds, hexOptions);158      await pipeline.exec();159      return;160    }161    const compositeKey = this.getCompositeKey(tables);162    pipeline.hset(compositeKey, { [key]: response });163    pipeline.hexpire(compositeKey, key, ttlSeconds, hexOptions);164    if (isTag) {165      pipeline.hset(UpstashCache.tagsMapKey, { [key]: compositeKey });166      pipeline.hexpire(UpstashCache.tagsMapKey, key, ttlSeconds, hexOptions);167    }168    for (const table of tables) {169      pipeline.sadd(this.addTablePrefix(table), compositeKey);170    }171    await pipeline.exec();172  }173  async onMutate(params) {174    const tags = Array.isArray(params.tags) ? params.tags : params.tags ? [params.tags] : [];175    const tables = Array.isArray(params.tables) ? params.tables : params.tables ? [params.tables] : [];176    const tableNames = tables.map((table) => (0, import_entity.is)(table, import__.Table) ? table[import__.OriginalName] : table);177    const compositeTableSets = tableNames.map((table) => this.addTablePrefix(table));178    await this.luaScripts.onMutateScript.exec([UpstashCache.tagsMapKey, ...compositeTableSets], tags);179  }180  addTablePrefix = (table) => `${UpstashCache.compositeTableSetPrefix}${table}`;181  getCompositeKey = (tables) => `${UpstashCache.compositeTablePrefix}${tables.sort().join(",")}`;182}183function upstashCache({ url, token, config, global = false }) {184  const redis = new import_redis.Redis({185    url,186    token187  });188  return new UpstashCache(redis, config, global);189}190// Annotate the CommonJS export names for ESM import in node:1910 && (module.exports = {192  UpstashCache,193  upstashCache194});195//# sourceMappingURL=cache.cjs.map