diff --git a/.claude/skills/release/SKILL.md b/.claude/skills/release/SKILL.md index 924f67c..accba77 100644 --- a/.claude/skills/release/SKILL.md +++ b/.claude/skills/release/SKILL.md @@ -15,6 +15,13 @@ The `branch-diff` tool must be installed globally: npm install branch-diff -g ``` +Fetch and fast-forward **both** branches before doing anything else. If you compare a +stale `v2.x` against a stale `main`, you get the wrong commit list without any warning: + +``` +git fetch origin && git checkout v2.x && git pull && git checkout main && git pull +``` + ## Steps ### 1. Identify commits to cherry-pick @@ -25,9 +32,35 @@ Use the `branch-diff` tool to list commits on `main` not yet applied to `v2.x`: branch-diff v2.x main ``` -Review the output with the user. Skip: -- Version bump commits (e.g. "Bump package version on to 3.0.0-pre") -- Commits that would result in empty cherry-picks (already applied or superseded) +`branch-diff` prints GitHub issue-lookup errors to stderr and the commit list to stdout. +The PR number is in the trailing URL (`.../pull/112`). Don't parse it from the `(#NNN)` +form, because that also matches PR references that happen to appear in commit titles. + +`branch-diff` compares commits, not content, so it reports **false positives**: commits +whose changes are already on `v2.x`. Don't cherry-pick these. They fall into these classes: + +**a. Squash-merged releases.** Some releases were squash-merged instead of rebased. +Squashing strips the identity of every commit in them, so `branch-diff` keeps reporting +those commits forever. Treat all of the following as already released: + +| Release | Proposal | PRs subsumed | +|---|---|---| +| 2.3.2 | #101 | 90, 91, 92, 94, 95, 96, 97, 98, 100 | + +If you squash-merge another release proposal, add a row here. To get the subsumed PRs, +look at the `* ... (#NNN)` lines in the squash commit's message on `v2.x`. + +**b. Superseded dependency bumps.** A Dependabot bump that never landed on `v2.x`, after +which `v2.x` got an equal or newer version of the same package directly. Cherry-picking +one would *downgrade* the branch. To spot these, compare the package's version in +`v2.x:package.json` with the bump's target, and skip the bump when `v2.x` is at or ahead +of it. + +**c. Version bump commits on `main`** (e.g. "Bump package version on to 3.0.0-pre"). +Never cherry-pick these onto `v2.x`. + +Anything left after removing these classes is a real candidate. Age alone doesn't make a +commit a false positive; classify by the rules above. Confirm the list of commits with the user before proceeding. @@ -42,6 +75,11 @@ gh pr view --json labels --jq '.labels[].name' - If any PR has a `semver-minor` label, the release is a **minor** bump. - If all PRs have at most a `semver-patch` label, the release is a **patch** bump. +Labels are often missing, especially on hand-written PRs. Also look at each commit's +conventional-commit prefix: a `feat:` commit means a **minor** bump even without a +`semver-minor` label. If the labels and the prefixes disagree, point that out when you +confirm the version. + Get the current version from the tip of `v2.x` (the most recent version commit message), then compute the next version accordingly. Confirm the version with the user. In the steps below, `$VERSION` refers to the determined version number. @@ -54,6 +92,14 @@ Create a git worktree from the current repo, checking out a new branch `v$VERSIO git worktree add ../pprof-format-v2 -b v$VERSION-proposal v2.x ``` +The path is usually still taken by the previous release's worktree. Once that proposal's +PR is merged, you can clear it. First check that the worktree is clean and the PR is +merged, then run: + +``` +git worktree remove ../pprof-format-v2 && git branch -D v-proposal +``` + All subsequent steps run in the worktree directory. ### 4. Cherry-pick commits @@ -66,7 +112,28 @@ git cherry-pick ... If a cherry-pick has conflicts, stop and resolve with the user. -### 5. Create the version bump commit +### 5. Verify the selection against `main` + +Before bumping the version, diff the worktree against `main`: + +``` +git diff --stat main -- . +``` + +The goal is **minimal divergence**. Ideally only `package.json` and `package-lock.json` +show up, because `main` doesn't track the released version (its `version` field lags +behind `v2.x`). This check validates step 1. If any *other* file shows up, it means one of +two things: + +- you wrongly classified a real commit as a false positive, so cherry-pick it, or +- the divergence is deliberate, so explain it in the PR body. + +A class-(b) superseded bump correctly shows up as a `package.json` / `package-lock.json` +difference where `v2.x` is *ahead* of `main`. That is expected; leave it alone. + +Also run `npm ci && npm test` in the worktree. + +### 6. Create the version bump commit Bump the version in package.json and package-lock.json using npm, then commit: @@ -76,7 +143,11 @@ git add package.json package-lock.json git commit -m "v$VERSION" ``` -### 6. Push and create a PR +Keep this commit last on the branch. If you need another cherry-pick after this point, +drop the version commit (`git reset --hard HEAD~1`), apply the cherry-pick, then run the +bump again. Don't stack the new commit on top of the release commit. + +### 7. Push and create a PR Push the branch and create a PR targeting `v2.x`: @@ -101,3 +172,5 @@ Create the PR with `gh pr create --base v2.x`. The PR body should categorize the ``` Only include sections that have entries. Reference PR numbers from the original commit messages. + +See https://github.com/DataDog/pprof-format/pull/117 for an example. diff --git a/package-lock.json b/package-lock.json index 7e0a5ea..8f6918c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,23 +1,23 @@ { "name": "pprof-format", - "version": "2.4.0", + "version": "2.4.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "pprof-format", - "version": "2.4.0", + "version": "2.4.1", "license": "MIT", "devDependencies": { "@eslint/eslintrc": "^3.3.7", "@eslint/js": "^10.0.1", - "@types/node": "^26.6.5", - "@typescript-eslint/eslint-plugin": "^8.72.1", + "@types/node": "^26.6.6", + "@typescript-eslint/eslint-plugin": "^8.72.2", "@typescript-eslint/parser": "^8.37.0", "eslint": "^10.14.0", "protobufjs": "^8.8.1", "protobufjs-cli": "^2.7.1", - "tshy": "^4.1.3", + "tshy": "^4.1.4", "typescript": "^6.0.3" } }, @@ -326,6 +326,13 @@ "url": "https://github.com/sponsors/nzakas" } }, + "node_modules/@isaacs/nonrecursive-glob-match": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@isaacs/nonrecursive-glob-match/-/nonrecursive-glob-match-1.1.0.tgz", + "integrity": "sha512-GPm/Dbvk5RLmhRnxXIa7nTpK0xtl4E0wj0MslsuNiJ1FIROU+2+9lgUC/dgF7Ey4QCWhfEsgxilMRMCdHPfDfw==", + "dev": true, + "license": "BlueOak-1.0.0" + }, "node_modules/@jsdoc/salty": { "version": "0.2.12", "resolved": "https://registry.npmjs.org/@jsdoc/salty/-/salty-0.2.12.tgz", @@ -410,9 +417,9 @@ "license": "MIT" }, "node_modules/@types/node": { - "version": "26.6.5", - "resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.5.tgz", - "integrity": "sha512-uMzsv9stDdofIZBx4UGh4Z9ZgXnGC9seRDscilBcTHAeOFk67MZg/k9bWVfO+bk4qZmG+l52hRnLwUiH2LnJTg==", + "version": "26.6.6", + "resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.6.tgz", + "integrity": "sha512-MzQj+8Kx3XI40OmUAE6Qoh58ZMNstNNMwn2nfd3qWsfe7nDNSqJNzes4njhz6AHwrSHOffSLwXU6yb474Q4aog==", "dev": true, "license": "MIT", "dependencies": { @@ -420,17 +427,17 @@ } }, "node_modules/@typescript-eslint/eslint-plugin": { - "version": "8.72.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.72.1.tgz", - "integrity": "sha512-5CokTWXpmbylfFabsbvHC0CAw3XLaGnoa+nFJX5FR592h/LoZsENUE6p/rg5xvkKrFEXz6pYmgI29AgXc2N3BQ==", + "version": "8.72.2", + "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.72.2.tgz", + "integrity": "sha512-222PKFXKihmFpi/pS5njoBgdAqsPhj2/GBmFbrNw8Tq8gEG9Sv+kSlKFy4u2q+mJv9ZzJgM2Gkv/bUzRZwZw5g==", "dev": true, "license": "MIT", "dependencies": { "@eslint-community/regexpp": "^4.12.2", - "@typescript-eslint/scope-manager": "8.72.1", - "@typescript-eslint/type-utils": "8.72.1", - "@typescript-eslint/utils": "8.72.1", - "@typescript-eslint/visitor-keys": "8.72.1", + "@typescript-eslint/scope-manager": "8.72.2", + "@typescript-eslint/type-utils": "8.72.2", + "@typescript-eslint/utils": "8.72.2", + "@typescript-eslint/visitor-keys": "8.72.2", "ignore": "^7.0.5", "natural-compare": "^1.4.0", "ts-api-utils": "^2.5.0" @@ -443,7 +450,7 @@ "url": "https://opencollective.com/typescript-eslint" }, "peerDependencies": { - "@typescript-eslint/parser": "^8.72.1", + "@typescript-eslint/parser": "^8.72.2", "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", "typescript": ">=4.8.4 <6.1.0" } @@ -459,16 +466,16 @@ } }, "node_modules/@typescript-eslint/parser": { - "version": "8.72.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.72.1.tgz", - "integrity": "sha512-ZGwZP4OCfyA0AQTpEAMWz+rtX01DRhQWW5hB0ucKDEIX5U7jdmPSaMx94rQfaPAQzIYz2BimOgKOJtjfpRFQ9g==", + "version": "8.72.2", + "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.72.2.tgz", + "integrity": "sha512-llP+T1YuJOLlxEciP6OyQGtz5SMxyn+9LA2BvZw5RmToGVa1y4beEDVQL6Gje7T5WFYh19WREjDCN9Ev4gm5AA==", "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/scope-manager": "8.72.1", - "@typescript-eslint/types": "8.72.1", - "@typescript-eslint/typescript-estree": "8.72.1", - "@typescript-eslint/visitor-keys": "8.72.1", + "@typescript-eslint/scope-manager": "8.72.2", + "@typescript-eslint/types": "8.72.2", + "@typescript-eslint/typescript-estree": "8.72.2", + "@typescript-eslint/visitor-keys": "8.72.2", "debug": "^4.4.3" }, "engines": { @@ -484,14 +491,14 @@ } }, "node_modules/@typescript-eslint/project-service": { - "version": "8.72.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/project-service/-/project-service-8.72.1.tgz", - "integrity": "sha512-fAuVMkwdO/huI8nyo/WKnNKf6Gag93S56Rh3Ts5mGcavwSdaN8tRg1gCeIGX8PF+nzp1BjGfO4gHhGzW1J6jTg==", + "version": "8.72.2", + "resolved": "https://registry.npmjs.org/@typescript-eslint/project-service/-/project-service-8.72.2.tgz", + "integrity": "sha512-6y5dLTZdHhI8Eh3yIQ/bfQhRKwn5e+TpJj64o18Cngc0iW/BCrVvrr6zGYqXPnYH31u6YXAYiFh0+qxX5mybJw==", "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/tsconfig-utils": "^8.72.1", - "@typescript-eslint/types": "^8.72.1", + "@typescript-eslint/tsconfig-utils": "^8.72.2", + "@typescript-eslint/types": "^8.72.2", "debug": "^4.4.3" }, "engines": { @@ -506,14 +513,14 @@ } }, "node_modules/@typescript-eslint/scope-manager": { - "version": "8.72.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.72.1.tgz", - "integrity": "sha512-lC/t6eMCZZQAAKZEYGL6RDVSuFehpdmMT6h+nJIjIa6oylN/PwDgDVtEIbB7O9xFfZYtZAYLoLlDNWKJhtF+uQ==", + "version": "8.72.2", + "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.72.2.tgz", + "integrity": "sha512-iIoMJ6/8c1/QpFNyFjU0d1YzPco4MsZjQw0k3V+vfzNWAFmUmvhlyMoYEoYYDQZXc+J6Gi1X5XcxlzW2taIIGQ==", "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/types": "8.72.1", - "@typescript-eslint/visitor-keys": "8.72.1" + "@typescript-eslint/types": "8.72.2", + "@typescript-eslint/visitor-keys": "8.72.2" }, "engines": { "node": "^18.18.0 || ^20.9.0 || >=21.1.0" @@ -524,9 +531,9 @@ } }, "node_modules/@typescript-eslint/tsconfig-utils": { - "version": "8.72.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.72.1.tgz", - "integrity": "sha512-e4D5R5vpeAEPBxT2BAzsFQL3sbwyeeeo5+aczgNSRK1V734jE7pTqaGFU+fXapWEQwnZbpFaTn32+Z8DwS6OTg==", + "version": "8.72.2", + "resolved": "https://registry.npmjs.org/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.72.2.tgz", + "integrity": "sha512-+h3iCgZXuTNtoLXcnnjP12ZUHLMqoUcIHPfQrFEXTUqvb9dF8QK9b5nv5VtSo5fLkdHuks8ehbTzZj3rImAm9w==", "dev": true, "license": "MIT", "engines": { @@ -541,15 +548,15 @@ } }, "node_modules/@typescript-eslint/type-utils": { - "version": "8.72.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.72.1.tgz", - "integrity": "sha512-iY2wlmyrXJmx4yxUGP3aYCFF3cA/6ShddOKmLU2dx7LnEykbAM8WThlxZEfd1NddqceF6eJmZUayxx9oKIYNlg==", + "version": "8.72.2", + "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.72.2.tgz", + "integrity": "sha512-STfkR38qIdhfkLpgtXnUjAzsNy4xouqiBO0lrVc/Wpk9Kem5/aHXUx1J8dGC16zpdYN1+yc2ILQ28er1kXX7ag==", "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/types": "8.72.1", - "@typescript-eslint/typescript-estree": "8.72.1", - "@typescript-eslint/utils": "8.72.1", + "@typescript-eslint/types": "8.72.2", + "@typescript-eslint/typescript-estree": "8.72.2", + "@typescript-eslint/utils": "8.72.2", "debug": "^4.4.3", "ts-api-utils": "^2.5.0" }, @@ -566,9 +573,9 @@ } }, "node_modules/@typescript-eslint/types": { - "version": "8.72.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.72.1.tgz", - "integrity": "sha512-LmE5IhQet1BWOWEXqBrVtBPsMAOQ6Nzk35d+WLh3mk4EUF33sqlfxjio1MdYeSvKSG5skactKKuixBIKXhL4Rw==", + "version": "8.72.2", + "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.72.2.tgz", + "integrity": "sha512-Xfn37OLZx03+PCU7qWx9DTv2FCRh1E6fk2+wONeNY15HXIwtcwuveaSwVpGAUptkNmPQegRxW5JyRel9T7wrog==", "dev": true, "license": "MIT", "engines": { @@ -580,16 +587,16 @@ } }, "node_modules/@typescript-eslint/typescript-estree": { - "version": "8.72.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.72.1.tgz", - "integrity": "sha512-DAlUoUV93hIvrtIQLwCbmZQYVZwOMhiHJrOVUUIWicFZaIYjTRqlY3I/NZevfkLmSqkNHRu2qYDcq9lrn16oOQ==", + "version": "8.72.2", + "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.72.2.tgz", + "integrity": "sha512-pQEGqIK/cqEvKivVWaFLYpe7XYejFxfuAOi4mu1oAWFvIo36aRHI9esRFTUxcIy/z8N482RJyH+LpZB0ZIU7Ow==", "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/project-service": "8.72.1", - "@typescript-eslint/tsconfig-utils": "8.72.1", - "@typescript-eslint/types": "8.72.1", - "@typescript-eslint/visitor-keys": "8.72.1", + "@typescript-eslint/project-service": "8.72.2", + "@typescript-eslint/tsconfig-utils": "8.72.2", + "@typescript-eslint/types": "8.72.2", + "@typescript-eslint/visitor-keys": "8.72.2", "debug": "^4.4.3", "minimatch": "^10.2.2", "semver": "^7.7.3", @@ -608,16 +615,16 @@ } }, "node_modules/@typescript-eslint/utils": { - "version": "8.72.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.72.1.tgz", - "integrity": "sha512-5v5liypurJBFHCBNqh/RjsymAD+VWcE0djuGY/BUqp5fC3Qn+luWDEksjuTtWjPn6i5zQlUtkZCRG/CYG0yCkA==", + "version": "8.72.2", + "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.72.2.tgz", + "integrity": "sha512-hv3eRYbpPbbpezuax1EfGrzpa3C4ySgNZkPUkLOWOAjU8HsOKowEDAr8C7nsNl1C+SBSKDpvno6VKHnlhvp9iA==", "dev": true, "license": "MIT", "dependencies": { "@eslint-community/eslint-utils": "^4.9.1", - "@typescript-eslint/scope-manager": "8.72.1", - "@typescript-eslint/types": "8.72.1", - "@typescript-eslint/typescript-estree": "8.72.1" + "@typescript-eslint/scope-manager": "8.72.2", + "@typescript-eslint/types": "8.72.2", + "@typescript-eslint/typescript-estree": "8.72.2" }, "engines": { "node": "^18.18.0 || ^20.9.0 || >=21.1.0" @@ -632,13 +639,13 @@ } }, "node_modules/@typescript-eslint/visitor-keys": { - "version": "8.72.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.72.1.tgz", - "integrity": "sha512-SB8xqipSzZHUePCCLNeYxqnxq83X61/qzNhjQGbTfjxGZIeOEP7tBgWYX05Tcd6CgE02WdTJnh5b8kMZJ/+bnQ==", + "version": "8.72.2", + "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.72.2.tgz", + "integrity": "sha512-NAGrjn0Pitjqzq/GkgMC4kBYm233PQ8GffyQ9+kTA3AlNQYEzOf25EIM02BAHZv5FRJSpHpJk+OGUxVkOB93GQ==", "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/types": "8.72.1", + "@typescript-eslint/types": "8.72.2", "eslint-visitor-keys": "^5.0.0" }, "engines": { @@ -1365,15 +1372,15 @@ "license": "ISC" }, "node_modules/glob": { - "version": "13.0.6", - "resolved": "https://registry.npmjs.org/glob/-/glob-13.0.6.tgz", - "integrity": "sha512-Wjlyrolmm8uDpm/ogGyXZXb1Z+Ca2B8NbJwqBVg0axK9GbBeoS7yGV6vjXnYdGm6X53iehEuxxbyiKp8QmN4Vw==", + "version": "14.0.6", + "resolved": "https://registry.npmjs.org/glob/-/glob-14.0.6.tgz", + "integrity": "sha512-OwXjVP2svY5EyLY75Vek96C8qK43gqrt4xsZ+qSILdnaEiJPXkd62mcfUSNx/TQErQRdu5uM5kF67sfONragKw==", "dev": true, "license": "BlueOak-1.0.0", "dependencies": { - "minimatch": "^10.2.2", + "minimatch": "^11.0.5", "minipass": "^7.1.3", - "path-scurry": "^2.0.2" + "path-scurry": "^3.0.0" }, "engines": { "node": "18 || 20 || >=22" @@ -1382,6 +1389,23 @@ "url": "https://github.com/sponsors/isaacs" } }, + "node_modules/glob/node_modules/minimatch": { + "version": "11.0.8", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.8.tgz", + "integrity": "sha512-nFQuYSTVrGvysVBps5Ih+0BdnYFN/Cj3C816r6+p7yK+FHrVLGE4O4N9AFwykrlNlvM2HYt+Rad1Uiro6h88Ig==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "@isaacs/nonrecursive-glob-match": "^1.1.0", + "brace-expansion": "^5.0.12" + }, + "engines": { + "node": "20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, "node_modules/globals": { "version": "14.0.0", "resolved": "https://registry.npmjs.org/globals/-/globals-14.0.0.tgz", @@ -1684,9 +1708,9 @@ "license": "Apache-2.0" }, "node_modules/lru-cache": { - "version": "11.3.2", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.3.2.tgz", - "integrity": "sha512-wgWa6FWQ3QRRJbIjbsldRJZxdxYngT/dO0I5Ynmlnin8qy7tC6xYzbcJjtN4wHLXtkbVwHzk0C+OejVw1XM+DQ==", + "version": "11.5.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.3.tgz", + "integrity": "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==", "dev": true, "license": "BlueOak-1.0.0", "engines": { @@ -1919,9 +1943,9 @@ } }, "node_modules/path-scurry": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-2.0.2.tgz", - "integrity": "sha512-3O/iVVsJAPsOnpwWIeD+d6z/7PmqApyQePUtCndjatj/9I5LylHvt5qluFaBT3I5h3r1ejfR056c+FCv+NnNXg==", + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-3.0.0.tgz", + "integrity": "sha512-1pTbQqH1wIwMi/eleQ5leFTTCkzFsPcgXNjwOA8YGGW/W4/kHT3dssE7Z6NH+zuqNLOzOB0uaD61yl7cAcVhgg==", "dev": true, "license": "BlueOak-1.0.0", "dependencies": { @@ -2157,13 +2181,13 @@ } }, "node_modules/resolve-import": { - "version": "2.4.0", - "resolved": "https://registry.npmjs.org/resolve-import/-/resolve-import-2.4.0.tgz", - "integrity": "sha512-gLWKdA5tiv5j/D7ipR47u3ovbVfzFPrctTdw2Ulnpmr6PPVVSvPKGNWu09jXVNlOSLLAeD6CA13bjIelpWttSw==", + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/resolve-import/-/resolve-import-2.4.2.tgz", + "integrity": "sha512-oPqmfjsmRlPxOTrEuJT4vl/gA9FXn+OmW6r/Qd3a6H6/gQULvOUUvd1cXT+DFJej3zQ4HzUxGWrfh5dkt2V8pA==", "dev": true, "license": "BlueOak-1.0.0", "dependencies": { - "glob": "^13.0.0", + "glob": "^14.0.3", "walk-up-path": "^4.0.0" }, "engines": { @@ -2174,13 +2198,13 @@ } }, "node_modules/rimraf": { - "version": "6.1.3", - "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-6.1.3.tgz", - "integrity": "sha512-LKg+Cr2ZF61fkcaK1UdkH2yEBBKnYjTyWzTJT6KNPcSPaiT7HSdhtMXQuN5wkTX0Xu72KQ1l8S42rlmexS2hSA==", + "version": "6.1.4", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-6.1.4.tgz", + "integrity": "sha512-Fk3reQDVPZUMbEm7Zwxz03BWQMW3V5buSk9aU8OckTrO8A1nQtbqvYsAantGNermwsIsXcuOBqcoJ3HuMELctw==", "dev": true, "license": "BlueOak-1.0.0", "dependencies": { - "glob": "^13.0.3", + "glob": "^14.0.3", "package-json-from-dist": "^1.0.1" }, "bin": { @@ -2194,9 +2218,9 @@ } }, "node_modules/semver": { - "version": "7.8.5", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", - "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", + "version": "7.8.6", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.6.tgz", + "integrity": "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==", "dev": true, "license": "ISC", "bin": { @@ -2267,15 +2291,15 @@ } }, "node_modules/sync-content": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/sync-content/-/sync-content-2.0.4.tgz", - "integrity": "sha512-w3ioiBmbaogob33WdLnuwFk+8tpePI58CTWKqtdAgEqc2hfGuSwP02gPETqNX/3PLS5skv5a1wQR0gbaa2W0XQ==", + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/sync-content/-/sync-content-2.0.5.tgz", + "integrity": "sha512-G4FgCnGtZTKEx3jCbUQlu4npTZezLX+BrLyPzu5ksCy6a5NCz1C44niznFoorAEAam0TplRnLgPrIq8Myi1jFw==", "dev": true, "license": "BlueOak-1.0.0", "dependencies": { - "glob": "^13.0.1", + "glob": "^14.0.3", "mkdirp": "^3.0.1", - "path-scurry": "^2.0.0", + "path-scurry": "^3.0.0", "rimraf": "^6.0.0" }, "bin": { @@ -2329,9 +2353,9 @@ } }, "node_modules/tshy": { - "version": "4.1.3", - "resolved": "https://registry.npmjs.org/tshy/-/tshy-4.1.3.tgz", - "integrity": "sha512-uEaLO1lFhu5X58KZxS5gKCabh+xd72MfXDOHhAIvnoreBAP1F4HNpbK2m0DUmrrzpcgxvXbsdXn1A0OaQxFYqw==", + "version": "4.1.4", + "resolved": "https://registry.npmjs.org/tshy/-/tshy-4.1.4.tgz", + "integrity": "sha512-yfCXXPt6MQm/NbO08SoU9j/3M0nxCj4DPo+59UBLVkRfCTiAnzy6cEC+JuncpjHgSyz56o/QuoSX/RjThD7eBw==", "dev": true, "license": "BlueOak-1.0.0", "dependencies": { @@ -2339,13 +2363,14 @@ "chalk": "^5.6.2", "chokidar": "^4.0.3", "foreground-child": "^4.0.0", + "glob": "^14.0.3", "jsonc-simple-parser": "^3.0.0", - "minimatch": "^10.0.3", + "minimatch": "^11.0.4", "mkdirp": "^3.0.1", "polite-json": "^5.0.0", - "resolve-import": "^2.4.0", - "rimraf": "^6.1.2", - "sync-content": "^2.0.3", + "resolve-import": "^2.4.2", + "rimraf": "^6.1.4", + "sync-content": "^2.0.5", "typescript": "^6.0.2", "walk-up-path": "^4.0.0" }, @@ -2356,6 +2381,23 @@ "node": "20 || >=22" } }, + "node_modules/tshy/node_modules/minimatch": { + "version": "11.0.8", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.8.tgz", + "integrity": "sha512-nFQuYSTVrGvysVBps5Ih+0BdnYFN/Cj3C816r6+p7yK+FHrVLGE4O4N9AFwykrlNlvM2HYt+Rad1Uiro6h88Ig==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "@isaacs/nonrecursive-glob-match": "^1.1.0", + "brace-expansion": "^5.0.12" + }, + "engines": { + "node": "20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, "node_modules/type-check": { "version": "0.4.0", "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz", diff --git a/package.json b/package.json index fc32336..620fc62 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "pprof-format", - "version": "2.4.0", + "version": "2.4.1", "description": "Pure JavaScript pprof encoder and decoder", "author": "Datadog Inc. ", "license": "MIT", @@ -69,13 +69,13 @@ "devDependencies": { "@eslint/eslintrc": "^3.3.7", "@eslint/js": "^10.0.1", - "@types/node": "^26.6.5", - "@typescript-eslint/eslint-plugin": "^8.72.1", + "@types/node": "^26.6.6", + "@typescript-eslint/eslint-plugin": "^8.72.2", "@typescript-eslint/parser": "^8.37.0", "eslint": "^10.14.0", "protobufjs": "^8.8.1", "protobufjs-cli": "^2.7.1", - "tshy": "^4.1.3", + "tshy": "^4.1.4", "typescript": "^6.0.3" }, "overrides": { diff --git a/src/index.test.ts b/src/index.test.ts index 26c8764..9202dd7 100644 --- a/src/index.test.ts +++ b/src/index.test.ts @@ -7,10 +7,14 @@ import { test } from 'node:test' import type { TestContext } from 'node:test' import assert from 'node:assert' +import { Buffer as NodeBuffer } from 'node:buffer' +import { spawnSync } from 'node:child_process' +import { fileURLToPath } from 'node:url' import { gunzipSync } from 'zlib' import * as fs from 'fs' import proto from '../testing/proto/profile.js' +import { ProfilesDictionary } from './otel.js' const {decode, toObject} = proto.perftools.profiles.Profile @@ -466,6 +470,71 @@ test('StringTable', async (t) => { table.dedup('hello') assert.strictEqual(bufToHex(table.encode()), encodings[''] + encodings['hello']) }) + + await t.test('encodes non-ASCII strings as TextEncoder does', async () => { + const strings = ['é', '日本語', '😀 emoji', 'lone \uD800 high', 'lone \uDC00 low', 'x'.repeat(200) + 'ü'] + const table = new StringTable() + for (const value of strings) { + table.dedup(value) + } + const encoded = table.encode() + assert.strictEqual(encoded.length, table.encodedLength) + assert.strictEqual(bufToHex(encoded), encodeStringTable(table)) + }) + + await t.test('re-encodes decoded strings byte for byte', async () => { + // 0xff is not valid UTF-8, so the decoded string alone can't reproduce it + const raw = hexToBuf('3200' + '3203' + '61ff62') + const decoded = Profile.decode(raw).stringTable + assert.strictEqual(bufToHex(decoded.encode()), bufToHex(raw)) + }) + + await t.test('owns decoded string bytes after the input changes', () => { + for (const ArrayType of [Uint8Array, NodeBuffer]) { + for (const length of [0, 1, 64, 65]) { + const bytes = new Uint8Array(length).fill(0xff) + const expected = Uint8Array.of(0x32, 0, 0x32, length, ...bytes) + for (const [MessageType, field] of [[Profile, 0x32], [ProfilesDictionary, 0x2a]] as const) { + const input = ArrayType.from([0xaa, field, 0, field, length, ...bytes, 0xaa]) + const decoded = MessageType.decode(input.subarray(1, -1)) + input.fill(0) + assert.deepStrictEqual(decoded.stringTable.encode(), expected, `${ArrayType.name}, ${length} bytes`) + } + } + } + }) + + await t.test('checks the capacity of supplied buffers', () => { + for (const value of ['', 'hello', 'é日本😀\uD800', 'x'.repeat(127), 'x'.repeat(128)]) { + const table = new StringTable() + table.dedup(value) + const expected = encodeStringTable(table) + for (const ArrayType of [Uint8Array, NodeBuffer]) { + for (const length of [0, table.encodedLength - 1]) { + assert.throws(() => table.encode(new ArrayType(length)), { name: 'RangeError' }) + } + for (const extra of [0, 1]) { + const backing = new ArrayType(table.encodedLength + extra + 2).fill(0xaa) + const target = backing.subarray(1, -1) + assert.strictEqual(table.encode(target), target) + assert.strictEqual(bufToHex(target.subarray(0, table.encodedLength)), expected) + assert.strictEqual(backing[0], 0xaa) + assert.strictEqual(backing[backing.length - 1], 0xaa) + if (extra) { + assert.strictEqual(target[table.encodedLength], 0xaa) + } + } + } + } + }) + + await t.test('works without the Buffer global', { skip: typeof globalThis.Buffer === 'undefined' }, () => { + const result = spawnSync(process.execPath, [ + '--import', 'data:text/javascript,globalThis.Buffer=undefined', + '--test', '--test-name-pattern=StringTable', fileURLToPath(import.meta.url), + ], { encoding: 'utf8', env: { ...process.env, NODE_TEST_CONTEXT: undefined } }) + assert.strictEqual(result.status, 0, result.stderr || result.stdout) + }) }) function profileToObject(profile: any): object { diff --git a/src/index.ts b/src/index.ts index 8cb67a9..f48d009 100644 --- a/src/index.ts +++ b/src/index.ts @@ -246,15 +246,15 @@ export class Sample extends Message { _measure(context: EncodeContext) { let total = 0 - total += measurePackedNumbersField(SampleField.locationId, this.locationId) - total += measurePackedNumbersField(SampleField.value, this.value) + total += measurePackedNumbersField(SampleField.locationId, this.locationId, context) + total += measurePackedNumbersField(SampleField.value, this.value, context) total += measureMessageArrayField(SampleField.label, this.label, context) return total } _encodeToBuffer(buffer: Uint8Array, offset: number, context: EncodeContext): number { - offset = encodePackedNumbersField(buffer, offset, SampleField.locationId, this.locationId) - offset = encodePackedNumbersField(buffer, offset, SampleField.value, this.value) + offset = encodePackedNumbersField(buffer, offset, SampleField.locationId, this.locationId, context) + offset = encodePackedNumbersField(buffer, offset, SampleField.value, this.value, context) offset = encodeMessageArrayField(buffer, offset, SampleField.label, this.label, context) return offset } @@ -658,7 +658,7 @@ export class Profile extends Message { total += measureNumberField(ProfileField.durationNanos, this.durationNanos) total += measureMessageField(ProfileField.periodType, this.periodType, context) total += measureNumberField(ProfileField.period, this.period) - total += measurePackedNumbersField(ProfileField.comment, this.comment) + total += measurePackedNumbersField(ProfileField.comment, this.comment, context) total += measureNumberField(ProfileField.defaultSampleType, this.defaultSampleType) total += measureNumberField(ProfileField.docUrl, this.docUrl) return total @@ -691,7 +691,7 @@ export class Profile extends Message { offset = encodeNumberField(buffer, offset, ProfileField.durationNanos, this.durationNanos) offset = encodeMessageField(buffer, offset, ProfileField.periodType, this.periodType, context) offset = encodeNumberField(buffer, offset, ProfileField.period, this.period) - offset = encodePackedNumbersField(buffer, offset, ProfileField.comment, this.comment) + offset = encodePackedNumbersField(buffer, offset, ProfileField.comment, this.comment, context) offset = encodeNumberField(buffer, offset, ProfileField.defaultSampleType, this.defaultSampleType) offset = encodeNumberField(buffer, offset, ProfileField.docUrl, this.docUrl) return offset diff --git a/src/otel.test.ts b/src/otel.test.ts index 6f647bb..8ef243b 100644 --- a/src/otel.test.ts +++ b/src/otel.test.ts @@ -26,6 +26,7 @@ import { } from './otel.js' import * as otel from './otel.js' import { StringTable as PprofStringTable } from './index.js' +import type { EncodeContext } from './protobuf.js' const pb = otelProto.opentelemetry.proto @@ -247,9 +248,9 @@ test('ExportProfilesServiceRequest.encodeAsync', async (t) => { await t.test('measures each submessage once', async () => { const measure = Sample.prototype._measure let calls = 0 - Sample.prototype._measure = function (this: Sample) { + Sample.prototype._measure = function (this: Sample, context: EncodeContext) { calls++ - return measure.call(this) + return measure.call(this, context) } try { await new ExportProfilesServiceRequest(exampleRequest()).encodeAsync() @@ -273,6 +274,11 @@ test('ExportProfilesServiceRequest.encodeAsync', async (t) => { }) }) +test('Stack encodes packed location indices without a parent message', () => { + assert.strictEqual(hex(new otel.Stack().encode()), '') + assert.strictEqual(hex(new otel.Stack({ locationIndices: [0, 128] }).encode()), '0a03008001') +}) + test('ExportProfilesServiceResponse', () => { const { ExportProfilesServiceResponse: PbResponse } = pb.collector.profiles.v1development const encoded = PbResponse.encode(PbResponse.fromObject({ @@ -326,7 +332,11 @@ test('ProfilesDictionary', async (t) => { }) test('string fields are encoded as UTF-8', () => { - for (const key of ['plain', 'café', '✓', '😀', 'lone \ud800 surrogate']) { + for (const key of [ + 'plain', 'café', '✓', '😀', 'lone \ud800 surrogate', + '\u007f', '\u0080', '\u07ff', '\u0800', '\ud7ff', '\ud800', '\udbff', '\udc00', '\udfff', '\ue000', '\uffff', + '\ud800\udc00', '\udbff\udfff', '\ud800\ud800', '\ud800\ue000', '\udc00\ud800', + ]) { const utf8 = Buffer.from(key, 'utf8') const encoded = new KeyValue({ key }).encode() assert.strictEqual(hex(encoded), '0a' + utf8.length.toString(16).padStart(2, '0') + utf8.toString('hex'), key) diff --git a/src/otel.ts b/src/otel.ts index cb01ee7..22220eb 100644 --- a/src/otel.ts +++ b/src/otel.ts @@ -1048,7 +1048,7 @@ export class Profile extends Message { total += measureNumberField(ProfileField.droppedAttributesCount, this.droppedAttributesCount) total += measureStringField(ProfileField.originalPayloadFormat, this.originalPayloadFormat) total += measureBytesField(ProfileField.originalPayload, this.originalPayload) - total += measurePackedNumbersField(ProfileField.attributeIndices, this.attributeIndices) + total += measurePackedNumbersField(ProfileField.attributeIndices, this.attributeIndices, context) return total } @@ -1063,7 +1063,7 @@ export class Profile extends Message { offset = encodeNumberField(buffer, offset, ProfileField.droppedAttributesCount, this.droppedAttributesCount) offset = encodeStringField(buffer, offset, ProfileField.originalPayloadFormat, this.originalPayloadFormat) offset = encodeBytesField(buffer, offset, ProfileField.originalPayload, this.originalPayload) - offset = encodePackedNumbersField(buffer, offset, ProfileField.attributeIndices, this.attributeIndices) + offset = encodePackedNumbersField(buffer, offset, ProfileField.attributeIndices, this.attributeIndices, context) return offset } @@ -1264,21 +1264,21 @@ export class Sample extends Message { this.timestampsUnixNano = data.timestampsUnixNano || [] } - _measure() { + _measure(context: EncodeContext) { let total = 0 total += measureNumberField(SampleField.stackIndex, this.stackIndex) - total += measurePackedNumbersField(SampleField.attributeIndices, this.attributeIndices) + total += measurePackedNumbersField(SampleField.attributeIndices, this.attributeIndices, context) total += measureNumberField(SampleField.linkIndex, this.linkIndex) - total += measurePackedNumbersField(SampleField.values, this.values) + total += measurePackedNumbersField(SampleField.values, this.values, context) total += measurePackedFixed64Field(SampleField.timestampsUnixNano, this.timestampsUnixNano) return total } - _encodeToBuffer(buffer: Uint8Array, offset = 0): number { + _encodeToBuffer(buffer: Uint8Array, offset: number, context: EncodeContext): number { offset = encodeNumberField(buffer, offset, SampleField.stackIndex, this.stackIndex) - offset = encodePackedNumbersField(buffer, offset, SampleField.attributeIndices, this.attributeIndices) + offset = encodePackedNumbersField(buffer, offset, SampleField.attributeIndices, this.attributeIndices, context) offset = encodeNumberField(buffer, offset, SampleField.linkIndex, this.linkIndex) - offset = encodePackedNumbersField(buffer, offset, SampleField.values, this.values) + offset = encodePackedNumbersField(buffer, offset, SampleField.values, this.values, context) offset = encodePackedFixed64Field(buffer, offset, SampleField.timestampsUnixNano, this.timestampsUnixNano) return offset } @@ -1353,22 +1353,22 @@ export class Mapping extends Message { this.attributeIndices = data.attributeIndices || [] } - _measure() { + _measure(context: EncodeContext) { let total = 0 total += measureNumberField(MappingField.memoryStart, this.memoryStart) total += measureNumberField(MappingField.memoryLimit, this.memoryLimit) total += measureNumberField(MappingField.fileOffset, this.fileOffset) total += measureNumberField(MappingField.filenameStrindex, this.filenameStrindex) - total += measurePackedNumbersField(MappingField.attributeIndices, this.attributeIndices) + total += measurePackedNumbersField(MappingField.attributeIndices, this.attributeIndices, context) return total } - _encodeToBuffer(buffer: Uint8Array, offset = 0): number { + _encodeToBuffer(buffer: Uint8Array, offset: number, context: EncodeContext): number { offset = encodeNumberField(buffer, offset, MappingField.memoryStart, this.memoryStart) offset = encodeNumberField(buffer, offset, MappingField.memoryLimit, this.memoryLimit) offset = encodeNumberField(buffer, offset, MappingField.fileOffset, this.fileOffset) offset = encodeNumberField(buffer, offset, MappingField.filenameStrindex, this.filenameStrindex) - offset = encodePackedNumbersField(buffer, offset, MappingField.attributeIndices, this.attributeIndices) + offset = encodePackedNumbersField(buffer, offset, MappingField.attributeIndices, this.attributeIndices, context) return offset } @@ -1421,12 +1421,12 @@ export class Stack extends Message { this.locationIndices = data.locationIndices || [] } - _measure() { - return measurePackedNumbersField(StackField.locationIndices, this.locationIndices) + _measure(context: EncodeContext) { + return measurePackedNumbersField(StackField.locationIndices, this.locationIndices, context) } - _encodeToBuffer(buffer: Uint8Array, offset = 0): number { - return encodePackedNumbersField(buffer, offset, StackField.locationIndices, this.locationIndices) + _encodeToBuffer(buffer: Uint8Array, offset: number, context: EncodeContext): number { + return encodePackedNumbersField(buffer, offset, StackField.locationIndices, this.locationIndices, context) } static decodeValue(data: StackInput, field: number, buffer: Uint8Array, start = 0, end = buffer.length, wireType?: number) { @@ -1483,7 +1483,7 @@ export class Location extends Message { total += measureNumberField(LocationField.mappingIndex, this.mappingIndex) total += measureNumberField(LocationField.address, this.address) total += measureMessageArrayField(LocationField.lines, this.lines, context) - total += measurePackedNumbersField(LocationField.attributeIndices, this.attributeIndices) + total += measurePackedNumbersField(LocationField.attributeIndices, this.attributeIndices, context) return total } @@ -1491,7 +1491,7 @@ export class Location extends Message { offset = encodeNumberField(buffer, offset, LocationField.mappingIndex, this.mappingIndex) offset = encodeNumberField(buffer, offset, LocationField.address, this.address) offset = encodeMessageArrayField(buffer, offset, LocationField.lines, this.lines, context) - offset = encodePackedNumbersField(buffer, offset, LocationField.attributeIndices, this.attributeIndices) + offset = encodePackedNumbersField(buffer, offset, LocationField.attributeIndices, this.attributeIndices, context) return offset } diff --git a/src/protobuf.test.ts b/src/protobuf.test.ts index f6f6e2a..8bbca06 100644 --- a/src/protobuf.test.ts +++ b/src/protobuf.test.ts @@ -5,7 +5,7 @@ */ import { test } from 'node:test' -import assert from 'node:assert' +import assert from 'node:assert/strict' import { EncodeContext, @@ -34,7 +34,7 @@ import { measurePackedFixed64Field, newEncodeContext } from './protobuf.js' -import { Label, LabelInput, Profile, Sample, StringTable, ValueType } from './index.js' +import { Label, LabelInput, Profile, Sample, StringTable, ValueType, emptyTableToken } from './index.js' function hex(buf: Uint8Array) { return Buffer.from(buf).toString('hex') @@ -77,21 +77,88 @@ test('multi-byte tags', async (t) => { } }) -test('fixed64', async (t) => { +test('varint boundaries', async (t) => { const cases: Array<[Numeric, string]> = [ - [1, '0100000000000000'], - [2 ** 53 - 1, 'ffffffffffff1f00'], - [1700000000123456789n, '15cd853dfe9c9717'], - [-1, 'ffffffffffffffff'] + [0, '00'], + [-0, '00'], + [1, '01'], + [0.5, '00'], + [-0.5, '00'], + [NaN, '00'], + [Infinity, '00'], + [-Infinity, '00'], + [127, '7f'], + [127.5, '7f'], + [128, '8001'], + [16383, 'ff7f'], + [16383.5, 'ff7f'], + [16384, '808001'], + [2097151, 'ffff7f'], + [2097151.5, 'ffff7f'], + [2097152, '80808001'], + [268435455, 'ffffff7f'], + [268435455.5, 'ffffff7f'], + [268435456, '8080808001'], + [4294967295, 'ffffffff0f'], + [4294967295.5, 'ffffffff0f'], + [4294967296, '8080808010'], + [2 ** 35 - 1, 'ffffffff7f'], + [2 ** 35, '808080808001'], + [2 ** 42 - 1, 'ffffffffff7f'], + [2 ** 42, '80808080808001'], + [2 ** 49 - 1, 'ffffffffffff7f'], + [2 ** 49, '8080808080808001'], + [Number.MAX_SAFE_INTEGER, 'ffffffffffffff0f'], + [-1, 'ffffffffffffffffff01'], + [-4294967296, '80808080f0ffffffff01'], + [2n ** 56n - 1n, 'ffffffffffffff7f'], + [2n ** 56n, '808080808080808001'], + [2n ** 63n - 1n, 'ffffffffffffffff7f'], + [2n ** 63n, '80808080808080808001'], + [2n ** 64n - 1n, 'ffffffffffffffffff01'], + [-(2n ** 63n), '80808080808080808001'], + [2n ** 64n, '00'], + [2n ** 64n + 1n, '01'], + [-(2n ** 64n) - 1n, 'ffffffffffffffffff01'], + [2n ** 128n + 2n ** 32n, '8080808010'] ] for (const [number, encoded] of cases) { + const values = typeof number === 'number' && Number.isInteger(number) ? [number, BigInt(number)] : [number] + for (const value of values) { + await t.test(`${value} (${typeof value})`, () => { + const sample = new Sample({ value: [value] }) + const buffer = sample.encode() + assert.strictEqual(hex(buffer), '12' + hex(Uint8Array.of(encoded.length / 2)) + encoded) + assert.strictEqual(sample.length, buffer.length) + + const label = new Label({ num: value }) + const expected = value === 0 || value === 0n || Number.isNaN(value) ? '' : '18' + encoded + assert.strictEqual(hex(label.encode()), expected) + assert.strictEqual(label.length, expected.length / 2) + }) + } + } +}) + +test('fixed64', async (t) => { + const cases: Array<[Numeric, string, Numeric]> = [ + [1, '0100000000000000', 1], + [2 ** 53 - 1, 'ffffffffffff1f00', 2 ** 53 - 1], + [1700000000123456789n, '15cd853dfe9c9717', 1700000000123456789n], + [-1, 'ffffffffffffffff', 2n ** 64n - 1n], + [-1n, 'ffffffffffffffff', 2n ** 64n - 1n], + [-(2n ** 63n), '0000000000000080', 2n ** 63n], + [2n ** 64n, '0000000000000000', 0], + [2n ** 96n + 1n, '0100000000000000', 1], + [-(2n ** 64n) - 1n, 'ffffffffffffffff', 2n ** 64n - 1n] + ] + for (const [number, encoded, expected] of cases) { await t.test(`encodes and decodes ${number}`, () => { const buffer = encodeField(measureFixed64Field, encodeFixed64Field, 3, number) assert.strictEqual(hex(buffer), '19' + encoded) const [field, wireType, value] = decodeSingle(buffer) assert.strictEqual(field, 3) assert.strictEqual(wireType, kTypeFixed64) - const expected = number === -1 ? 2n ** 64n - 1n : number assert.strictEqual(decodeFixed64(value), expected) }) } @@ -149,6 +216,23 @@ test('bytes', () => { }) test('message fields', async (t) => { + await t.test('interleaves empty and packed fields with nested messages', async () => { + const profile = new Profile({ + stringTable: new StringTable(emptyTableToken), + sample: [{}, { locationId: [0, 128], value: [0, -1n], label: [{ key: 1 }] }, { value: [1] }], + periodType: {}, + comment: [0, 16384] + }) + const expected = '120012160a03008001120b00ffffffffffffffffff011a02080112031201015a006a0400808001' + assert.strictEqual(hex(profile.encode()), expected) + assert.strictEqual(profile.length, expected.length / 2) + const pending = Promise.all([profile.encodeAsync(), profile.encodeAsync()]) + assert.strictEqual(hex(profile.encode()), expected) + for (const encoded of await pending) { + assert.strictEqual(hex(encoded), expected) + } + }) + await t.test('encodes an empty message that is present', () => { const empty = new ValueType({}) const context = newEncodeContext() diff --git a/src/protobuf.ts b/src/protobuf.ts index f78f182..fd44957 100644 --- a/src/protobuf.ts +++ b/src/protobuf.ts @@ -6,7 +6,6 @@ /* Internal protobuf wire-format helpers shared by the codecs. */ -const lowMaxBig = 2n ** 32n - 1n const lowMax = 2 ** 32 - 1 const lowMaxPlus1 = lowMax + 1 // Largest high 32 bits of a 64-bit integer that still fits in a safe integer. @@ -58,31 +57,27 @@ function decodeSmallNumber(buffer: Uint8Array, start: number, end: number): numb return value } -function lowBits(number: Numeric): number { - return typeof number !== 'bigint' - ? (number >>> 0) % lowMaxPlus1 - : Number(number & lowMaxBig) -} - -function highBits(number: Numeric): number { - return typeof number !== 'bigint' - ? (number / lowMaxPlus1) >>> 0 - : Number(number >> 32n & lowMaxBig) -} - function long(number: Numeric): Array { + if (typeof number === 'bigint') { + return [Number(BigInt.asUintN(32, number >> 32n)), Number(BigInt.asUintN(32, number))] + } + const sign = number < 0 - if (sign) number = -number + if (sign) { + number = -number + } - let lo = lowBits(number) - let hi = highBits(number) + let lo = (number >>> 0) % lowMaxPlus1 + let hi = (number / lowMaxPlus1) >>> 0 if (sign) { hi = ~hi >>> 0 lo = ~lo >>> 0 if (++lo > lowMax) { lo = 0 - if (++hi > lowMax) { hi = 0 } + if (++hi > lowMax) { + hi = 0 + } } } @@ -184,30 +179,39 @@ export function pushAll(values: Array, list?: Array): Array { } export function measureNumber(number: Numeric): number { - if (number === 0 || number === 0n) return 0 - const [hi, lo] = long(number) - - const a = lo - const b = (lo >>> 28 | hi << 4) >>> 0 - const c = hi >>> 24 - - if (c !== 0) { - return c < 128 ? 9 : 10 - } - - if (b !== 0) { - if (b < 16384) { - return b < 128 ? 5 : 6 + let lo: number + if (typeof number === 'number' && number >= 0 && number <= lowMax) { + if (number === 0) { + return 0 + } + lo = number + } else { + if (number === 0n) { + return 0 + } + const words = long(number) + const hi = words[0] + lo = words[1] + if (hi !== 0) { + const c = hi >>> 24 + if (c !== 0) { + return c < 128 ? 9 : 10 + } + const b = (lo >>> 28 | hi << 4) >>> 0 + if (b < 16384) { + return b < 128 ? 5 : 6 + } + return b < 2097152 ? 7 : 8 } - - return b < 2097152 ? 7 : 8 } - if (a < 16384) { - return a < 128 ? 1 : 2 + if (lo < 16384) { + return lo < 128 ? 1 : 2 } - - return a < 2097152 ? 3 : 4 + if (lo < 268435456) { + return lo < 2097152 ? 3 : 4 + } + return 5 } /** @@ -221,18 +225,19 @@ export function varintLength(number: Numeric): number { } export function encodeNumber(buffer: Uint8Array, i: number, number: Numeric): number { - if (number === 0 || number === 0n) { - buffer[i++] = 0 - return i + let lo = number as number + if (typeof number !== 'number' || number < 0 || number > lowMax) { + const words = long(number) + let hi = words[0] + lo = words[1] + while (hi) { + buffer[i++] = lo & 127 | 128 + lo = (lo >>> 7 | hi << 25) >>> 0 + hi >>>= 7 + } } - let [hi, lo] = long(number) - - while (hi) { - buffer[i++] = lo & 127 | 128 - lo = (lo >>> 7 | hi << 25) >>> 0 - hi >>>= 7 - } + lo >>>= 0 while (lo > 127) { buffer[i++] = lo & 127 | 128 lo = lo >>> 7 @@ -256,7 +261,7 @@ export function encodeFixed64(buffer: Uint8Array, i: number, number: Numeric): n } /** - * Submessage lengths for one encode, recorded in length-prefix order and read + * Payload lengths for one encode, recorded in length-prefix order and read * back sequentially to avoid remeasuring. No state is stored on the messages; * the context is passed through measuring and encoding instead. */ @@ -363,16 +368,22 @@ function measurePackedNumbers(values: Numeric[]): number { return total } -export function measurePackedNumbersField(field: number, values: Numeric[]): number { +export function measurePackedNumbersField(field: number, values: Numeric[], context: EncodeContext): number { // Packed arrays are encoded as Tag,Len,ConcatenatedElements const total = measurePackedNumbers(values) - return total ? measureTag(field) + measureNumber(total) + total : 0 + if (!total) { + return 0 + } + context.lengths.push(total) + return measureTag(field) + measureNumber(total) + total } -export function encodePackedNumbersField(buffer: Uint8Array, offset: number, field: number, values: Numeric[]): number { - if (!values.length) return offset +export function encodePackedNumbersField(buffer: Uint8Array, offset: number, field: number, values: Numeric[], context: EncodeContext): number { + if (!values.length) { + return offset + } offset = encodeTag(buffer, offset, field, kTypeLengthDelim) - offset = encodeNumber(buffer, offset, measurePackedNumbers(values)) + offset = encodeNumber(buffer, offset, context.lengths[context.cursor++]) for (const value of values) { offset = encodeNumber(buffer, offset, value) } @@ -435,19 +446,20 @@ export function encodeBytesField(buffer: Uint8Array, offset: number, field: numb /** UTF-8 byte length; lone surrogates become U+FFFD (3 bytes), as in TextEncoder. */ export function utf8Length(string: string): number { - let length = 0 + let length = string.length for (let i = 0; i < string.length; i++) { const code = string.charCodeAt(i) if (code < 0x80) { + continue + } + if (code < 0x800) { length += 1 - } else if (code < 0x800) { + } else if (code >= 0xd800 && code <= 0xdbff && i + 1 < string.length && + (string.charCodeAt(i + 1) & 0xfc00) === 0xdc00) { length += 2 - } else if ((code & 0xfc00) === 0xd800 && (string.charCodeAt(i + 1) & 0xfc00) === 0xdc00) { - // A surrogate pair encodes one code point in 4 bytes - length += 4 i++ } else { - length += 3 + length += 2 } } return length diff --git a/src/string-table.ts b/src/string-table.ts index d099c5b..14a495c 100644 --- a/src/string-table.ts +++ b/src/string-table.ts @@ -10,7 +10,9 @@ import { encodeTag, kTypeLengthDelim, measureTag, + prepareBuffer, toUtf8, + utf8Length, varintLength, } from './protobuf.js' @@ -29,14 +31,31 @@ function encodeLengthDelimited(utf8: Uint8Array | Buffer): Uint8Array { return buffer } +const utf8ByteLength = typeof Buffer === 'undefined' + ? utf8Length + : (value: string) => Buffer.byteLength(value, 'utf8') + +// Writes a string's UTF-8 bytes into `buffer` at `offset` +function utf8Writer(buffer: Uint8Array): (value: string, offset: number) => void { + if (typeof Buffer === 'undefined') { + const encoder = new TextEncoder() + return (value, offset) => { encoder.encodeInto(value, buffer.subarray(offset)) } + } + const view = Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength) + return (value, offset) => { view.write(value, offset, 'utf8') } +} + /** - * The strings of a profile, each encoded once as it is added. The enclosing - * message supplies the field number when it encodes the table, so one table - * type serves both pprof and OTel. + * The strings of a profile. A string's UTF-8 bytes are written straight into + * the output when the table is encoded, so adding a string allocates no + * buffer. The enclosing message supplies the field number when it encodes the + * table, so one table type serves both pprof and OTel. */ export class StringTable { strings = new Array() - #encodings = new Array() + #byteLengths = new Array() + // The bytes of strings read from a profile, which re-encoding reproduces exactly + #decoded = new Array() #positions = new Map() #encodedLength = 0 @@ -54,21 +73,30 @@ export class StringTable { /** Measures the strings as the repeated string field `field`. */ _measure(field: number): number { - return this.#encodings.length * measureTag(field) + this.#encodedLength + return this.#byteLengths.length * measureTag(field) + this.#encodedLength } /** Encodes the strings as the repeated string field `field`. */ _encodeToBuffer(buffer: Uint8Array, offset: number, field: number): number { - for (const encoded of this.#encodings) { + const writeUtf8 = utf8Writer(buffer) + for (let i = 0; i < this.#byteLengths.length; i++) { + const byteLength = this.#byteLengths[i] offset = encodeTag(buffer, offset, field, kTypeLengthDelim) - buffer.set(encoded, offset) - offset += encoded.length + offset = encodeNumber(buffer, offset, byteLength) + const decoded = this.#decoded[i] + if (decoded !== undefined) { + buffer.set(decoded, offset) + } else if (byteLength > 0) { + writeUtf8(this.strings[i], offset) + } + offset += byteLength } return offset } /** Encodes the strings as pprof's string_table. */ - encode(buffer = new Uint8Array(this.encodedLength)): Uint8Array { + encode(buffer?: Uint8Array): Uint8Array { + buffer = prepareBuffer(buffer, this.encodedLength) this._encodeToBuffer(buffer, 0, pprofStringTableField) return buffer } @@ -89,22 +117,23 @@ export class StringTable { if (typeof value === 'number') return value let position = this.#positions.get(value) if (position === undefined) { - position = this.strings.push(value) - 1 - this.#positions.set(value, position) - - // Encode strings on insertion - const encoded = encodeLengthDelimited(toUtf8(value)) - this.#encodings.push(encoded) - this.#encodedLength += encoded.length + position = this.#add(value, utf8ByteLength(value)) } return position } _decodeString(buffer: Uint8Array) { - const value = decodeString(buffer) - this.#positions.set(value, this.strings.push(value) - 1) - const encoded = encodeLengthDelimited(buffer) - this.#encodings.push(encoded) - this.#encodedLength += encoded.length + const position = this.#add(decodeString(buffer), buffer.length) + this.#decoded[position] = buffer.length <= 64 || typeof Buffer === 'undefined' + ? new Uint8Array(buffer) + : Buffer.from(buffer) + } + + #add(value: string, byteLength: number): number { + const position = this.strings.push(value) - 1 + this.#positions.set(value, position) + this.#byteLengths.push(byteLength) + this.#encodedLength += varintLength(byteLength) + byteLength + return position } }