데이터 통합사용 가능한 커넥터GitHub

본 번역은 검증되지 않았습니다. AIP를 통해 영문원문으로부터 번역되었습니다.

GitHub

GitHub 커넥터는 Palantir 제공 드라이버입니다.

새로운 GitHub 소스를 생성하려면 Palantir 제공 드라이버의 표준 설정 흐름을 따르고, 아래 섹션에서 GitHub에 특화된 설정 및 네트워킹을 확인 해주세요. 전체 속성 출처는 공식 GitHub 드라이버 문서 ↗를 참고하세요.

지원되는 기능

기능상태
탐색🟢 일반적으로 사용 가능
배치 동기화🟢 일반적으로 사용 가능
점진적 동기화🟢 일반적으로 사용 가능
OAuth 2.0 인증🟢 일반적으로 사용 가능
표 내보내기🟢 일반적으로 사용 가능

소개

GitHub 커넥터는 대량으로 데이터 읽기에 가장 적합합니다. GitHub 데이터 모델(저장소, Issues, Pull Request, 커밋 및 관련 엔티티)을 관계형 표로 제공합니다. 소스 탐색기에서 이를 탐색하고 배치 동기화를 통해 Foundry로 가져올 수 있습니다. 이를 통해 전체 저장소 또는 조직을 Foundry로 미러링하여 후속 분석에 활용하기에 적합합니다.

GitHub 소스 탐색기에서 Commits와 같은 표를 동기화에 추가하기 전에 미리보기하는 화면

GitHub에서 레코드를 생성하거나 업데이트하려면 기존 GitHub 소스를 재사용하고 외부 변환 또는 외부 Function을 통해 GitHub REST API ↗를 호출하세요. 추가 소스는 필요하지 않습니다. 아래 코드에서 GitHub 소스 사용을 확인 해주세요.

인증

커넥터는 OAuth 2.0을 통해 GitHub에 인증합니다. GitHub에서 애플리케이션을 등록한 후 Foundry 소스에서 Client ID와 Client secret을 입력합니다 (OAuthClientId / OAuthClientSecret). InitiateOAuth를 REFRESH로 설정하면 드라이버가 첫 번째 동기화 시 GitHub의 OAuth 웹 애플리케이션 흐름 ↗을 실행하고 토큰을 갱신합니다.

GitHub은 두 가지 애플리케이션 유형을 제공합니다. 둘 다 OAuth 2.0을 기반으로 하며 동일한 방식으로 구성됩니다. GitHub App(권장)은 세부적인 리소스별 권한(예: 특정 저장소의 Issues에 대한 읽기 전용 액세스)과 단기 토큰을 제공합니다. OAuth 앱은 repo와 같은 계정 수준 범위를 사용합니다. 아래 단계는 GitHub App을 사용하며, OAuth 앱은 권한 프로비저닝 워크플로우에서 Settings > Developer settings에서 OAuth 앱을 선택하는 것을 제외하고 동일합니다. 전체 비교는 GitHub Apps와 OAuth Apps의 차이 ↗를 참고하세요.

애플리케이션 생성

GitHub에서 **Settings > Developer settings > GitHub Apps > New GitHub App ↗**을 선택하고 Callback URL을 Foundry 소스 설정 페이지에 표시된 값으로 설정하세요.

GitHub Create GitHub App 양식, 앱 이름, 홈페이지 URL, 및 콜백 URL 필드 표시

Permissions & events에서 동기화에 필요한 권한만 부여하세요(예: 읽기 전용 Contents 및 Issues). 앱을 생성하고 Install App 탭에서 대상 저장소 또는 조직에 설치합니다. 그런 다음, 앱의 General 페이지에서 Client ID를 복사하고 Client secret을 생성하세요.

GitHub App General 페이지, Client ID 및 Client secrets 섹션 표시

GitHub Client ID 및 Secret을 소스에 추가

Foundry의 Data Connection으로 이동하여 소스의 OAuthClientId 및 OAuthClientSecret 속성에 Client ID와 Client secret을 입력하고 InitiateOAuth를 REFRESH로 유지하세요.

Foundry GitHub 소스 연결 설정, OAuth Client ID, Client Secret, 및 Callback URL 속성과 승인된 egress 정책 표시

설정

아래 속성은 필수 또는 권장됩니다.

