Skip to content

Commit

Permalink
chore: extract github request logic in new file - githubClient.ts
Browse files Browse the repository at this point in the history
Signed-off-by: Victor Yanev <victor.yanev@limechain.tech>
  • Loading branch information
victor-yanev committed Jul 18, 2024
1 parent 97badf6 commit 45075f8
Show file tree
Hide file tree
Showing 3 changed files with 118 additions and 40 deletions.
84 changes: 84 additions & 0 deletions packages/server/tests/clients/githubClient.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
/*-
*
* Hedera JSON RPC Relay
*
* Copyright (C) 2022-2024 Hedera Hashgraph, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/

import { Octokit } from '@octokit/core';
import { GitHubContext } from '../types/GitHubContext';

/**
* Client for interacting with GitHub, providing methods to perform operations such as adding comments to pull requests.
*/
export class GitHubClient {
private static readonly CREATE_COMMENT_ENDPOINT = 'POST /repos/{owner}/{repo}/pulls/{pull_number}/comments';

/**
* The Octokit instance used to interact with GitHub.
* @private
*/
private readonly octokit: Octokit;

constructor(octokit?: Octokit) {
this.octokit = octokit || new Octokit({ auth: process.env.GITHUB_TOKEN });
}

/**
* Adds a comment to a pull request.
* @param {string} commentBody - The body of the comment.
* @param {string} path - The file path related to the comment.
* @returns {Promise<void>} A promise that resolves when the comment is successfully posted.
*/
async addCommentToPullRequest(commentBody: string, path: string): Promise<void> {
try {
const context = GitHubClient.getContext();
const response = await this.octokit.request(GitHubClient.CREATE_COMMENT_ENDPOINT, {
owner: context.owner,
repo: context.repo,
pull_number: context.pullNumber,
body: commentBody,
commit_id: context.commitId,
// @ts-ignore
subject_type: 'file',
path,
});
console.info('Comment posted successfully:', response);
} catch (error) {
console.error('Failed to post comment to PR:', error);
}
}

/**
* Retrieves the GitHub context from environment variables.
* @returns {GitHubContext} The GitHub context.
*/
private static getContext(): GitHubContext {
const { GITHUB_REPOSITORY, GITHUB_PR_NUMBER, GITHUB_COMMIT_SHA, GITHUB_TOKEN } = process.env;
if (!GITHUB_REPOSITORY || !GITHUB_PR_NUMBER || !GITHUB_COMMIT_SHA || !GITHUB_TOKEN) {
throw new Error(
`Missing required environment variables:
$GITHUB_REPOSITORY, $GITHUB_PR_NUMBER, $GITHUB_COMMIT_SHA, $GITHUB_TOKEN`,
);
}
const [owner, repo] = GITHUB_REPOSITORY.split('/');
const pullNumber = parseInt(GITHUB_PR_NUMBER);
if (isNaN(pullNumber)) {
throw new Error('Invalid PR number: $GITHUB_PR_NUMBER must be a valid number.');
}
return { owner, repo, pullNumber, token: GITHUB_TOKEN, commitId: GITHUB_COMMIT_SHA };
}
}
47 changes: 7 additions & 40 deletions packages/server/tests/helpers/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,11 @@ import { GCProfiler, setFlagsFromString } from 'v8';
import { runInNewContext } from 'vm';
import { Context } from 'mocha';
import { writeSnapshot } from 'heapdump';
import { Octokit } from '@octokit/core';
import path from 'path';

type GithubContext = { owner: string; repo: string; token: string; pullNumber: number; commitId: string };
import { GitHubClient } from '../clients/githubClient';
import MirrorClient from '../clients/mirrorClient';

