mirror of
https://github.com/KuekHaoYang/KVideo.git
synced 2026-08-12 23:33:43 +08:00
app/api/user/{sync,config} 用 @upstash/redis/cloudflare 的
Redis.fromEnv() 创建客户端。该实现只读传入的 env 参数或 Cloudflare
全局绑定,从不回退到 process.env,因此在 Docker / Node 自托管下
url 与 token 恒为 undefined,两个接口必定返回 500,跨设备同步
(收藏、历史、设置)完全不可用。认证走的是 auth.ts 里的
new Redis({ url, token }),所以登录正常,只有用户数据读写失败。
把 auth.ts 中已有的双源回退抽成 lib/server/runtime-env.ts,Redis
客户端抽成 lib/server/redis.ts,两个路由改为惰性获取共享客户端。
惰性创建同时修正了另一个隐患:Cloudflare 的 per-request 绑定在
模块求值阶段不可达,而原先客户端是在模块作用域创建的。
未配置 Upstash 时返回 503 并给出明确说明,而不是当成请求失败。
Fixes #226
37 lines
1.2 KiB
TypeScript
37 lines
1.2 KiB
TypeScript
import { Redis } from '@upstash/redis/cloudflare';
|
|
|
|
import { getRuntimeEnvValue } from '@/lib/server/runtime-env';
|
|
|
|
let cachedRedis: Redis | null | undefined;
|
|
|
|
/**
|
|
* Build the shared Upstash client from whichever environment source is available.
|
|
*
|
|
* `Redis.fromEnv()` is deliberately not used here: the `@upstash/redis/cloudflare`
|
|
* implementation only reads Cloudflare's global bindings and never falls back to
|
|
* `process.env`, so it always resolves to `undefined` on Docker / Node
|
|
* self-hosted deployments. The client is also created lazily because Cloudflare's
|
|
* per-request bindings are not reachable while a module is being evaluated.
|
|
*
|
|
* Returns `null` when Upstash is not configured, which callers should treat as
|
|
* "server-side sync unavailable" rather than as a request failure.
|
|
*/
|
|
export function getRedisClient(): Redis | null {
|
|
if (cachedRedis !== undefined) {
|
|
return cachedRedis;
|
|
}
|
|
|
|
const url = getRuntimeEnvValue('UPSTASH_REDIS_REST_URL');
|
|
const token = getRuntimeEnvValue('UPSTASH_REDIS_REST_TOKEN');
|
|
if (!url || !token) {
|
|
cachedRedis = null;
|
|
return cachedRedis;
|
|
}
|
|
|
|
cachedRedis = new Redis({
|
|
url,
|
|
token,
|
|
});
|
|
return cachedRedis;
|
|
}
|