|
| 1 | +/* |
| 2 | + * Copyright (c) 2024, Salesforce, Inc. |
| 3 | + * All rights reserved. |
| 4 | + * SPDX-License-Identifier: BSD-3-Clause |
| 5 | + * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause |
| 6 | + */ |
| 7 | + |
| 8 | +import * as vscode from 'vscode'; |
| 9 | +import * as fspromises from 'fs/promises'; |
| 10 | +import { CoreExtensionService, Connection, TelemetryService } from '../lib/core-extension-service'; |
| 11 | +import * as Constants from '../lib/constants'; |
| 12 | +import {messages} from '../lib/messages'; |
| 13 | +import { RuleResult, ApexGuruViolation } from '../types'; |
| 14 | +import { DiagnosticManager } from '../lib/diagnostics'; |
| 15 | +import { RunInfo } from '../extension'; |
| 16 | + |
| 17 | +export async function isApexGuruEnabledInOrg(outputChannel: vscode.LogOutputChannel): Promise<boolean> { |
| 18 | + try { |
| 19 | + const connection = await CoreExtensionService.getConnection(); |
| 20 | + const response:ApexGuruAuthResponse = await connection.request({ |
| 21 | + method: 'GET', |
| 22 | + url: Constants.APEX_GURU_AUTH_ENDPOINT, |
| 23 | + body: '' |
| 24 | + }); |
| 25 | + return response.status == 'Success'; |
| 26 | + } catch(e) { |
| 27 | + // This could throw an error for a variety of reasons. The API endpoint has not been deployed to the instance, org has no perms, timeouts etc,. |
| 28 | + // In all of these scenarios, we return false. |
| 29 | + const errMsg = e instanceof Error ? e.message : e as string; |
| 30 | + outputChannel.error('Apex Guru perm check failed with error:' + errMsg); |
| 31 | + outputChannel.show(); |
| 32 | + return false; |
| 33 | + } |
| 34 | +} |
| 35 | + |
| 36 | +export async function runApexGuruOnFile(selection: vscode.Uri, runInfo: RunInfo) { |
| 37 | + const { |
| 38 | + diagnosticCollection, |
| 39 | + commandName, |
| 40 | + outputChannel |
| 41 | + } = runInfo; |
| 42 | + const startTime = Date.now(); |
| 43 | + try { |
| 44 | + await vscode.window.withProgress({ |
| 45 | + location: vscode.ProgressLocation.Notification |
| 46 | + }, async (progress) => { |
| 47 | + progress.report(messages.apexGuru.progress); |
| 48 | + const connection = await CoreExtensionService.getConnection(); |
| 49 | + const requestId = await initiateApexGuruRequest(selection, outputChannel, connection); |
| 50 | + outputChannel.appendLine('Code Analyzer with ApexGuru request Id:' + requestId); |
| 51 | + |
| 52 | + const queryResponse: ApexGuruQueryResponse = await pollAndGetApexGuruResponse(connection, requestId, Constants.APEX_GURU_MAX_TIMEOUT_SECONDS, Constants.APEX_GURU_RETRY_INTERVAL_MILLIS); |
| 53 | + |
| 54 | + const decodedReport = Buffer.from(queryResponse.report, 'base64').toString('utf8'); |
| 55 | + |
| 56 | + const ruleResult = transformStringToRuleResult(selection.fsPath, decodedReport); |
| 57 | + new DiagnosticManager().displayDiagnostics([selection.fsPath], [ruleResult], diagnosticCollection); |
| 58 | + TelemetryService.sendCommandEvent(Constants.TELEM_SUCCESSFUL_APEX_GURU_FILE_ANALYSIS, { |
| 59 | + executedCommand: commandName, |
| 60 | + duration: (Date.now() - startTime).toString() |
| 61 | + }); |
| 62 | + void vscode.window.showInformationMessage(messages.apexGuru.finishedScan(ruleResult.violations.length)); |
| 63 | + }); |
| 64 | + } catch (e) { |
| 65 | + const errMsg = e instanceof Error ? e.message : e as string; |
| 66 | + outputChannel.error('Initial Code Analyzer with ApexGuru request failed.'); |
| 67 | + outputChannel.appendLine(errMsg); |
| 68 | + } |
| 69 | +} |
| 70 | + |
| 71 | +export async function pollAndGetApexGuruResponse(connection: Connection, requestId: string, maxWaitTimeInSeconds: number, retryIntervalInMillis: number): Promise<ApexGuruQueryResponse> { |
| 72 | + let queryResponse: ApexGuruQueryResponse; |
| 73 | + let lastErrorMessage = ''; |
| 74 | + const startTime = Date.now(); |
| 75 | + while ((Date.now() - startTime) < maxWaitTimeInSeconds * 1000) { |
| 76 | + try { |
| 77 | + queryResponse = await connection.request({ |
| 78 | + method: 'GET', |
| 79 | + url: `${Constants.APEX_GURU_REQUEST}/${requestId}`, |
| 80 | + body: '' |
| 81 | + }); |
| 82 | + if (queryResponse.status == 'success') { |
| 83 | + return queryResponse; |
| 84 | + } |
| 85 | + } catch (error) { |
| 86 | + lastErrorMessage = (error as Error).message; |
| 87 | + } |
| 88 | + await new Promise(resolve => setTimeout(resolve, retryIntervalInMillis)); |
| 89 | + |
| 90 | + } |
| 91 | + if (queryResponse) { |
| 92 | + return queryResponse; |
| 93 | + } |
| 94 | + throw new Error(`Failed to get a successful response from Apex Guru after maximum retries.${lastErrorMessage}`); |
| 95 | +} |
| 96 | + |
| 97 | +export async function initiateApexGuruRequest(selection: vscode.Uri, outputChannel: vscode.LogOutputChannel, connection: Connection): Promise<string> { |
| 98 | + const fileContent = await fileSystem.readFile(selection.fsPath); |
| 99 | + const base64EncodedContent = Buffer.from(fileContent).toString('base64'); |
| 100 | + const response: ApexGuruInitialResponse = await connection.request({ |
| 101 | + method: 'POST', |
| 102 | + url: Constants.APEX_GURU_REQUEST, |
| 103 | + body: JSON.stringify({ |
| 104 | + classContent: base64EncodedContent |
| 105 | + }) |
| 106 | + }); |
| 107 | + |
| 108 | + if (response.status != 'new' && response.status != 'success') { |
| 109 | + outputChannel.warn('Code Analyzer with Apex Guru returned unexpected response:' + response.status); |
| 110 | + throw Error('Code Analyzer with Apex Guru returned unexpected response:' + response.status); |
| 111 | + } |
| 112 | + |
| 113 | + const requestId = response.requestId; |
| 114 | + return requestId; |
| 115 | +} |
| 116 | + |
| 117 | +export const fileSystem = { |
| 118 | + readFile: (path: string) => fspromises.readFile(path, 'utf8') |
| 119 | +}; |
| 120 | + |
| 121 | +export function transformStringToRuleResult(fileName: string, jsonString: string): RuleResult { |
| 122 | + const reports = JSON.parse(jsonString) as ApexGuruReport[]; |
| 123 | + |
| 124 | + const ruleResult: RuleResult = { |
| 125 | + engine: 'apexguru', |
| 126 | + fileName: fileName, |
| 127 | + violations: [] |
| 128 | + }; |
| 129 | + |
| 130 | + reports.forEach(parsed => { |
| 131 | + const encodedCodeBefore = |
| 132 | + parsed.properties.find((prop: ApexGuruProperty) => prop.name === 'code_before')?.value |
| 133 | + ?? parsed.properties.find((prop: ApexGuruProperty) => prop.name === 'class_before')?.value |
| 134 | + ?? ''; |
| 135 | + const encodedCodeAfter = |
| 136 | + parsed.properties.find((prop: ApexGuruProperty) => prop.name === 'code_after')?.value |
| 137 | + ?? parsed.properties.find((prop: ApexGuruProperty) => prop.name === 'class_after')?.value |
| 138 | + ?? ''; |
| 139 | + const lineNumber = parseInt(parsed.properties.find((prop: ApexGuruProperty) => prop.name === 'line_number')?.value); |
| 140 | + |
| 141 | + const violation: ApexGuruViolation = { |
| 142 | + ruleName: parsed.type, |
| 143 | + message: parsed.value, |
| 144 | + severity: 1, |
| 145 | + category: parsed.type, // Replace with actual category if available |
| 146 | + line: lineNumber, |
| 147 | + column: 1, |
| 148 | + currentCode: Buffer.from(encodedCodeBefore, 'base64').toString('utf8'), |
| 149 | + suggestedCode: Buffer.from(encodedCodeAfter, 'base64').toString('utf8'), |
| 150 | + url: fileName |
| 151 | + }; |
| 152 | + |
| 153 | + ruleResult.violations.push(violation); |
| 154 | + }); |
| 155 | + |
| 156 | + return ruleResult; |
| 157 | +} |
| 158 | + |
| 159 | +export type ApexGuruAuthResponse = { |
| 160 | + status: string; |
| 161 | +} |
| 162 | + |
| 163 | +export type ApexGuruInitialResponse = { |
| 164 | + status: string; |
| 165 | + requestId: string; |
| 166 | + message: string; |
| 167 | +} |
| 168 | + |
| 169 | +export type ApexGuruQueryResponse = { |
| 170 | + status: string; |
| 171 | + message?: string; |
| 172 | + report?: string; |
| 173 | +} |
| 174 | + |
| 175 | +export type ApexGuruProperty = { |
| 176 | + name: string; |
| 177 | + value: string; |
| 178 | +}; |
| 179 | + |
| 180 | +export type ApexGuruReport = { |
| 181 | + id: string; |
| 182 | + type: string; |
| 183 | + value: string; |
| 184 | + properties: ApexGuruProperty[]; |
| 185 | +} |
0 commit comments