속성필수 여부설명기본값
InitiateOAuth ↗권장인증된 사용자가 작업하는 동안 사용자 액세스를 유지하는 OAuth 액세스 토큰을 얻거나 갱신하는 과정을 지정합니다.REFRESH
OAuthClientId ↗권장사용자 지정 OAuth 애플리케이션에 할당된 Client ID(소비자 키라고도 함)를 지정합니다. 이 ID는 인증 중 OAuth 인증 서버에 애플리케이션을 식별하는 데 필요합니다.—
OAuthClientSecret ↗권장사용자 지정 OAuth 애플리케이션에 할당된 Client Secret을 지정합니다. 이 비공개 값은 OAuth 인증 서버에 애플리케이션을 인증하는 데 사용됩니다.—

네트워킹

아래 표는 소스가 실행되기 위해 액세스해야 하는 도메인을 나열합니다.

각 도메인에 대해 egress 정책을 추가하세요. 소스가 온프레미스에서 호스팅되고 Foundry에서 직접 접근할 수 없는 경우, 대신 에이전트 프록시 egress 정책을 사용하세요. 에이전트 호스트 자체도 나열된 도메인에 접근할 수 있어야 합니다. 자세한 내용은 에이전트를 프록시로 사용을 참고하세요.

도메인필수 여부
github.com항상
api.github.com항상

OAuth 2.0 인증

이 커넥터는 OAuth 2.0 인증을 지원합니다. 연결을 구성하고 인증하려면 Palantir 제공 드라이버의 OAuth 2.0 가이드를 참고하세요.

표 내보내기

이 커넥터는 표 내보내기를 지원합니다. 표 내보내기 설정을 확인 해주세요.

코드에서 GitHub 소스 사용

GitHub에서 레코드를 생성하거나 업데이트하거나 대량 읽기 외의 GitHub REST API ↗ 일부를 사용하려면 외부 변환 또는 외부 Function을 통해 API를 호출하세요. 기존 GitHub 소스를 재사용하며, 코드에서 생성된 단기(약 1시간 TTL) GitHub App 설치 토큰으로 인증합니다. 추가 소스는 필요하지 않습니다.

다음으로, 소스를 외부 변환 또는 Functions 저장소에 가져옵니다. 소스는 내장된 HTTPS 클라이언트(get_https_connection().get_client())를 노출하지 않지만, api.github.com egress를 상속받아 위 네트워크 egress 정책에 포함됩니다. Python의 requests ↗ 또는 TypeScript의 소스 fetch를 사용하여 GitHub REST API를 직접 호출할 수 있습니다.

GitHub Issues 읽기

아래 예제는 Python 또는 TypeScript를 사용하여 GitHub App을 통해 GitHub Issues를 읽습니다.

이 워크플로우는 개인 액세스 토큰이 필요한 OAuth 앱에서는 지원되지 않습니다.

먼저, Data Connection에서 소스의 Connection details 페이지로 이동하여 GitHub App의 개인 키를 추가합니다. Add property > New encrypted property를 선택하고 속성 이름을 Other로 지정하여 get_secret("Other")로 읽을 수 있도록 설정하세요.

다음으로, Python 예제에서 APP_ID를 GitHub App ID 또는 Client ID로 설정하세요. 이 식별자는 공개적이며 비밀 저장소가 필요하지 않습니다. TypeScript 예제는 대신 소스의 OAuthClientId 속성에서 이를 읽습니다.

Function 프리뷰 실패

라이브 프리뷰는 소스를 Function에 바인딩할 수 없으므로, 이러한 예제는 프리뷰 중 항상 오류가 발생합니다. 대신 Function을 배포하고 Workshop 애플리케이션에서 실행하거나 서버리스 실행을 통해 작동 여부를 확인하세요.

