@preventive/triage 1.0.0-alpha.6 → 1.0.0-alpha.61
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 +36 -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 +43 -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-2XUEZHIP.js +28 -0
- package/out/chunk-4EMM6UCD.js +1 -0
- package/out/chunk-4ISO5F7Y.js +7 -0
- package/out/chunk-4XIH7YTX.js +1 -0
- package/out/chunk-6CCSTJWB.js +1 -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-B3FNMHOE.js +1 -0
- package/out/chunk-BNH52UHC.js +2 -0
- package/out/chunk-BRO77PQY.js +42 -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-G3LY2FV4.js +1 -0
- package/out/chunk-GO7FT4OD.js +1 -0
- package/out/chunk-GRGIZOTP.js +4 -0
- package/out/chunk-HAZKDK4M.js +4 -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-JJK5OZG2.js +15 -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-OFZYEWBH.js +244 -0
- package/out/chunk-OIERSXON.js +1 -0
- package/out/chunk-OOJM4CTU.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-QCOGVL37.js +52 -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-UCP3JRE2.js +1 -0
- package/out/chunk-VFWMQ3LG.js +2 -0
- package/out/chunk-VRX2APNA.js +9 -0
- package/out/chunk-W3QFV4SP.js +3 -0
- package/out/chunk-W6VOKW2N.js +12 -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-Z667U2UJ.js +1 -0
- package/out/chunk-ZQHLECTI.js +1 -0
- package/out/chunk-ZQNEWVGG.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 +40 -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 +383 -63
- 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 +238 -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 +26 -0
- package/server-managed/brotli.ts +10 -0
- package/server-managed/bundle-advisories.ts +103 -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 +238 -0
- package/server-managed/bundle-build.ts +240 -0
- package/server-managed/bundle-cache.ts +199 -0
- package/server-managed/bundle-catalog.ts +29 -0
- package/server-managed/bundle-commits.ts +133 -0
- package/server-managed/bundle-dependency-reviews.ts +68 -0
- package/server-managed/bundle-store.ts +24 -0
- package/server-managed/bundle-summary-cache.ts +139 -0
- package/server-managed/bundle-validation.ts +33 -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 +43 -0
- package/server-managed/comments.ts +138 -0
- package/server-managed/commit-coauthors.ts +105 -0
- package/server-managed/commit-lockfiles.ts +77 -0
- package/server-managed/comparison.ts +50 -0
- package/server-managed/config.ts +163 -0
- package/server-managed/content-access.ts +15 -0
- package/server-managed/crypto.ts +25 -0
- package/server-managed/db-methods.ts +1877 -0
- package/server-managed/db-neon.ts +388 -0
- package/server-managed/db-schema.ts +253 -0
- package/server-managed/db-table-names.ts +22 -0
- package/server-managed/db.ts +146 -0
- package/server-managed/dependabot-access.ts +61 -0
- package/server-managed/dependabot-alerts.ts +180 -0
- package/server-managed/dependency-review-comments.ts +92 -0
- package/server-managed/dependency-reviews.ts +363 -0
- package/server-managed/github-accounts.ts +59 -0
- package/server-managed/github-actions.ts +71 -0
- package/server-managed/github-app.ts +347 -0
- package/server-managed/github-errors.ts +70 -0
- package/server-managed/github-graphql.ts +42 -0
- package/server-managed/github-issue-links.ts +264 -0
- package/server-managed/github-issue-oauth.ts +30 -0
- package/server-managed/github-issues.ts +157 -0
- package/server-managed/github-link-oauth.ts +56 -0
- package/server-managed/github-links.ts +204 -0
- package/server-managed/github-metadata.ts +213 -0
- package/server-managed/github-oauth.ts +264 -0
- package/server-managed/github-pulls.ts +257 -0
- package/server-managed/github-requests.ts +179 -0
- package/server-managed/github-users.ts +30 -0
- package/server-managed/github-values.ts +26 -0
- package/server-managed/history-windows.ts +172 -0
- package/server-managed/http-response.ts +76 -0
- package/server-managed/http.ts +5796 -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 +149 -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 +110 -0
- package/server-managed/npm-delta-worker.js +23 -0
- package/server-managed/npm-delta.ts +159 -0
- package/server-managed/npm-insights.ts +455 -0
- package/server-managed/npm-kept.ts +234 -0
- package/server-managed/npm-loads.ts +259 -0
- package/server-managed/npm-manifest.ts +117 -0
- package/server-managed/npm-packages.ts +462 -0
- package/server-managed/npm-patch.ts +317 -0
- package/server-managed/npm-provenance.ts +127 -0
- package/server-managed/npm-risk.ts +287 -0
- package/server-managed/object-storage-disk.ts +147 -0
- package/server-managed/object-storage-vercel.ts +71 -0
- package/server-managed/object-storage.ts +82 -0
- package/server-managed/package-entry-points.ts +79 -0
- package/server-managed/pretty-print.ts +425 -0
- package/server-managed/public-workspace.ts +242 -0
- package/server-managed/pull-comment-reviews.ts +161 -0
- package/server-managed/pull-dependencies.ts +340 -0
- package/server-managed/pull-dependency-reviews.ts +327 -0
- package/server-managed/pull-reviews.ts +202 -0
- package/server-managed/queue.ts +53 -0
- package/server-managed/release-commits.ts +85 -0
- package/server-managed/rename-diff-worker.js +26 -0
- package/server-managed/rename-diff.ts +236 -0
- package/server-managed/repo-path.ts +21 -0
- package/server-managed/report-migration.ts +32 -0
- package/server-managed/report-query.ts +10 -0
- package/server-managed/report-response.ts +16 -0
- package/server-managed/report-sources.ts +181 -0
- package/server-managed/report-store.ts +77 -0
- package/server-managed/repository-actions.ts +220 -0
- package/server-managed/repository-agents.ts +422 -0
- package/server-managed/repository-aliases.ts +85 -0
- package/server-managed/repository-browser.ts +303 -0
- package/server-managed/repository-changes.ts +280 -0
- package/server-managed/repository-code.ts +215 -0
- package/server-managed/repository-dependency-reviews.ts +159 -0
- package/server-managed/repository-discovery.ts +83 -0
- package/server-managed/repository-history.ts +428 -0
- package/server-managed/repository-issues.ts +224 -0
- package/server-managed/repository-policy.ts +27 -0
- package/server-managed/repository-pulls.ts +207 -0
- package/server-managed/repository-pulse.ts +477 -0
- package/server-managed/repository-risk-assess.ts +108 -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 +483 -0
- package/server-managed/repository-squashes.ts +160 -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 +107 -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 +288 -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 +154 -0
- package/server-managed/team-catalog.ts +7 -0
- package/server-managed/team-feed.ts +180 -0
- package/server-managed/team-npm-scopes.ts +103 -0
- package/server-managed/team-reports.ts +351 -0
- package/server-managed/triage-response.ts +16 -0
- package/server-managed/type-only-proof.js +108 -0
- package/server-managed/type-only-worker.js +31 -0
- package/server-managed/type-only.ts +115 -0
- package/server-managed/uploads.ts +106 -0
- package/server-managed/upstream-cache.ts +250 -0
- package/server-managed/view-as.ts +58 -0
- package/server-managed/worker-turns.ts +76 -0
- package/server-managed/workspace-shares.ts +170 -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,240 @@
|
|
|
1
|
+
import { Buffer } from 'node:buffer'
|
|
2
|
+
import { createHash, randomUUID } from 'node:crypto'
|
|
3
|
+
import { totalmem } from 'node:os'
|
|
4
|
+
import { posix } from 'node:path'
|
|
5
|
+
import { Worker } from 'node:worker_threads'
|
|
6
|
+
import { BUNDLE_BUILD_TIMEOUT_MS, type BundleBuildLeaseStore } from './bundle-build-leases.ts'
|
|
7
|
+
import { type BundleBuildDiagnostic, type BundleBuildStage, bundleBuildDiagnostic } from './bundle-build-diagnostics.js'
|
|
8
|
+
import type { BundleBuildConditions } from './db-methods.ts'
|
|
9
|
+
|
|
10
|
+
export class BundleBuildError extends Error {
|
|
11
|
+
status: number
|
|
12
|
+
code: string
|
|
13
|
+
constructor(status: number, code: string) { super(code); this.status = status; this.code = code }
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
interface BundleBuildInput {
|
|
17
|
+
repoId: number
|
|
18
|
+
commit: string
|
|
19
|
+
entries: string[]
|
|
20
|
+
directory: string
|
|
21
|
+
options: { conditions?: string[]; mainFields?: string[]; metro?: boolean; platforms?: string[]; jsx?: boolean; packageManager?: 'soldeer' }
|
|
22
|
+
// What the stored bundle records; null for Solidity, which takes no
|
|
23
|
+
// conditions, and for entries given none, which stasis.config.json must
|
|
24
|
+
// then list (the build checks: bundle-build-worker.js).
|
|
25
|
+
conditions: BundleBuildConditions | null
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function path(value: unknown): value is string {
|
|
29
|
+
return typeof value === 'string' && value.length > 0 && value.length <= 1024 && !/[\\\p{Cc}]/u.test(value)
|
|
30
|
+
&& value.split('/').every(part => part !== '' && part !== '.' && part !== '..')
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const isScript = (entry: string) => /\.[cm]?[tj]sx?$/iu.test(entry)
|
|
34
|
+
|
|
35
|
+
// Whether a build takes `value` as an entry point, with others in its language.
|
|
36
|
+
export function buildableEntry(value: unknown): value is string {
|
|
37
|
+
return path(value) && (isScript(value) || value.endsWith('.sol'))
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function parseBundleBuild(value: unknown): BundleBuildInput {
|
|
41
|
+
const fail = (code = 'bad-request'): never => { throw new BundleBuildError(400, code) }
|
|
42
|
+
if (value == null || typeof value !== 'object' || Array.isArray(value)) return fail()
|
|
43
|
+
const { repoId, commit, entries, conditions } = value as Record<string, unknown>
|
|
44
|
+
if (typeof repoId !== 'number' || !Number.isSafeInteger(repoId) || repoId <= 0
|
|
45
|
+
|| typeof commit !== 'string' || !/^[a-f\d]{40}$/u.test(commit)
|
|
46
|
+
|| !Array.isArray(entries) || entries.length === 0 || entries.length > 100 || !entries.every(path)) return fail()
|
|
47
|
+
const selected = [...new Set(entries as string[])]
|
|
48
|
+
const scripts = selected.every(isScript)
|
|
49
|
+
if (!scripts && !selected.every(entry => entry.endsWith('.sol'))) return fail('unsupported-entries')
|
|
50
|
+
const parts = posix.dirname(selected[0]!).split('/').filter(part => part !== '.')
|
|
51
|
+
for (const entry of selected) {
|
|
52
|
+
const parent = posix.dirname(entry).split('/')
|
|
53
|
+
while (parts.some((part, i) => parent[i] !== part)) parts.pop()
|
|
54
|
+
}
|
|
55
|
+
// Stasis builds Solidity with Soldeer alone. Named, a JS lockfile beside or
|
|
56
|
+
// above the project no longer leaves it unable to tell which one installs it.
|
|
57
|
+
const options: BundleBuildInput['options'] = scripts ? {} : { packageManager: 'soldeer' }
|
|
58
|
+
let recorded: BundleBuildConditions | null = null
|
|
59
|
+
if (scripts && conditions != null) {
|
|
60
|
+
if (typeof conditions !== 'object' || Array.isArray(conditions)) return fail('bad-conditions')
|
|
61
|
+
const { preset, conditions: names, platforms } = conditions as Record<string, unknown>
|
|
62
|
+
if (typeof preset !== 'string' || !['node', 'browser', 'metro'].includes(preset) || !Array.isArray(names) || names.length > 16
|
|
63
|
+
|| !names.every(name => typeof name === 'string' && name.length > 0 && name.length <= 64
|
|
64
|
+
&& !/^\.|^\d+$|[\s,/\\\p{Cc}]/u.test(name) && !['default', 'import', 'require'].includes(name))) return fail('bad-conditions')
|
|
65
|
+
if (preset === 'metro') {
|
|
66
|
+
if (names.length !== 1 || names[0] !== 'react-native') return fail('metro-conditions')
|
|
67
|
+
if (!Array.isArray(platforms) || platforms.length === 0 || platforms.length > 2
|
|
68
|
+
|| !platforms.every(platform => ['ios', 'android'].includes(platform))) return fail('bad-conditions')
|
|
69
|
+
// React Native's convention puts JSX in .js files, which Stasis parses as
|
|
70
|
+
// JSX only on request. TypeScript is left to Stasis to detect.
|
|
71
|
+
Object.assign(options, { metro: true, platforms: [...new Set(platforms)], jsx: true })
|
|
72
|
+
} else {
|
|
73
|
+
options.conditions = [...new Set(names)]
|
|
74
|
+
if (preset === 'browser') options.mainFields = ['browser', 'module', 'main']
|
|
75
|
+
}
|
|
76
|
+
recorded = { preset: preset as BundleBuildConditions['preset'], conditions: [...new Set(names as string[])],
|
|
77
|
+
platforms: options.platforms ?? [] }
|
|
78
|
+
}
|
|
79
|
+
return { repoId, commit, entries: selected, directory: parts.join('/'), options, conditions: recorded }
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// A package name as a filename base: `@scope/name` as `scope-name`, or as
|
|
83
|
+
// `name` alone where it is `scope` or already starts with `scope-`. Null for
|
|
84
|
+
// a name npm could not publish by its length or leading dot.
|
|
85
|
+
function packageBase(name: string): string | null {
|
|
86
|
+
const match = name.length <= 214 ? /^(?:@([^/.][^/]*)\/)?([^/.][^/]*)$/u.exec(name) : null
|
|
87
|
+
if (!match) return null
|
|
88
|
+
const base = match[2]!, scope = match[1]
|
|
89
|
+
return scope === undefined || base === scope || base.startsWith(`${scope}-`) ? base : `${scope}-${base}`
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// Same portable name and 255-character limit as Stasis's githubBundleFile
|
|
93
|
+
// (src/cmd/github-bundle.js), which is not a public package export, except
|
|
94
|
+
// that a usable `packageName` replaces both the repo and the directory.
|
|
95
|
+
export function githubBundleFilename(github: string, directory: string, commit: string, packageName: string | null = null): string {
|
|
96
|
+
const portable = (value: string) => value.replaceAll(/[^\w.-]/gu, '_')
|
|
97
|
+
const tail = `.${portable(commit.slice(0, 7))}.stasis.code.br`
|
|
98
|
+
const named = packageName === null ? null : packageBase(packageName)
|
|
99
|
+
if (named !== null) return `${portable(named)}${tail}`
|
|
100
|
+
const repo = portable(github.replace('/', '-'))
|
|
101
|
+
if (!directory) return `${repo}${tail}`
|
|
102
|
+
const room = 255 - `${repo}.${tail}`.length
|
|
103
|
+
let dir = portable(directory.replaceAll('/', '-'))
|
|
104
|
+
if (dir.length > room) dir = `${dir.slice(0, room - 9)}_${createHash('sha256').update(directory).digest('hex').slice(0, 8)}`
|
|
105
|
+
return `${repo}.${dir}${tail}`
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
interface BuiltBundle { bytes: Buffer; directory: string; filename: string }
|
|
109
|
+
interface BuildRequest {
|
|
110
|
+
input: BundleBuildInput; github: string; token: string | null; maxBytes: number; scopes: (string | null)[]
|
|
111
|
+
// Upstream's disk cache for what a build fetches (setCacheDir), or null for
|
|
112
|
+
// none, as on Vercel. Resolved here: the worker's env holds NPM_TOKEN alone.
|
|
113
|
+
cacheDir: string | null
|
|
114
|
+
}
|
|
115
|
+
// An extra per-process ceiling, one build at a time, its worker given the heap
|
|
116
|
+
// buildHeapLimitMib sizes; admission must also hold the shared DB lease.
|
|
117
|
+
const active = new Set<string>()
|
|
118
|
+
const MAX_ACTIVE_BUILDS = 1
|
|
119
|
+
|
|
120
|
+
// What a build's worker may take of the JS heap, in MiB: the memory the
|
|
121
|
+
// process may use, its container's limit else the machine's, less
|
|
122
|
+
// RESERVED_MIB, at least the 512 MiB a build always had. A large project's
|
|
123
|
+
// tree, as a React Native app's, laid out and scanned in memory, takes more
|
|
124
|
+
// than 2 GiB, as `stasis github-bundle` takes what Node's default heap gives
|
|
125
|
+
// it. What is reserved is the server's, and the worker's own beyond its heap:
|
|
126
|
+
// the bytes of the files it lays out, its bundle's JSON (512 MiB at most, the
|
|
127
|
+
// worker's MAX_SERIALIZED_BYTES) and that compressed. Past it, Node
|
|
128
|
+
// terminates the worker (build-memory), not the process.
|
|
129
|
+
const RESERVED_MIB = 512
|
|
130
|
+
const MIN_BUILD_HEAP_MIB = 512
|
|
131
|
+
const processMemory = () => Math.min(process.constrainedMemory() || Infinity, totalmem())
|
|
132
|
+
export function buildHeapLimitMib(memory = processMemory()): number {
|
|
133
|
+
return Math.max(MIN_BUILD_HEAP_MIB, Math.floor(memory / 1024 ** 2) - RESERVED_MIB)
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
export async function withBundleBuildLease<T>(db: BundleBuildLeaseStore, userId: string, signal: AbortSignal,
|
|
137
|
+
work: (signal: AbortSignal) => Promise<T>): Promise<T> {
|
|
138
|
+
signal.throwIfAborted()
|
|
139
|
+
const owner = randomUUID(), started = performance.now(), timeout = new AbortController()
|
|
140
|
+
const expired = () => timeout.abort(new BundleBuildError(504, 'build-timeout'))
|
|
141
|
+
const timer = setTimeout(expired, BUNDLE_BUILD_TIMEOUT_MS)
|
|
142
|
+
const combined = AbortSignal.any([signal, timeout.signal])
|
|
143
|
+
let claimed = false
|
|
144
|
+
try {
|
|
145
|
+
claimed = await db.claimBundleBuildLease(userId, owner)
|
|
146
|
+
if (!claimed) throw new BundleBuildError(429, 'build-busy')
|
|
147
|
+
// Account for a slow/lost claim response or a suspended invocation before
|
|
148
|
+
// starting work. The three-minute budget starts before lease acquisition.
|
|
149
|
+
if (performance.now() - started >= BUNDLE_BUILD_TIMEOUT_MS) expired()
|
|
150
|
+
combined.throwIfAborted()
|
|
151
|
+
return await work(combined)
|
|
152
|
+
} catch (error) {
|
|
153
|
+
if (timeout.signal.aborted && !signal.aborted) throw timeout.signal.reason
|
|
154
|
+
throw error
|
|
155
|
+
} finally {
|
|
156
|
+
clearTimeout(timer)
|
|
157
|
+
// buildRepositoryBundle waits for worker termination before settling.
|
|
158
|
+
// Unknown claim/release outcomes expire safely without starting more work.
|
|
159
|
+
if (claimed) await db.releaseBundleBuildLease(owner)
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
// Parsing repositories and compressing bundles stays off the HTTP event loop.
|
|
164
|
+
// Cap concurrent builds, terminate disconnected/timed-out work, and share no
|
|
165
|
+
// credentials or mutable Stasis state between requests.
|
|
166
|
+
export async function buildRepositoryBundle(userId: string, request: BuildRequest, signal: AbortSignal): Promise<BuiltBundle> {
|
|
167
|
+
if (active.has(userId) || active.size >= MAX_ACTIVE_BUILDS) throw new BundleBuildError(429, 'build-busy')
|
|
168
|
+
signal.throwIfAborted()
|
|
169
|
+
active.add(userId)
|
|
170
|
+
let worker: Worker | undefined
|
|
171
|
+
let workerUrl: URL | undefined
|
|
172
|
+
let stage: BundleBuildStage = 'worker-start'
|
|
173
|
+
const buildId = randomUUID(), started = performance.now()
|
|
174
|
+
const heapLimitMib = buildHeapLimitMib()
|
|
175
|
+
// How this Node was built, as it decides what a heap holds the same objects in.
|
|
176
|
+
const { v8_enable_pointer_compression: pointerCompression, v8_enable_sandbox: v8Sandbox } = process.config.variables as Record<string, unknown>
|
|
177
|
+
const context = { buildId, repoId: request.input.repoId, github: request.github, commit: request.input.commit,
|
|
178
|
+
directory: request.input.directory, entryCount: request.input.entries.length, node: process.version, v8: process.versions.v8, pointerCompression, v8Sandbox,
|
|
179
|
+
memoryMib: Math.round(processMemory() / 1024 ** 2), heapLimitMib }
|
|
180
|
+
const log = (event: string, details: Record<string, unknown> = {}) => {
|
|
181
|
+
const write = event === 'failed' ? console.error : console.info
|
|
182
|
+
write('managed-bundle-build:', JSON.stringify({ ...context, workerUrl: workerUrl?.href, event, stage, elapsedMs: Math.round(performance.now() - started), ...details }))
|
|
183
|
+
}
|
|
184
|
+
try {
|
|
185
|
+
workerUrl = new URL('./bundle-build-worker.js', import.meta.url)
|
|
186
|
+
log('started')
|
|
187
|
+
// Upstream reads NPM_TOKEN from the env for scoped packages, which npm
|
|
188
|
+
// answers with 404 when private and asked without it. Nothing else passes.
|
|
189
|
+
const npmToken = process.env['NPM_TOKEN']
|
|
190
|
+
const env = npmToken ? { NPM_TOKEN: npmToken } : {}
|
|
191
|
+
worker = new Worker(workerUrl, {
|
|
192
|
+
workerData: { ...request, type: 'managed-bundle-build' }, env, execArgv: [], resourceLimits: { maxOldGenerationSizeMb: heapLimitMib },
|
|
193
|
+
})
|
|
194
|
+
const running = worker
|
|
195
|
+
return await new Promise((resolve, reject) => {
|
|
196
|
+
let settled = false
|
|
197
|
+
const cleanup = () => { clearTimeout(timer); signal.removeEventListener('abort', abort) }
|
|
198
|
+
const fail = (status: number, code: string, details: Record<string, unknown> = {}) => {
|
|
199
|
+
if (settled) return
|
|
200
|
+
settled = true
|
|
201
|
+
cleanup()
|
|
202
|
+
log(code === 'build-cancelled' ? 'cancelled' : 'failed', { code, ...details })
|
|
203
|
+
reject(new BundleBuildError(status, code))
|
|
204
|
+
}
|
|
205
|
+
const timer = setTimeout(() => fail(504, 'build-timeout'), BUNDLE_BUILD_TIMEOUT_MS)
|
|
206
|
+
const abort = () => signal.reason instanceof BundleBuildError ? fail(signal.reason.status, signal.reason.code) : fail(499, 'build-cancelled')
|
|
207
|
+
signal.addEventListener('abort', abort, { once: true })
|
|
208
|
+
// The worker's memory and notes are the log's alone: the response tells
|
|
209
|
+
// the bundle, or the error's code, and nothing of them.
|
|
210
|
+
running.on('message', (message: Omit<BuiltBundle, 'bytes'> & { bytes: Uint8Array; type?: string; stage?: BundleBuildStage; error?: string; status?: number;
|
|
211
|
+
diagnostic?: BundleBuildDiagnostic; memory?: Record<string, number>; event?: string; details?: Record<string, unknown> }) => {
|
|
212
|
+
if (settled) return
|
|
213
|
+
if (message.type === 'progress' && message.stage) { stage = message.stage; log('progress', { memory: message.memory }); return }
|
|
214
|
+
if (message.type === 'memory') { log('memory', { memory: message.memory }); return }
|
|
215
|
+
if (message.type === 'note' && typeof message.event === 'string') { log(message.event, message.details ?? {}); return }
|
|
216
|
+
if (message.error) { fail(message.status ?? 422, message.error, { diagnostic: message.diagnostic, memory: message.memory }); return }
|
|
217
|
+
settled = true
|
|
218
|
+
cleanup()
|
|
219
|
+
log('completed', { byteSize: message.bytes.length })
|
|
220
|
+
// A view of the bytes the worker handed over, not a copy of them.
|
|
221
|
+
const { bytes } = message
|
|
222
|
+
resolve({ bytes: Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength), directory: message.directory, filename: message.filename })
|
|
223
|
+
})
|
|
224
|
+
// Past its heap (heapLimitMib), Node terminates the worker with ERR_WORKER_OUT_OF_MEMORY.
|
|
225
|
+
running.once('error', error => {
|
|
226
|
+
const outOfMemory = (error as { code?: unknown }).code === 'ERR_WORKER_OUT_OF_MEMORY'
|
|
227
|
+
fail(outOfMemory ? 413 : 422, outOfMemory ? 'build-memory' : 'build-failed', { diagnostic: bundleBuildDiagnostic(error, request.token) })
|
|
228
|
+
})
|
|
229
|
+
running.once('exit', exitCode => fail(422, 'build-failed', { exitCode }))
|
|
230
|
+
if (signal.aborted) abort()
|
|
231
|
+
})
|
|
232
|
+
} catch (error) {
|
|
233
|
+
if (!(error instanceof BundleBuildError)) {
|
|
234
|
+
log('failed', { code: 'build-failed', diagnostic: bundleBuildDiagnostic(error, request.token) })
|
|
235
|
+
}
|
|
236
|
+
throw error
|
|
237
|
+
} finally {
|
|
238
|
+
try { await worker?.terminate() } finally { active.delete(userId) }
|
|
239
|
+
}
|
|
240
|
+
}
|
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
// Metadata is cached as Brotli. Contents use the stored Brotli bytes directly:
|
|
2
|
+
// unchanged Stasis uploads or sourcemaps compressed once at upload.
|
|
3
|
+
import { Buffer } from 'node:buffer'
|
|
4
|
+
import { brotliDecompress } from 'node:zlib'
|
|
5
|
+
import { promisify } from 'node:util'
|
|
6
|
+
import { bundleEdges } from '@preventive/sourcemap/edges.js'
|
|
7
|
+
import { BUNDLE_METADATA_VERSION, type BundleDetails, createBundleMetadata, createBundleSummary, parseBundleContents, parseBundleMetadata } from '../common/bundle-metadata.js'
|
|
8
|
+
import { bundleReasons } from '../common/bundle-reasons.js'
|
|
9
|
+
import { sourcemapEdges } from '../common/bundle-sourcemap.js'
|
|
10
|
+
import { type BundleAdvisoryInventory, bundleAdvisoryInventory } from './bundle-advisory-inventory.ts'
|
|
11
|
+
import { decodeUtf8 } from '../common/utf8.js'
|
|
12
|
+
import { type OpenedBlob, readBytes } from './blob-store.ts'
|
|
13
|
+
import type { BundleStore } from './bundle-store.ts'
|
|
14
|
+
import { encodeBrotli } from './brotli.ts'
|
|
15
|
+
import type { ManagedBundle, ManagedDb } from './db.ts'
|
|
16
|
+
import { CacheMissError } from './cache-storage.ts'
|
|
17
|
+
import { SUMMARY_FILENAME, createBundleSummaryCache, readCachedBytes } from './bundle-summary-cache.ts'
|
|
18
|
+
|
|
19
|
+
const decompress = promisify(brotliDecompress)
|
|
20
|
+
const MAX_DECODED_BYTES = 512 * 1024 * 1024
|
|
21
|
+
export const MAX_PACKAGE_INVENTORY_BYTES = 1024 * 1024
|
|
22
|
+
export type BundleCachePart = 'metadata' | 'contents'
|
|
23
|
+
export type BundleCacheRecord = Pick<ManagedBundle, 'id' | 'integrity' | 'filename' | 'kind' | 'byteSize'>
|
|
24
|
+
export interface BundleSummary { files: number; codeFiles: number; lines: number; commit?: string; stasisVersion?: number; versionedPackages?: number }
|
|
25
|
+
|
|
26
|
+
export async function readBundleDetails(record: BundleCacheRecord, store: BundleStore) {
|
|
27
|
+
return (await readSizedBundleDetails(record, store))?.details ?? null
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// As readBundleDetails, with the bytes the bundle decoded to: about what
|
|
31
|
+
// holding its details takes.
|
|
32
|
+
export async function readSizedBundleDetails(record: BundleCacheRecord, store: BundleStore) {
|
|
33
|
+
const bytes = await store.get(record.id, record.kind)
|
|
34
|
+
if (!bytes) return null
|
|
35
|
+
const decoded = record.kind === 'stasis' || record.kind === 'sourcemap' ? await decompress(bytes, { maxOutputLength: MAX_DECODED_BYTES }) : bytes
|
|
36
|
+
if (decoded.length > MAX_DECODED_BYTES) throw new Error('Decoded bundle too large')
|
|
37
|
+
return { details: parseBundleContents(decodeUtf8(decoded), { integrity: record.integrity, kind: record.kind, size: record.byteSize }), decodedBytes: decoded.length }
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export interface BundleCacheStorage {
|
|
41
|
+
exists(id: string, file: string): Promise<boolean>
|
|
42
|
+
put(id: string, file: string, bytes: Buffer): Promise<void>
|
|
43
|
+
open(id: string, file: string): Promise<OpenedBlob>
|
|
44
|
+
// Remove all cached versions for this bundle, including legacy derivatives.
|
|
45
|
+
delete(id: string): Promise<void>
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const filename = `v${BUNDLE_METADATA_VERSION}-metadata.json.br`
|
|
49
|
+
const packagesFilename = 'v6-advisory-inventory.json'
|
|
50
|
+
|
|
51
|
+
// All scopes share one bounded derivative. Never decode full bundle metadata
|
|
52
|
+
// on advisory requests, including when selecting a reason. Persist null when
|
|
53
|
+
// the combined inventory exceeds the budget, without disabling metadata.
|
|
54
|
+
function encodePackageInventory(details: BundleDetails): Buffer {
|
|
55
|
+
const parts: string[] = []
|
|
56
|
+
let size = 0
|
|
57
|
+
function append(part: string) {
|
|
58
|
+
size += Buffer.byteLength(part)
|
|
59
|
+
if (size > MAX_PACKAGE_INVENTORY_BYTES) return false
|
|
60
|
+
parts.push(part)
|
|
61
|
+
return true
|
|
62
|
+
}
|
|
63
|
+
// `items` as `write` writes each, a comma apart, between `open` and
|
|
64
|
+
// `close`: false once past the budget, as `append` is.
|
|
65
|
+
function list<T>(open: string, items: Iterable<T>, write: (item: T) => boolean, close: string) {
|
|
66
|
+
if (!append(open)) return false
|
|
67
|
+
let first = true
|
|
68
|
+
for (const item of items) {
|
|
69
|
+
if (!append(first ? '' : ',') || !write(item)) return false
|
|
70
|
+
first = false
|
|
71
|
+
}
|
|
72
|
+
return append(close)
|
|
73
|
+
}
|
|
74
|
+
const rows = (items: unknown[]) => list('[', items, row => append(JSON.stringify(row)), ']')
|
|
75
|
+
function inventory(paths: Set<string> | null) {
|
|
76
|
+
const { packages, skipped } = bundleAdvisoryInventory(details, paths)
|
|
77
|
+
return append('{"packages":') && rows(packages) && append(',"skipped":') && rows(skipped) && append('}')
|
|
78
|
+
}
|
|
79
|
+
const whole = append('{"all":') && inventory(null)
|
|
80
|
+
&& list(',"reasons":{', bundleReasons(details), ([reason, paths]) => append(`${JSON.stringify(reason)}:`) && inventory(paths), '}}')
|
|
81
|
+
return Buffer.from(whole ? parts.join('') : 'null')
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// What a catalog sends of a bundle before it opens. A Stasis bundle's
|
|
85
|
+
// `versionedPackages` counts the name@version pairs its unscoped advisory
|
|
86
|
+
// audit covers, audited or skipped: with none, Advisories has nothing to show.
|
|
87
|
+
export function bundleSummary(details: BundleDetails, metadata?: Parameters<typeof createBundleSummary>[1]): BundleSummary {
|
|
88
|
+
const summary = createBundleSummary(details, metadata)
|
|
89
|
+
if (details.kind !== 'stasis') return summary
|
|
90
|
+
const { packages, skipped } = bundleAdvisoryInventory(details)
|
|
91
|
+
return { ...summary, versionedPackages: packages.reduce((count, pkg) => count + pkg.versions.length, 0) + skipped.length }
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// A sourcemap's edges, read with the parser (edges.js) that the client goes
|
|
95
|
+
// without: every map's, where the client reads Metro's alone. Without it,
|
|
96
|
+
// the metadata keeps what the client would read. A map with no
|
|
97
|
+
// sourcesContent has no source to read them from.
|
|
98
|
+
function readSourcemapEdges(details: BundleDetails) {
|
|
99
|
+
if (details.kind !== 'sourcemap' || !details.map?.files.some(file => file.content !== null)) return
|
|
100
|
+
try { details.edges = sourcemapEdges(details.map, bundleEdges) }
|
|
101
|
+
catch (err) { console.warn('managed: sourcemap edges failed:', err) }
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// As readBundleDetails, thrown where the bundle's bytes are gone.
|
|
105
|
+
async function storedDetails(record: BundleCacheRecord, store: BundleStore) {
|
|
106
|
+
const details = await readBundleDetails(record, store)
|
|
107
|
+
if (!details) throw new Error('Bundle bytes unavailable')
|
|
108
|
+
return details
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
async function build(record: BundleCacheRecord, storage: BundleCacheStorage, db: ManagedDb, store: BundleStore) {
|
|
112
|
+
const details = await storedDetails(record, store)
|
|
113
|
+
readSourcemapEdges(details)
|
|
114
|
+
const metadata = { ...await createBundleMetadata(details), id: record.id, filename: record.filename }
|
|
115
|
+
const body = await encodeBrotli(Buffer.from(JSON.stringify(metadata)))
|
|
116
|
+
if (!(await db.getBundle(record.id))) throw new Error('Bundle deleted')
|
|
117
|
+
const summary = bundleSummary(details, metadata)
|
|
118
|
+
// Written together, each settled before the row is looked at again: one
|
|
119
|
+
// failing leaves the others, which a later open builds over.
|
|
120
|
+
const written = await Promise.allSettled([
|
|
121
|
+
storage.put(record.id, filename, body),
|
|
122
|
+
...record.kind === 'stasis' ? [storage.put(record.id, packagesFilename, encodePackageInventory(details))] : [],
|
|
123
|
+
storage.put(record.id, SUMMARY_FILENAME, Buffer.from(JSON.stringify(summary))),
|
|
124
|
+
])
|
|
125
|
+
// A different instance may have deleted the row while these writes ran.
|
|
126
|
+
// Reconcile after publishing so its cleanup cannot be undone by us.
|
|
127
|
+
if (!(await db.getBundle(record.id))) {
|
|
128
|
+
await storage.delete(record.id)
|
|
129
|
+
throw new Error('Bundle deleted')
|
|
130
|
+
}
|
|
131
|
+
const failed = written.find(result => result.status === 'rejected')
|
|
132
|
+
if (failed) throw failed.reason
|
|
133
|
+
return summary
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
export function createBundleCache(storage: BundleCacheStorage, db: ManagedDb, store: BundleStore) {
|
|
137
|
+
const pending = new Map<string, Promise<void>>()
|
|
138
|
+
// The database deduplicates by integrity, so each hash has one persistent
|
|
139
|
+
// bundle/cache directory, shared across teams and repeated uploads.
|
|
140
|
+
const summaries = createBundleSummaryCache(storage, async record => bundleSummary(await storedDetails(record, store)), id => db.getBundle(id))
|
|
141
|
+
let queue = Promise.resolve()
|
|
142
|
+
async function ensure(record: BundleCacheRecord): Promise<void> {
|
|
143
|
+
const existing = pending.get(record.id)
|
|
144
|
+
if (existing) return existing
|
|
145
|
+
const job = (async () => {
|
|
146
|
+
if (await storage.exists(record.id, filename) && (record.kind !== 'stasis' || await storage.exists(record.id, packagesFilename))) return
|
|
147
|
+
const work = queue.then(async () => summaries.remember(record, await build(record, storage, db, store)))
|
|
148
|
+
queue = work.catch(() => {})
|
|
149
|
+
await work
|
|
150
|
+
})()
|
|
151
|
+
pending.set(record.id, job)
|
|
152
|
+
try { await job } finally { if (pending.get(record.id) === job) pending.delete(record.id) }
|
|
153
|
+
}
|
|
154
|
+
async function openCached(record: BundleCacheRecord, file: string) {
|
|
155
|
+
try { return await storage.open(record.id, file) }
|
|
156
|
+
catch (error) { if (!(error instanceof CacheMissError)) throw error }
|
|
157
|
+
await ensure(record)
|
|
158
|
+
return storage.open(record.id, file)
|
|
159
|
+
}
|
|
160
|
+
return {
|
|
161
|
+
prebuild: ensure,
|
|
162
|
+
summary: summaries.summary,
|
|
163
|
+
summaryStatus: summaries.summaryStatus,
|
|
164
|
+
backfillSummaries: summaries.backfill,
|
|
165
|
+
async open(record: ManagedBundle, part: BundleCachePart) {
|
|
166
|
+
if (part === 'contents') {
|
|
167
|
+
if (record.kind !== 'stasis' && record.kind !== 'sourcemap') throw new Error('Unsupported bundle')
|
|
168
|
+
const stored = await store.open(record.id, record.kind)
|
|
169
|
+
if (!stored) throw new Error('Bundle bytes unavailable')
|
|
170
|
+
return stored
|
|
171
|
+
}
|
|
172
|
+
return openCached(record, filename)
|
|
173
|
+
},
|
|
174
|
+
// A sourcemap's edges as its metadata keeps them, read with the parser
|
|
175
|
+
// once, for a derivative that reads the bundle itself (report previews).
|
|
176
|
+
async sourcemapEdges(record: ManagedBundle): Promise<BundleDetails['edges']> {
|
|
177
|
+
const decoded = await decompress(await readBytes(await openCached(record, filename)), { maxOutputLength: MAX_DECODED_BYTES })
|
|
178
|
+
return parseBundleMetadata(JSON.parse(decodeUtf8(decoded)), record.integrity).edges
|
|
179
|
+
},
|
|
180
|
+
async advisoryInventory(record: ManagedBundle, reason = ''): Promise<BundleAdvisoryInventory | null | undefined> {
|
|
181
|
+
if (record.kind !== 'stasis') return { packages: [], skipped: [] }
|
|
182
|
+
const cached = await openCached(record, packagesFilename)
|
|
183
|
+
if (cached.size != null && cached.size > MAX_PACKAGE_INVENTORY_BYTES) { cached.stream.destroy(); return null }
|
|
184
|
+
const bytes = await readCachedBytes(cached, MAX_PACKAGE_INVENTORY_BYTES)
|
|
185
|
+
if (!bytes) return null
|
|
186
|
+
const inventory = JSON.parse(decodeUtf8(bytes))
|
|
187
|
+
if (inventory === null) return null
|
|
188
|
+
return reason ? (Object.hasOwn(inventory.reasons, reason) ? inventory.reasons[reason] : undefined) : inventory.all
|
|
189
|
+
},
|
|
190
|
+
async delete(id: string) {
|
|
191
|
+
// Call after deleting the row. Waiting prevents an in-flight builder
|
|
192
|
+
// from recreating its files after deletion has completed.
|
|
193
|
+
await pending.get(id)?.catch(() => {})
|
|
194
|
+
await summaries.forget(id)
|
|
195
|
+
await storage.delete(id)
|
|
196
|
+
},
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
export type BundleCache = ReturnType<typeof createBundleCache>
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { BundleCache, BundleSummary } from './bundle-cache.ts'
|
|
2
|
+
import type { AdminBundle, UserTeamBundle } from './db.ts'
|
|
3
|
+
import { eachOf } from './queue.ts'
|
|
4
|
+
|
|
5
|
+
const SUMMARY_READ_CONCURRENCY = 8
|
|
6
|
+
type ListedBundle = AdminBundle | UserTeamBundle
|
|
7
|
+
|
|
8
|
+
// The bundles, one of each content hash.
|
|
9
|
+
const byIntegrity = (bundles: readonly ListedBundle[]) => [...new Map(bundles.map(bundle => [bundle.integrity, bundle])).values()]
|
|
10
|
+
|
|
11
|
+
// Read only existing summaries: cold/malformed bundles must never trigger
|
|
12
|
+
// parsing or wait for metadata builds before the catalog response is sent.
|
|
13
|
+
export async function bundleSummaries(bundles: readonly ListedBundle[], cache?: BundleCache) {
|
|
14
|
+
const summaries = new Map<string, { summary: BundleSummary | null; summaryRetryAt: number | null }>()
|
|
15
|
+
if (cache) {
|
|
16
|
+
// Cold reads may each access remote storage. Bound those requests as well
|
|
17
|
+
// as the subsequent backfill, without dropping entries from large catalogs.
|
|
18
|
+
await eachOf(byIntegrity(bundles), SUMMARY_READ_CONCURRENCY, async bundle => {
|
|
19
|
+
summaries.set(bundle.integrity, await cache.summaryStatus(bundle).catch(() => ({ summary: null, summaryRetryAt: null })))
|
|
20
|
+
})
|
|
21
|
+
}
|
|
22
|
+
return summaries
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// Called after sending the response. Each cache permits one small batch at a
|
|
26
|
+
// time, deduplicated by content hash, and skips persisted retry-backoff markers.
|
|
27
|
+
export async function backfillBundleSummaries(bundles: readonly ListedBundle[], cache?: BundleCache) {
|
|
28
|
+
await cache?.backfillSummaries(byIntegrity(bundles))
|
|
29
|
+
}
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import { setImmediate } from 'node:timers/promises'
|
|
2
|
+
import { bundleCommitHash } from '../common/bundle-commit.js'
|
|
3
|
+
import type { BundleSummary } from './bundle-cache.ts'
|
|
4
|
+
import type { ManagedDb } from './db.ts'
|
|
5
|
+
import { type GithubCommit, githubCommitKey } from './github-metadata.ts'
|
|
6
|
+
import { LOGIN, MAX_NAME, timeOf } from './github-values.ts'
|
|
7
|
+
|
|
8
|
+
const MAX_MESSAGE_LENGTH = 65_536
|
|
9
|
+
const BACKFILL_LIMIT = 4
|
|
10
|
+
const RETRY_MS = 5 * 60_000
|
|
11
|
+
|
|
12
|
+
type CommitDetails = Omit<GithubCommit, 'key' | 'fetchedAt'>
|
|
13
|
+
// What viewers see of a cached commit: its subject in place of the message.
|
|
14
|
+
type CatalogCommitDetails = Omit<CommitDetails, 'message'> & { subject: string }
|
|
15
|
+
// What a catalog sends with a bundle whose summary records a commit, when
|
|
16
|
+
// the cache holds its details, tags pointing to it, or both. `github` is the
|
|
17
|
+
// repository they were cached for: the one the bundle is stored at.
|
|
18
|
+
interface BundleCommitInfo { sha: string; github: string; tags: string[]; details: CatalogCommitDetails | null }
|
|
19
|
+
interface CatalogBundle { integrity: string; repoId: number | null; repoFullName: string | null }
|
|
20
|
+
type Summaries = ReadonlyMap<string, { summary: BundleSummary | null }>
|
|
21
|
+
export interface CatalogCommit { repoId: number; sha: string; key: string }
|
|
22
|
+
interface CommitReader { commitDetails(sha: string): Promise<CommitDetails | null> }
|
|
23
|
+
|
|
24
|
+
function truncate(value: string, max: number): string {
|
|
25
|
+
if (value.length <= max) return value
|
|
26
|
+
// Never leave half of a surrogate pair at the end.
|
|
27
|
+
return value.slice(0, /[\uD800-\uDBFF]/u.test(value[max - 1]!) ? max - 1 : max)
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function name(value: unknown): string | null {
|
|
31
|
+
return typeof value === 'string' && value.trim() ? truncate(value.trim(), MAX_NAME) : null
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// `body` is a GitHub list-commits page that starts at `sha`, so its first
|
|
35
|
+
// commit is that one, without the files GET /commits/:sha would add.
|
|
36
|
+
export function parseGithubCommit(sha: string, body: unknown): CommitDetails | null {
|
|
37
|
+
const item = Array.isArray(body) ? body[0] as {
|
|
38
|
+
sha?: unknown; author?: { login?: unknown } | null
|
|
39
|
+
commit?: { message?: unknown; author?: { name?: unknown; date?: unknown } | null; committer?: { date?: unknown } | null }
|
|
40
|
+
} | null : null
|
|
41
|
+
if (item?.sha !== sha || typeof item.commit?.message !== 'string') return null
|
|
42
|
+
const login = item.author?.login
|
|
43
|
+
return {
|
|
44
|
+
message: truncate(item.commit.message, MAX_MESSAGE_LENGTH),
|
|
45
|
+
authorName: name(item.commit.author?.name),
|
|
46
|
+
authorLogin: typeof login === 'string' && LOGIN.test(login) ? login : null,
|
|
47
|
+
authoredAt: timeOf(item.commit.author?.date),
|
|
48
|
+
committedAt: timeOf(item.commit.committer?.date),
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// A commit's subject, as `git log --format=%s` gives it: the message's first
|
|
53
|
+
// paragraph on one line, here without the Claude-Session lines Claude Code
|
|
54
|
+
// adds. Viewers see no more of the message, so catalogs send no more.
|
|
55
|
+
export function commitSubject(message: string): string {
|
|
56
|
+
const paragraph = message.replaceAll('\r\n', '\n').trim().split(/\n[ \t]*\n/u, 1)[0] ?? ''
|
|
57
|
+
return paragraph.split('\n').map(line => line.trim()).filter(line => line && !/^Claude-Session:/iu.test(line)).join(' ')
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// The commit a bundle's own summary records, in the repository it is stored at.
|
|
61
|
+
function catalogCommit(bundle: CatalogBundle, summaries: Summaries): CatalogCommit | null {
|
|
62
|
+
const sha = bundleCommitHash(summaries.get(bundle.integrity)?.summary?.commit)
|
|
63
|
+
return sha && bundle.repoId != null ? { repoId: bundle.repoId, sha, key: githubCommitKey(bundle.repoId, sha) } : null
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// Reads only the cache: viewing a bundle never requests its commit's tags,
|
|
67
|
+
// and a commit missing from the cache is left for backfillBundleCommits.
|
|
68
|
+
// Call it before the catalog's final access check: `commitInfo` answers for
|
|
69
|
+
// the bundles of that last snapshot without another await, and has nothing
|
|
70
|
+
// for a commit or repository this read did not cover.
|
|
71
|
+
export async function bundleCommits(db: ManagedDb, bundles: readonly CatalogBundle[], summaries: Summaries) {
|
|
72
|
+
const wanted = new Map<string, CatalogCommit>()
|
|
73
|
+
for (const bundle of bundles) {
|
|
74
|
+
const commit = catalogCommit(bundle, summaries)
|
|
75
|
+
if (commit) wanted.set(commit.key, commit)
|
|
76
|
+
}
|
|
77
|
+
const keys = [...wanted.keys()]
|
|
78
|
+
const details = new Map<string, CatalogCommitDetails>()
|
|
79
|
+
const tags = new Map<string, string[]>()
|
|
80
|
+
if (keys.length > 0) {
|
|
81
|
+
for (const { key, fetchedAt: _fetchedAt, message, ...commit } of await db.listGithubCommits(keys)) {
|
|
82
|
+
details.set(key, { subject: commitSubject(message), ...commit })
|
|
83
|
+
}
|
|
84
|
+
for (const tag of await db.listGithubCommitTags(keys)) tags.set(tag.key, [...tags.get(tag.key) ?? [], tag.name])
|
|
85
|
+
}
|
|
86
|
+
return {
|
|
87
|
+
commitInfo(bundle: CatalogBundle): BundleCommitInfo | null {
|
|
88
|
+
const commit = catalogCommit(bundle, summaries)
|
|
89
|
+
if (!commit || !bundle.repoFullName || (!details.has(commit.key) && !tags.has(commit.key))) return null
|
|
90
|
+
return { sha: commit.sha, github: bundle.repoFullName, tags: tags.get(commit.key) ?? [], details: details.get(commit.key) ?? null }
|
|
91
|
+
},
|
|
92
|
+
missing: [...wanted.values()].filter(commit => !details.has(commit.key)),
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// Store the details of a commit, read with the reader's verified repository
|
|
97
|
+
// access, unless the cache already has them. Best effort: true once cached.
|
|
98
|
+
export async function cacheCommitDetails(db: ManagedDb, reader: CommitReader, repoId: number, sha: string): Promise<boolean> {
|
|
99
|
+
const key = githubCommitKey(repoId, sha)
|
|
100
|
+
try {
|
|
101
|
+
if ((await db.listGithubCommits([key])).length > 0) return true
|
|
102
|
+
const details = await reader.commitDetails(sha)
|
|
103
|
+
if (details) await db.setGithubCommits([{ key, ...details, fetchedAt: Date.now() }])
|
|
104
|
+
return details !== null
|
|
105
|
+
} catch { return false }
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
const active = new Set<string>()
|
|
109
|
+
const retries = new Map<string, number>()
|
|
110
|
+
|
|
111
|
+
// Called after the catalog response is sent: the next one has the details.
|
|
112
|
+
// Reads each commit with the viewer's own repository access, so a viewer who
|
|
113
|
+
// cannot read it on GitHub leaves it for another (retried after a delay for
|
|
114
|
+
// them). Commits never change, so each is stored once and kept.
|
|
115
|
+
export async function backfillBundleCommits(db: ManagedDb, userId: string, missing: readonly CatalogCommit[],
|
|
116
|
+
readerFor: (repoId: number) => Promise<CommitReader | null>): Promise<void> {
|
|
117
|
+
if (missing.length === 0) return
|
|
118
|
+
await setImmediate()
|
|
119
|
+
const now = Date.now()
|
|
120
|
+
for (const [key, retryAt] of retries) if (retryAt <= now) retries.delete(key)
|
|
121
|
+
const batch = missing.filter(commit => !active.has(commit.key) && !retries.has(`${userId}\n${commit.key}`)).slice(0, BACKFILL_LIMIT)
|
|
122
|
+
for (const commit of batch) active.add(commit.key)
|
|
123
|
+
try {
|
|
124
|
+
for (const repoId of new Set(batch.map(commit => commit.repoId))) {
|
|
125
|
+
const reader = await readerFor(repoId).catch(() => null)
|
|
126
|
+
for (const commit of batch.filter(entry => entry.repoId === repoId)) {
|
|
127
|
+
if (!reader || !await cacheCommitDetails(db, reader, repoId, commit.sha)) retries.set(`${userId}\n${commit.key}`, Date.now() + RETRY_MS)
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
} finally {
|
|
131
|
+
for (const commit of batch) active.delete(commit.key)
|
|
132
|
+
}
|
|
133
|
+
}
|