From 131beeb07ff2c56075f4e95fddc0357d209b0732 Mon Sep 17 00:00:00 2001 From: ner Date: Thu, 6 Aug 2026 21:02:13 +0300 Subject: [PATCH] feat(tlk): persist Toloka session in Redis across cold starts Store the serialized cookie jar in Upstash Redis after login and restore it on instance start, so serverless cold starts reuse the session instead of re-authenticating. Falls back to the previous in-memory behavior when Redis is not configured or unavailable. Co-Authored-By: Claude Fable 5 --- .gitignore | 1 + data/clients/redis.ts | 10 ++++++++ data/parsers/tlk/index.ts | 52 ++++++++++++++++++++++++++++++++++++++- env.example | 5 +++- env.ts | 3 +++ package-lock.json | 29 ++++++++++++++++++++++ package.json | 8 +++++- 7 files changed, 105 insertions(+), 3 deletions(-) create mode 100644 data/clients/redis.ts diff --git a/.gitignore b/.gitignore index ee23ae8..a517672 100644 --- a/.gitignore +++ b/.gitignore @@ -42,3 +42,4 @@ certificates /public/*.js /public/robots.txt /public/sitemap* +.env* diff --git a/data/clients/redis.ts b/data/clients/redis.ts new file mode 100644 index 0000000..99708f5 --- /dev/null +++ b/data/clients/redis.ts @@ -0,0 +1,10 @@ +import { Redis } from '@upstash/redis'; + +import { UPSTASH_REDIS_REST_TOKEN, UPSTASH_REDIS_REST_URL } from '@/env'; + +const redis = + UPSTASH_REDIS_REST_URL && UPSTASH_REDIS_REST_TOKEN + ? new Redis({ url: UPSTASH_REDIS_REST_URL, token: UPSTASH_REDIS_REST_TOKEN }) + : null; + +export default redis; diff --git a/data/parsers/tlk/index.ts b/data/parsers/tlk/index.ts index 43b3507..6eeba4b 100644 --- a/data/parsers/tlk/index.ts +++ b/data/parsers/tlk/index.ts @@ -3,12 +3,19 @@ import { wrapper } from 'axios-cookiejar-support'; import { load } from 'cheerio'; import parseTorrent, { Instance } from 'parse-torrent'; import torrentTitle from 'parse-torrent-title'; -import { CookieJar } from 'tough-cookie'; +import { Cookie, CookieJar, SerializedCookieJar } from 'tough-cookie'; +import redis from '@/data/clients/redis'; import { TOLOKA_HOST, TOLOKA_PASSWORD, TOLOKA_USERNAME } from '@/env'; import { Sort } from '../index'; +const COOKIE_JAR_KEY = 'toloka:cookie-jar'; + +// UpstashError messages embed the full command, including cookie values — never log them +const redisWarn = (message: string, error: unknown) => + console.warn(message, error instanceof Error ? error.message.split(', command was:')[0] : error); + export class Toloka { private client: AxiosInstance; private host: string; @@ -19,6 +26,8 @@ export class Toloka { private cookieJar = new CookieJar(); + private hydration?: Promise; + private magnets: Record = {}; constructor() { @@ -37,7 +46,42 @@ export class Toloka { return !load(data)('[href="/login.php"]').length; } + private hydrate() { + this.hydration ??= (async () => { + if (!redis) return; + + const serialized = await redis.get(COOKIE_JAR_KEY); + const cookies = serialized?.cookies || []; + + for (const data of cookies) { + const cookie = Cookie.fromJSON(data); + + if (cookie) await this.cookieJar.store.putCookie(cookie); + } + + console.info(`[tlk] restored ${cookies.length} session cookies from Redis`); + })().catch((error) => { + redisWarn('Failed to restore Toloka session from Redis:', error); + }); + + return this.hydration; + } + + private async persist() { + if (!redis) return; + + try { + await redis.set(COOKIE_JAR_KEY, await this.cookieJar.serialize()); + + console.info('[tlk] session persisted to Redis'); + } catch (error) { + redisWarn('Failed to persist Toloka session to Redis:', error); + } + } + private async auth() { + console.info('[tlk] logging in to Toloka'); + const data = new FormData(); data.append('username', TOLOKA_USERNAME as string); @@ -49,9 +93,13 @@ export class Toloka { await this.client.post('/login.php', data, { headers: { 'Content-Type': 'multipart/form-data' } }); + + await this.persist(); } async search({ query, sort = Sort.size }: { query: string; sort?: Sort }): Promise { + await this.hydrate(); + const fetchPage = () => this.client.get(`/tracker.php?o=${this.sort[sort]}&nm=${query}`); const parseTorrents = (data: string) => { @@ -101,6 +149,8 @@ export class Toloka { async magnet(url: string) { if (this.magnets[url]) return this.magnets[url]; + await this.hydrate(); + const fetchTorrent = async () => { const { data: buffer } = await this.client.get(`/${url}`, { responseType: 'arraybuffer' diff --git a/env.example b/env.example index b8dee0f..a37d02a 100644 --- a/env.example +++ b/env.example @@ -4,4 +4,7 @@ YTS_HOST=https://yts.mx/api/v2/list_movies.json TOLOKA_HOST=https://toloka.to TOLOKA_USERNAME=your_toloka_username TOLOKA_PASSWORD=your_toloka_password -NEXT_PUBLIC_TORRENT_PROXY=http://localhost:8090 \ No newline at end of file +NEXT_PUBLIC_TORRENT_PROXY=http://localhost:8090 +# Optional: persists the Toloka session across serverless cold starts (falls back to in-memory) +UPSTASH_REDIS_REST_URL=https://your-db.upstash.io +UPSTASH_REDIS_REST_TOKEN=your_upstash_token \ No newline at end of file diff --git a/env.ts b/env.ts index 94c76e0..bef7705 100644 --- a/env.ts +++ b/env.ts @@ -18,3 +18,6 @@ export const TOLOKA_PASSWORD = process.env.TOLOKA_PASSWORD; export const PIRATE_BAY_HOST = process.env.PIRATE_BAY_HOST; export const YTS_HOST = process.env.YTS_HOST; + +export const UPSTASH_REDIS_REST_URL = process.env.UPSTASH_REDIS_REST_URL || process.env.KV_REST_API_URL; +export const UPSTASH_REDIS_REST_TOKEN = process.env.UPSTASH_REDIS_REST_TOKEN || process.env.KV_REST_API_TOKEN; diff --git a/package-lock.json b/package-lock.json index a8c9005..401f250 100644 --- a/package-lock.json +++ b/package-lock.json @@ -18,6 +18,7 @@ "@tanstack/react-query": "^5.59.15", "@tanstack/react-query-next-experimental": "^5.59.16", "@types/cheerio": "^0.22.35", + "@upstash/redis": "^1.38.2", "@vidstack/react": "^1.12.13", "axios": "^1.7.7", "axios-cookiejar-support": "^5.0.3", @@ -4599,6 +4600,15 @@ "url": "https://opencollective.com/typescript-eslint" } }, + "node_modules/@upstash/redis": { + "version": "1.38.2", + "resolved": "https://registry.npmjs.org/@upstash/redis/-/redis-1.38.2.tgz", + "integrity": "sha512-RZ+JaRCVIS+ZTGnjOnDMr+/0aqDxsBb5rV6aW+Pys4SGELwr5lwE3UbLHRCHqMQ5Ulxj0b/CFBHfbmE175Otog==", + "license": "MIT", + "dependencies": { + "uncrypto": "^0.1.3" + } + }, "node_modules/@vidstack/react": { "version": "1.12.13", "resolved": "https://registry.npmjs.org/@vidstack/react/-/react-1.12.13.tgz", @@ -11790,6 +11800,12 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/uncrypto": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/uncrypto/-/uncrypto-0.1.3.tgz", + "integrity": "sha512-Ql87qFHB3s/De2ClA9e0gsnS6zXG27SkTiSJwjCc9MebbfapQfuPzumMIUMi38ezPZVNFcHI9sUIepeQfw8J8Q==", + "license": "MIT" + }, "node_modules/undici": { "version": "6.20.1", "resolved": "https://registry.npmjs.org/undici/-/undici-6.20.1.tgz", @@ -15180,6 +15196,14 @@ "eslint-visitor-keys": "^3.3.0" } }, + "@upstash/redis": { + "version": "1.38.2", + "resolved": "https://registry.npmjs.org/@upstash/redis/-/redis-1.38.2.tgz", + "integrity": "sha512-RZ+JaRCVIS+ZTGnjOnDMr+/0aqDxsBb5rV6aW+Pys4SGELwr5lwE3UbLHRCHqMQ5Ulxj0b/CFBHfbmE175Otog==", + "requires": { + "uncrypto": "^0.1.3" + } + }, "@vidstack/react": { "version": "1.12.13", "resolved": "https://registry.npmjs.org/@vidstack/react/-/react-1.12.13.tgz", @@ -20027,6 +20051,11 @@ "which-boxed-primitive": "^1.0.2" } }, + "uncrypto": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/uncrypto/-/uncrypto-0.1.3.tgz", + "integrity": "sha512-Ql87qFHB3s/De2ClA9e0gsnS6zXG27SkTiSJwjCc9MebbfapQfuPzumMIUMi38ezPZVNFcHI9sUIepeQfw8J8Q==" + }, "undici": { "version": "6.20.1", "resolved": "https://registry.npmjs.org/undici/-/undici-6.20.1.tgz", diff --git a/package.json b/package.json index e2786cd..8d2c5a6 100644 --- a/package.json +++ b/package.json @@ -15,7 +15,12 @@ "engines": { "node": "22.x" }, - "browserslist": ["chrome >= 91", "edge >= 91", "firefox >= 90", "safari >= 15"], + "browserslist": [ + "chrome >= 91", + "edge >= 91", + "firefox >= 90", + "safari >= 15" + ], "dependencies": { "@dnd-kit/core": "^6.3.1", "@dnd-kit/sortable": "^10.0.0", @@ -27,6 +32,7 @@ "@tanstack/react-query": "^5.59.15", "@tanstack/react-query-next-experimental": "^5.59.16", "@types/cheerio": "^0.22.35", + "@upstash/redis": "^1.38.2", "@vidstack/react": "^1.12.13", "axios": "^1.7.7", "axios-cookiejar-support": "^5.0.3",