Copied!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 import time import jwt import pandas as pd import requests from transforms.api import LightweightOutput, Output, transform from transforms.external.systems import ResolvedSource, Source, external_systems API = "https://api.github.com" APP_ID = "<github_app_id_or_client_id>" OWNER = "<owner>" REPOSITORY = "<repository>" def github_headers(github: ResolvedSource) -> dict[str, str]: now = int(time.time()) app_jwt = jwt.encode( {"iat": now - 60, "exp": now + 540, "iss": APP_ID}, github.get_secret("Other"), algorithm="RS256", ) headers = { "Accept": "application/vnd.github+json", "X-GitHub-Api-Version": "2022-11-28", "Authorization": f"Bearer {app_jwt}", } installation_id = requests.get( f"{API}/repos/{OWNER}/{REPOSITORY}/installation", headers=headers ).json()["id"] token = requests.post( f"{API}/app/installations/{installation_id}/access_tokens", headers=headers, ).json()["token"] return {**headers, "Authorization": f"Bearer {token}"} @external_systems(github=Source("<source_rid>")) @transform.using(output=Output("<issues_output_dataset_rid>")) def get_issues(github: ResolvedSource, output: LightweightOutput) -> None: response = requests.get( f"{API}/repos/{OWNER}/{REPOSITORY}/issues", headers=github_headers(github), params={"state": "all", "per_page": 100}, ) response.raise_for_status() output.write_table(pd.DataFrame([{ "number": issue["number"], "title": issue["title"], "body": issue["body"], "state": issue["state"], } for issue in response.json()]))
Copied!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 import time from dataclasses import dataclass import jwt import requests from functions.api import function from functions.sources import get_source API = "https://api.github.com" APP_ID = "<github_app_id_or_client_id>" SOURCE_ALIAS = "<source_alias>" @dataclass class GitHubIssue: number: int title: str body: str | None state: str def github_headers(github, owner: str, repository: str) -> dict[str, str]: now = int(time.time()) app_jwt = jwt.encode( {"iat": now - 60, "exp": now + 540, "iss": APP_ID}, github.get_secret("Other"), algorithm="RS256", ) headers = { "Accept": "application/vnd.github+json", "X-GitHub-Api-Version": "2022-11-28", "Authorization": f"Bearer {app_jwt}", } installation_id = requests.get( f"{API}/repos/{owner}/{repository}/installation", headers=headers ).json()["id"] token = requests.post( f"{API}/app/installations/{installation_id}/access_tokens", headers=headers, ).json()["token"] return {**headers, "Authorization": f"Bearer {token}"} @function(sources=["<source_alias>"]) def get_issues(owner: str, repository: str) -> list[GitHubIssue]: response = requests.get( f"{API}/repos/{owner}/{repository}/issues", headers=github_headers(get_source(SOURCE_ALIAS), owner, repository), params={"state": "all", "per_page": 100}, ) response.raise_for_status() return [GitHubIssue(issue["number"], issue["title"], issue["body"], issue["state"]) for issue in response.json()]
Copied!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 import { ExternalSystems, Function, Integer } from "@foundry/functions-api"; import { GitHubSource } from "@foundry/external-systems/sources"; import * as jwt from "jsonwebtoken"; const API = "https://api.github.com"; export interface GitHubIssue { number: Integer; title: string; body?: string; state: string; } async function githubHeaders(owner: string, repository: string): Promise<Record<string, string>> { const now = Math.floor(Date.now() / 1000); const appJwt = jwt.sign( { iat: now - 60, exp: now + 540, iss: GitHubSource.getSecret("OAuthClientId") }, GitHubSource.getSecret("Other"), { algorithm: "RS256" }, ); const headers = { Accept: "application/vnd.github+json", "X-GitHub-Api-Version": "2022-11-28", Authorization: `Bearer ${appJwt}`, }; const installation = await GitHubSource.fetch( `${API}/repos/${owner}/${repository}/installation`, { method: "GET", headers } ); const { id } = await installation.json() as { id: number }; const tokenResponse = await GitHubSource.fetch( `${API}/app/installations/${id}/access_tokens`, { method: "POST", headers } ); const { token } = await tokenResponse.json() as { token: string }; return { ...headers, Authorization: `Bearer ${token}` }; } export class GitHubFunctions { @ExternalSystems({ sources: [GitHubSource] }) @Function() public async getIssues(owner: string, repository: string): Promise<GitHubIssue[]> { const response = await GitHubSource.fetch( `${API}/repos/${owner}/${repository}/issues?state=all&per_page=100`, { method: "GET", headers: await githubHeaders(owner, repository) }, ); if (!response.ok) throw new Error(`GitHub returned ${response.status}`); const issues = await response.json() as Array<{ number: number; title: string; body: string | null; state: string; }>; return issues.map(({ number, title, body, state }) => ({ number, title, body: body ?? undefined, state, })); } }
Copied!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 import { Integer } from "@osdk/functions"; import { getFetch, getSource } from "@palantir/functions-sources"; import jwt from "jsonwebtoken"; const API = "https://api.github.com"; const SOURCE_RID = "<source_rid>"; export const config = { sources: [SOURCE_RID] }; export interface GitHubIssue { number: Integer; title: string; body?: string; state: string; } async function githubClient(owner: string, repository: string) { const source = await getSource({ rid: SOURCE_RID }); const request = await getFetch(source); const now = Math.floor(Date.now() / 1000); const appJwt = jwt.sign( { iat: now - 60, exp: now + 540, iss: source.secrets.OAuthClientId! }, source.secrets.Other!, { algorithm: "RS256" }, ); const headers = { Accept: "application/vnd.github+json", "X-GitHub-Api-Version": "2022-11-28", Authorization: `Bearer ${appJwt}`, }; const installation = await request( `${API}/repos/${owner}/${repository}/installation`, { method: "GET", headers } ); const { id } = await installation.json() as { id: number }; const tokenResponse = await request( `${API}/app/installations/${id}/access_tokens`, { method: "POST", headers } ); const { token } = await tokenResponse.json() as { token: string }; return { request, headers: { ...headers, Authorization: `Bearer ${token}` } }; } export default async function getIssues(owner: string, repository: string): Promise<GitHubIssue[]> { const { request, headers } = await githubClient(owner, repository); const response = await request( `${API}/repos/${owner}/${repository}/issues?state=all&per_page=100`, { method: "GET", headers }, ); if (!response.ok) throw new Error(`GitHub returned ${response.status}`); const issues = await response.json() as Array<{ number: number; title: string; body: string | null; state: string; }>; return issues.map(({ number, title, body, state }) => ({ number, title, body: body ?? undefined, state, })); }

