@preventive/triage 1.0.0-alpha.6 → 1.0.0-alpha.60
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE-APACHE +202 -0
- package/README.md +16 -0
- package/api/reap.ts +17 -0
- package/cli.js +6 -0
- package/client/dependency-paths.d.ts +3 -0
- package/client/dependency-paths.js +36 -0
- package/client/finding-link.js +305 -0
- package/client/linked-findings.d.ts +1 -0
- package/client/linked-findings.js +115 -0
- package/common/bundle-commit.d.ts +1 -0
- package/common/bundle-commit.js +4 -0
- package/common/bundle-compare-diff.d.ts +3 -0
- package/common/bundle-compare-diff.js +376 -0
- package/common/bundle-compare-inputs.d.ts +3 -0
- package/common/bundle-compare-inputs.js +141 -0
- package/common/bundle-compare-versions.js +172 -0
- package/common/bundle-comparison.d.ts +8 -0
- package/common/bundle-comparison.js +69 -0
- package/common/bundle-metadata.d.ts +15 -0
- package/common/bundle-metadata.js +226 -0
- package/common/bundle-pkg-of.d.ts +1 -0
- package/common/bundle-pkg-of.js +90 -0
- package/common/bundle-reasons.d.ts +2 -0
- package/common/bundle-reasons.js +21 -0
- package/common/bundle-source-links.d.ts +6 -0
- package/common/bundle-source-links.js +216 -0
- package/common/bundle-sourcemap.d.ts +10 -0
- package/common/bundle-sourcemap.js +100 -0
- package/common/bundle-sources.d.ts +7 -0
- package/common/bundle-sources.js +333 -0
- package/common/bundle-stats.js +41 -0
- package/common/bundle-tabs.js +1 -0
- package/common/code-language.js +65 -0
- package/common/default-scan-models.ts +35 -0
- package/common/dependency-reviews.d.ts +18 -0
- package/common/dependency-reviews.js +64 -0
- package/common/finding-duplicates.js +58 -0
- package/common/finding-filters.js +274 -0
- package/common/finding-id.js +47 -0
- package/common/finding-repo.d.ts +5 -0
- package/common/finding-repo.js +67 -0
- package/common/github-issue-labels.d.ts +1 -0
- package/common/github-issue-labels.js +11 -0
- package/common/github-pr.ts +56 -0
- package/common/gzip.js +59 -0
- package/common/line-diff.d.ts +8 -0
- package/common/line-diff.js +57 -0
- package/common/linked-workspace-groups.js +63 -0
- package/common/managed/agent-tasks.ts +292 -0
- package/common/managed/comments.ts +34 -0
- package/common/managed/finding-detail.d.ts +5 -0
- package/common/managed/finding-detail.js +75 -0
- package/common/managed/finding-values.d.ts +2 -0
- package/common/managed/finding-values.js +44 -0
- package/common/managed/github-agents.ts +114 -0
- package/common/managed/github-logins.ts +49 -0
- package/common/managed/lite-name.d.ts +2 -0
- package/common/managed/lite-name.js +20 -0
- package/common/managed/npm-packages.d.ts +7 -0
- package/common/managed/npm-packages.js +51 -0
- package/common/managed/permissions.ts +31 -0
- package/common/managed/report-content.ts +72 -0
- package/common/managed/report-filter.ts +120 -0
- package/common/managed/repository-alias.ts +65 -0
- package/common/managed/roles.ts +35 -0
- package/common/managed/routes.d.ts +2 -0
- package/common/managed/routes.js +363 -0
- package/common/managed/scan-models.ts +6 -0
- package/common/managed/team-app.d.ts +15 -0
- package/common/managed/team-app.js +100 -0
- package/common/managed/team-filters.js +26 -0
- package/common/managed/triage.ts +83 -0
- package/common/managed/upload-seal.ts +126 -0
- package/common/pretty-print.d.ts +5 -0
- package/common/pretty-print.js +24 -0
- package/common/repo-commit.d.ts +4 -0
- package/common/repo-commit.js +30 -0
- package/common/revalidation-conflicts.js +48 -0
- package/common/revalidation-input-groups.js +56 -0
- package/common/save-error-reason.ts +20 -7
- package/common/scan-server.ts +13 -0
- package/common/security-links.d.ts +5 -0
- package/common/security-links.js +33 -0
- package/common/server-info.ts +46 -0
- package/common/utf8.d.ts +3 -0
- package/common/utf8.js +45 -0
- package/common/workspace-app.js +71 -0
- package/common/workspace-groups.js +176 -0
- package/out/activity.js +4 -0
- package/out/brotli-fallback.js +3 -3
- package/out/chunk-2SY4PYUQ.js +4 -0
- package/out/chunk-2XUEZHIP.js +28 -0
- package/out/chunk-4EMM6UCD.js +1 -0
- package/out/chunk-4HI2MSAV.js +17 -0
- package/out/chunk-4ISO5F7Y.js +7 -0
- package/out/chunk-4TQKM3JC.js +42 -0
- package/out/chunk-4XIH7YTX.js +1 -0
- package/out/chunk-6VDDCFHT.js +3 -0
- package/out/chunk-74AEKRES.js +10 -0
- package/out/chunk-7BKKYVWR.js +7 -0
- package/out/chunk-7C7DWL7I.js +1 -0
- package/out/chunk-C4Z6ZBXV.js +10 -0
- package/out/chunk-DEVAORP2.js +1 -0
- package/out/chunk-E3LFSUDJ.js +9 -0
- package/out/chunk-EEQHVKR3.js +1 -0
- package/out/chunk-G3LY2FV4.js +1 -0
- package/out/chunk-GO7FT4OD.js +1 -0
- package/out/chunk-HAZKDK4M.js +4 -0
- package/out/chunk-HNQNDNIE.js +12 -0
- package/out/chunk-HOB3YPS5.js +1 -0
- package/out/chunk-IYPY47MC.js +1 -0
- package/out/chunk-IZ6MYRYB.js +3 -0
- package/out/chunk-J2FWBXFV.js +1 -0
- package/out/chunk-JCIIBLKR.js +1 -0
- package/out/chunk-JFL7WLRV.js +1 -0
- package/out/chunk-JMG5DXII.js +2 -0
- package/out/chunk-JOXLZXMI.js +1 -0
- package/out/chunk-M37X4LCF.js +14 -0
- package/out/chunk-M3Y6SLC4.js +1 -0
- package/out/chunk-NRPC74AM.js +1 -0
- package/out/chunk-NXATZJQ2.js +1 -0
- package/out/chunk-OFPDMZJF.js +244 -0
- package/out/chunk-OOJM4CTU.js +1 -0
- package/out/chunk-OQRSIBSC.js +1 -0
- package/out/chunk-PAD2JHZT.js +1 -0
- package/out/chunk-PNHBZGDD.js +1 -0
- package/out/chunk-PTFQKLKO.js +1 -0
- package/out/chunk-PWFUOLZK.js +17 -0
- package/out/chunk-PXK7EU4V.js +1 -0
- package/out/chunk-QMVOEBWC.js +13 -0
- package/out/chunk-QRKFPLA4.js +80 -0
- package/out/chunk-R3NZFXVR.js +1 -0
- package/out/chunk-R5O6FAW4.js +2 -0
- package/out/chunk-RRBIJL2B.js +1 -0
- package/out/chunk-SYXT3SFP.js +2 -0
- package/out/chunk-TOXMUOIW.js +5 -0
- package/out/chunk-TUII34K2.js +1 -0
- package/out/chunk-TZS7KERJ.js +52 -0
- package/out/chunk-UCP3JRE2.js +1 -0
- package/out/chunk-VFWMQ3LG.js +2 -0
- package/out/chunk-VRX2APNA.js +9 -0
- package/out/chunk-VZJIHHTQ.js +1 -0
- package/out/chunk-WCPJDAYA.js +10 -0
- package/out/chunk-WMFDQS2L.js +11 -0
- package/out/chunk-WREU7JAG.js +1 -0
- package/out/chunk-Y5ZHFNBD.js +2 -0
- package/out/chunk-YF4M5OCI.js +1 -0
- package/out/chunk-YGRRXC2L.js +1 -0
- package/out/chunk-YTO6AQZM.js +2 -0
- package/out/chunk-Z667U2UJ.js +1 -0
- package/out/chunk-ZQHLECTI.js +1 -0
- package/out/client-managed-import.js +4 -0
- package/out/client-managed.js +34 -0
- package/out/client-sync.js +11 -17
- package/out/compare.js +35 -0
- package/out/dialogs.js +40 -0
- package/out/github-issue-authorized.html +3 -0
- package/out/github-issue-authorized.js +1 -0
- package/out/graph.js +19 -4
- package/out/index.html +106 -8
- package/out/prism.js +14 -10
- package/out/scan.js +2 -0
- package/out/stasis.svg +20 -0
- package/out/terminal.js +366 -39
- package/out/view.css +1 -1
- package/out/view.js +19 -144
- package/package.json +379 -62
- package/risk/actions/findings.js +161 -0
- package/risk/actions/resolve.js +250 -0
- package/risk/actions/scripts/commands.js +182 -0
- package/risk/actions/scripts/grade.js +113 -0
- package/risk/actions/scripts/packages.js +123 -0
- package/risk/actions/scripts/shell.js +169 -0
- package/risk/actions/uses.js +76 -0
- package/risk/actions/workflow.js +110 -0
- package/risk/files/characters.js +196 -0
- package/risk/files/hosts.js +205 -0
- package/risk/files/readability.js +177 -0
- package/risk/files/runs-code.js +615 -0
- package/risk/files/script.js +118 -0
- package/risk/files/stamps.js +47 -0
- package/risk/index.d.ts +272 -0
- package/risk/index.js +11 -0
- package/risk/npm/assess.js +285 -0
- package/risk/npm/combined.js +68 -0
- package/risk/npm/compare.js +257 -0
- package/risk/npm/dependencies.js +172 -0
- package/risk/npm/diff.js +79 -0
- package/risk/npm/downloads.js +84 -0
- package/risk/npm/files.js +445 -0
- package/risk/npm/held.js +63 -0
- package/risk/npm/install-scripts.js +34 -0
- package/risk/npm/malware.js +38 -0
- package/risk/npm/manifest.js +65 -0
- package/risk/npm/new-dependency.js +60 -0
- package/risk/npm/old-version.js +108 -0
- package/risk/npm/registry.js +390 -0
- package/risk/npm/release.js +85 -0
- package/risk/npm/score.js +59 -0
- package/risk/npm/specs.js +124 -0
- package/risk/npm/tarball.js +96 -0
- package/server-common/database-config.ts +16 -0
- package/server-common/initialize.ts +18 -0
- package/server-common/npm-advisories.ts +101 -0
- package/{server → server-common}/origin.ts +5 -5
- package/server-common/reap.ts +48 -0
- package/server-common/scan-config.ts +19 -0
- package/server-common/standalone.ts +29 -0
- package/server-common/storage-crypto.ts +182 -0
- package/server-common/storage-log.ts +38 -0
- package/server-common/vercel-blob.ts +103 -0
- package/server-e2e/app.ts +487 -0
- package/{server → server-e2e}/bus-receiver.ts +2 -1
- package/{server → server-e2e}/cli.js +9 -4
- package/{server → server-e2e}/config.ts +50 -42
- package/{server → server-e2e}/db-neon.ts +2 -2
- package/{server → server-e2e}/db-revision-sql.ts +1 -1
- package/{server → server-e2e}/db-stmt.ts +2 -2
- package/{server → server-e2e}/db.ts +7 -7
- package/{server → server-e2e}/http.ts +44 -13
- package/{server → server-e2e}/hub.ts +40 -9
- package/server-e2e/index.ts +17 -0
- package/server-e2e/lifecycle.ts +95 -0
- package/{server → server-e2e}/neon-driver.ts +2 -2
- package/{server → server-e2e}/npm-proxy.ts +12 -145
- package/{server → server-e2e}/objstore/blob-vercel.ts +10 -114
- package/{server → server-e2e}/objstore/blob.ts +1 -1
- package/{server → server-e2e}/objstore/fetch-mint-guard.ts +2 -2
- package/{server → server-e2e}/objstore/handlers.ts +9 -8
- package/{server → server-e2e}/objstore/init.ts +19 -27
- package/{server → server-e2e}/objstore/reaper.ts +1 -1
- package/{server → server-e2e}/objstore/rest-deny.ts +1 -1
- package/{server → server-e2e}/objstore/rest-mint.ts +3 -3
- package/{server → server-e2e}/objstore/rest.ts +3 -3
- package/{server → server-e2e}/objstore/store-neon.ts +6 -10
- package/{server → server-e2e}/objstore/store.ts +7 -7
- package/{server → server-e2e}/objstore/tokens.ts +2 -2
- package/{server → server-e2e}/pubsub.ts +12 -9
- package/{server → server-e2e}/sign.ts +4 -4
- package/{server → server-e2e}/sse-server.ts +60 -33
- package/{server → server-e2e}/static.ts +31 -21
- package/{server → server-e2e}/sync-handlers.ts +64 -30
- package/{server → server-e2e}/ws-server.ts +20 -9
- package/server-managed/activity.ts +258 -0
- package/server-managed/agent-merges.ts +109 -0
- package/server-managed/app-agents.ts +23 -0
- package/server-managed/avatar-store.ts +13 -0
- package/server-managed/blob-store.ts +17 -0
- package/server-managed/brotli.ts +10 -0
- package/server-managed/bundle-advisories.ts +102 -0
- package/server-managed/bundle-advisory-inventory.ts +77 -0
- package/server-managed/bundle-build-diagnostics.d.ts +10 -0
- package/server-managed/bundle-build-diagnostics.js +23 -0
- package/server-managed/bundle-build-leases.ts +41 -0
- package/server-managed/bundle-build-worker.js +203 -0
- package/server-managed/bundle-build.ts +232 -0
- package/server-managed/bundle-cache.ts +211 -0
- package/server-managed/bundle-catalog.ts +29 -0
- package/server-managed/bundle-commits.ts +140 -0
- package/server-managed/bundle-dependency-reviews.ts +74 -0
- package/server-managed/bundle-store.ts +24 -0
- package/server-managed/bundle-summary-cache.ts +130 -0
- package/server-managed/bundle-validation.ts +32 -0
- package/server-managed/bundle.ts +119 -0
- package/server-managed/cache-storage.ts +20 -0
- package/server-managed/cli.js +21 -0
- package/server-managed/combined.ts +47 -0
- package/server-managed/comments.ts +151 -0
- package/server-managed/commit-coauthors.ts +106 -0
- package/server-managed/commit-lockfiles.ts +76 -0
- package/server-managed/comparison.ts +52 -0
- package/server-managed/config.ts +164 -0
- package/server-managed/content-access.ts +15 -0
- package/server-managed/crypto.ts +25 -0
- package/server-managed/db-methods.ts +1958 -0
- package/server-managed/db-neon.ts +484 -0
- package/server-managed/db-schema.ts +238 -0
- package/server-managed/db-table-names.ts +22 -0
- package/server-managed/db.ts +152 -0
- package/server-managed/dependabot-access.ts +60 -0
- package/server-managed/dependabot-alerts.ts +185 -0
- package/server-managed/dependency-review-comments.ts +98 -0
- package/server-managed/dependency-reviews.ts +364 -0
- package/server-managed/github-accounts.ts +60 -0
- package/server-managed/github-actions.ts +71 -0
- package/server-managed/github-app.ts +376 -0
- package/server-managed/github-errors.ts +70 -0
- package/server-managed/github-graphql.ts +39 -0
- package/server-managed/github-issue-links.ts +244 -0
- package/server-managed/github-issue-oauth.ts +47 -0
- package/server-managed/github-issues.ts +155 -0
- package/server-managed/github-link-oauth.ts +69 -0
- package/server-managed/github-links.ts +204 -0
- package/server-managed/github-metadata.ts +213 -0
- package/server-managed/github-oauth.ts +238 -0
- package/server-managed/github-pulls.ts +246 -0
- package/server-managed/github-requests.ts +166 -0
- package/server-managed/github-users.ts +30 -0
- package/server-managed/history-windows.ts +172 -0
- package/server-managed/http-response.ts +76 -0
- package/server-managed/http.ts +5855 -0
- package/server-managed/import-triage.ts +51 -0
- package/server-managed/index.ts +204 -0
- package/server-managed/kept-briefly.ts +37 -0
- package/server-managed/kept.ts +28 -0
- package/server-managed/link-reports.ts +162 -0
- package/server-managed/listed-activity.ts +39 -0
- package/server-managed/locked-packages.ts +152 -0
- package/server-managed/lockfile-scope.ts +49 -0
- package/server-managed/lru.ts +30 -0
- package/server-managed/managed-issues.ts +92 -0
- package/server-managed/management-catalog.ts +45 -0
- package/server-managed/management.ts +99 -0
- package/server-managed/npm-delta-worker.js +23 -0
- package/server-managed/npm-delta.ts +194 -0
- package/server-managed/npm-insights.ts +450 -0
- package/server-managed/npm-kept.ts +233 -0
- package/server-managed/npm-loads.ts +264 -0
- package/server-managed/npm-manifest.ts +115 -0
- package/server-managed/npm-packages.ts +454 -0
- package/server-managed/npm-patch.ts +325 -0
- package/server-managed/npm-provenance.ts +123 -0
- package/server-managed/npm-risk.ts +285 -0
- package/server-managed/object-storage-disk.ts +148 -0
- package/server-managed/object-storage-vercel.ts +67 -0
- package/server-managed/object-storage.ts +75 -0
- package/server-managed/package-entry-points.ts +79 -0
- package/server-managed/pretty-print.ts +436 -0
- package/server-managed/public-workspace.ts +238 -0
- package/server-managed/pull-comment-reviews.ts +161 -0
- package/server-managed/pull-dependencies.ts +351 -0
- package/server-managed/pull-dependency-reviews.ts +334 -0
- package/server-managed/pull-reviews.ts +205 -0
- package/server-managed/queue.ts +39 -0
- package/server-managed/release-commits.ts +84 -0
- package/server-managed/rename-diff-worker.js +26 -0
- package/server-managed/rename-diff.ts +279 -0
- package/server-managed/repo-path.ts +21 -0
- package/server-managed/report-migration.ts +35 -0
- package/server-managed/report-query.ts +10 -0
- package/server-managed/report-response.ts +16 -0
- package/server-managed/report-sources.ts +185 -0
- package/server-managed/report-store.ts +85 -0
- package/server-managed/repository-actions.ts +221 -0
- package/server-managed/repository-agents.ts +448 -0
- package/server-managed/repository-aliases.ts +91 -0
- package/server-managed/repository-browser.ts +301 -0
- package/server-managed/repository-changes.ts +284 -0
- package/server-managed/repository-code.ts +215 -0
- package/server-managed/repository-dependency-reviews.ts +166 -0
- package/server-managed/repository-discovery.ts +82 -0
- package/server-managed/repository-history.ts +432 -0
- package/server-managed/repository-issues.ts +195 -0
- package/server-managed/repository-policy.ts +27 -0
- package/server-managed/repository-pulls.ts +212 -0
- package/server-managed/repository-pulse.ts +471 -0
- package/server-managed/repository-risk-assess.ts +105 -0
- package/server-managed/repository-risk-audit.ts +78 -0
- package/server-managed/repository-risk-read.ts +170 -0
- package/server-managed/repository-risk.ts +491 -0
- package/server-managed/repository-squashes.ts +168 -0
- package/server-managed/repository-stamp.ts +41 -0
- package/server-managed/request-timing.ts +63 -0
- package/server-managed/reviewed-dependencies.ts +149 -0
- package/server-managed/revisions.ts +35 -0
- package/server-managed/scan-downloads.ts +87 -0
- package/server-managed/session.ts +132 -0
- package/server-managed/slugs.ts +38 -0
- package/server-managed/solidity-entry-points.ts +71 -0
- package/server-managed/sql-postgres.ts +34 -0
- package/server-managed/sql.ts +89 -0
- package/server-managed/stasis-config.ts +55 -0
- package/server-managed/static.ts +28 -0
- package/server-managed/storage-command.ts +16 -0
- package/server-managed/storage-db.ts +183 -0
- package/server-managed/storage-encryption.ts +290 -0
- package/server-managed/storage-maintenance.ts +259 -0
- package/server-managed/storage-payload.ts +121 -0
- package/server-managed/storage-stores.ts +91 -0
- package/server-managed/storage.ts +82 -0
- package/server-managed/team-app-summaries.ts +54 -0
- package/server-managed/team-app.ts +157 -0
- package/server-managed/team-catalog.ts +7 -0
- package/server-managed/team-feed.ts +180 -0
- package/server-managed/team-npm-scopes.ts +106 -0
- package/server-managed/team-reports.ts +351 -0
- package/server-managed/triage-response.ts +16 -0
- package/server-managed/type-only-worker.js +19 -0
- package/server-managed/type-only.ts +105 -0
- package/server-managed/uploads.ts +106 -0
- package/server-managed/upstream-cache.ts +252 -0
- package/server-managed/view-as.ts +58 -0
- package/server-managed/workspace-shares.ts +171 -0
- package/server.ts +70 -0
- package/server/index.ts +0 -480
- package/server/lifecycle.ts +0 -208
- /package/{LICENSE → LICENSE-MIT} +0 -0
- /package/{server → server-e2e}/auth.ts +0 -0
- /package/{server → server-e2e}/config.example.json +0 -0
- /package/{server → server-e2e}/objstore/blob-fs.ts +0 -0
- /package/{server → server-e2e}/objstore/fs.ts +0 -0
- /package/{server → server-e2e}/objstore/sign.ts +0 -0
- /package/{server → server-e2e}/peer.ts +0 -0
- /package/{server → server-e2e}/sse-session.ts +0 -0
- /package/{server → server-e2e}/util.ts +0 -0
- /package/{server → server-e2e}/validation.ts +0 -0
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
import { type GithubFixRef, type GithubFixResult, type GithubFixStatus, githubIssueClosedReason, isGithubRepoName, parseGithubFixUrl } from '../common/github-pr.ts'
|
|
2
|
+
import type { ManagedConfig } from './config.ts'
|
|
3
|
+
import type { ManagedDb, TeamReportAccessSnapshot } from './db.ts'
|
|
4
|
+
import type { GithubMetadata, GithubRepositoryVisibility } from './github-metadata.ts'
|
|
5
|
+
import { ensureUserAccessToken } from './github-oauth.ts'
|
|
6
|
+
|
|
7
|
+
type Metadata = Pick<GithubMetadata, 'title' | 'description' | 'status' | 'stateReason'>
|
|
8
|
+
const MAX_GITHUB_LOOKUPS = 200
|
|
9
|
+
// A load reading this many open or unknown items anew also rechecks one closed
|
|
10
|
+
// item, rounded up (lookupFixes).
|
|
11
|
+
const CLOSED_RECHECK_EVERY = 10
|
|
12
|
+
const GITHUB_LOOKUP_TIMEOUT_MS = 10_000
|
|
13
|
+
const GITHUB_METADATA_TTL_MS = 60_000
|
|
14
|
+
const GITHUB_PUBLIC_VISIBILITY_TTL_MS = 60_000
|
|
15
|
+
const GITHUB_PRIVATE_REPOSITORIES_URL = 'https://api.github.com/user/repos?visibility=private&per_page=100&page=1'
|
|
16
|
+
|
|
17
|
+
type Repository = TeamReportAccessSnapshot['repositories'][number]
|
|
18
|
+
type RepositoryPayload = { id?: unknown; full_name?: unknown; private?: unknown; visibility?: unknown; permissions?: { pull?: unknown } }
|
|
19
|
+
type RepositoryChecks = { remaining: number; verified: Set<string> }
|
|
20
|
+
type RepositoryAccessContext = {
|
|
21
|
+
db: ManagedDb
|
|
22
|
+
visibility: GithubRepositoryVisibility[]
|
|
23
|
+
publicRepos: Set<string>
|
|
24
|
+
token: string | null
|
|
25
|
+
signal: AbortSignal
|
|
26
|
+
fetchImpl: typeof fetch
|
|
27
|
+
checks: RepositoryChecks
|
|
28
|
+
includePrivateList?: boolean
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function githubRequest(token: string | null): RequestInit {
|
|
32
|
+
return {
|
|
33
|
+
headers: {
|
|
34
|
+
...(token ? { authorization: `Bearer ${token}` } : {}), accept: 'application/vnd.github+json',
|
|
35
|
+
'user-agent': 'deepview-triage', 'x-github-api-version': '2022-11-28',
|
|
36
|
+
},
|
|
37
|
+
redirect: 'error',
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function repositoryMatches(repo: Repository, body: RepositoryPayload | null): boolean {
|
|
42
|
+
return body?.id === repo.repoId && typeof body.full_name === 'string' && body.full_name.toLowerCase() === repo.github.toLowerCase()
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
async function listPrivateRepositories(token: string, signal: AbortSignal, fetchImpl: typeof fetch): Promise<(RepositoryPayload | null)[]> {
|
|
46
|
+
try {
|
|
47
|
+
const response = await fetchImpl(GITHUB_PRIVATE_REPOSITORIES_URL, githubRequest(token))
|
|
48
|
+
if (!response.ok) return []
|
|
49
|
+
const body = await response.json() as (RepositoryPayload | null)[] | null
|
|
50
|
+
return Array.isArray(body) && body.length <= 100 && !signal.aborted ? body : []
|
|
51
|
+
} catch { return [] } // A failed list is unknown access; direct checks can still verify it.
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// Public visibility can be reused briefly across users. Private access stays
|
|
55
|
+
// request-local: one page of the viewer's own repo list grants matching repos,
|
|
56
|
+
// then direct checks cover omissions, pagination and failed list requests.
|
|
57
|
+
async function readableRepositories(repositories: Repository[], { db, visibility, publicRepos, token, signal, fetchImpl, checks, includePrivateList = true }: RepositoryAccessContext): Promise<Set<string>> {
|
|
58
|
+
const readable = new Set(publicRepos)
|
|
59
|
+
const byId = new Map(repositories.map(repo => [repo.repoId, repo]))
|
|
60
|
+
const unverified = repositories.filter(repo => !readable.has(repo.github))
|
|
61
|
+
const updates = new Map<number, GithubRepositoryVisibility>()
|
|
62
|
+
const grant = (repo: Repository, body: RepositoryPayload, checkedAt: number) => {
|
|
63
|
+
const isPublic = body.private === false && body.visibility === 'public'
|
|
64
|
+
readable.add(repo.github)
|
|
65
|
+
checks.verified.add(repo.github)
|
|
66
|
+
if (isPublic) publicRepos.add(repo.github)
|
|
67
|
+
updates.set(repo.repoId, { repoId: repo.repoId, github: repo.github, public: isPublic, checkedAt })
|
|
68
|
+
}
|
|
69
|
+
if (includePrivateList && token && unverified.length > 0 && !signal.aborted) {
|
|
70
|
+
const checkedAt = Date.now()
|
|
71
|
+
for (const entry of await listPrivateRepositories(token, signal, fetchImpl)) {
|
|
72
|
+
const repo = typeof entry?.id === 'number' ? byId.get(entry.id) : undefined
|
|
73
|
+
if (repo && !readable.has(repo.github) && repositoryMatches(repo, entry) && entry?.permissions?.pull === true) grant(repo, entry, checkedAt)
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
const formerlyPublic = new Set(visibility.filter(entry => entry.public
|
|
77
|
+
&& byId.get(entry.repoId)?.github.toLowerCase() === entry.github.toLowerCase()).map(entry => entry.repoId))
|
|
78
|
+
const pending = unverified.filter(repo => !readable.has(repo.github) && (token || formerlyPublic.has(repo.repoId))).slice(0, checks.remaining)
|
|
79
|
+
checks.remaining -= pending.length
|
|
80
|
+
for (let i = 0; i < pending.length && !signal.aborted; i += 4) {
|
|
81
|
+
await Promise.all(pending.slice(i, i + 4).map(async repo => {
|
|
82
|
+
if (signal.aborted) return
|
|
83
|
+
const checkedAt = Date.now()
|
|
84
|
+
try {
|
|
85
|
+
const response = await fetchImpl(`https://api.github.com/repos/${repo.github}`, githubRequest(token))
|
|
86
|
+
if (!response.ok) return
|
|
87
|
+
const body = await response.json() as RepositoryPayload | null
|
|
88
|
+
if (!signal.aborted && body && repositoryMatches(repo, body)
|
|
89
|
+
&& (token || (body.private === false && body.visibility === 'public'))) grant(repo, body, checkedAt)
|
|
90
|
+
} catch { /* Unverified access must never expose cached metadata. */ }
|
|
91
|
+
}))
|
|
92
|
+
}
|
|
93
|
+
if (updates.size > 0) await db.setGithubRepositoryVisibility([...updates.values()])
|
|
94
|
+
return readable
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
async function verifyPublicRefreshes(config: ManagedConfig, userId: string, repositories: Repository[], context: RepositoryAccessContext): Promise<string | null> {
|
|
98
|
+
// Cached public metadata needs no credentials. New content uses a viewer
|
|
99
|
+
// token only after a live check, so privatization cannot publish private data
|
|
100
|
+
// under an old public grant. Anonymous reads remain available without a token.
|
|
101
|
+
const { db, publicRepos } = context
|
|
102
|
+
const token = context.token ?? await ensureUserAccessToken(config, db, userId, Date.now(), context.fetchImpl)
|
|
103
|
+
if (token) {
|
|
104
|
+
const currentPublic = new Set<string>()
|
|
105
|
+
const readable = await readableRepositories(repositories, { ...context, publicRepos: currentPublic, token, includePrivateList: false })
|
|
106
|
+
for (const repo of repositories) if (readable.has(repo.github) && !currentPublic.has(repo.github)) publicRepos.delete(repo.github)
|
|
107
|
+
}
|
|
108
|
+
return token
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// ref.repo is always the canonical name from managed_selected_repo, never an
|
|
112
|
+
// owner/repo/path taken from a Fix URL. Redirects cannot move the user token.
|
|
113
|
+
async function fetchMetadata(ref: GithubFixRef, token: string | null, fetchImpl: typeof fetch): Promise<Metadata | null> {
|
|
114
|
+
try {
|
|
115
|
+
const response = await fetchImpl(`https://api.github.com/repos/${ref.repo}/${ref.kind === 'pull' ? 'pulls' : 'issues'}/${ref.number}`, githubRequest(token))
|
|
116
|
+
if (!response.ok) return null
|
|
117
|
+
const body = await response.json() as { number?: unknown; title?: unknown; body?: unknown; state?: unknown; merged?: unknown;
|
|
118
|
+
draft?: unknown; base?: { repo?: { full_name?: unknown } }; repository_url?: unknown; pull_request?: unknown; state_reason?: unknown } | null
|
|
119
|
+
if (body?.number !== ref.number || typeof body.title !== 'string' || !body.title.trim() || body.title.length > 1024
|
|
120
|
+
|| !['open', 'closed'].includes(String(body.state)) || (body.body != null && typeof body.body !== 'string')) return null
|
|
121
|
+
let status: GithubFixStatus
|
|
122
|
+
if (ref.kind === 'pull') {
|
|
123
|
+
if (typeof body.merged !== 'boolean' || typeof body.base?.repo?.full_name !== 'string'
|
|
124
|
+
|| body.base.repo.full_name.toLowerCase() !== ref.repo.toLowerCase()) return null
|
|
125
|
+
status = body.merged ? 'merged' : body.state === 'closed' ? 'closed' : body.draft === true ? 'draft' : 'open'
|
|
126
|
+
} else {
|
|
127
|
+
// The issues API also accepts PR numbers. Do not cache a PR as a closed
|
|
128
|
+
// ordinary issue: only the pulls API can establish its merged state.
|
|
129
|
+
if (body.pull_request != null || typeof body.repository_url !== 'string'
|
|
130
|
+
|| body.repository_url.toLowerCase() !== `https://api.github.com/repos/${ref.repo}`.toLowerCase()) return null
|
|
131
|
+
status = body.state === 'closed' ? 'closed' : 'open'
|
|
132
|
+
}
|
|
133
|
+
const stateReason = ref.kind === 'issue' && status === 'closed' ? githubIssueClosedReason(body.state_reason) : null
|
|
134
|
+
return { title: body.title, description: body.body ?? null, status, stateReason }
|
|
135
|
+
} catch { return null }
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
// What a load reads of its `entries`, by what is cached of them at `now`:
|
|
139
|
+
// those missing or stale, the least recently checked first, as many as
|
|
140
|
+
// MAX_GITHUB_LOOKUPS. Closed items are kept once fetched, but GitHub can
|
|
141
|
+
// reopen them (merged ones are final): a load reading open or unknown items
|
|
142
|
+
// anew also rechecks a tenth as many closed ones, the least recently checked
|
|
143
|
+
// first, after them. None where every item is closed or fresh, and a busy
|
|
144
|
+
// workspace cycles through its closed items, a recheck rotating its item
|
|
145
|
+
// behind the others whether or not GitHub answers.
|
|
146
|
+
function readsOf<Entry extends [string, GithubFixRef]>(entries: Entry[], metadata: Map<string, GithubMetadata>, now: number): Entry[] {
|
|
147
|
+
const lastCheckedAt = ([key]: Entry) => Math.max(metadata.get(key)?.fetchedAt ?? 0, metadata.get(key)?.attemptedAt ?? 0)
|
|
148
|
+
const oldestFirst = (a: Entry, b: Entry) => lastCheckedAt(a) - lastCheckedAt(b)
|
|
149
|
+
const stale = ([key, ref]: Entry) => {
|
|
150
|
+
const cached = metadata.get(key)
|
|
151
|
+
// Backfill closed issues cached before closure reasons existed, within the
|
|
152
|
+
// same authorized/capped queue. Even an unknown reason completes backfill.
|
|
153
|
+
return !cached || (ref.kind === 'issue' && cached.status === 'closed' && cached.stateReason == null)
|
|
154
|
+
|| (['open', 'draft'].includes(cached.status) && cached.fetchedAt + GITHUB_METADATA_TTL_MS <= now)
|
|
155
|
+
}
|
|
156
|
+
const pending = entries.filter(stale).toSorted(oldestFirst).slice(0, MAX_GITHUB_LOOKUPS)
|
|
157
|
+
// Stale ones are missing, open, draft, or closed issues awaiting backfill.
|
|
158
|
+
const reread = pending.filter(([key]) => metadata.get(key)?.status !== 'closed').length
|
|
159
|
+
const rechecks = entries.filter(entry => metadata.get(entry[0])?.status === 'closed' && !stale(entry))
|
|
160
|
+
.toSorted(oldestFirst).slice(0, Math.ceil(reread / CLOSED_RECHECK_EVERY))
|
|
161
|
+
return [...pending, ...rechecks]
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
// The workspace handler checks user -> team membership and finding visibility.
|
|
165
|
+
// Shared private metadata also requires this viewer's live GitHub access,
|
|
166
|
+
// including for admins. Only recently verified public repos skip that check.
|
|
167
|
+
export async function lookupFixes(config: ManagedConfig, db: ManagedDb, snapshot: TeamReportAccessSnapshot, urls: string[], fetchImpl: typeof fetch = globalThis.fetch): Promise<GithubFixResult[]> {
|
|
168
|
+
const allowed = new Map(snapshot.repositories.filter(repo => isGithubRepoName(repo.github)).map(repo => [repo.github.toLowerCase(), repo]))
|
|
169
|
+
const parsed = urls.map(parseGithubFixUrl)
|
|
170
|
+
const jobs = new Map<string, GithubFixRef>()
|
|
171
|
+
const keys = parsed.map(ref => {
|
|
172
|
+
const repo = ref && allowed.get(ref.repo.toLowerCase())
|
|
173
|
+
if (!ref || !repo) return null
|
|
174
|
+
const key = `${repo.repoId}:${ref.kind}:${ref.number}`
|
|
175
|
+
jobs.set(key, { ...ref, repo: repo.github })
|
|
176
|
+
return key
|
|
177
|
+
})
|
|
178
|
+
if (jobs.size === 0) return []
|
|
179
|
+
const now = Date.now()
|
|
180
|
+
const signal = AbortSignal.timeout(GITHUB_LOOKUP_TIMEOUT_MS)
|
|
181
|
+
const fetchWithinDeadline: typeof fetch = (input, init) => {
|
|
182
|
+
signal.throwIfAborted()
|
|
183
|
+
return fetchImpl(input, { ...init, signal })
|
|
184
|
+
}
|
|
185
|
+
const repositories = [...new Map([...jobs.values()].map(ref => {
|
|
186
|
+
const repo = allowed.get(ref.repo.toLowerCase())!
|
|
187
|
+
return [repo.repoId, repo] as const
|
|
188
|
+
})).values()]
|
|
189
|
+
const visibility = await db.listGithubRepositoryVisibility(repositories.map(repo => repo.repoId))
|
|
190
|
+
const byId = new Map(repositories.map(repo => [repo.repoId, repo]))
|
|
191
|
+
const publicRepos = new Set(visibility.filter(entry => entry.public && entry.checkedAt <= now
|
|
192
|
+
&& entry.checkedAt + GITHUB_PUBLIC_VISIBILITY_TTL_MS > now
|
|
193
|
+
&& byId.get(entry.repoId)?.github.toLowerCase() === entry.github.toLowerCase()).map(entry => byId.get(entry.repoId)!.github))
|
|
194
|
+
let token = repositories.some(repo => !publicRepos.has(repo.github))
|
|
195
|
+
? await ensureUserAccessToken(config, db, snapshot.user.id, now, fetchWithinDeadline) : null
|
|
196
|
+
const checks: RepositoryChecks = { remaining: MAX_GITHUB_LOOKUPS, verified: new Set() }
|
|
197
|
+
const context = { db, visibility, publicRepos, token, signal, fetchImpl: fetchWithinDeadline, checks }
|
|
198
|
+
const readable = await readableRepositories(repositories, context)
|
|
199
|
+
const authorized = [...jobs.entries()].filter(([, ref]) => readable.has(ref.repo))
|
|
200
|
+
const metadata = new Map((await db.listGithubMetadata(authorized.map(([key]) => key))).map(entry => [entry.key, entry]))
|
|
201
|
+
const reads = readsOf(authorized, metadata, now)
|
|
202
|
+
// Only stale/missing, distinct, authorized entries consume the request budget.
|
|
203
|
+
// Prioritize missing/oldest entries so a large workspace makes progress.
|
|
204
|
+
if (reads.length > 0) {
|
|
205
|
+
const publicRefreshes = new Set(reads.filter(([, ref]) => publicRepos.has(ref.repo) && !checks.verified.has(ref.repo)).map(([, ref]) => ref.repo))
|
|
206
|
+
if (publicRefreshes.size > 0) token = await verifyPublicRefreshes(config, snapshot.user.id, repositories.filter(repo => publicRefreshes.has(repo.github)), context)
|
|
207
|
+
const fresh: Omit<GithubMetadata, 'attemptedAt'>[] = []
|
|
208
|
+
const attempted: string[] = []
|
|
209
|
+
// All waves and access checks share one deadline and four-call limit.
|
|
210
|
+
for (let i = 0; i < reads.length && !signal.aborted; i += 4) {
|
|
211
|
+
await Promise.all(reads.slice(i, i + 4).map(async ([key, ref]) => {
|
|
212
|
+
if (signal.aborted) return
|
|
213
|
+
if (metadata.has(key)) attempted.push(key)
|
|
214
|
+
const result = await fetchMetadata(ref, publicRepos.has(ref.repo) && !checks.verified.has(ref.repo) ? null : token, fetchWithinDeadline)
|
|
215
|
+
if (result) fresh.push({ key, ...result, fetchedAt: Date.now() })
|
|
216
|
+
}))
|
|
217
|
+
}
|
|
218
|
+
// Only started cached reads rotate. Missing entries retain priority, and
|
|
219
|
+
// jobs skipped by the cap, deadline or absent token keep their place.
|
|
220
|
+
if (attempted.length > 0) await db.recordGithubMetadataAttempts(attempted, Date.now())
|
|
221
|
+
if (fresh.length > 0) {
|
|
222
|
+
await db.setGithubMetadata(fresh)
|
|
223
|
+
// A concurrent merged result must win over a slower open/closed read.
|
|
224
|
+
for (const entry of await db.listGithubMetadata(fresh.map(row => row.key))) metadata.set(entry.key, entry)
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
if (publicRepos.size > 0) {
|
|
228
|
+
// Another request may already have discovered a public -> private change
|
|
229
|
+
// and written new private metadata. Honor that newer visibility observation.
|
|
230
|
+
const current = await db.listGithubRepositoryVisibility(repositories.filter(repo => publicRepos.has(repo.github)).map(repo => repo.repoId))
|
|
231
|
+
const stillPublic = new Set(current.filter(entry => entry.public
|
|
232
|
+
&& byId.get(entry.repoId)?.github.toLowerCase() === entry.github.toLowerCase()).map(entry => byId.get(entry.repoId)!.github))
|
|
233
|
+
for (const [key, ref] of authorized) if (publicRepos.has(ref.repo) && !stillPublic.has(ref.repo)) metadata.delete(key)
|
|
234
|
+
}
|
|
235
|
+
// The handler rechecks workspace access and saved Fix links before returning.
|
|
236
|
+
return urls.flatMap((url, index): GithubFixResult[] => {
|
|
237
|
+
const key = keys[index]
|
|
238
|
+
if (!key) return []
|
|
239
|
+
const found = metadata.get(key)
|
|
240
|
+
return [found ? { url, title: found.title, description: found.description, status: found.status, stateReason: found.stateReason } : { url, error: 'unavailable' }]
|
|
241
|
+
})
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
export function storedFixUrls(fixes: string[]): string[] {
|
|
245
|
+
return [...new Set(fixes.filter(fix => parseGithubFixUrl(fix)))].toSorted()
|
|
246
|
+
}
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto'
|
|
2
|
+
import { GithubApiError, githubUnreachable, throwGithubResponseError } from './github-errors.ts'
|
|
3
|
+
import { timed } from './request-timing.ts'
|
|
4
|
+
|
|
5
|
+
const API_VERSION = '2022-11-28'
|
|
6
|
+
export const USER_AGENT = 'deepview-triage'
|
|
7
|
+
|
|
8
|
+
// Only outstanding reads: a completed answer (or failure) is never reused.
|
|
9
|
+
// Keep transports and credentials separate, including anonymous reads. When
|
|
10
|
+
// full, new reads proceed normally rather than waiting for an unrelated one.
|
|
11
|
+
const MAX_PENDING_READS = 1000
|
|
12
|
+
type PendingRead = { promise: Promise<unknown>; shared: boolean }
|
|
13
|
+
const pendingReads = new WeakMap<typeof fetch, Map<string, PendingRead>>()
|
|
14
|
+
|
|
15
|
+
// Invalidate installation credentials and access verdicts when GitHub rejects
|
|
16
|
+
// a token, including when several callers share the rejected request.
|
|
17
|
+
const rejectedTokenListeners = new Set<(token: string, fetchImpl: typeof fetch) => void>()
|
|
18
|
+
export function onTokenRejected(listener: (token: string, fetchImpl: typeof fetch) => void): void {
|
|
19
|
+
rejectedTokenListeners.add(listener)
|
|
20
|
+
}
|
|
21
|
+
export function tokenRejected(token: string, fetchImpl: typeof fetch): void {
|
|
22
|
+
for (const listener of rejectedTokenListeners) listener(token, fetchImpl)
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export async function shareGithubRead<T>(fetchImpl: typeof fetch, request: string, read: () => Promise<T>): Promise<T> {
|
|
26
|
+
let pending = pendingReads.get(fetchImpl)
|
|
27
|
+
if (!pending) { pending = new Map(); pendingReads.set(fetchImpl, pending) }
|
|
28
|
+
// The request includes credentials and query variables. Retain only its hash.
|
|
29
|
+
const key = createHash('sha256').update(request).digest('hex')
|
|
30
|
+
const held = pending.get(key)
|
|
31
|
+
if (held) {
|
|
32
|
+
held.shared = true
|
|
33
|
+
return structuredClone(await held.promise) as T
|
|
34
|
+
}
|
|
35
|
+
if (pending.size >= MAX_PENDING_READS) return read()
|
|
36
|
+
const entry: PendingRead = { promise: read(), shared: false }
|
|
37
|
+
pending.set(key, entry)
|
|
38
|
+
try {
|
|
39
|
+
const value = await entry.promise
|
|
40
|
+
// Independent objects for coalesced callers, without copying large trees
|
|
41
|
+
// or histories when nobody joined the read.
|
|
42
|
+
return (entry.shared ? structuredClone(value) : value) as T
|
|
43
|
+
} finally { pending.delete(key) }
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// GitHub's answers to GETs that came with an ETag, by the request (its URL
|
|
47
|
+
// and credential, hashed as outstanding reads are; an installation's token,
|
|
48
|
+
// which the App mints anew every few minutes on every instance, as the
|
|
49
|
+
// installations' one credential, GitHub telling apart which may read what):
|
|
50
|
+
// the next asked again If-None-Match, GitHub checking the credential as
|
|
51
|
+
// ever, and a 304, which it doesn't count against the rate limit, answered
|
|
52
|
+
// by the body kept. Each transport's own, as many as MAX_TAGGED_READS and
|
|
53
|
+
// MAX_TAGGED_BYTES hold, the least recently used first to go; none larger
|
|
54
|
+
// than MAX_TAGGED_READ_BYTES. Those one this process doesn't hold, read of
|
|
55
|
+
// the store kept beyond it (keepTaggedReadsIn), as a serverless instance
|
|
56
|
+
// starting anew holds none, as many as fit it (MAX_STORED_READ_BYTES).
|
|
57
|
+
const MAX_TAGGED_READS = 1000
|
|
58
|
+
const MAX_TAGGED_BYTES = 32 * 1024 * 1024
|
|
59
|
+
const MAX_TAGGED_READ_BYTES = 1024 * 1024
|
|
60
|
+
const MAX_STORED_READ_BYTES = 256 * 1024
|
|
61
|
+
export type TaggedRead = { etag: string; text: string }
|
|
62
|
+
const taggedReads = new WeakMap<typeof fetch, { reads: Map<string, TaggedRead>; bytes: number }>()
|
|
63
|
+
const taggedOf = (fetchImpl: typeof fetch) => {
|
|
64
|
+
let tagged = taggedReads.get(fetchImpl)
|
|
65
|
+
if (!tagged) taggedReads.set(fetchImpl, tagged = { reads: new Map(), bytes: 0 })
|
|
66
|
+
return tagged
|
|
67
|
+
}
|
|
68
|
+
const requestKey = (request: string) => createHash('sha256').update(request).digest('hex')
|
|
69
|
+
// A GET's request as its answer is kept by: its URL and credential.
|
|
70
|
+
const taggedRequest = (url: string, token: string | null) => JSON.stringify([url, token?.startsWith('ghs_') ? { installation: true } : token])
|
|
71
|
+
|
|
72
|
+
// Where GitHub's tagged answers are kept beyond this process (http.ts
|
|
73
|
+
// registers the database's), by the request's key; its failures are none
|
|
74
|
+
// kept, or none written.
|
|
75
|
+
export interface TaggedStore { read(key: string): Promise<TaggedRead | null>; write(key: string, read: TaggedRead): Promise<void> }
|
|
76
|
+
let taggedStore: TaggedStore | null = null
|
|
77
|
+
export function keepTaggedReadsIn(store: TaggedStore | null): void { taggedStore = store }
|
|
78
|
+
|
|
79
|
+
// The answer kept to `request`, its ETag and body as GitHub wrote it: as
|
|
80
|
+
// this process holds it, else, where a store is kept beyond it, as that
|
|
81
|
+
// keeps it.
|
|
82
|
+
export function taggedRead(fetchImpl: typeof fetch, request: string): TaggedRead | undefined | Promise<TaggedRead | undefined> {
|
|
83
|
+
const { reads } = taggedOf(fetchImpl)
|
|
84
|
+
const key = requestKey(request)
|
|
85
|
+
const read = reads.get(key)
|
|
86
|
+
if (read) { reads.delete(key); reads.set(key, read); return read }
|
|
87
|
+
return taggedStore ? storedTaggedRead(fetchImpl, key, taggedStore) : undefined
|
|
88
|
+
}
|
|
89
|
+
async function storedTaggedRead(fetchImpl: typeof fetch, key: string, store: TaggedStore) {
|
|
90
|
+
const stored = await store.read(key).catch(() => null)
|
|
91
|
+
if (!stored || typeof stored.etag !== 'string' || typeof stored.text !== 'string') return undefined
|
|
92
|
+
holdTaggedRead(fetchImpl, key, stored)
|
|
93
|
+
return stored
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// `text` kept as GitHub's answer to `request`, by its ETag.
|
|
97
|
+
export async function keepTaggedRead(fetchImpl: typeof fetch, request: string, etag: string, text: string): Promise<void> {
|
|
98
|
+
const key = requestKey(request)
|
|
99
|
+
holdTaggedRead(fetchImpl, key, { etag, text })
|
|
100
|
+
if (text.length <= MAX_STORED_READ_BYTES) await taggedStore?.write(key, { etag, text }).catch(() => {})
|
|
101
|
+
}
|
|
102
|
+
function holdTaggedRead(fetchImpl: typeof fetch, key: string, read: TaggedRead) {
|
|
103
|
+
const tagged = taggedOf(fetchImpl)
|
|
104
|
+
const before = tagged.reads.get(key)
|
|
105
|
+
if (before) { tagged.reads.delete(key); tagged.bytes -= before.text.length }
|
|
106
|
+
if (read.text.length > MAX_TAGGED_READ_BYTES) return
|
|
107
|
+
tagged.reads.set(key, read)
|
|
108
|
+
tagged.bytes += read.text.length
|
|
109
|
+
for (const [oldest, held] of tagged.reads) {
|
|
110
|
+
if (tagged.reads.size <= MAX_TAGGED_READS && tagged.bytes <= MAX_TAGGED_BYTES) break
|
|
111
|
+
tagged.reads.delete(oldest)
|
|
112
|
+
tagged.bytes -= held.text.length
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// One GitHub API call returning parsed JSON, optionally Bearer-authed by a
|
|
117
|
+
// user token, App JWT, or installation token, `body` sent as JSON (a GraphQL
|
|
118
|
+
// query's, given longer to answer). Network / non-2xx / malformed fold into a
|
|
119
|
+
// GithubApiError (401 passes through for the caller to handle). Identical GETs
|
|
120
|
+
// share an outstanding read through its body; one GitHub answered with an
|
|
121
|
+
// ETag is asked again If-None-Match, its body kept answering a 304
|
|
122
|
+
// (taggedRead). POSTs only opt in for read-only GraphQL
|
|
123
|
+
// queries (repository-history.ts), never for mutations or token mints.
|
|
124
|
+
export function githubJson(url: string, token: string | null, fetchImpl: typeof fetch, method: 'GET' | 'POST' = 'GET', body?: unknown,
|
|
125
|
+
readOnly = method === 'GET'): Promise<unknown> {
|
|
126
|
+
if (readOnly) return shareGithubRead(fetchImpl, JSON.stringify([url, token, method, body]), () => githubJson(url, token, fetchImpl, method, body, false))
|
|
127
|
+
const request = method === 'GET' && body === undefined ? taggedRequest(url, token) : null
|
|
128
|
+
// Each call told in its request's Server-Timing (request-timing.ts).
|
|
129
|
+
return timed('gh', async () => {
|
|
130
|
+
const held = request === null ? undefined : taggedRead(fetchImpl, request)
|
|
131
|
+
const tagged = held instanceof Promise ? await held : held
|
|
132
|
+
let res: Response
|
|
133
|
+
const started = Date.now()
|
|
134
|
+
try {
|
|
135
|
+
res = await fetchImpl(url, {
|
|
136
|
+
method,
|
|
137
|
+
signal: AbortSignal.timeout(body === undefined ? 10_000 : 20_000),
|
|
138
|
+
redirect: 'error',
|
|
139
|
+
headers: {
|
|
140
|
+
...(token == null ? {} : { authorization: `Bearer ${token}` }), 'accept': 'application/vnd.github+json',
|
|
141
|
+
...(body === undefined ? {} : { 'content-type': 'application/json' }), 'user-agent': USER_AGENT, 'x-github-api-version': API_VERSION,
|
|
142
|
+
...(tagged ? { 'if-none-match': tagged.etag } : {}),
|
|
143
|
+
},
|
|
144
|
+
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
|
145
|
+
})
|
|
146
|
+
} catch (error) { throw githubUnreachable(error, started) }
|
|
147
|
+
if (res.status === 401 && token) tokenRejected(token, fetchImpl)
|
|
148
|
+
if (res.status === 304 && tagged) return JSON.parse(tagged.text) as unknown
|
|
149
|
+
if (!res.ok) await throwGithubResponseError(res)
|
|
150
|
+
// The answer's body is read within the same timeout: one not read whole is
|
|
151
|
+
// GitHub not reached, as one not answered is; only one that isn't JSON is
|
|
152
|
+
// malformed.
|
|
153
|
+
// Kept only whole: never a 202's, GitHub still working out its answer.
|
|
154
|
+
const etag = request === null || res.status !== 200 ? null : res.headers?.get('etag') ?? null
|
|
155
|
+
let text: string | null = null, value: unknown
|
|
156
|
+
try {
|
|
157
|
+
if (etag === null) return await res.json()
|
|
158
|
+
text = await res.text()
|
|
159
|
+
value = JSON.parse(text)
|
|
160
|
+
} catch (error) {
|
|
161
|
+
throw error instanceof SyntaxError ? new GithubApiError(502, 'github-malformed') : githubUnreachable(error, started)
|
|
162
|
+
}
|
|
163
|
+
await keepTaggedRead(fetchImpl, request!, etag, text)
|
|
164
|
+
return value
|
|
165
|
+
})
|
|
166
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
// The app's users and agents where a repository's activity names their
|
|
2
|
+
// GitHub accounts (GET /api/admin/repositories/history, issues, item, agents
|
|
3
|
+
// and pulse): of the accounts an answer names (common/managed/github-logins.ts),
|
|
4
|
+
// the agents' (common/managed/github-agents.ts), and those an approved user
|
|
5
|
+
// signs in with or linked to theirs (github-links.ts), each as that user
|
|
6
|
+
// shows in the app, linked accounts as their user; each by its numeric id
|
|
7
|
+
// where the answer names it, else by its login. Resolved as each answer is
|
|
8
|
+
// sent, never kept with it, and only for the accounts it names: a reader is
|
|
9
|
+
// never sent a list of users.
|
|
10
|
+
import { type GithubAgentId, githubAgent } from '../common/managed/github-agents.ts'
|
|
11
|
+
import { namedAccounts } from '../common/managed/github-logins.ts'
|
|
12
|
+
import type { ManagedDb } from './db.ts'
|
|
13
|
+
import type { AppUser } from './github-links.ts'
|
|
14
|
+
|
|
15
|
+
// An agent, as the app draws it (GITHUB_AGENTS).
|
|
16
|
+
export interface AppAgentUser { agent: GithubAgentId }
|
|
17
|
+
|
|
18
|
+
// `answer` with the app's users and agents its accounts are (`users`, by
|
|
19
|
+
// login), as a new object: what was kept of it, every reader's, is left as
|
|
20
|
+
// it was. A login it names by more than one account is no one's.
|
|
21
|
+
export async function withAppUsers<T extends object>(db: ManagedDb, answer: T): Promise<T & { users: Record<string, AppUser | AppAgentUser> }> {
|
|
22
|
+
const agents: Record<string, AppAgentUser> = {}
|
|
23
|
+
const accounts = [...namedAccounts(answer)].flatMap(([login, githubId]) => {
|
|
24
|
+
if (githubId === 'ambiguous') return []
|
|
25
|
+
const agent = githubAgent(login, githubId)
|
|
26
|
+
if (agent) agents[login] = { agent }
|
|
27
|
+
return agent ? [] : [{ login, githubId }]
|
|
28
|
+
})
|
|
29
|
+
return { ...answer, users: { ...await db.listUsersByAccount(accounts), ...agents } }
|
|
30
|
+
}
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
// A default branch's history read by when its commits were made, for the
|
|
2
|
+
// Pulse (repository-pulse.ts yearCommits): where the pages kept from a head
|
|
3
|
+
// run out, the rest of the time it needs read at once, in windows of time
|
|
4
|
+
// (GitHub's `history(since:, until:)`), not a page after another, each page
|
|
5
|
+
// waiting on the last; and the pages GitHub would list from the commits read
|
|
6
|
+
// (git log) kept by their tops, as reading a page at a time keeps them, so a
|
|
7
|
+
// walk later, from a head moved on or in the Commits tab, reads them kept.
|
|
8
|
+
import { linkNoreplyUsers } from './github-accounts.ts'
|
|
9
|
+
import { githubGraphql } from './github-graphql.ts'
|
|
10
|
+
import { COMMIT_FRAGMENT, type GraphCommit, HISTORY_PAGE, type HistoryCommit, type HistoryPages, PAGES_PARALLEL, PAGES_PER_QUERY, commitActors, graphCommit,
|
|
11
|
+
inBatches, variablesOf } from './repository-history.ts'
|
|
12
|
+
|
|
13
|
+
// Windows a read is split into at most, each meant to hold as many commits
|
|
14
|
+
// as WINDOW_COMMITS, a page's worth with room to spare, as often as the
|
|
15
|
+
// commits read before it were made, as far back as they reach, the rest left
|
|
16
|
+
// to the next read; pages read of them at most a read, those over going on
|
|
17
|
+
// where a window holds more, as many times as MAX_WAVES, each waiting on the
|
|
18
|
+
// last; and pages kept of what was read at most.
|
|
19
|
+
const MAX_WINDOWS = 40
|
|
20
|
+
const WINDOW_COMMITS = 70
|
|
21
|
+
const WINDOW_PAGES = 50
|
|
22
|
+
const MAX_WAVES = 5
|
|
23
|
+
const MAX_KEPT = 500
|
|
24
|
+
const KEPT_AT_ONCE = 10
|
|
25
|
+
const WINDOWS_AFTER = 2
|
|
26
|
+
const HOUR_MS = 60 * 60_000
|
|
27
|
+
|
|
28
|
+
// Each window's commits from `$head`, `w<n>` the `n`th's: those made since
|
|
29
|
+
// `$s<n>` (none, any time) and until `$u<n>`, after `$a<n>`.
|
|
30
|
+
const windowsQuery = (count: number) => `query($owner: String!, $name: String!, $head: GitObjectID!, ${variablesOf('s', count, 'GitTimestamp')}, ${
|
|
31
|
+
variablesOf('u', count, 'GitTimestamp!')}, ${variablesOf('a', count, 'String')}) {
|
|
32
|
+
repository(owner: $owner, name: $name) {
|
|
33
|
+
object(oid: $head) { ... on Commit {
|
|
34
|
+
${Array.from({ length: count }, (_, at) => `w${at}: history(first: ${HISTORY_PAGE}, since: $s${at}, until: $u${at}, after: $a${at}) {
|
|
35
|
+
pageInfo { hasNextPage endCursor } nodes { ...historyCommit } }`).join('\n ')}
|
|
36
|
+
} }
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
${COMMIT_FRAGMENT}`
|
|
40
|
+
|
|
41
|
+
type Window = { since: number | null; until: number; after: string | null; oldest?: number }
|
|
42
|
+
type WindowPage = { pageInfo?: { hasNextPage?: unknown; endCursor?: unknown }; nodes?: GraphCommit[] } | null
|
|
43
|
+
type Windows = { repository?: { object?: Record<string, WindowPage> | null } | null } | null
|
|
44
|
+
// A time as GitHub takes it, to the second: a window's start rounded down,
|
|
45
|
+
// its end up, so that those beside each other overlap rather than part.
|
|
46
|
+
const stamp = (at: number, up: boolean) => new Date((up ? Math.ceil : Math.floor)(at / 1000) * 1000).toISOString()
|
|
47
|
+
|
|
48
|
+
// The commits from `head` made from `low` to `high`, as often as `perMs` (commits
|
|
49
|
+
// a millisecond) says they are made, as many windows as MAX_WINDOWS reach
|
|
50
|
+
// down from `high`, read at once (inBatches), the latest first, each paged on
|
|
51
|
+
// as far as it goes, as many pages as WINDOW_PAGES; and, those reaching
|
|
52
|
+
// `low`, a page of those made before it besides, where a walk reading them
|
|
53
|
+
// goes on from. Since when every one is read (`through`: where the windows
|
|
54
|
+
// reach, each read whole, else, of the latest not, just after the earliest
|
|
55
|
+
// made of those it read, as GitHub lists them the latest made first, those
|
|
56
|
+
// made together left out; or its end, none read), and how many pages were
|
|
57
|
+
// read (`read`).
|
|
58
|
+
export async function readWindows(fullName: string, token: string, head: string, low: number, high: number, perMs: number, fetchImpl: typeof fetch) {
|
|
59
|
+
const [owner, name] = fullName.split('/') as [string, string]
|
|
60
|
+
const bottom = Math.max(low, high - MAX_WINDOWS * WINDOW_COMMITS / perMs)
|
|
61
|
+
const count = Math.min(MAX_WINDOWS, Math.max(1, Math.ceil((high - bottom) * perMs / WINDOW_COMMITS)))
|
|
62
|
+
const width = (high - bottom) / count
|
|
63
|
+
let open: Window[] = [...Array.from({ length: count }, (_, at) => ({ since: high - (at + 1) * width, until: high - at * width, after: null })),
|
|
64
|
+
...bottom > low ? [] : [{ since: null, until: low - 1000, after: null }]]
|
|
65
|
+
const commits = new Map<string, HistoryCommit>()
|
|
66
|
+
let [read, waves] = [0, 0]
|
|
67
|
+
while (open.length > 0 && read < WINDOW_PAGES && waves++ < MAX_WAVES) {
|
|
68
|
+
const wave = open.slice(0, WINDOW_PAGES - read)
|
|
69
|
+
const next: Window[] = []
|
|
70
|
+
read += wave.length
|
|
71
|
+
await inBatches(wave, PAGES_PER_QUERY, PAGES_PARALLEL, async batch => {
|
|
72
|
+
const data = await githubGraphql(windowsQuery(batch.length), { owner, name, head, ...Object.fromEntries(batch.flatMap((window, at) => [
|
|
73
|
+
[`s${at}`, window.since === null ? null : stamp(window.since, false)], [`u${at}`, stamp(window.until, true)], [`a${at}`, window.after]])) }, token, fetchImpl) as Windows
|
|
74
|
+
const pages = batch.map((_, at) => data?.repository?.object?.[`w${at}`] ?? null)
|
|
75
|
+
await linkNoreplyUsers(pages.flatMap(page => page?.nodes ?? []).flatMap(commitActors), token, fetchImpl)
|
|
76
|
+
for (const [at, window] of batch.entries()) {
|
|
77
|
+
let oldest = window.oldest ?? Number.POSITIVE_INFINITY
|
|
78
|
+
for (const commit of (pages[at]?.nodes ?? []).flatMap(node => graphCommit(node) ?? [])) {
|
|
79
|
+
if (!commits.has(commit.sha)) commits.set(commit.sha, commit)
|
|
80
|
+
oldest = Math.min(oldest, commit.committedAt ?? Number.POSITIVE_INFINITY)
|
|
81
|
+
}
|
|
82
|
+
const info = pages[at]?.pageInfo
|
|
83
|
+
if (window.since !== null && info?.hasNextPage === true && typeof info.endCursor === 'string') next.push({ ...window, after: info.endCursor, oldest })
|
|
84
|
+
}
|
|
85
|
+
})
|
|
86
|
+
open = [...next, ...open.slice(wave.length)]
|
|
87
|
+
}
|
|
88
|
+
const through = Math.max(bottom, ...open.flatMap(window => window.since === null ? [] : [Number.isFinite(window.oldest) ? window.oldest! + 1 : window.until]))
|
|
89
|
+
return { commits: [...commits.values()], through, read }
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// The page GitHub would list from `top` (git log: of those reached, the
|
|
93
|
+
// latest made first, of those made together the first reached) of `known`
|
|
94
|
+
// commits, every one made since `low` known; none where it would list one not
|
|
95
|
+
// known, or one made before `low` while one not known waits beside it.
|
|
96
|
+
export function gitLogPage(top: string, known: Map<string, HistoryCommit>, low: number): HistoryCommit[] | null {
|
|
97
|
+
if (!known.has(top)) return null
|
|
98
|
+
const page: HistoryCommit[] = []
|
|
99
|
+
const reached = new Set<string>()
|
|
100
|
+
const waiting: HistoryCommit[] = []
|
|
101
|
+
let unknown = 0
|
|
102
|
+
const reach = (sha: string) => {
|
|
103
|
+
if (reached.has(sha)) return
|
|
104
|
+
reached.add(sha)
|
|
105
|
+
const commit = known.get(sha)
|
|
106
|
+
if (!commit || commit.committedAt === null) { unknown++; return }
|
|
107
|
+
const at = waiting.findIndex(other => other.committedAt! < commit.committedAt!)
|
|
108
|
+
waiting.splice(at < 0 ? waiting.length : at, 0, commit)
|
|
109
|
+
}
|
|
110
|
+
reach(top)
|
|
111
|
+
while (page.length < HISTORY_PAGE && waiting.length > 0) {
|
|
112
|
+
const commit = waiting.shift()!
|
|
113
|
+
if (commit.committedAt! < low && unknown > 0) return null
|
|
114
|
+
page.push(commit)
|
|
115
|
+
for (const parent of commit.parents) reach(parent)
|
|
116
|
+
}
|
|
117
|
+
return page.length < HISTORY_PAGE && unknown > 0 ? null : page
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// The pages from each of `tops` GitHub would list of `known` commits
|
|
121
|
+
// (gitLogPage), kept by their tops, KEPT_AT_ONCE at a time, and from the
|
|
122
|
+
// parents of those they list that none of `listed` is nor any kept lists, on
|
|
123
|
+
// till none is left, as many as MAX_KEPT: as a walk reading pages goes on to
|
|
124
|
+
// them.
|
|
125
|
+
export async function keepPages(tops: string[], known: Map<string, HistoryCommit>, listed: Set<string>, low: number, pages: HistoryPages) {
|
|
126
|
+
const covered = new Set(listed)
|
|
127
|
+
const kept: [string, HistoryCommit[]][] = []
|
|
128
|
+
const waiting = [...tops]
|
|
129
|
+
while (waiting.length > 0 && kept.length < MAX_KEPT) {
|
|
130
|
+
const top = waiting.shift()!
|
|
131
|
+
if (covered.has(top)) continue
|
|
132
|
+
const page = gitLogPage(top, known, low)
|
|
133
|
+
if (!page) continue
|
|
134
|
+
kept.push([top, page])
|
|
135
|
+
for (const commit of page) covered.add(commit.sha)
|
|
136
|
+
for (const commit of page) for (const parent of commit.parents) if (!covered.has(parent) && known.has(parent)) waiting.push(parent)
|
|
137
|
+
}
|
|
138
|
+
for (let at = 0; at < kept.length; at += KEPT_AT_ONCE) await Promise.all(kept.slice(at, at + KEPT_AT_ONCE).map(([top, page]) => pages.write(top, page)))
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
// What a walk from `head` (yearCommits) reads next of `starts`: those a page
|
|
142
|
+
// is kept from (`batch`), where any is, or all of them, a page at a time, as
|
|
143
|
+
// long as it has read GitHub fewer times than WINDOWS_AFTER (`queries`), a
|
|
144
|
+
// head moved on soon reaching the pages kept from where it was; else, none
|
|
145
|
+
// kept, those made from
|
|
146
|
+
// `low` to `high` read at once (readWindows), as often as those `found`
|
|
147
|
+
// were made, told it (`found`), and the pages from `starts` on kept of them,
|
|
148
|
+
// as far down as every one is read (keepPages), the queries that took
|
|
149
|
+
// (`queries`, PAGES_PER_QUERY pages each, as many at once as PAGES_PARALLEL
|
|
150
|
+
// a query of its) and none to read (`windowed`); where the windows can't be
|
|
151
|
+
// read, all of them, a page at a time (`windowed` all the same).
|
|
152
|
+
export async function windowsOn(fullName: string, token: string, head: string, starts: string[], found: Map<string, HistoryCommit>, low: number, high: number,
|
|
153
|
+
pages: HistoryPages, fetchImpl: typeof fetch, queries: number): Promise<{ batch: string[]; queries: number; windowed: boolean }> {
|
|
154
|
+
const kept = await pages.read(starts)
|
|
155
|
+
if (kept.size > 0 || queries < WINDOWS_AFTER || !(high > low) || !Number.isFinite(high)) {
|
|
156
|
+
return { batch: kept.size > 0 ? starts.filter(sha => kept.has(sha)) : starts, queries: 0, windowed: false }
|
|
157
|
+
}
|
|
158
|
+
let [newest, oldest, dated] = [Number.NEGATIVE_INFINITY, Number.POSITIVE_INFINITY, 0]
|
|
159
|
+
for (const { committedAt } of found.values()) {
|
|
160
|
+
if (committedAt === null) continue
|
|
161
|
+
[newest, oldest, dated] = [Math.max(newest, committedAt), Math.min(oldest, committedAt), dated + 1]
|
|
162
|
+
}
|
|
163
|
+
// From the one commit the walk goes on from, where there is one, none of
|
|
164
|
+
// those read listed again; else from the head.
|
|
165
|
+
const read = await readWindows(fullName, token, starts.length === 1 ? starts[0]! : head, low, high, dated / Math.max(newest - oldest, HOUR_MS), fetchImpl)
|
|
166
|
+
.catch((err: unknown) => { console.warn('managed: history windows read failed:', err); return null })
|
|
167
|
+
if (!read) return { batch: starts, queries: 0, windowed: true }
|
|
168
|
+
const listed = new Set(found.keys())
|
|
169
|
+
for (const commit of read.commits) if (!found.has(commit.sha)) found.set(commit.sha, commit)
|
|
170
|
+
await keepPages(starts, found, listed, read.through, pages)
|
|
171
|
+
return { batch: [], queries: Math.ceil(read.read / (PAGES_PER_QUERY * PAGES_PARALLEL)), windowed: true }
|
|
172
|
+
}
|