From 5fa1fe2c3ecd592a24c77af37872602dd3872d2e Mon Sep 17 00:00:00 2001 From: kakkokari-gtyih <67428053+kakkokari-gtyih@users.noreply.github.com> Date: Wed, 25 Dec 2024 19:07:49 +0900 Subject: [PATCH] =?UTF-8?q?enhance(url-preview):=20Summaly=E3=81=AE?= =?UTF-8?q?=E7=B5=90=E6=9E=9C=E3=82=92=E5=86=85=E9=83=A8=E3=81=A7=E3=82=AD?= =?UTF-8?q?=E3=83=A3=E3=83=83=E3=82=B7=E3=83=A5=E3=81=99=E3=82=8B=E3=82=88?= =?UTF-8?q?=E3=81=86=E3=81=AB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/server/web/UrlPreviewService.ts | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/packages/backend/src/server/web/UrlPreviewService.ts b/packages/backend/src/server/web/UrlPreviewService.ts index 9b5f0acd2c..da6c85cc56 100644 --- a/packages/backend/src/server/web/UrlPreviewService.ts +++ b/packages/backend/src/server/web/UrlPreviewService.ts @@ -4,6 +4,7 @@ */ import { Inject, Injectable } from '@nestjs/common'; +import * as Redis from 'ioredis'; import { summaly } from '@misskey-dev/summaly'; import { SummalyResult } from '@misskey-dev/summaly/built/summary.js'; import { DI } from '@/di-symbols.js'; @@ -15,6 +16,7 @@ import { LoggerService } from '@/core/LoggerService.js'; import { bindThis } from '@/decorators.js'; import { ApiError } from '@/server/api/error.js'; import { MiMeta } from '@/models/Meta.js'; +import { createHash } from 'crypto'; import type { FastifyRequest, FastifyReply } from 'fastify'; @Injectable() @@ -25,6 +27,9 @@ export class UrlPreviewService { @Inject(DI.config) private config: Config, + @Inject(DI.redis) + private redisClient: Redis.Redis, + @Inject(DI.meta) private meta: MiMeta, @@ -74,6 +79,19 @@ export class UrlPreviewService { }; } + const redisCacheKey = createHash('sha256').update(url.trim()).digest('hex'); + + const cachedSummary = await this.redisClient.get(`url-preview:${lang}:${redisCacheKey}`); + + if (cachedSummary) { + this.logger.succ(`Got preview of ${url}@${lang} from cache`); + + // Cache 7days + reply.header('Cache-Control', 'max-age=604800, immutable'); + + return JSON.parse(cachedSummary); + } + this.logger.info(this.meta.urlPreviewSummaryProxyUrl ? `(Proxy) Getting preview of ${url}@${lang} ...` : `Getting preview of ${url}@${lang} ...`); @@ -99,6 +117,9 @@ export class UrlPreviewService { // Cache 7days reply.header('Cache-Control', 'max-age=604800, immutable'); + // Cache internally for 1day + this.redisClient.setex(`url-preview:${lang}:${redisCacheKey}`, 86400, JSON.stringify(summary)); + return summary; } catch (err) { this.logger.warn(`Failed to get preview of ${url}: ${err}`);