GitHub Issues 업데이트

아래 예제는 GitHub Issues 읽기 예제와 동일한 GitHub App 인증 흐름을 통해 GitHub Issue의 본문을 업데이트합니다.

각 예제는 선택된 Issue의 전체 본문을 즉시 대체합니다. 덮어쓰려는 본문이 있는 Issue만 제공하세요.

Copied!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 import time import jwt import pandas as pd import requests from transforms.api import LightweightOutput, Output, transform from transforms.external.systems import ResolvedSource, Source, external_systems API = "https://api.github.com" APP_ID = "<github_app_id_or_client_id>" OWNER = "<owner>" REPOSITORY = "<repository>" ISSUE_NUMBER = "<issue_number>" UPDATED_BODY = "<updated_issue_body>" def github_headers(github: ResolvedSource) -> dict[str, str]: now = int(time.time()) app_jwt = jwt.encode( {"iat": now - 60, "exp": now + 540, "iss": APP_ID}, github.get_secret("Other"), algorithm="RS256", ) headers = { "Accept": "application/vnd.github+json", "X-GitHub-Api-Version": "2022-11-28", "Authorization": f"Bearer {app_jwt}", } installation_id = requests.get( f"{API}/repos/{OWNER}/{REPOSITORY}/installation", headers=headers ).json()["id"] token = requests.post( f"{API}/app/installations/{installation_id}/access_tokens", headers=headers, ).json()["token"] return {**headers, "Authorization": f"Bearer {token}"} @external_systems(github=Source("<source_rid>")) @transform.using(output=Output("<update_output_dataset_rid>")) def patch_issue(github: ResolvedSource, output: LightweightOutput) -> None: response = requests.patch( f"{API}/repos/{OWNER}/{REPOSITORY}/issues/{ISSUE_NUMBER}", headers=github_headers(github), json={"body": UPDATED_BODY}, ) response.raise_for_status() output.write_table(pd.DataFrame([{ "issue_number": ISSUE_NUMBER, "body": UPDATED_BODY, }]))
Copied!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 import time import jwt import requests from functions.api import function from functions.sources import get_source API = "https://api.github.com" APP_ID = "<github_app_id_or_client_id>" SOURCE_ALIAS = "<source_alias>" def github_headers(github, owner: str, repository: str) -> dict[str, str]: now = int(time.time()) app_jwt = jwt.encode( {"iat": now - 60, "exp": now + 540, "iss": APP_ID}, github.get_secret("Other"), algorithm="RS256", ) headers = { "Accept": "application/vnd.github+json", "X-GitHub-Api-Version": "2022-11-28", "Authorization": f"Bearer {app_jwt}", } installation_id = requests.get( f"{API}/repos/{owner}/{repository}/installation", headers=headers ).json()["id"] token = requests.post( f"{API}/app/installations/{installation_id}/access_tokens", headers=headers, ).json()["token"] return {**headers, "Authorization": f"Bearer {token}"} @function(sources=["<source_alias>"]) def patch_issue( owner: str, repository: str, issue_number: int, body: str ) -> str: response = requests.patch( f"{API}/repos/{owner}/{repository}/issues/{issue_number}", headers=github_headers(get_source(SOURCE_ALIAS), owner, repository), json={"body": body}, ) response.raise_for_status() return body
Copied!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 import { ExternalSystems, Function, Integer } from "@foundry/functions-api"; import { GitHubSource } from "@foundry/external-systems/sources"; import * as jwt from "jsonwebtoken"; const API = "https://api.github.com"; async function githubHeaders(owner: string, repository: string): Promise<Record<string, string>> { const now = Math.floor(Date.now() / 1000); const appJwt = jwt.sign( { iat: now - 60, exp: now + 540, iss: GitHubSource.getSecret("OAuthClientId") }, GitHubSource.getSecret("Other"), { algorithm: "RS256" }, ); const headers = { Accept: "application/vnd.github+json", "X-GitHub-Api-Version": "2022-11-28", Authorization: `Bearer ${appJwt}`, }; const installation = await GitHubSource.fetch( `${API}/repos/${owner}/${repository}/installation`, { method: "GET", headers } ); const { id } = await installation.json() as { id: number }; const tokenResponse = await GitHubSource.fetch( `${API}/app/installations/${id}/access_tokens`, { method: "POST", headers } ); const { token } = await tokenResponse.json() as { token: string }; return { ...headers, Authorization: `Bearer ${token}` }; } export class GitHubFunctions { @ExternalSystems({ sources: [GitHubSource] }) @Function() public async patchIssue( owner: string, repository: string, issueNumber: Integer, body: string ): Promise<string> { const response = await GitHubSource.fetch( `${API}/repos/${owner}/${repository}/issues/${issueNumber}`, { method: "PATCH", headers: { ...await githubHeaders(owner, repository), "Content-Type": "application/json" }, body: JSON.stringify({ body }), }, ); if (!response.ok) throw new Error(`GitHub returned ${response.status}`); return body; } }
Copied!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 import { Integer } from "@osdk/functions"; import { getFetch, getSource } from "@palantir/functions-sources"; import jwt from "jsonwebtoken"; const API = "https://api.github.com"; const SOURCE_RID = "<source_rid>"; export const config = { sources: [SOURCE_RID] }; async function githubClient(owner: string, repository: string) { const source = await getSource({ rid: SOURCE_RID }); const request = await getFetch(source); const now = Math.floor(Date.now() / 1000); const appJwt = jwt.sign( { iat: now - 60, exp: now + 540, iss: source.secrets.OAuthClientId! }, source.secrets.Other!, { algorithm: "RS256" }, ); const headers = { Accept: "application/vnd.github+json", "X-GitHub-Api-Version": "2022-11-28", Authorization: `Bearer ${appJwt}`, }; const installation = await request( `${API}/repos/${owner}/${repository}/installation`, { method: "GET", headers } ); const { id } = await installation.json() as { id: number }; const tokenResponse = await request( `${API}/app/installations/${id}/access_tokens`, { method: "POST", headers } ); const { token } = await tokenResponse.json() as { token: string }; return { request, headers: { ...headers, Authorization: `Bearer ${token}` } }; } export default async function patchIssue( owner: string, repository: string, issueNumber: Integer, body: string ): Promise<string> { const { request, headers } = await githubClient(owner, repository); const response = await request( `${API}/repos/${owner}/${repository}/issues/${issueNumber}`, { method: "PATCH", headers: { ...headers, "Content-Type": "application/json" }, body: JSON.stringify({ body }), }, ); if (!response.ok) throw new Error(`GitHub returned ${response.status}`); return body; }