Skip to content

Commit

Permalink
Add heap-snapshot route
Browse files Browse the repository at this point in the history
  • Loading branch information
mskelton committed Mar 28, 2024
1 parent 0d8c2a9 commit aecf04a
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 10 deletions.
40 changes: 40 additions & 0 deletions app/api/heap-snapshot/route.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import fs from "node:fs"
import os from "node:os"
import path from "node:path"
import v8 from "node:v8"
import { requireToken } from "api/utils/auth"

export async function GET(request: Request) {
requireToken(request)

const tempDir = os.tmpdir()
const filepath = path.join(
tempDir,
`mskelton.dev-${new Date().toISOString()}.heapsnapshot`,
)

const snapshotPath = v8.writeHeapSnapshot(filepath)
if (!snapshotPath) {
throw new Response("No snapshot saved", { status: 500 })
}

const body = new ReadableStream({
start(controller) {
const stream = fs.createReadStream(snapshotPath)
stream.on("data", (chunk) => controller.enqueue(chunk))
stream.on("end", () => controller.close())
stream.on("error", (err) => controller.error(err))
},
})

return new Response(body, {
headers: {
"Content-Disposition": `attachment; filename="${path.basename(
snapshotPath,
)}"`,
"Content-Length": (await fs.promises.stat(snapshotPath)).size.toString(),
"Content-Type": "application/octet-stream",
},
status: 200,
})
}
13 changes: 3 additions & 10 deletions app/api/reindex/route.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { headers } from "next/headers"
import { NextResponse } from "next/server"
import { requireToken } from "api/utils/auth"
import { upsertByte } from "lib/api/bytes"
import { getByteSource, octokit } from "lib/api/github"
import { toId } from "lib/parser"
Expand All @@ -22,15 +22,8 @@ async function getAllByteIds() {
return data.map((item) => toId(item.name))
}

export async function POST() {
const token = headers().get("Authorization")?.replace("Bearer ", "")

if (
process.env.NODE_ENV === "production" &&
process.env.API_AUTH_TOKEN !== token
) {
return NextResponse.json({ message: "Forbidden" }, { status: 403 })
}
export async function POST(request: Request) {
requireToken(request)

// Prep the reindexing before clearing content. Make sure we get all the
// content from the GitHub API before we start clearing the database.
Expand Down
12 changes: 12 additions & 0 deletions app/api/utils/auth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { NextResponse } from "next/server"

export function requireToken(request: Request) {
const token = request.headers.get("Authorization")?.replace("Bearer ", "")

if (
process.env.NODE_ENV === "production" &&
process.env.API_AUTH_TOKEN !== token
) {
return NextResponse.json({ message: "Forbidden" }, { status: 403 })
}
}

0 comments on commit aecf04a

Please sign in to comment.