From 30833db87e005e4ef0257eaed728ea569b03c359 Mon Sep 17 00:00:00 2001 From: Jeremias Menichelli Date: Wed, 4 Nov 2026 10:24:19 +0100 Subject: [PATCH] chore: Refactor sync troubleshooting scripts after data reconciliation (#52713) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Problem We solved manually some `troubleshooting_entries` table missing data and mismatches. - **Rows without slugs.** Some `troubleshooting_entries` rows had no slug, so no guide could match them and the guides looked "new". - **Duplicate discussions.** A guide that didn't match its row got a fresh GitHub discussion, leaving the original behind (sometimes with extras). - **Slug mismatch.** The fetch stripped the hash suffix from file names while the table keeps it, so those guides never matched their rows. - **Overlapping runs.** The workflow had no concurrency control, so two runs could both create a discussion for the same guide, and `upsert` silently overwrote the first run's row. - **Missing checksums.** Rows without a checksum counted as "changed" and were re-pushed to GitHub on every run. - **Weak dry run.** `--dry-run` only printed slugs, so it was hard to see what a run would actually do. - **Fragile lookup and duplicated code.** Rows were fetched with every slug in the URL (`.in('slug', …)`), and both scripts carried their own copy of the guide reader and checksum. ## Solution After those steps we applied successfully to the database, we revamp our existing sync scripts to allow dry runs to make sure the changes we apply are going to generate the correct impact. A new improvement to prevent bulk discussion errors on GitHub API. ## Review instructions _Sadly, we need to merge, and pray..._ ## Checklist Check all before review: - [x] I have read [CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md) - [x] If I wrote a new docs topic or edited an existing topic, I used the `/write-the-docs` or `/edit-the-docs` skill, which applies the docs [style guide](https://github.com/supabase/supabase/tree/master/apps/docs/style-guide) --- .github/workflows/kb-troubleshooting-sync.yml | 14 +- apps/kb/AGENTS.md | 10 +- apps/kb/README.md | 4 +- apps/kb/package.json | 1 - .../backfill-legacy-slugs.ts | 63 ---- .../fetch-federated-content.ts | 7 +- .../federated-content/github-throttle.test.ts | 86 +++++ .../federated-content/github-throttle.ts | 59 ++++ .../legacy-troubleshooting-slugs.json | 172 ---------- .../sync-troubleshooting-entries.ts | 312 +++++++++++------- .../sync-troubleshooting-updates.ts | 182 ++++++---- .../troubleshooting-sync-shared.test.ts | 98 ++++++ .../troubleshooting-sync-shared.ts | 175 ++++++++++ 13 files changed, 751 insertions(+), 432 deletions(-) delete mode 100644 apps/kb/scripts/federated-content/backfill-legacy-slugs.ts create mode 100644 apps/kb/scripts/federated-content/github-throttle.test.ts create mode 100644 apps/kb/scripts/federated-content/github-throttle.ts delete mode 100644 apps/kb/scripts/federated-content/legacy-troubleshooting-slugs.json create mode 100644 apps/kb/scripts/federated-content/troubleshooting-sync-shared.test.ts create mode 100644 apps/kb/scripts/federated-content/troubleshooting-sync-shared.ts diff --git a/.github/workflows/kb-troubleshooting-sync.yml b/.github/workflows/kb-troubleshooting-sync.yml index 9103d2278b4..9b987731375 100644 --- a/.github/workflows/kb-troubleshooting-sync.yml +++ b/.github/workflows/kb-troubleshooting-sync.yml @@ -4,11 +4,22 @@ on: push: branches: - master + paths: + - '.github/workflows/kb-troubleshooting-sync.yml' + - 'apps/kb/**' workflow_dispatch: permissions: contents: read +# Overlapping runs (e.g. two quick pushes to master) must not interleave: both +# would see a new guide as "no row yet" and create a discussion for it. Queue, +# never cancel — a run cancelled between creating a discussion and writing its +# row would leave that discussion orphaned. +concurrency: + group: kb-troubleshooting-sync + cancel-in-progress: false + jobs: sync: runs-on: blacksmith-4vcpu-ubuntu-2404 @@ -43,9 +54,6 @@ jobs: - name: Install dependencies run: pnpm install --frozen-lockfile - - name: Backfill legacy troubleshooting slugs - run: pnpm run --filter kb sync:legacy-slugs - - name: Fetch federated troubleshooting content run: pnpm run --filter kb fetch:federated-content diff --git a/apps/kb/AGENTS.md b/apps/kb/AGENTS.md index fa5041cbef5..830fb54f04b 100644 --- a/apps/kb/AGENTS.md +++ b/apps/kb/AGENTS.md @@ -96,6 +96,10 @@ Syncing guides to GitHub Discussions (`scripts/federated-content/sync-troublesho `sync-troubleshooting-updates.ts`) is a separate concern from fetching — see `.github/workflows/kb-troubleshooting-sync.yml` and the README's "Workflows" section. Those scripts are CI-only, never part of `prebuild`. -`backfill-legacy-slugs.ts` is a one-time migration aid for the 278 pre-existing (apps/docs-origin) rows in -`troubleshooting_entries` — safe to delete (with its JSON file, package.json script, and workflow step) once -those rows are all backfilled; see the comment at the top of that file. +How the sync scripts match guides to rows: a guide's key is its file name without the extension, hash suffix +included (`foo-bar-94a76b.mdx` -> `foo-bar-94a76b`), and that exact string is `troubleshooting_entries.slug`. +Never strip or normalize it — a slug that doesn't match makes a guide look new and creates a duplicate +discussion. Both scripts take `--dry-run` (read-only: prints the discussions/rows they would create or update). +`sync-troubleshooting-entries.ts` also refuses to create a discussion whose title already exists in the category +without a slugged row, and the workflow's `concurrency` group keeps runs from overlapping. Shared logic +(including the checksum definition) lives in `troubleshooting-sync-shared.ts`. diff --git a/apps/kb/README.md b/apps/kb/README.md index 0024c25880a..07ee8c67b12 100644 --- a/apps/kb/README.md +++ b/apps/kb/README.md @@ -53,8 +53,8 @@ and is gitignored. See `AGENTS.md` for how it works and what's intentionally lef ## Workflows -`.github/workflows/kb-troubleshooting-sync.yml` runs on every push to `master`: it fetches troubleshooting -content, creates a GitHub Discussion for any guide that doesn't have one yet +`.github/workflows/kb-troubleshooting-sync.yml` runs on pushes to `master` that touch `apps/kb/**` (or can be +triggered manually): it fetches troubleshooting content, creates a GitHub Discussion for any guide that doesn't have one yet (`sync:troubleshooting-entries`), and pushes title/content updates to discussions whose guide has since changed (`sync:troubleshooting-updates`). This is separate from kb's own build — it has real side effects (creating/updating Discussions, writing DB rows), so it never runs as part of `pnpm build`/`prebuild`. diff --git a/apps/kb/package.json b/apps/kb/package.json index 98251f5e0ba..c6d8b285846 100644 --- a/apps/kb/package.json +++ b/apps/kb/package.json @@ -13,7 +13,6 @@ "generate:markdown": "tsx ./scripts/generate-markdown.ts", "presearch:ingest": "pnpm run fetch:federated-content && pnpm run generate:markdown", "search:ingest": "tsx ./scripts/search/ingest.ts", - "sync:legacy-slugs": "tsx ./scripts/federated-content/backfill-legacy-slugs.ts", "sync:troubleshooting-entries": "tsx ./scripts/federated-content/sync-troubleshooting-entries.ts", "sync:troubleshooting-updates": "tsx ./scripts/federated-content/sync-troubleshooting-updates.ts", "preview": "astro preview", diff --git a/apps/kb/scripts/federated-content/backfill-legacy-slugs.ts b/apps/kb/scripts/federated-content/backfill-legacy-slugs.ts deleted file mode 100644 index db62d761fb8..00000000000 --- a/apps/kb/scripts/federated-content/backfill-legacy-slugs.ts +++ /dev/null @@ -1,63 +0,0 @@ -// One-time migration aid: troubleshooting_entries has 278 rows pre-dating kb -// (apps/docs' own discussions), all with slug = NULL. legacy-troubleshooting-slugs.json -// maps each row's id (docs' own `database_id` frontmatter field) to the slug -// of the docs content file it came from, extracted once from -// apps/docs/content/troubleshooting/*.mdx (that content isn't checked out by -// this workflow and doesn't need to be — these ids never change). -// -// Stored as the bare slug, not prefixed: as these files get migrated into the -// federated supabase/troubleshooting repo under the same slug, sync-troubleshooting-entries.ts -// needs to match them by slug against these rows' existing github_url — otherwise -// it treats the guide as new and creates a duplicate discussion, orphaning the -// original (with its comments and links). -// -// Delete this file, legacy-troubleshooting-slugs.json, its package.json script, -// and its workflow step once all legacy rows are backfilled — safe to remove -// as a unit, nothing else depends on it. -import '../utils/dotenv.js' - -import { createClient } from '@supabase/supabase-js' - -import legacySlugs from './legacy-troubleshooting-slugs.json' with { type: 'json' } - -const DRY_RUN = process.argv.includes('--dry-run') - -async function backfillLegacySlugs() { - if (DRY_RUN) { - for (const [databaseId, slug] of Object.entries(legacySlugs)) { - console.log(` - ${databaseId} -> ${slug}`) - } - return - } - - const db = createClient( - process.env.SUPABASE_URL as string, - process.env.SUPABASE_SERVICE_ROLE_KEY as string - ) - - let backfilled = 0 - let alreadyDone = 0 - - for (const [databaseId, slug] of Object.entries(legacySlugs)) { - // .is('slug', null) makes this idempotent/concurrency-safe: a duplicate - // run updates 0 rows instead of racing. - const { data, error } = await db - .from('troubleshooting_entries') - .update({ slug }) - .eq('id', databaseId) - .is('slug', null) - .select('id') - if (error) throw error - - if (data.length > 0) backfilled++ - else alreadyDone++ - } - - console.log( - `[backfill-legacy-slugs] Backfilled ${backfilled}, already done ${alreadyDone}, total ${Object.keys(legacySlugs).length}.` - ) -} - -backfillLegacySlugs().catch((error) => { - throw error -}) diff --git a/apps/kb/scripts/federated-content/fetch-federated-content.ts b/apps/kb/scripts/federated-content/fetch-federated-content.ts index 5ac9d4f6383..9a5ce24bb15 100644 --- a/apps/kb/scripts/federated-content/fetch-federated-content.ts +++ b/apps/kb/scripts/federated-content/fetch-federated-content.ts @@ -57,10 +57,11 @@ async function getFileContents(path: string): Promise { return Buffer.from(response.data.content, 'base64').toString('utf-8') } -// Local slug: strip the extension and the random hex suffix some filenames -// carry (e.g. `foo-bar-94a76b.mdx` -> `foo-bar`). +// Local slug: the filename without its extension. The hash suffix some +// filenames carry (e.g. `foo-bar-94a76b.mdx` -> `foo-bar-94a76b`) is part of +// the slug and is kept, matching what troubleshooting_entries.slug stores. function slugFromFilename(filename: string): string { - return filename.replace(/\.mdx?$/, '').replace(/-[0-9a-f]{6}$/i, '') + return filename.replace(/\.mdx?$/, '') } // Most source files use TOML frontmatter (`title = "..."`), which gray-matter diff --git a/apps/kb/scripts/federated-content/github-throttle.test.ts b/apps/kb/scripts/federated-content/github-throttle.test.ts new file mode 100644 index 00000000000..96c7999c763 --- /dev/null +++ b/apps/kb/scripts/federated-content/github-throttle.test.ts @@ -0,0 +1,86 @@ +import { describe, expect, it, vi } from 'vitest' + +import { createPacer, isRateLimitError, readMinIntervalMs } from './github-throttle.ts' + +const requestError = (status: number, message = 'error', headers: Record = {}) => + Object.assign(new Error(message), { status, response: { headers } }) + +describe('isRateLimitError', () => { + it('recognizes a secondary rate limit 403 by its message', () => { + expect(isRateLimitError(requestError(403, 'You have exceeded a secondary rate limit'))).toBe( + true + ) + }) + + it('recognizes a 403 carrying Retry-After or an exhausted quota', () => { + expect(isRateLimitError(requestError(403, 'Forbidden', { 'retry-after': '30' }))).toBe(true) + expect(isRateLimitError(requestError(403, 'Forbidden', { 'x-ratelimit-remaining': '0' }))).toBe( + true + ) + }) + + it('recognizes any 429', () => { + expect(isRateLimitError(requestError(429))).toBe(true) + }) + + it('recognizes a GraphQL RATE_LIMITED response error', () => { + const error = Object.assign(new Error('API rate limit already exceeded'), { + errors: [{ type: 'RATE_LIMITED' }], + headers: {}, + }) + + expect(isRateLimitError(error)).toBe(true) + }) + + it('does not treat other failures as rate limits', () => { + expect(isRateLimitError(requestError(403, 'Resource not accessible by integration'))).toBe( + false + ) + expect(isRateLimitError(requestError(404))).toBe(false) + expect(isRateLimitError(requestError(502))).toBe(false) + expect(isRateLimitError(new TypeError('fetch failed'))).toBe(false) + expect(isRateLimitError('boom')).toBe(false) + expect(isRateLimitError(null)).toBe(false) + }) +}) + +describe('createPacer', () => { + it('waits out the remainder of the minimum interval between calls', async () => { + let clock = 1_000 + const sleep = vi.fn(async (ms: number) => { + clock += ms + }) + const pace = createPacer(2_000, { now: () => clock, sleep }) + + await pace() // the first call never waits + clock += 500 + await pace() + + expect(sleep).toHaveBeenCalledTimes(1) + expect(sleep).toHaveBeenCalledWith(1_500) + }) + + it('does not wait when the interval has already passed', async () => { + let clock = 0 + const sleep = vi.fn(async () => {}) + const pace = createPacer(2_000, { now: () => clock, sleep }) + + await pace() + clock += 5_000 + await pace() + + expect(sleep).not.toHaveBeenCalled() + }) +}) + +describe('readMinIntervalMs', () => { + it('defaults to 2s', () => { + expect(readMinIntervalMs(['node', 'script'])).toBe(2000) + }) + + it('reads --delay-ms and ignores invalid values', () => { + expect(readMinIntervalMs(['--delay-ms=5000'])).toBe(5000) + expect(readMinIntervalMs(['--delay-ms=abc'])).toBe(2000) + expect(readMinIntervalMs(['--delay-ms=-1'])).toBe(2000) + }) +}) diff --git a/apps/kb/scripts/federated-content/github-throttle.ts b/apps/kb/scripts/federated-content/github-throttle.ts new file mode 100644 index 00000000000..f29e4c7c213 --- /dev/null +++ b/apps/kb/scripts/federated-content/github-throttle.ts @@ -0,0 +1,59 @@ +// Pacing for the sync's GitHub GraphQL mutations. GitHub rate-limits content +// creation, so createPacer() keeps a minimum gap between mutations and +// isRateLimitError() lets the scripts stop cleanly if the limit is hit anyway. +// Mutations are never retried: a retry after a timeout could create a second +// discussion (callers pass `request: { retries: 0 }` to disable the plugin's). + +export const DEFAULT_MIN_INTERVAL_MS = 2000 + +const realSleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)) + +/** Resolves once `minIntervalMs` has passed since the previous call resolved. */ +export function createPacer( + minIntervalMs: number, + { + now = Date.now, + sleep = realSleep, + }: { now?: () => number; sleep?: (ms: number) => Promise } = {} +): () => Promise { + let lastAt = Number.NEGATIVE_INFINITY + return async () => { + const wait = lastAt + minIntervalMs - now() + if (wait > 0) await sleep(wait) + lastAt = now() + } +} + +type GitHubErrorLike = { + status?: number + message?: string + response?: { headers?: Record } // RequestError + headers?: Record // GraphqlResponseError + errors?: Array<{ type?: string }> +} + +/** A GraphQL RATE_LIMITED error, any 429, or a 403 that signals rate limiting. */ +export function isRateLimitError(error: unknown): boolean { + if (typeof error !== 'object' || error === null) return false + const e = error as GitHubErrorLike + + if (e.errors?.some((err) => err.type === 'RATE_LIMITED')) return true + if (e.status === 429) return true + if (e.status !== 403) return false + + const headers = e.response?.headers ?? e.headers ?? {} + return ( + /rate limit|abuse detection/i.test(e.message ?? '') || + Number.isFinite(Number(headers['retry-after'])) || + String(headers['x-ratelimit-remaining']) === '0' + ) +} + +/** `--delay-ms=3000` overrides the minimum gap between mutations. */ +export function readMinIntervalMs(argv: string[] = process.argv): number { + const raw = argv.find((arg) => arg.startsWith('--delay-ms='))?.split('=')[1] + const parsed = Number(raw) + return raw !== undefined && Number.isFinite(parsed) && parsed >= 0 + ? parsed + : DEFAULT_MIN_INTERVAL_MS +} diff --git a/apps/kb/scripts/federated-content/legacy-troubleshooting-slugs.json b/apps/kb/scripts/federated-content/legacy-troubleshooting-slugs.json deleted file mode 100644 index bee60c2b163..00000000000 --- a/apps/kb/scripts/federated-content/legacy-troubleshooting-slugs.json +++ /dev/null @@ -1,172 +0,0 @@ -{ - "97923126-7d0b-4bf0-bb65-55dae289a8a3": "42501--permission-denied-for-table-httprequestqueue-KnozmQ", - "ba593989-12b5-464f-8ede-a525e1ca2ffb": "all-about-supabase-egress-a_Sg_e", - "7183351e-dba3-484d-83b3-bb89a027e36a": "an-invalid-response-was-received-from-the-upstream-server-error-when-querying-auth-RI4Vl-", - "ce8c04e4-d493-4e15-832a-e59bdcf2b093": "app-store-rejection-tls-error-in-ipv6-only-environments-4e9c62", - "03854567-8838-4f12-8a6c-095fc1671d9f": "are-all-features-available-in-self-hosted-supabase-THPcqw", - "e90ca9e0-0376-4313-b32b-b9a4ae81bf7a": "auth-error-401-invalid-claim-missing-sub--AFwMR", - "c1de4561-e95f-41e3-b298-fac9ae331a54": "auth-hooks-invalid-payload-when-anonymous-users-attempt-phone-changes-022c47", - "a931b8af-3210-4188-bb03-87452923a498": "autovacuum-stalled-due-to-inactive-replication-slot-d55aa2", - "8bb130d5-d298-49c7-8cfb-dd7a3f231154": "avoiding-timeouts-in-long-running-queries-6nmbdN", - "4a41e734-6883-452f-bc8e-82ff4ac22a81": "canceling-statement-due-to-statement-timeout-581wFv", - "f7f2d68b-f336-4578-9541-17ca37aaa327": "cant-access-supabase-project-lovable-cloud", - "df9518df-d019-42bb-8d91-918c6d57b452": "certain-operations-are-too-complex-to-perform-directly-using-the-client-libraries-8JaphH", - "6de3c3a9-8614-48d7-827e-cf41d6a1ce23": "change-email-associated-with-supabase-account-T5eHNT", - "fd711d33-9703-402f-84b2-8e74034e7690": "change-project-region-eWJo5Z", - "1759134d-a98d-4bfa-9501-71e06180700e": "check-usage-for-monthly-active-users-mau-MwZaBs", - "a60ee728-3add-438d-b8bf-433f1746cb3e": "cloudflare-origin-error-1016-on-custom-domain-a57af4", - "94c6e33b-cc05-49b3-b010-7480f8dde843": "converted-github-account-to-organisation---lost-supabase-account-access-5wsE_1", - "2ebc2849-0cf7-4c94-ac13-22167a196a92": "customizing-emails-by-language-KZ_38Q", - "c5d8260b-c17a-4f6c-ab20-801f953f6c94": "dashboard-errors-when-managing-users-N1ls4A", - "49b51a3a-9753-4747-a24e-8afcb075792b": "database-api-42501-errors", - "b3a73631-0b8d-460d-8033-28df88d26d75": "database-error-remaining-connection-slots-are-reserved-for-non-replication-superuser-connections-3V3nIb", - "5d1c44ed-b2f6-4509-9312-1eeb8838e701": "database-error-saving-new-user-RU_EwB", - "58c0cb7c-50a0-4a96-9551-bc97c28b7393": "deprecated-rls-features-Pm77Zs", - "04801b69-e7eb-4f40-8d41-81110397bbc2": "disabling-prepared-statements-qL8lEL", - "188986c9-019d-4f26-baaf-6f58cec8fa7a": "discovering-and-interpreting-api-errors-in-the-logs-7xREI9", - "1e02e989-fc12-4838-b304-c7d1356f6d2c": "do-i-need-to-expose-security-definer-functions-in-row-level-security-policies-iI0uOw", - "91ae4c49-bf22-4b8c-b96b-cd11f1c38158": "download-logical-backups", - "a3cfff33-d640-4395-99bc-a110b7fb637c": "edge-function-404-error-response", - "4e6ff2e4-2abb-4fba-8233-5883b3d56fb0": "edge-function-546-error-response", - "aaf9e673-64ae-460a-88e0-b83ea4963382": "edge-function-bundle-size-issues", - "1765884f-81d6-415a-a78f-7085f7b7ddbf": "edge-function-cpu-limits", - "e079a9d0-419a-4e31-b7ec-1206d9012d0b": "edge-function-dependency-analysis", - "30b3f7a4-a2b7-4430-8176-31aa4d92b2e9": "edge-function-fails-deploy", - "33e8e407-951b-4f7d-b8b4-8e9085cd4d10": "edge-function-monitoring-resource-usage", - "109b964f-c28c-4554-b059-cd8b165c63f8": "edge-function-shutdown-reasons-explained", - "89b868a9-17fe-4c6d-86f6-0b04e5794678": "edge-function-takes-too-long-to-respond", - "5a3a0125-84c7-463b-a886-ca53edfba5f4": "edge-function-wall-clock-time-limit-reached-Nk38bW", - "f988e832-b0c3-4b30-8e20-8d5854943b32": "email-password-login-disabled-supabase-vercel-marketplace-a7dd36", - "47c4e2c7-0ff3-48e7-8c8a-912494ff8c24": "email-template-not-updating", - "02f5f200-3c1c-425e-945f-b80b3fce3ec0": "enabling-ipv4-addon", - "9d8b179c-ff4d-4072-b9e6-2d16e63b2aaa": "error-connection-refused-when-trying-to-connect-to-supabase-database-hwG0Dr", - "da3aa582-b115-44e2-97e3-9ab76206f0db": "error-index-row-size-exceeds-btree-version-4-maximum-for-index-LMmoeU", - "12128731-0af6-4c57-9aa2-66e177f0c3f4": "error-invalid-byte-sequence-for-encoding-utf8-0x00-when-accessing-triggers-or-webhooks-e78cf8", - "58d5a2de-2f7e-45fc-8dfa-7fb36da41ca8": "error-invalid-totp-code-entered-CukLCj", - "0739256c-1b25-46ec-963b-2f8e4dccedc7": "error-no-pghbaconf-entry-for-host-xxxxxxxxxxx-user-postgres-database-postgres-ssl-off-GOt5Ja", - "8688dad6-3dce-4912-9b90-4f128daf79d7": "error-prepared-statement-xxx-already-exists-3laqeM", - "6083c9eb-b9fc-4d19-bc64-bb4b7efeecdd": "error-target-organization-is-not-managed-by-vercel-marketplace-during-project-transfer-5262c3", - "4844905d-1456-44a1-858e-7a4995e5054c": "exhaust-disk-io", - "a589d411-ee50-455a-892e-526914ddb40d": "exhaust-ram", - "2db43a09-792b-484b-b97d-5d96a405b525": "exhaust-swap", - "23c4e1b5-c7e7-497f-acf8-006133e243a4": "failed-to-fetch-in-dashboard-and-other-areas----browser-extension-dyDTRU", - "aa5fda82-5838-4975-b0ac-ba4d7fb9e638": "failed-to-restore-from-backup-all-subscriptions-and-replication-slots-must-be-dropped-before-a-backup-can-be-restored-L-rCvt", - "095da77f-b97f-455c-88d1-b6a0341452b1": "failed-to-retrieve-tables", - "7529ca12-114b-485c-9b64-bca3b2dc744b": "failed-to-run-sql-query-connection-terminated-due-to-connection-timeout", - "6f19b113-09cb-45ce-8141-0d6dc10ea464": "fetch-requests-to-api-endpoints-arent-showing-the-session-UbUwRs", - "6ec0c9a3-b52b-49b9-ba6e-c91984f7f9bf": "fixing-520-errors-in-the-database-rest-api-Ur5-B2", - "b095c3ed-23e7-4a17-9e33-d811af25ba67": "forbidden-resource-error-from-the-cli-L6rm6l", - "2c33968e-26c0-4613-aee1-5de36d068394": "get-detailed-storage-metrics-with-the-aws-cli-587a7d", - "1ea7b605-dc1d-43d8-a365-5bc2801dd90e": "google-auth-fails-for-some-users-XcFXEu", - "76a4099e-450f-4b5b-a539-224760348c18": "grafana-not-displaying-data-sXJrMj", - "23668386-7a72-44ff-a412-4cd8a005fa18": "high-cpu-and-slow-queries-with-error-must-be-a-superuser-to-terminate-superuser-process", - "3d1bb799-453f-4a6c-9fdc-056f15bec88c": "high-cpu-usage", - "a715c0d3-8636-41b7-a6da-6d49f1b1777c": "high-latency-with-supabase-client-z0pZzR", - "b7edb30b-beee-40ae-9b4f-666ef6411bb6": "how-can-i-revoke-execution-of-a-postgresql-function-2GYb0A", - "74972531-f2fc-4d68-a745-21f9c75761e6": "how-do-i-check-gotrueapi-version-of-a-supabase-project-lQAnOR", - "cdaa76a4-3e5b-4c8f-82f0-b713c4cf19ab": "how-do-i-make-the-cookies-httponly-vwweFx", - "6e4a515c-5e70-4b92-808c-f076d47d4e35": "how-do-i-reset-my-supabase-database-password-oTs5sB", - "dfefd00c-31d8-4969-86a4-03d586110f4c": "how-do-i-update-connection-pool-settings-in-my-dashboard-wAxTJ_", - "4017d331-0b24-439a-9231-793801395ca2": "how-do-you-troubleshoot-nextjs---supabase-auth-issues-riMCZV", - "cc852935-510f-4beb-9f70-b4582505a863": "how-long-does-it-take-to-restore-a-database-from-a-point-in-time-backup-pitr-qO8gOG", - "e7671f20-2639-442e-9df9-4f6fa3766598": "how-postgres-chooses-which-index-to-use-_JHrf4", - "6f6a34a6-ac3f-4fba-9c70-4f4b8c7aeda7": "how-to-bypass-cooldown-period", - "78f06ca5-6a69-4536-89fc-ed2e6ff334e5": "how-to-change-max-database-connections-_BQ8P5", - "990ed738-2e00-42ce-9892-77c16f870cdc": "how-to-check-if-my-queries-are-being-blocked-by-other-queries-NSKtR1", - "085d7649-0b5d-4c3c-b6a1-f2da4b9f33dd": "how-to-delete-a-role-in-postgres-8-AvxY", - "aafe6f52-de09-44ec-b329-1bbbf26146dd": "how-to-delete-vercel-linked-projects-9d08aa", - "8b000bb4-180b-4a6c-b280-ba02965060f6": "how-to-interpret-and-explore-the-postgres-logs-OuCIOj", - "273b79ad-b8ff-4669-8544-b99920e2d3c8": "how-to-migrate-from-supabase-auth-helpers-to-ssr-package-5NRunM", - "da2d95e5-abc5-47c8-8389-1554d12abf91": "how-to-view-database-metrics-uqf2z_", - "e9fb853f-a37f-442a-b180-4aefd234a385": "http-api-issues", - "b98c7288-8c38-4dc2-8591-d18ea9eb4cbc": "http-status-codes", - "ec816bde-1a27-461f-89ef-211e96810dd9": "i-am-not-receiving-password-reset-emails-for-supabase-dashboard--cO5yf", - "37244f4a-cf99-4b1d-b7f2-ee70c3a126ab": "identify-lovable-cloud-or-supabase-backend", - "225cb141-f442-47cf-834d-1d82d703748a": "importing-stripe-or-other-modules-from-esmsh-on-deno-edge-functions-throws-an-error-TmbB5p", - "7d755701-747f-4c3a-b8be-236c5518e4eb": "increase-vector-lookup-speeds-by-applying-an-hsnw-index-ohLHUM", - "a1156bbe-289e-4462-a32d-2b0ca03691e4": "inserting-into-sequenceserial-table-causes-duplicate-key-violates-unique-constraint-error-pi6DnC", - "f47c9b0e-f537-4908-8d35-5dd3dc4c5627": "inspecting-edge-function-environment-variables-wg5qOQ", - "1da315be-38ac-487a-b178-f865a1a73c09": "insufficient-privilege-when-accessing-pgstatstatements-e5M_EQ", - "ef05da0a-f8bc-44a4-9719-5ae811dba104": "interpreting-supabase-grafana-cpu-charts-9JSlkC", - "0056cd40-df04-4045-bbfb-c245cb15b85d": "interpreting-supabase-grafana-io-charts-MUynDR", - "1cff12df-7ad6-48c5-b518-5ea468b54bab": "issues-serving-edge-functions-locally", - "362840be-a99c-4a98-bf4b-6e44a399af12": "jwt-expired-error-in-supabase-dashboard-F06k3x", - "449482fb-6e21-4a25-99ee-1ce6fffbc975": "keeping-free-projects-after-pro-upgrade-Kf9Xm2", - "60bd4a35-fc2e-4e42-bcf6-a430d380c930": "lost-accessforgot-the-mfa-device-nAPT-7", - "f6420e72-ea67-4825-b3f7-e722ea5c0d96": "manually-created-databases-are-not-visible-in-the-supabase-dashboard-4415aa", - "43b62743-252c-4069-a719-0c0737839fd9": "memory-and-swap-usage-explained-aPNgm0", - "7bd3de18-a4ab-4b76-85e4-b72924dacd2a": "migrating-auth-users-between-projects", - "bdd39473-ae02-41f5-b75d-877a79f361f6": "monitor-supavisor-postgres-connections", - "c5dae428-8dd0-4879-b312-df7f7da25986": "new-branch-doesnt-copy-database", - "f5cabb97-aae3-4fb5-b597-4e7857821753": "new-variable-is-null-in-a-trigger-function--l9AOZ", - "9be3727b-c3ea-4dda-b30c-55f3c8aa8f35": "nextjs-1314-stale-data-when-changing-rls-or-table-data-85b8oQ", - "a1bb1131-dd11-4a76-8a70-98a666c08286": "no-toast-messages-on-the-dashboard-BrvP8h", - "98e3b318-ad9a-41f5-ada0-44b61970ab4f": "not-receiving-auth-emails-from-the-supabase-project-OFSNzw", - "3e9246cb-d592-4051-93c8-53e4e555711c": "oauth-sign-in-isnt-redirecting-on-the-server-side-ShGMtr", - "25eddb73-3cca-485b-b87f-7279dd46b7a7": "otp-verification-failures-token-has-expired-or-otp_expired-errors-5ee4d0", - "3142f418-028e-4ab1-8f82-a7096be90422": "partitioning-an-existing-table-with-same-name-VEnbzK", - "76b2e2b6-8f1d-448a-a3dd-cdf68755d1a9": "pausing-pro-projects-vNL-2a", - "0d3389c0-5e75-473c-a18b-0699d0911fb2": "performing-administration-tasks-on-the-server-side-with-the-servicerole-secret-BYM4Fa", - "c000b4ea-23e2-4e19-af54-63ccd00c4904": "pg_cron-launcher-crashes-with-duplicate-key-value-violates-unique-constraint-cc6472", - "9a55c946-877f-46ae-8b57-51934e02a36c": "pgcron-debugging-guide-n1KTaz", - "91dda1aa-52f7-4a1c-9248-92fad9f3dec7": "pgrst106-the-schema-must-be-one-of-the-following-error-when-querying-an-exposed-schema", - "f9f9842b-e66c-4ea3-a45b-713895d8b7c6": "pkce-flow-errors-cannot-parse-response-or-zgotmplz-in-magic-link-emails-433665", - "c3481097-1a32-4e94-b4f6-7aeb88132a41": "postgrest-not-recognizing-new-columns-or-functions-bd75f5", - "28d842fd-8ba3-46f0-a307-082d946e0d94": "prisma-error-management-Cm5P_o", - "357e90d6-58a7-4347-a6c0-00622fcf9c81": "project-status-reports-unhealthy-services", - "0dab3e43-2ba9-4421-9af3-b97e45123069": "rclone-error-s3-protocol-error-received-listing-v1-with-istruncated-set-no-nextmarker-and-no-contents-e64d34", - "01e0dd67-5208-4e65-b489-2afd5a0b2af3": "realtime-concurrent-peak-connections-quota-jdDqcp", - "b99fac0e-09da-4a31-93a1-6375ed8ce041": "realtime-connections-timed_out-status", - "4112ff74-dd74-4003-9f4f-479590afed3c": "realtime-debugging-with-logger", - "b826b34a-f7c0-405e-a836-54c543198964": "realtime-handling-silent-disconnections-in-backgrounded-applications-592794", - "e882c2a2-b04c-48d3-9aae-615ec3458477": "realtime-heartbeat-messages", - "3f5acb57-2ccd-4bd7-86c2-df8e23fe2685": "realtime-project-suspended-for-exceeding-quotas", - "dee93cc3-0ab1-4101-8ad4-31d8682c8844": "realtime-too-many-channels-error", - "027fba24-c7bc-4c54-9e6b-6f13ec85ad56": "realtime-warn-sending-broadcast-message", - "b76ac13f-db24-4d19-9d00-af60c978cd26": "refresh-postgrest-schema", - "72e93bc8-597d-4c72-8d86-4997679196fd": "resolving-42p01-relation-does-not-exist-error-W4_9-V", - "031ba6d7-4928-4d95-a2da-bff8dbb740ec": "resolving-500-status-authentication-errors-7bU5U8", - "c89147f8-a66a-4c04-a1a7-45442fd7f2ee": "resolving-database-hostname-and-managing-your-ip-address-pVlwE0", - "bb06ff88-e0a9-41bc-b00b-9afde10468a5": "rls-performance-and-best-practices-Z5Jjwv", - "5b8a5115-f81a-4a1f-bcc3-fdc2a2672e80": "rls-simplified-BJTcS8", - "caa72a34-696c-47c6-8976-e50cf7fb396e": "rotating-anon-service-and-jwt-secrets-1Jq6yd", - "1d62cace-c0f6-47a0-8690-002a797da33b": "running-explain-analyze-on-functions", - "02a26b95-3029-49a1-9319-161cf1c4c21d": "scan-error-on-column-confirmation_token-converting-null-to-string-is-unsupported-during-auth-login-a0c686", - "46bab0a2-9780-4e4f-99f5-fcc9fa51c496": "security-of-anonymous-sign-ins-iOrGCL", - "9faf3ed3-d373-41c8-a083-ccc83dfc16d7": "seeing-no-pghbaconf-entry-for-host-errors-in-postgres-and-they-come-from-an-ip-address-that-i-dont-recognize-4gds9f", - "e51bedf0-cdc4-4880-865b-e39c06dfe497": "should-i-set-a-shorter-max-age-parameter-on-the-cookies-8sbF4V", - "571d4ad9-b596-44bc-b8a4-a3115b862436": "slow-execution-of-alter-table-on-large-table-when-changing-column-type-qmZRpZ", - "c1ca57fb-91ab-4526-987b-65106dc63a2f": "soft-deletes-with-supabase-js", - "37d147df-caa7-4b0b-82b5-eab6852f2cff": "sso-error-you-do-not-have-permissions-to-join-this-organization-or-prompts-to-create-new-organization", - "fb1cbd42-e172-44b2-af2b-fda5aecde5c2": "steps-to-improve-query-performance-with-indexes-q8PoC9", - "f27145c7-0ff5-4621-a364-5d5704bce0ff": "supabase--your-network-ipv4-and-ipv6-compatibility-cHe3BP", - "4a32736f-1d7f-4c41-9c96-ab84e35ad394": "supabase-cli-failed-sasl-auth-or-invalid-scram-server-final-message", - "9d3377c9-fa79-4734-9fa9-8ccc99415f7f": "supabase-dashboard-not-loading-project-not-loading-on-dashboard-LfMq9F", - "179d70f3-1e26-4346-9ee8-d340fad382a3": "supabase-grafana-memory-charts", - "d64f5f5d-ef80-4423-ba24-1a79b4e69ce6": "supabase-project-provisioned-via-bolt-not-visible-in-dashboard-7188fc", - "3b52daf2-d78d-4630-8e9f-8bf5d90208bf": "supabase-storage-inefficient-folder-operations-and-hierarchical-rls-challenges-b05a4d", - "e008e056-453d-44b5-8a8a-27c2d70681fe": "supavisor-and-connection-terminology-explained-9pr_ZO", - "f252ba39-e540-462b-868f-42eb31a5d40c": "supavisor-faq-YyP5tI", - "83446166-2539-44ce-bde5-9252ce59d2e3": "transfer-edge-function-from-one-project-to-another", - "c6b6ae3c-1b5b-4ba8-a40f-5f2ca1f007e2": "transferring-from-cloud-to-self-host-in-supabase-2oWNvW", - "cd298838-6f13-4b70-a198-a8bd26b2c0bd": "unable-to-call-edge-function", - "68bb6df6-6a07-40fa-ad4d-dfa5e21d7e9c": "unable-to-deploy-edge-function", - "0ce5b1e4-bd0a-439e-9fb1-8e27bad2ef10": "understanding-postgresql-explain-output-Un9dqX", - "10186830-8cce-4f10-8cb9-7cbf39310763": "understanding-postgresql-logging-levels-and-how-they-impact-your-project-KXiJRm", - "f379a628-6821-40b0-9793-4bf819b8c085": "understanding-the-usage-summary-on-the-dashboard-D7Gnle", - "e3ad9b0e-0533-444b-a998-c8e65171b529": "unused-external-import-warning-vite-rollup", - "3b0aa0f2-9608-4691-94d6-4fca8a32130e": "upload-file-size-restrictions-Y4wQLT", - "4d5390a0-445d-4e0a-ae7e-9b713b7cc4f6": "using-google-smtp-with-supabase-custom-smtp-ZZzU4Y", - "da4efcda-cd02-4001-965b-f0294300152f": "using-sqlalchemy-with-supabase-FUqebT", - "a5524182-9dc4-4470-86fe-45ace109a53a": "webhook-debugging-guide-M8sk47", - "d4b45e90-9c52-4781-8cc2-d936e8f4edeb": "why-am-i-being-redirected-to-the-wrong-url-when-using-auth-redirectto-option-_vqIeO", - "0c0369db-2968-4ea7-9f99-c5f5ce55acad": "why-are-there-gaps-in-my-postgres-id-sequence-Frifus", - "8abd4a38-041b-4620-95af-53673f698dea": "why-cant-i-uploadlistetc-my-public-bucket-Z6CmGt", - "f85935d8-e871-4463-8288-f118f4e24afd": "why-do-i-see-auth--api-requests-in-the-dashboard-my-app-has-no-users-CyadiO", - "9dbcf760-7b1f-4cc4-8653-4e884fd02dad": "why-is-my-camelcase-name-not-working-in-postgres-functions-or-rls-policies-EJMzVd", - "6fa68831-6db8-4836-a1b4-e9e51296d529": "why-is-my-select-returning-an-empty-data-array-and-i-have-data-in-the-table-xvOPgx", - "677f0a69-e454-4718-ad92-91053d40c085": "why-is-my-service-role-key-client-getting-rls-errors-or-not-returning-data-7_1K9z", - "0a6f6d33-7331-4b47-87ec-7ade7a6a5924": "why-is-my-supabase-api-call-not-returning-PGzXw0", - "99b56e92-62f2-4602-8e13-d38caf7aff4c": "why-supabase-edge-functions-cannot-provide-static-egress-ips-for-whitelisting-3d78b0", - "fa5bb840-a5ac-447f-b9bb-e319cbe0797e": "will-backups-be-accessible-from-the-dashboard-immediately-after-upgrading-to-a-paid-plan-hXY4rs" -} diff --git a/apps/kb/scripts/federated-content/sync-troubleshooting-entries.ts b/apps/kb/scripts/federated-content/sync-troubleshooting-entries.ts index d577053c0a9..9c863783d74 100644 --- a/apps/kb/scripts/federated-content/sync-troubleshooting-entries.ts +++ b/apps/kb/scripts/federated-content/sync-troubleshooting-entries.ts @@ -1,47 +1,48 @@ -// Creates a GitHub Discussion for every troubleshooting guide that doesn't -// have a troubleshooting_entries row yet. Run after fetch-federated-content.ts, -// from CI only (never kb's own prebuild — this has real side effects). Pass -// --dry-run to log what would be created without creating anything. +// Creates a GitHub Discussion for every guide with no troubleshooting_entries +// row yet, and inserts the row (slug, github_id, github_url, checksum). Guides +// are matched to rows by exact slug. Run after fetch-federated-content.ts, +// from CI only. +// +// Duplicate guards: +// - A new guide whose title already belongs to an unreferenced discussion, +// or to a slug-less row, is reported instead of created. +// - The row is inserted, not upserted: if it already exists (e.g. an +// overlapping run), the new discussion is deleted again. +// - Creations are paced (2s apart, `--delay-ms=`) and never retried, since +// a retry after a timeout could create a second discussion. On a GitHub +// rate limit the run stops and the next run resumes. +// +// --dry-run is read-only: prints what it would create and insert, writes nothing. import '../utils/dotenv.js' -import { createHash } from 'node:crypto' -import { readdir, readFile } from 'node:fs/promises' -import { dirname, join } from 'node:path' -import { fileURLToPath } from 'node:url' -import { Octokit } from '@octokit/core' -import { retry } from '@octokit/plugin-retry' -import { createClient, type SupabaseClient } from '@supabase/supabase-js' -import matter from 'gray-matter' +import type { SupabaseClient } from '@supabase/supabase-js' -import { githubAuthOptions } from './github-auth.ts' - -const REPOSITORY_ID = 'MDEwOlJlcG9zaXRvcnkyMTQ1ODcxOTM=' // supabase/supabase -const TROUBLESHOOTING_CATEGORY_ID = 'DIC_kwDODMpXOc4CUvEr' // "Troubleshooting" discussion category - -const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url)) -const TROUBLESHOOTING_DIRECTORY = join(SCRIPT_DIR, '../../src/content/troubleshooting') +import { createPacer, isRateLimitError, readMinIntervalMs } from './github-throttle.ts' +import { + computeChecksum, + createDb, + createOctokit, + describeConflict, + fetchAllEntries, + findTitleConflicts, + isBlocking, + listCategoryDiscussions, + readLocalGuides, + REPOSITORY_ID, + TROUBLESHOOTING_CATEGORY_ID, + type EntryRow, + type LocalGuide, + type RetryOctokitInstance, +} from './troubleshooting-sync-shared.ts' const DRY_RUN = process.argv.includes('--dry-run') +const LOG = '[sync-troubleshooting-entries]' -const RetryOctokit = Octokit.plugin(retry) -const octokit = new RetryOctokit(githubAuthOptions()) - -async function readLocalGuides(): Promise> { - const filenames = (await readdir(TROUBLESHOOTING_DIRECTORY)).filter((f) => f.endsWith('.mdx')) - return Promise.all( - filenames.map(async (filename) => { - const raw = await readFile(join(TROUBLESHOOTING_DIRECTORY, filename), 'utf-8') - const { data, content: body } = matter(raw) - return { slug: filename.replace(/\.mdx$/, ''), title: data.title as string, body } - }) - ) -} - -function computeChecksum(title: string, body: string): string { - return createHash('sha256').update(JSON.stringify({ title, body })).digest('hex') -} - -async function createDiscussion(title: string, body: string): Promise<{ id: string; url: string }> { +async function createDiscussion( + octokit: RetryOctokitInstance, + title: string, + body: string +): Promise<{ id: string; url: string }> { const mutation = ` mutation CreateDiscussionMutation($repository: ID!, $category: ID!, $title: String!, $body: String!) { createDiscussion(input: { repositoryId: $repository, categoryId: $category, title: $title, body: $body }) { @@ -49,112 +50,197 @@ async function createDiscussion(title: string, body: string): Promise<{ id: stri } } ` + // retries: 0 disables @octokit/plugin-retry, which would re-send on a 5xx. const result = await octokit.graphql<{ createDiscussion: { discussion: { id: string; url: string } } - }>(mutation, { repository: REPOSITORY_ID, category: TROUBLESHOOTING_CATEGORY_ID, title, body }) + }>(mutation, { + repository: REPOSITORY_ID, + category: TROUBLESHOOTING_CATEGORY_ID, + title, + body, + request: { retries: 0 }, + }) return result.createDiscussion.discussion } -async function deleteDiscussion(id: string): Promise { +async function deleteDiscussion(octokit: RetryOctokitInstance, id: string): Promise { const mutation = ` mutation DeleteDiscussionMutation($discussionId: ID!) { deleteDiscussion(input: { discussionId: $discussionId }) { discussion { id } } } ` - await octokit.graphql(mutation, { discussionId: id }) + await octokit.graphql(mutation, { discussionId: id, request: { retries: 0 } }) } -// Small sequential batches, not one unbounded Promise.all — stays clear of -// GitHub's secondary rate limits when many guides are new at once (e.g. the -// first run). Isolates failures per guide instead of letting one abort the -// rest; failures are collected and reported (non-zero exit) at the end. -async function createNewGuides( +async function createGuide( db: SupabaseClient, - guides: Array<{ slug: string; title: string; body: string }> -): Promise { - const failures: string[] = [] - const batchSize = 5 - - for (let i = 0; i < guides.length; i += batchSize) { - const batch = guides.slice(i, i + batchSize) - const results = await Promise.allSettled( - batch.map(async (guide) => { - console.log(` - ${guide.slug}`) - if (DRY_RUN) return - - const discussion = await createDiscussion(guide.title, guide.body) - // upsert, not insert: a row can already exist here (matched by slug, - // just without a github_id yet) — onConflict updates it in place - // instead of colliding with the slug unique constraint. - const { error } = await db.from('troubleshooting_entries').upsert( - { - slug: guide.slug, - github_url: discussion.url, - github_id: discussion.id, - checksum: computeChecksum(guide.title, guide.body), - }, - { onConflict: 'slug' } - ) - if (error) { - console.error( - `[sync-troubleshooting-entries] DB upsert failed for ${guide.slug}, rolling back discussion` - ) - await deleteDiscussion(discussion.id) - throw error - } - }) - ) - results.forEach((result, j) => { - if (result.status === 'rejected') { - console.error(`[sync-troubleshooting-entries] Failed for ${batch[j].slug}:`, result.reason) - failures.push(batch[j].slug) - } - }) + octokit: RetryOctokitInstance, + guide: LocalGuide, + existingRow: EntryRow | undefined, + pace: () => Promise +): Promise { + // Sent once: if a timeout hid a success, the next run's title check flags it. + await pace() + const discussion = await createDiscussion(octokit, guide.title, guide.body) + const row = { + slug: guide.slug, + github_url: discussion.url, + github_id: discussion.id, + checksum: computeChecksum(guide.title, guide.body), } - return failures + // An existing row here has an empty github_id; fill it in place. + const { error } = existingRow + ? await db.from('troubleshooting_entries').update(row).eq('id', existingRow.id) + : await db.from('troubleshooting_entries').insert(row) + + if (error) { + console.error(`${LOG} DB write failed for ${guide.slug}, rolling back discussion`) + try { + await pace() + await deleteDiscussion(octokit, discussion.id) + } catch (rollbackError) { + console.error( + `${LOG} ROLLBACK FAILED for ${guide.slug}: discussion ${discussion.url} is orphaned, delete it manually.`, + rollbackError + ) + } + throw error + } + console.log(` - created ${guide.slug} -> ${discussion.url}`) +} + +function printDryRunGuide(guide: LocalGuide, existingRow: EntryRow | undefined) { + const checksum = computeChecksum(guide.title, guide.body) + console.log(` + ${guide.slug}`) + console.log(` title: ${guide.title}`) + console.log( + ` discussion: CREATE in the Troubleshooting category (${guide.body.length} chars of body)` + ) + console.log( + ` row: ${existingRow ? `UPDATE row ${existingRow.id}` : 'INSERT'} ` + + `{ slug: "${guide.slug}", github_id: , github_url: , checksum: ${checksum} }` + ) } async function syncNewDiscussions() { const guides = await readLocalGuides() - const db = createClient( - process.env.SUPABASE_URL as string, - process.env.SUPABASE_SERVICE_ROLE_KEY as string + const db = createDb() + const octokit = createOctokit() + const entries = await fetchAllEntries(db) + + const entryBySlug = new Map() + for (const entry of entries) if (entry.slug) entryBySlug.set(entry.slug, entry) + const localSlugs = new Set(guides.map((guide) => guide.slug)) + const sluglessRows = entries.filter((entry) => !entry.slug) + const rowsWithoutGuide = entries.filter((entry) => entry.slug && !localSlugs.has(entry.slug)) + + // New = no row for this slug with a discussion. + const newGuides = guides.filter((guide) => !entryBySlug.get(guide.slug)?.github_id) + + console.log( + `${LOG} ${guides.length} local guide(s), ${entries.length} row(s)${DRY_RUN ? ' (dry run)' : ''}: ` + + `${guides.length - newGuides.length} already synced, ${newGuides.length} new.` ) - - const { data: existing, error } = await db - .from('troubleshooting_entries') - .select('slug, github_id') - .in( - 'slug', - guides.map((guide) => guide.slug) + if (sluglessRows.length > 0) { + console.warn( + `${LOG} ${sluglessRows.length} row(s) have no slug, so no guide can match them` + + `${DRY_RUN ? ':' : '.'} (a guide for one of them would look new — see the duplicate check below)` ) - if (error) throw error - - // github_id present means a discussion already exists for that slug — the - // actual "already synced" signal, not mere row presence (a backfilled - // legacy row's slug can exist before it has a discussion). - const githubIdBySlug = new Map((existing ?? []).map((row) => [row.slug, row.github_id])) - const newGuides = guides.filter((guide) => !githubIdBySlug.get(guide.slug)) + if (DRY_RUN) + for (const row of sluglessRows) console.warn(` - row ${row.id} ${row.github_url}`) + } + if (DRY_RUN && rowsWithoutGuide.length > 0) { + console.log( + `${LOG} ${rowsWithoutGuide.length} row(s) have a slug but no local guide (untouched):` + ) + for (const row of rowsWithoutGuide) console.log(` - ${row.slug}`) + } if (newGuides.length === 0) { - console.log('[sync-troubleshooting-entries] No new troubleshooting guides to sync.') + console.log(`${LOG} No new troubleshooting guides to sync.`) return } - console.log( - `[sync-troubleshooting-entries] ${newGuides.length} new guide(s)${DRY_RUN ? ' (dry run)' : ''}:` - ) - const failures = await createNewGuides(db, newGuides) + // Read-only. If it fails nothing is created: duplicates can't be ruled out. + const discussions = await listCategoryDiscussions(octokit) + + const blocked: Array<{ slug: string; reasons: string[] }> = [] + const failures: string[] = [] + const notAttempted: string[] = [] + let created = 0 + + const minIntervalMs = readMinIntervalMs() + const pace = createPacer(minIntervalMs) + let rateLimited = false + + console.log(`\n${LOG} New guide(s):`) + if (DRY_RUN) { + console.log( + ` (pacing: at least ${minIntervalMs}ms between creations; a failed creation is not retried)` + ) + } + for (const guide of newGuides) { + // After a rate limit the next calls would fail too: stop, next run resumes. + if (rateLimited) { + notAttempted.push(guide.slug) + continue + } + + const conflicts = findTitleConflicts(guide.title, discussions, entries) + const blockers = conflicts.filter(isBlocking) + + if (blockers.length > 0) { + const reasons = blockers.map(describeConflict) + blocked.push({ slug: guide.slug, reasons }) + console.error(` ! ${guide.slug} — NOT created, would duplicate an existing discussion:`) + for (const reason of reasons) console.error(` ${reason}`) + continue + } + + const existingRow = entryBySlug.get(guide.slug) + if (DRY_RUN) { + printDryRunGuide(guide, existingRow) + for (const c of conflicts) console.warn(` warning: ${describeConflict(c)}`) + created++ + continue + } + + for (const c of conflicts) console.warn(` ? ${guide.slug}: ${describeConflict(c)}`) + try { + await createGuide(db, octokit, guide, existingRow, pace) + created++ + } catch (error) { + console.error(`${LOG} Failed for ${guide.slug}:`, error) + failures.push(guide.slug) + if (isRateLimitError(error)) rateLimited = true + } + } console.log( - `[sync-troubleshooting-entries] Synced ${newGuides.length - failures.length}/${newGuides.length} new guide(s).` + `\n${LOG} ${DRY_RUN ? 'Would create' : 'Created'} ${created}/${newGuides.length} new guide(s) ` + + `(a discussion and a row each); ${blocked.length} blocked as duplicates, ${failures.length} failed.` ) - if (failures.length > 0) { - throw new Error(`Failed to sync: ${failures.join(', ')}`) + + if (notAttempted.length > 0) { + console.error( + `${LOG} Stopped early: GitHub rate-limited the request. ${notAttempted.length} guide(s) were not attempted ` + + `and will be picked up by the next run (or raise --delay-ms): ${notAttempted.join(', ')}` + ) + process.exitCode = 1 + } + + if (blocked.length > 0 || failures.length > 0) { + if (blocked.length > 0) { + console.error(`${LOG} Blocked (fix the existing row's slug, then re-run):`) + for (const { slug, reasons } of blocked) console.error(` - ${slug}`, reasons.join('\n')) + } + if (failures.length > 0) console.error(`${LOG} Failed: ${failures.join(', ')}`) + process.exitCode = 1 } } syncNewDiscussions().catch((error) => { - throw error + console.error(error) + process.exit(1) }) diff --git a/apps/kb/scripts/federated-content/sync-troubleshooting-updates.ts b/apps/kb/scripts/federated-content/sync-troubleshooting-updates.ts index acea5586ae9..b961e7f0ce1 100644 --- a/apps/kb/scripts/federated-content/sync-troubleshooting-updates.ts +++ b/apps/kb/scripts/federated-content/sync-troubleshooting-updates.ts @@ -1,49 +1,36 @@ // Pushes title/content updates to already-synced GitHub Discussions when the -// local troubleshooting guide has changed. Compares a stored checksum against -// a freshly computed one — never the discussion's live content — so this is -// immune to whatever GitHub does internally to stored title/body. A null -// checksum (a row created before this column existed) always counts as -// changed. Updates target the discussion directly via the row's stored -// github_id — no need to list/paginate the category's discussions. Run after -// sync-troubleshooting-entries.ts, from CI only. Pass --dry-run to log -// without writing anything. +// local guide's checksum differs from the one stored on its row (a null +// checksum counts as changed). Guides are matched to rows by exact slug; a +// guide with no row is skipped (sync-troubleshooting-entries.ts creates it). +// The discussion is updated first and the checksum stored second, so a failed +// DB write only means the next run pushes the same content again. +// +// Run after sync-troubleshooting-entries.ts, from CI only. +// +// --dry-run is read-only: prints each discussion it would update (url, id, +// old -> new checksum) and updates nothing. import '../utils/dotenv.js' -import { createHash } from 'node:crypto' -import { readdir, readFile } from 'node:fs/promises' -import { dirname, join } from 'node:path' -import { fileURLToPath } from 'node:url' -import { Octokit } from '@octokit/core' -import { retry } from '@octokit/plugin-retry' -import { createClient } from '@supabase/supabase-js' -import matter from 'gray-matter' - -import { githubAuthOptions } from './github-auth.ts' - -const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url)) -const TROUBLESHOOTING_DIRECTORY = join(SCRIPT_DIR, '../../src/content/troubleshooting') +import { createPacer, isRateLimitError, readMinIntervalMs } from './github-throttle.ts' +import { + computeChecksum, + createDb, + createOctokit, + fetchAllEntries, + readLocalGuides, + type EntryRow, + type RetryOctokitInstance, +} from './troubleshooting-sync-shared.ts' const DRY_RUN = process.argv.includes('--dry-run') +const LOG = '[sync-troubleshooting-updates]' -const RetryOctokit = Octokit.plugin(retry) -const octokit = new RetryOctokit(githubAuthOptions()) - -async function readLocalGuides(): Promise> { - const filenames = (await readdir(TROUBLESHOOTING_DIRECTORY)).filter((f) => f.endsWith('.mdx')) - return Promise.all( - filenames.map(async (filename) => { - const raw = await readFile(join(TROUBLESHOOTING_DIRECTORY, filename), 'utf-8') - const { data, content: body } = matter(raw) - return { slug: filename.replace(/\.mdx$/, ''), title: data.title as string, body } - }) - ) -} - -function computeChecksum(title: string, body: string): string { - return createHash('sha256').update(JSON.stringify({ title, body })).digest('hex') -} - -async function updateDiscussion(discussionId: string, title: string, body: string): Promise { +async function updateDiscussion( + octokit: RetryOctokitInstance, + discussionId: string, + title: string, + body: string +): Promise { const mutation = ` mutation UpdateDiscussionMutation($discussionId: ID!, $title: String!, $body: String!) { updateDiscussion(input: { discussionId: $discussionId, title: $title, body: $body }) { @@ -51,65 +38,116 @@ async function updateDiscussion(discussionId: string, title: string, body: strin } } ` - await octokit.graphql(mutation, { discussionId, title, body }) + // retries: 0 disables @octokit/plugin-retry; mutations are sent once. + await octokit.graphql(mutation, { discussionId, title, body, request: { retries: 0 } }) } async function syncDiscussionUpdates() { const guides = await readLocalGuides() - const db = createClient( - process.env.SUPABASE_URL as string, - process.env.SUPABASE_SERVICE_ROLE_KEY as string - ) + const db = createDb() + const octokit = createOctokit() + const entries = await fetchAllEntries(db) - const { data: rows, error } = await db - .from('troubleshooting_entries') - .select('slug, github_id, checksum') - .in( - 'slug', - guides.map((guide) => guide.slug) - ) - if (error) throw error + const entryBySlug = new Map() + for (const entry of entries) if (entry.slug) entryBySlug.set(entry.slug, entry) - const rowBySlug = new Map((rows ?? []).map((row) => [row.slug, row])) - - let updatedCount = 0 + let unchanged = 0 + let withoutRow = 0 + let updated = 0 + let noStoredChecksum = 0 const failures: string[] = [] + const notAttempted: string[] = [] + + const minIntervalMs = readMinIntervalMs() + const pace = createPacer(minIntervalMs) + let rateLimited = false + + console.log( + `${LOG} ${guides.length} local guide(s), ${entries.length} row(s)${DRY_RUN ? ' (dry run)' : ''}.` + ) + if (DRY_RUN) { + console.log( + ` (pacing: at least ${minIntervalMs}ms between updates; a failed update is not retried)` + ) + } for (const guide of guides) { - const row = rowBySlug.get(guide.slug) - if (!row) continue // not synced yet — sync-troubleshooting-entries.ts handles that + const row = entryBySlug.get(guide.slug) + if (!row) { + withoutRow++ + continue + } const newChecksum = computeChecksum(guide.title, guide.body) - if (row.checksum !== null && row.checksum === newChecksum) continue + if (row.checksum && row.checksum === newChecksum) { + unchanged++ + continue + } + + if (!row.github_id) { + console.error(`${LOG} ${guide.slug}: row ${row.id} has no github_id, cannot update.`) + failures.push(guide.slug) + continue + } + + const reason = row.checksum ? 'content changed' : 'no stored checksum' + if (!row.checksum) noStoredChecksum++ - console.log( - `[sync-troubleshooting-updates] Content changed for ${guide.slug}${DRY_RUN ? ' (dry run)' : ''}` - ) if (DRY_RUN) { - updatedCount++ + console.log(` ~ ${guide.slug}`) + console.log(` reason: ${reason}`) + console.log(` discussion: UPDATE ${row.github_url} (${row.github_id})`) + console.log(` title: ${guide.title}`) + console.log(` body: ${guide.body.length} chars`) + console.log( + ` row: UPDATE row ${row.id} { checksum: ${row.checksum ?? 'null'} -> ${newChecksum} }` + ) + updated++ + continue + } + + // After a rate limit the next calls would fail too: stop, next run resumes. + if (rateLimited) { + notAttempted.push(guide.slug) continue } try { - await updateDiscussion(row.github_id, guide.title, guide.body) - const { error: updateError } = await db + await pace() + await updateDiscussion(octokit, row.github_id, guide.title, guide.body) + const { error } = await db .from('troubleshooting_entries') .update({ checksum: newChecksum }) - .eq('slug', guide.slug) - if (updateError) throw updateError - updatedCount++ + .eq('id', row.id) + if (error) throw error + console.log(` - updated ${guide.slug} (${reason}) -> ${row.github_url}`) + updated++ } catch (err) { - console.error(`[sync-troubleshooting-updates] Failed to update ${guide.slug}:`, err) + console.error(`${LOG} Failed to update ${guide.slug}:`, err) failures.push(guide.slug) + if (isRateLimitError(err)) rateLimited = true } } - console.log(`[sync-troubleshooting-updates] Updated ${updatedCount} discussion(s).`) + console.log( + `\n${LOG} ${DRY_RUN ? 'Would update' : 'Updated'} ${updated} discussion(s) ` + + `(${updated - noStoredChecksum} changed, ${noStoredChecksum} with no stored checksum); ` + + `${unchanged} unchanged, ${withoutRow} without a row yet.` + ) + if (notAttempted.length > 0) { + console.error( + `${LOG} Stopped early: GitHub rate-limited the request. ${notAttempted.length} discussion(s) not ` + + `attempted, the next run will pick them up (or raise --delay-ms): ${notAttempted.join(', ')}` + ) + process.exitCode = 1 + } if (failures.length > 0) { - throw new Error(`Failed to sync: ${failures.join(', ')}`) + console.error(`${LOG} Failed: ${failures.join(', ')}`) + process.exitCode = 1 } } syncDiscussionUpdates().catch((error) => { - throw error + console.error(error) + process.exit(1) }) diff --git a/apps/kb/scripts/federated-content/troubleshooting-sync-shared.test.ts b/apps/kb/scripts/federated-content/troubleshooting-sync-shared.test.ts new file mode 100644 index 00000000000..68fcfa700f0 --- /dev/null +++ b/apps/kb/scripts/federated-content/troubleshooting-sync-shared.test.ts @@ -0,0 +1,98 @@ +import { describe, expect, it } from 'vitest' + +import { + computeChecksum, + describeConflict, + findTitleConflicts, + isBlocking, + type CategoryDiscussion, + type EntryRow, +} from './troubleshooting-sync-shared.ts' + +const discussion = (id: string, title: string): CategoryDiscussion => ({ + id, + title, + url: `https://github.com/orgs/supabase/discussions/${id}`, +}) + +const entry = (id: string, slug: string | null, github_id: string): EntryRow => ({ + id, + slug, + github_id, + github_url: `https://github.com/orgs/supabase/discussions/${github_id}`, + checksum: null, +}) + +describe('computeChecksum', () => { + it('is the sha256 of JSON.stringify({ title, body }), hex encoded', () => { + // Pinned: sync-troubleshooting-updates.ts compares this against stored + // values, so changing the formula would mark every guide as changed. + expect(computeChecksum('Title', 'Body')).toBe( + '01e5f0f389e0155e1ecc739dbc285466e73240ec3a9a6bc062caec4dd18d536f' + ) + }) + + it('changes when either the title or the body changes', () => { + const base = computeChecksum('Title', 'Body') + expect(computeChecksum('Title!', 'Body')).not.toBe(base) + expect(computeChecksum('Title', 'Body!')).not.toBe(base) + }) + + it('does not confuse a title/body boundary shift', () => { + expect(computeChecksum('ab', 'c')).not.toBe(computeChecksum('a', 'bc')) + }) +}) + +describe('findTitleConflicts', () => { + it('finds nothing when no discussion has the title', () => { + expect( + findTitleConflicts('New guide', [discussion('1', 'Other guide')], [entry('r1', 'other', '1')]) + ).toEqual([]) + }) + + it('flags a discussion no row references as an orphan, and blocks on it', () => { + const [conflict] = findTitleConflicts('New guide', [discussion('1', 'New guide')], []) + + expect(conflict.kind).toBe('orphan') + expect(isBlocking(conflict)).toBe(true) + }) + + it('flags a discussion owned by a slug-less row, and blocks on it', () => { + const [conflict] = findTitleConflicts( + 'New guide', + [discussion('1', 'New guide')], + [entry('r1', null, '1')] + ) + + expect(conflict.kind).toBe('slugless-row') + expect(isBlocking(conflict)).toBe(true) + expect(describeConflict(conflict)).toContain('backfill') + }) + + it('only warns when the discussion belongs to a row with a different slug', () => { + const [conflict] = findTitleConflicts( + 'New guide', + [discussion('1', 'New guide')], + [entry('r1', 'some-other-slug', '1')] + ) + + expect(conflict.kind).toBe('other-slug') + expect(isBlocking(conflict)).toBe(false) + }) + + it('compares titles ignoring case and surrounding whitespace', () => { + const conflicts = findTitleConflicts(' New Guide ', [discussion('1', 'new guide')], []) + + expect(conflicts).toHaveLength(1) + }) + + it('reports every discussion that carries the title', () => { + const conflicts = findTitleConflicts( + 'Dup', + [discussion('1', 'Dup'), discussion('2', 'Dup'), discussion('3', 'Else')], + [entry('r1', 'dup', '1')] + ) + + expect(conflicts.map((c) => c.kind)).toEqual(['other-slug', 'orphan']) + }) +}) diff --git a/apps/kb/scripts/federated-content/troubleshooting-sync-shared.ts b/apps/kb/scripts/federated-content/troubleshooting-sync-shared.ts new file mode 100644 index 00000000000..146865b9e1a --- /dev/null +++ b/apps/kb/scripts/federated-content/troubleshooting-sync-shared.ts @@ -0,0 +1,175 @@ +// Shared by sync-troubleshooting-entries.ts and sync-troubleshooting-updates.ts, +// so both agree on how guides are read, checksummed, and matched to rows. +import { createHash } from 'node:crypto' +import { readdir, readFile } from 'node:fs/promises' +import { dirname, join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { Octokit } from '@octokit/core' +import { retry } from '@octokit/plugin-retry' +import { createClient, type SupabaseClient } from '@supabase/supabase-js' +import matter from 'gray-matter' + +import { githubAuthOptions } from './github-auth.ts' + +export const REPOSITORY_ID = 'MDEwOlJlcG9zaXRvcnkyMTQ1ODcxOTM=' // supabase/supabase +export const TROUBLESHOOTING_CATEGORY_ID = 'DIC_kwDODMpXOc4CUvEr' // "Troubleshooting" discussion category + +const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url)) +export const TROUBLESHOOTING_DIRECTORY = join(SCRIPT_DIR, '../../src/content/troubleshooting') + +export type LocalGuide = { slug: string; title: string; body: string } + +export type EntryRow = { + id: string + slug: string | null + github_id: string + github_url: string + checksum: string | null +} + +export type CategoryDiscussion = { id: string; url: string; title: string } + +const RetryOctokit = Octokit.plugin(retry) +export type RetryOctokitInstance = InstanceType + +export function createOctokit(): RetryOctokitInstance { + return new RetryOctokit(githubAuthOptions()) +} + +export function createDb(): SupabaseClient { + return createClient( + process.env.SUPABASE_URL as string, + process.env.SUPABASE_SERVICE_ROLE_KEY as string + ) +} + +/** The one definition of a guide's checksum. Changing it invalidates every stored one. */ +export function computeChecksum(title: string, body: string): string { + return createHash('sha256').update(JSON.stringify({ title, body })).digest('hex') +} + +/** + * Reads the guides fetch-federated-content.ts wrote. The slug is the file name + * without its extension (hash suffix included), the key to the guide's row. + * Throws if there are none, so a failed fetch isn't reported as "nothing to do". + */ +export async function readLocalGuides(): Promise { + const filenames = (await readdir(TROUBLESHOOTING_DIRECTORY)).filter((f) => f.endsWith('.mdx')) + if (filenames.length === 0) { + throw new Error( + `No .mdx guides in ${TROUBLESHOOTING_DIRECTORY}. Run fetch-federated-content.ts first.` + ) + } + + const guides: LocalGuide[] = [] + await Promise.all( + filenames.map(async (filename) => { + const raw = await readFile(join(TROUBLESHOOTING_DIRECTORY, filename), 'utf-8') + const { data, content: body } = matter(raw) + const slug = filename.replace(/\.mdx$/, '') + // Never create or push a discussion titled "undefined". + if (typeof data.title !== 'string' || data.title.trim() === '') { + console.warn(`[troubleshooting-sync] Skipping ${slug}: no string \`title\` in frontmatter.`) + return + } + guides.push({ slug, title: data.title, body }) + }) + ) + return guides.sort((a, b) => a.slug.localeCompare(b.slug)) +} + +/** Every row, slug-less ones included, paged (PostgREST caps responses at 1000). */ +export async function fetchAllEntries(db: SupabaseClient): Promise { + const pageSize = 1000 + const rows: EntryRow[] = [] + for (let from = 0; ; from += pageSize) { + const { data, error } = await db + .from('troubleshooting_entries') + .select('id, slug, github_id, github_url, checksum') + .order('id') + .range(from, from + pageSize - 1) + if (error) throw error + rows.push(...(data as EntryRow[])) + if (data.length < pageSize) return rows + } +} + +/** Every discussion currently in the Troubleshooting category. */ +export async function listCategoryDiscussions( + octokit: RetryOctokitInstance +): Promise { + const discussions: CategoryDiscussion[] = [] + let after: string | null = null + for (;;) { + const page: { + node: { + discussions: { + nodes: CategoryDiscussion[] + pageInfo: { hasNextPage: boolean; endCursor: string | null } + } + } | null + } = await octokit.graphql( + `query ($repository: ID!, $category: ID!, $after: String) { + node(id: $repository) { + ... on Repository { + discussions(categoryId: $category, first: 100, after: $after) { + nodes { id url title } + pageInfo { hasNextPage endCursor } + } + } + } + }`, + { repository: REPOSITORY_ID, category: TROUBLESHOOTING_CATEGORY_ID, after } + ) + if (!page.node) throw new Error('Could not read discussions: repository node not found.') + discussions.push(...page.node.discussions.nodes) + const { hasNextPage, endCursor } = page.node.discussions.pageInfo + if (!hasNextPage) return discussions + after = endCursor + } +} + +export type TitleConflict = + | { kind: 'orphan'; discussion: CategoryDiscussion } + | { kind: 'slugless-row'; discussion: CategoryDiscussion; row: EntryRow } + | { kind: 'other-slug'; discussion: CategoryDiscussion; row: EntryRow } + +const normalizeTitle = (title: string) => title.trim().toLowerCase() + +/** + * Discussions that already carry a new guide's title: + * - orphan: no row references it, + * - slugless-row: a slug-less row references it (its slug needs backfilling), + * - other-slug: a row with a different slug references it (warn only). + * The first two block creation (see `isBlocking`). + */ +export function findTitleConflicts( + guideTitle: string, + discussions: CategoryDiscussion[], + entries: EntryRow[] +): TitleConflict[] { + const rowByGithubId = new Map(entries.map((row) => [row.github_id, row])) + const title = normalizeTitle(guideTitle) + + return discussions + .filter((discussion) => normalizeTitle(discussion.title) === title) + .map((discussion): TitleConflict => { + const row = rowByGithubId.get(discussion.id) + if (!row) return { kind: 'orphan', discussion } + if (!row.slug) return { kind: 'slugless-row', discussion, row } + return { kind: 'other-slug', discussion, row } + }) +} + +export const isBlocking = (conflict: TitleConflict) => conflict.kind !== 'other-slug' + +export function describeConflict(conflict: TitleConflict): string { + switch (conflict.kind) { + case 'orphan': + return `discussion ${conflict.discussion.url} already has this title and no row references it` + case 'slugless-row': + return `discussion ${conflict.discussion.url} already has this title and belongs to slug-less row ${conflict.row.id} — backfill that row's slug instead` + case 'other-slug': + return `discussion ${conflict.discussion.url} has the same title but belongs to slug "${conflict.row.slug}"` + } +}