diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 355ef0a..95eaad1 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -23,7 +23,7 @@ GITHUB_API=https://github.example.com/api/graphql Run local server. ```sh -deno run --allow-net --allow-read --allow-env debug.ts +deno run --allow-net --allow-read --allow-env --allow-write debug.ts ``` Open localhost from your browser. diff --git a/index.ts b/index.ts index 2498b87..5f7f6cd 100644 --- a/index.ts +++ b/index.ts @@ -4,11 +4,25 @@ import { CONSTANTS, parseParams } from "./src/utils.ts"; import { COLORS, Theme } from "./src/theme.ts"; import { Error400, Error404 } from "./src/error_page.ts"; import "https://deno.land/x/dotenv@v0.5.0/load.ts"; - +import {staticRenderRegeneration} from "./src/StaticRenderRegeneration/index.ts"; const apiEndpoint = Deno.env.get("GITHUB_API") || CONSTANTS.DEFAULT_GITHUB_API; const client = new GithubAPIClient(apiEndpoint); -export default async (req: Request) => { +const defaultHeaders = new Headers( + { + "Content-Type": "image/svg+xml", + "Cache-Control": `public, max-age=${CONSTANTS.CACHE_MAX_AGE}`, + }, +) + +export default (request: Request) => staticRenderRegeneration(request, { + revalidate: CONSTANTS.REVALIDATE_TIME, + headers: defaultHeaders +}, function (req: Request) { + return app(req); +}); + +async function app (req: Request): Promise{ const params = parseParams(req); const username = params.get("username"); const row = params.getNumberValue("row", CONSTANTS.DEFAULT_MAX_ROW); @@ -69,6 +83,7 @@ export default async (req: Request) => { }, ); } + // Success Response return new Response( new Card( @@ -83,12 +98,7 @@ export default async (req: Request) => { noFrame, ).render(userInfo, theme), { - headers: new Headers( - { - "Content-Type": "image/svg+xml", - "Cache-Control": `public, max-age=${CONSTANTS.CACHE_MAX_AGE}`, - }, - ), + headers: defaultHeaders, }, ); }; diff --git a/src/StaticRenderRegeneration/cache_manager.ts b/src/StaticRenderRegeneration/cache_manager.ts new file mode 100644 index 0000000..3a93e4b --- /dev/null +++ b/src/StaticRenderRegeneration/cache_manager.ts @@ -0,0 +1,49 @@ +import { existsSync } from './utils.ts' + +export class CacheManager { + constructor(private revalidateTime: number, private cacheFile: string) {} + + // Reason to use /tmp/: + // https://github.com/orgs/vercel/discussions/314 + get cacheFilePath(): string { + return `/tmp/${this.cacheFile}`; + } + get cacheFileExists(): boolean { + return existsSync(this.cacheFilePath); + } + + get cacheFileLastModified(): Date | null { + if (!this.cacheFileExists) { + return null; + } + const fileInfo = Deno.statSync(this.cacheFilePath); + return fileInfo.mtime ?? null; + } + + get cacheFileLastModifiedGetTime(): number | null { + const lastModified = this.cacheFileLastModified; + if (lastModified === null) { + return null; + } + return lastModified.getTime(); + } + + get isCacheValid(): boolean { + if (this.cacheFileLastModifiedGetTime === null) { + return false; + } + const currentTime = new Date().getTime(); + return currentTime - this.cacheFileLastModifiedGetTime < this.revalidateTime; + } + + async save (response: Response): Promise { + if(response === null) return + // Prevent TypeError: ReadableStream is locked + const text = await response.clone().text() + const data = new TextEncoder().encode(text) + + Deno.writeFile(this.cacheFilePath, data, { create: true }).catch(() => { + console.warn("Failed to save cache file") + }); + } +} \ No newline at end of file diff --git a/src/StaticRenderRegeneration/index.ts b/src/StaticRenderRegeneration/index.ts new file mode 100644 index 0000000..d93fc61 --- /dev/null +++ b/src/StaticRenderRegeneration/index.ts @@ -0,0 +1,29 @@ +import { CacheManager } from "./cache_manager.ts"; +import { StaticRegenerationOptions } from "./types.ts"; +import { getUrl, readCache, generateUUID } from "./utils.ts"; + +export async function staticRenderRegeneration(request: Request, options: StaticRegenerationOptions, render: (request: Request) => Promise) { + // avoid TypeError: Invalid URL at deno:core + const url = getUrl(request) + + // if more conditions are added, make sure to create a variable to skipCache + if (url.pathname === "/favicon.ico") { + return await render(request); + } + + const cacheFile = await generateUUID(url.pathname + (url.search ?? "")); + const cacheManager = new CacheManager(options.revalidate ?? 0, cacheFile); + if (cacheManager.isCacheValid) { + const cache = readCache(cacheManager.cacheFilePath) + if(cache !== null) { + return new Response(cache, { + headers: options.headers ?? new Headers({}), + }); + } + } + + const response = await render(request) + cacheManager.save(response) + + return response +} diff --git a/src/StaticRenderRegeneration/types.ts b/src/StaticRenderRegeneration/types.ts new file mode 100644 index 0000000..e9b7907 --- /dev/null +++ b/src/StaticRenderRegeneration/types.ts @@ -0,0 +1,6 @@ +export interface StaticRegenerationOptions { + // The number of milliseconds before the page should be revalidated + revalidate?: number + // The headers to be sent with the response + headers?: Headers +} \ No newline at end of file diff --git a/src/StaticRenderRegeneration/utils.ts b/src/StaticRenderRegeneration/utils.ts new file mode 100644 index 0000000..ebc19c4 --- /dev/null +++ b/src/StaticRenderRegeneration/utils.ts @@ -0,0 +1,42 @@ +export function getUrl(request: Request) { + try { + return new URL(request.url) + } catch { + return { + pathname: request.url, + search: request.url + } + } +} + +export function readCache(cacheFilePath: string): Uint8Array | null { + try { + return Deno.readFileSync(cacheFilePath) + } catch { + return null + } +} + +// https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest +export async function generateUUID(message: string): Promise { + const encoder = new TextEncoder(); + const data = encoder.encode(message); + const hashBuffer = await crypto.subtle.digest("SHA-256", data); + + const hashArray = Array.from(new Uint8Array(hashBuffer)); + const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join(''); + + return hashHex; +} + + +export const existsSync = (filename: string): boolean => { + try { + Deno.statSync(filename); + // successful, file or directory must exist + return true; + } catch { + return false; + } +}; + \ No newline at end of file diff --git a/src/utils.ts b/src/utils.ts index 9f868f7..3b65043 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -53,6 +53,8 @@ export function abridgeScore(score: number): string { return (Math.sign(score) * Math.abs(score)).toString() + "pt"; } +const HOUR_IN_MILLISECONDS = 60 * 60 * 1000; + export const CONSTANTS = { CACHE_MAX_AGE: 7200, DEFAULT_PANEL_SIZE: 110, @@ -63,6 +65,7 @@ export const CONSTANTS = { DEFAULT_NO_BACKGROUND: false, DEFAULT_NO_FRAME: false, DEFAULT_GITHUB_API: "https://api.github.com/graphql", + REVALIDATE_TIME: HOUR_IN_MILLISECONDS, }; export enum RANK {