-
Notifications
You must be signed in to change notification settings - Fork 10
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
KrosFire
wants to merge
2
commits into
main
Choose a base branch
from
crash-report-endpoint
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+263
−0
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -33,3 +33,6 @@ yarn-error.log* | |
# typescript | ||
*.tsbuildinfo | ||
next-env.d.ts | ||
|
||
# testing files | ||
test* |
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Please consider using |
||
|
||
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; | ||
} | ||
|
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.