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 <noreply@anthropic.com>
This commit is contained in:
1 parent
16601f20f3
commit
131beeb07f
7 files changed
+104
-2
No files matched your search
@@ -42,3 +42,4 @@ certificates
|
||||
/public/*.js
|
||||
/public/robots.txt
|
||||
/public/sitemap*
|
||||
.env*
|
||||
@@ -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;
|
||||
@@ -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<void>;
|
||||
|
||||
private magnets: Record<string, string> = {};
|
||||
|
||||
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<SerializedCookieJar>(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<Torrent[]> {
|
||||
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'
|
||||
|
||||
@@ -5,3 +5,6 @@ TOLOKA_HOST=https://toloka.to
|
||||
TOLOKA_USERNAME=your_toloka_username
|
||||
TOLOKA_PASSWORD=your_toloka_password
|
||||
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
|
||||
@@ -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;
|
||||
Generated
+29
@@ -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",
|
||||
|
||||
+7
-1
@@ -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",
|
||||
|
||||
Reference in new issue
Block a user