Skip to content

Created crash report endpoint #91

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
GITHUB_TOKEN=GITHUB_PERSONAL_ACCESS_TOKEN
GITHUB_REPO_OWNER=amber-lang
GITHUB_REPO_NAME=amber-lsp
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -33,3 +33,6 @@ yarn-error.log*
# typescript
*.tsbuildinfo
next-env.d.ts

# testing files
test*
60 changes: 60 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
"eslint": "8.44.0",
"eslint-config-next": "^14.0.4",
"highlight.js": "^11.10.0",
"joi": "^17.13.3",
"next": "^14.0.4",
"nextjs-toploader": "^3.7.15",
"react": "^18.3.1",
Expand All @@ -32,5 +33,8 @@
"three": "^0.170.0",
"typescript": "5.6.3",
"usehooks-ts": "^3.1.0"
},
"devDependencies": {
"github-types": "^1.0.0"
}
}
193 changes: 193 additions & 0 deletions src/app/api/amber-lsp/crash-report/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,193 @@
import { NextRequest, NextResponse } from 'next/server';
import { Issue as GithubIssue } from 'github-types'
import crypto from 'crypto';
import Joi from 'joi';
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please consider using zod


const GITHUB_TOKEN = process.env.GITHUB_TOKEN!;
const GITHUB_REPO_OWNER = process.env.GITHUB_REPO_OWNER!;
const GITHUB_REPO_NAME = process.env.GITHUB_REPO_NAME!;

const GITHUB_API_URL = `https://api.github.com/repos/${GITHUB_REPO_OWNER}/${GITHUB_REPO_NAME}/issues`;

type CrashReportBody = {
logs: string;
editor: string;
os: string;
lspVersion: string;
}

const bodySchema = Joi.object<CrashReportBody, true>({
logs : Joi.string().max(1_000).required(),
editor: Joi.string().max(50).required(),
os: Joi.string().max(50).required(),
lspVersion: Joi.string().max(50).required(),
}).required();

type Issue = Omit<GithubIssue, 'body'> & {
body: string | null;
}

export async function POST(req: NextRequest) {
if (req.method !== 'POST') {
return new NextResponse('Method Not Allowed', { status: 405 });
}

try {
const body = await req.json();

const validation = bodySchema.validate(body);

if (validation.error) {
return NextResponse.json(
{ message: `Invalid request body. ${validation.error.message}` },
{ status: 400 }
);
}

const { logs, editor, os, lspVersion } = validation.value

const fingerprint = generateErrorFingerprint(logs);

const foundIssue = await findIssueByFingerprint(fingerprint);

if (foundIssue) {
return createGitHubComment(foundIssue);
}

const { issueTitle, issueBody } = prepareIssue(logs, editor, os, lspVersion, fingerprint);

const githubResponse = await fetch(GITHUB_API_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `token ${GITHUB_TOKEN}`,
'Accept': 'application/vnd.github.v3+json'
},
body: JSON.stringify({
title: issueTitle,
body: issueBody,
labels: ['bug', 'crash-report'],
}),
})

if (githubResponse.ok) {
const githubIssue = await githubResponse.json();
return NextResponse.json({
message: 'Crash report received and GitHub issue created successfully!',
issueUrl: githubIssue.html_url,
}, { status: 200 });
} else {
const errorData = await githubResponse.json();
return NextResponse.json({
message: 'Crash report received, but failed to create GitHub issue.',
githubError: errorData,
}, { status: 500 });
}
} catch (e) {
return new NextResponse('Internal Server Error', { status: 500 });
}
}

const createGitHubComment = async (issue: Issue) => {
const commentUrl = `${GITHUB_API_URL}/${issue.number}/comments`;
const commentBody = `
Another occurrence of this crash was reported at ${new Date().toISOString()}.
---
*Auto-reported by crash handler.*
`.trim();

const commentResponse = await fetch(commentUrl, {
method: 'POST',
headers: {
'Authorization': `Bearer ${GITHUB_TOKEN}`,
'Content-Type': 'application/json',
'Accept': 'application/vnd.github.v3+json',
},
body: JSON.stringify({ body: commentBody }),
});

if (commentResponse.ok) {
return NextResponse.json({
message: 'Crash report received and added as a comment to existing GitHub issue.',
issueUrl: issue.html_url,
}, { status: 200 });
} else {
const errorData = await commentResponse.json();
console.error('Failed to add comment to GitHub issue:', commentResponse.status, errorData);

return NextResponse.json({
message: 'Crash report received, but failed to add comment to existing GitHub issue.',
issueUrl: issue.html_url,
githubApiError: errorData,
}, { status: 200 });
}
}

const prepareIssue = (logs: string, editor: string, os: string, lspVersion: string, fingerprint: string) => ({
issueTitle: `Crash Report - ${editor} - ${os} - ${lspVersion} (Fingerprint: ${fingerprint.substring(0, 30)}...)`,
issueBody: `
### Crash Report Details
**Editor:** ${editor}
**OS:** ${os}
**LSP Version:** ${lspVersion}
**DATE:** ${new Date().toISOString()}
---
**Logs:**
\`\`\`
${logs}
\`\`\`
---
**Fingerprint:** ${fingerprint}
This issue was automatically generated from a crash report submitted by the Amber LSP client.
`,
})

const generateErrorFingerprint = (logs: string): string => {
const lines = logs.split('\n');

const normalizedLines = lines
// Remove timestamps and normalize the lines
.map(line => line.replaceAll(/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d+Z/g, '').trim())
// Remove level prefixes (e.g., "ERROR:", "WARN:", etc.)
.map(line => line.replaceAll(/(ERROR|WARN|INFO|DEBUG)/g, '').trim())
// Remove busy timestamps (e.g., "time.busy=123ms")
.map(line => line.replaceAll(/(time.busy=\d+(\.\d+)*(ms|µs|s)|time.idle=\d+(\.\d+)*(ms|µs|s))/g, '').trim())
// Remove any identifiers
.map(line => line.replaceAll(/FileId\(\d+\)/g, 'FileId').trim())
.map(line => line.replaceAll(/FileVersion\(\d+\)/g, 'FileVersion').trim())
// Filter out empty lines
.filter(line => line.length > 0);

// Join the normalized lines back into a single string
const normalizedLogs = normalizedLines.join('\n');

return crypto.createHash('sha256').update(normalizedLogs).digest('hex');
}

const findIssueByFingerprint = async (fingerprint: string): Promise<Issue | undefined> => {
const searchUrl = `${GITHUB_API_URL}?state=open&q=${encodeURIComponent(`fingerprint:${fingerprint}`)}`;

const response = await fetch(searchUrl, {
headers: {
'Authorization': `token ${GITHUB_TOKEN}`,
'Accept': 'application/vnd.github.v3+json'
}
});

if (!response.ok) {
return
}

const existingIssues = await response.json() as Issue[];

const foundIssue = existingIssues.find((issue: Issue) =>
issue.title.includes(fingerprint) || issue.body?.includes(fingerprint)
);

return foundIssue;
}