export class Utils {
static readonly CREATE_COMMENT_ENDPOINT = 'POST /repos/{owner}/{repo}/pulls/{pull_number}/comments';
static readonly PROJECT_ROOT_PATH = path.resolve('../..');
static readonly TOTAL_HEAP_SIZE_MEMORY_LEAK_THRESHOLD: number = 100e6; // 100 MB
static readonly MEMORY_LEAK_SNAPSHOT_THRESHOLD: number = 1e6; // 1 MB
Expand Down Expand Up @@ -261,11 +259,11 @@ export class Utils {
* @param {MirrorClient} mirrorNode The mirror node client.
* @param {AliasAccount} creator The creator account for the alias.
* @param {string} requestId The unique identifier for the request.
* @param {string} balanceInWeiBars The initial balance for the alias account in wei bars. Defaults to 10 HBAR (10,000,000,000,000,000,000 wei).
* @param {string} balanceInTinyBar The initial balance for the alias account in tiny bars. Defaults to 10 HBAR.
* @returns {Promise<AliasAccount>} A promise resolving to the created alias account.
*/
static readonly createAliasAccount = async (
mirrorNode,
mirrorNode: MirrorClient,
creator: AliasAccount,
requestId: string,
balanceInTinyBar: string = '1000000000', //10 HBAR
Expand Down Expand Up @@ -305,7 +303,7 @@ export class Utils {
};

static async createMultipleAliasAccounts(
mirrorNode,
mirrorNode: MirrorClient,
initialAccount: AliasAccount,
neededAccounts: number,
initialAmountInTinyBar: string,
Expand Down Expand Up @@ -408,6 +406,7 @@ export class Utils {
// TODO: Used for debugging, remove this as its cluttering the logs with traces from the garbage collector
setFlagsFromString('--trace_gc');
const gc = runInNewContext('gc');
const githubClient = new GitHubClient();

beforeEach(function () {
profiler.start();
Expand Down Expand Up @@ -446,7 +445,7 @@ export class Utils {
`Memory leak of ${Utils.formatBytes(totalDiffBytes)}: --> ` + JSON.stringify(statsDiff, null, 2),
);
// add comment on PR highlighting after which test the memory leak is happening
await Utils.addCommentToPullRequest(
await githubClient.addCommentToPullRequest(
`Memory leak detected in test: ${this.currentTest?.title}\n
Details: ${JSON.stringify(statsDiff, null, 2)}`,
this.test?.file ? path.relative(Utils.PROJECT_ROOT_PATH, this.test?.file) : '',
Expand Down Expand Up @@ -525,36 +524,4 @@ export class Utils {
const size = bytes / Math.pow(1000, power);
return `${size.toFixed(2)} ${units[power]}`;
}

private static async addCommentToPullRequest(commentBody: string, path: string): Promise<void> {
try {
const context = Utils.getGithubContext();
const octokit = new Octokit({ auth: context.token });
const response = await octokit.request(Utils.CREATE_COMMENT_ENDPOINT, {
owner: context.owner,
repo: context.repo,
pull_number: context.pullNumber,
body: commentBody,
commit_id: context.commitId,
subject_type: 'FILE',
path,
});
console.log('Comment posted successfully:', response);
} catch (error) {
console.warn('Failed to post comment to PR:', error);
}
}

private static getGithubContext(): GithubContext {
const { GITHUB_REPOSITORY, GITHUB_PR_NUMBER, GITHUB_COMMIT_SHA, GITHUB_TOKEN } = process.env;
if (!GITHUB_REPOSITORY || !GITHUB_PR_NUMBER || !GITHUB_COMMIT_SHA || !GITHUB_TOKEN) {
throw new Error(
`Missing required environment variables:
$GITHUB_REPOSITORY, $GITHUB_PR_NUMBER, $GITHUB_COMMIT_SHA, $GITHUB_TOKEN`,
);
}
const [owner, repo] = GITHUB_REPOSITORY.split('/');
const pullNumber = parseInt(GITHUB_PR_NUMBER);
return { owner, repo, pullNumber, token: GITHUB_TOKEN, commitId: GITHUB_COMMIT_SHA };
}
}
27 changes: 27 additions & 0 deletions packages/server/tests/types/GitHubContext.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
/*-
*
* Hedera JSON RPC Relay
*
* Copyright (C) 2022-2024 Hedera Hashgraph, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/

export interface GitHubContext {
readonly owner: string;
readonly repo: string;
readonly token: string;
readonly pullNumber: number;
readonly commitId: string;
}

0 comments on commit 45075f8

Please sign in to comment.