key.js
859 Bytes
/**
* store key 构造(纯函数)。
*
* 由 (endpoint, by, subject) 拼出 store 内唯一的桶 key,保证:
* - 不同 endpoint / 不同 by 维度 / 不同 subject 互不串桶;
* - 带命名空间前缀,与同一 redis 实例上的其它业务 key 不撞。
*
* subject 是不透明字符串(IP 或匿名 device-id),本包不解析其语义。
* 用 `\x1f`(单元分隔符)做字段分隔,避免 subject 内含 `:` 时与结构分隔混淆。
*/
/** 命名空间前缀,隔离限流 key 与其它 redis key。 */
export const KEY_NAMESPACE = 'rl'
const SEP = '\x1f'
/**
* 构造桶 key。
* @param {{ endpoint: string, by: string }} rule
* @param {string} subject
* @returns {string}
*/
export function bucketKey(rule, subject) {
return `${KEY_NAMESPACE}${SEP}${rule.endpoint}${SEP}${rule.by}${SEP}${subject}`
}