[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7AYK7M670B6TN8KWVH0S7WD":3,"skill-same:01M7AYK7M670B6TN8KWVH0S7WD":81},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":44,"commitSha":45,"skillDirectory":46,"forksCount":47,"repositoryHtmlUrl":48,"repositoryHomepageUrl":6,"ownerHtmlUrl":49,"ownerBlogUrl":50,"ownerDescription":51,"updatedAt":52,"install":53,"resources":66},"01M7AYK7M670B6TN8KWVH0S7WD","go-background-scheduler-api-poller",null,"Use when building a Go background API-poller scheduler.","oat431\u002Fhermes_config_backup","oat431","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F54722120?v=4","01M7AYD07EH8SYPMYY8CGZKS22","Oralita","01M7AYD0816QDF77E3TWCRSQC9",1,"MIT","https:\u002F\u002Fgithub.com\u002Foat431\u002Fhermes_config_backup\u002Fblob\u002Fmain\u002Fworkflow\u002Ffull-stack\u002Fgo-background-scheduler-api-poller\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: go-background-scheduler-api-poller\ndescription: \"Use when building a Go background API-poller scheduler.\"\nversion: 1.0.0\nauthor: Hermes Agent\nlicense: MIT\nplatforms: [windows, macos, linux]\nmetadata:\n  hermes:\n    tags: [go, scheduler, background-goroutine, api-poller, oauth, external-integration, tdd]\n    related_skills: [test-driven-development, github-pr-workflow, systematic-debugging]\n---\n\n# Go Background Scheduler — External API Poller\n\n## Trigger\n\nUse when implementing a Go background scheduler goroutine that periodically\npolls an external API (YouTube Data API, EasyDonate REST API, etc.) with:\n- OAuth 2.0 refresh-token exchange for access tokens\n- Structured error classification (403 quota, 401 auth, empty response)\n- Skip-cycle or alert-operator behavior on specific API errors\n- Integration with an existing service layer for data persistence\n\nThis pattern recurs across multiple schedulers in spec-driven projects\n(e.g., the Deerngo Bot SAD defines three: YouTube poller 15 min, EasyDonate\nsync 5 min, name matcher 2 min). Build the first one right and the rest follow\nthe same shape.\n\n## Architecture\n\n```\ncmd\u002Fserver\u002Fmain.go          → wires scheduler with config + DB + service\ninternal\u002Fyoutube\u002Fclient.go   → external API client (OAuth + endpoint)\ninternal\u002Fscheduler\u002Fpoller.go → ticker goroutine, error classification\ninternal\u002Frepository\u002Ftoken.go → OAuth token CRUD on oauth_tokens table\ninternal\u002Fservice\u002F*.go         → existing business logic (reused, not duplicated)\n```\n\n### Key design rules\n\n1. **The scheduler does NOT contain business logic.** It calls the existing\n   service layer (`SubscriberService.Register()`) — same code path as the HTTP\n   handler. No parallel validation, no separate upsert SQL.\n\n2. **The API client is a separate package** (`internal\u002Fyoutube\u002F` or\n   `internal\u002Feasydonate\u002F`). It handles: OAuth token exchange, HTTP request\n   construction, response parsing, and error classification. It knows nothing\n   about the database or service layer.\n\n3. **The scheduler orchestrates**: load token → call client → classify errors\n   → call service for each result. The `PollOnce(ctx)` method is the\n   unit-testable entry point. `Start(ctx)` wraps it in a ticker goroutine.\n\n4. **OAuth tokens live in the database** (`oauth_tokens` table), not in\n   environment variables. The scheduler loads the refresh token at startup from\n   a `TokenRepository`. A separate CLI (`cmd\u002Foauth-init`) performs the one-time\n   consent flow and seeds the token.\n\n## TDD approach — vertical tracer bullets\n\nDo NOT write all tests first, then all implementation. Build one behavior slice\nat a time:\n\n### Slice 1: API client happy path (mock HTTP server)\n\n```go\n\u002F\u002F RED: Write test against httptest.Server that returns 200 + subscriber JSON\nfunc TestFetchSubscribersReturnsSubscribersOnSuccess(t *testing.T) { ... }\n\n\u002F\u002F GREEN: Implement FetchSubscribers with:\n\u002F\u002F   exchangeRefreshToken(ctx) → access token\n\u002F\u002F   GET \u002Fsubscriptions with Bearer header\n\u002F\u002F   parse JSON response → []Subscriber\n```\n\n### Slice 2: Empty response\n\n```go\nfunc TestFetchSubscribersReturnsEmptyOnEmptyResponse(t *testing.T) { ... }\n```\n\n### Slice 3: Error classification (403\u002F401)\n\n```go\nfunc TestFetchSubscribersReturnsQuotaExceededOn403(t *testing.T) { ... }\nfunc TestFetchSubscribersReturnsUnauthorizedOn401(t *testing.T) { ... }\n```\n\n### Slice 4: Scheduler poll cycle (mock fetcher + mock registrar)\n\n```go\nfunc TestPollOnceCreatesSubscribersFromAPI(t *testing.T) { ... }\nfunc TestPollOnceHandlesEmptyResponse(t *testing.T) { ... }\nfunc TestPollOnceQuotaExceededSetsSkipFlag(t *testing.T) { ... }\nfunc TestPollOnceUnauthorizedAlertsOperator(t *testing.T) { ... }\n```\n\n### Slice 5: Token repository (PostgreSQL integration)\n\n```go\nfunc TestPostgresTokenRepositoryUpsertAndLoad(t *testing.T) { ... }\n```\n\n## Error classification pattern\n\nExport typed error checkers so the scheduler can branch without knowing\nHTTP details:\n\n```go\n\u002F\u002F In the API client package:\nfunc IsQuotaExceeded(err error) bool {\n    var ae *apiError\n    return errors.As(err, &ae) && ae.Code == 403 && ae.Reason == \"quotaExceeded\"\n}\n\nfunc IsUnauthorized(err error) bool {\n    var ae *apiError\n    return errors.As(err, &ae) && ae.Code == 401\n}\n\n\u002F\u002F Exported constructor for test use (avoids needing HTTP in unit tests):\nfunc NewAPIError(statusCode int, reason, message string) error {\n    return &apiError{Code: statusCode, Reason: reason, Message: message}\n}\n```\n\nThe scheduler branches on these:\n\n```go\nif youtube.IsQuotaExceeded(err) {\n    p.logger.Error(\"quota exceeded, skipping next cycle\", \"error\", err)\n    p.skipNext = true\n    return nil  \u002F\u002F handled, not an error\n}\nif youtube.IsUnauthorized(err) {\n    p.logger.Error(\"unauthorized — operator must re-authenticate\",\n        \"error\", err, \"action\", \"manual_reauth_required\")\n    return nil  \u002F\u002F handled\n}\nreturn err  \u002F\u002F unexpected — propagate\n```\n\n## Skip-cycle pattern\n\nFor quota errors, use a `skipNext bool` field on the poller. `PollOnce` checks\nit at the top:\n\n```go\nif p.skipNext {\n    p.logger.Info(\"skipping poll cycle due to previous quota error\")\n    p.skipNext = false\n    return nil\n}\n```\n\nThis is testable without waiting for a real timer — call `PollOnce` three times\nand verify the second call is skipped.\n\n## Configurable interval\n\nThe poll interval must be configurable for tests via env var, with a production\ndefault:\n\n```go\n\u002F\u002F config.go\npollMinutes, err := strconv.Atoi(getEnv(\"YOUTUBE_POLL_INTERVAL_MINUTES\", \"15\"))\nif err != nil || pollMinutes \u003C= 0 {\n    pollMinutes = 15\n}\ncfg.YouTubePollInterval = time.Duration(pollMinutes) * time.Minute\n```\n\nNever hardcode `15 * time.Minute` in the scheduler — the constructor should\napply the default if the config value is zero.\n\n## OAuth one-time consent CLI\n\nBuild a separate `cmd\u002Foauth-init` binary that reads the Google credentials\nJSON (gitignored, not in code) and stores a refresh token in `oauth_tokens`\nvia `TokenRepository.UpsertToken`. Two flows exist — pick based on WHERE the\nauthorizing user sits:\n\n**Flow A — operator is local (owns the account):** start a local HTTP\nlistener (e.g., `127.0.0.1:18090\u002Fcallback`), print the consent URL, receive\nthe code via redirect, exchange.\n\n**Flow B — authorizer is a REMOTE person (channel owner ≠ developer):** the\nlocalhost callback FAILS for them — Google redirects to\n`http:\u002F\u002Flocalhost:18090\u002Fcallback?code=...` on THEIR machine, no server is\nlistening, the page won't load. That's expected: they copy the FULL URL from\nthe browser address bar and send it back; you paste it into the CLI, which\nextracts `?code=...`, exchanges it, and stores the token. No public callback\nendpoint needed. (This was the deciding factor in the Deerngo project: the\nYouTube channel owner and the developer are different people.)\n\nThe main server binary loads the token at startup — if missing, it logs a\nwarning with a hint to run the CLI, but the HTTP API still works.\n\n### Google Cloud Console setup\n\nIf the OAuth client is a **Desktop\u002Finstalled app** (`\"installed\"` type in the\ncredentials JSON), **no redirect URI registration is needed.** Google accepts\nloopback redirects (`http:\u002F\u002Flocalhost:\u003Cport>` \u002F `http:\u002F\u002F127.0.0.1:\u003Cport>`)\nwith ANY port for installed apps. Only Web-app clients require the redirect\nURI to be registered. Use `prompt=consent` and `access_type=offline` to\nguarantee a refresh token is returned. If the owner previously granted\naccess, they must revoke the app at https:\u002F\u002Fmyaccount.google.com\u002Fpermissions\nfirst, or Google may not issue a refresh_token.\n\n**Check the OAuth consent screen app status:** if the app is in \"Testing\"\nmode, Google issues refresh tokens that **expire after 7 days** — the poller\nbreaks weekly. Publish the app (\"In production\") before running the consent\nflow (personal projects with a single test user need no verification).\n\n## Mock HTTP server pattern for API client tests\n\nUse `httptest.NewServer` to simulate the external API and token endpoint\nwithout network calls:\n\n```go\nfunc mockTokenServer() *httptest.Server {\n    return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n        w.Header().Set(\"Content-Type\", \"application\u002Fjson\")\n        json.NewEncoder(w).Encode(map[string]string{\"access_token\": \"test-token\"})\n    }))\n}\n\nfunc mockYouTubeAPI(t *testing.T, statusCode int, body string) *httptest.Server {\n    return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n        \u002F\u002F Assert Authorization header and query params\n        w.WriteHeader(statusCode)\n        w.Write([]byte(body))\n    }))\n}\n```\n\nInject the test server URLs via `ClientConfig.TokenURL` and `ClientConfig.APIBaseURL`.\n\n## Scheduler stub pattern for poller tests\n\nThe scheduler test uses two mocks — no HTTP, no database:\n\n```go\ntype mockFetcher struct {\n    subscribers []youtube.Subscriber\n    err         error\n    callCount   int\n}\nfunc (m *mockFetcher) FetchSubscribers(_ context.Context) ([]youtube.Subscriber, error) {\n    m.callCount++\n    return m.subscribers, m.err\n}\n\ntype mockRegistrar struct {\n    registered []service.RegisterSubscriberInput\n    \u002F\u002F ... results slice for per-call return values\n}\n```\n\nInject `youtube.NewAPIError(403, \"quotaExceeded\", \"...\")` as the fetcher error\nto test skip-cycle behavior without a live HTTP server.\n\n## Wiring into main.go\n\nThe scheduler starts as a background goroutine with context cancellation:\n\n```go\nctx, cancel := context.WithCancel(context.Background())\ndefer cancel()\n\n\u002F\u002F Start poller only if credentials are configured.\nstartYouTubePoller(ctx, cfg, db, subscriberService, logger)\n\n\u002F\u002F HTTP server runs in main goroutine.\ngo func() { app.Listen(\":\" + cfg.Port) }()\n\n\u002F\u002F Graceful shutdown.\nquit := make(chan os.Signal, 1)\nsignal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)\n\u003C-quit\ncancel()\n```\n\n`startYouTubePoller` checks for missing credentials and logs a warning —\nthe HTTP API should still work even if the poller is disabled.\n\n## Verification\n\n```bash\nmake fmt\nmake test\nmake vet\nmake build\ngo test -race -count=1 .\u002F...\ngo build -trimpath -o bin\u002Foauth-init .\u002Fcmd\u002Foauth-init\n```\n\nIntegration tests for the token repository run via `make test-integration`\nagainst an isolated PostgreSQL database. On a Windows host with PostgreSQL in\nDocker, cross-compile the test binaries and run them inside the container —\nsee `references\u002Fwindows-docker-postgres-integration-testing.md` for the full\nrecipe (cross-compile → `docker cp` → Unix-socket DSN) plus cross-package\nisolation rules (unique UUID handles, `-p=1`) and the CI PostgreSQL-service\nworkflow.\n\n## Live end-to-end verification (before shipping a poller)\n\nMock tests prove the code paths; a live run proves the integration. When real\ncredentials exist, run the actual poller against the real API + local DB:\n\n1. Start the server with the real `.env` (background process, watch for the\n   poll log): the poller fires an **immediate poll on startup**.\n2. Confirm the log line: `youtube poll completed fetched=N created=N upserted=0`.\n3. Query the DB to confirm rows exist with the expected `source` and real data.\n4. **Restart the server** — the startup poll now exercises the UPSERT path:\n   expect `fetched=N created=0 upserted=N` and the DB row count unchanged\n   (proves AC \"no duplicates\" live, without waiting for the real interval).\n\nThis pattern catches contract bugs that mocks cannot: wrong query parameters,\nresponse field mismatches, and auth flow breaks. In the Deerngo session it\ncaught that the spec's endpoint URL was wrong (see Pitfalls).\n\n## Verifying secrets exist WITHOUT printing them\n\nWhen the user says \"the token is in the DB, check it\", never print the secret.\nProve presence + liveness with masked checks:\n\n```bash\n# 1. Row exists, correct shape, value masked:\ndocker exec local-postgres psql -U postgres -d deerngo -Atc \\\n  \"SELECT provider, youtube_channel_id, created_at, LENGTH(refresh_token), LEFT(refresh_token,3) FROM oauth_tokens\"\n\n# 2. Cross-check the channel ID matches .env (length\u002Fprefix only):\nCH=$(grep '^YOUTUBE_CHANNEL_ID=' .env | cut -d= -f2); echo \"${#CH} ${CH:0:4}\"\n\n# 3. LIVE token-exchange probe — values stay in shell vars, only statuses print:\nREFRESH_TOKEN=$(docker exec ... psql -Atc \"SELECT refresh_token FROM oauth_tokens LIMIT 1;\")\nACCESS_TOKEN=$(curl -sS -X POST \"$TOKEN_URI\" \\\n  -d \"client_id=$CLIENT_ID&client_secret=$CLIENT_SECRET&refresh_token=$REFRESH_TOKEN&grant_type=refresh_token\" \\\n  | python3 -c \"import json,sys;print(json.load(sys.stdin)['access_token'])\")\ncurl -sS -o \u002Fdev\u002Fnull -w '%{http_code}\\n' -H \"Authorization: Bearer $ACCESS_TOKEN\" \\\n  \"https:\u002F\u002Fwww.googleapis.com\u002Fyoutube\u002Fv3\u002Fchannels?part=statistics&id=$CHANNEL_ID\"\n```\n\nPrint only lengths, prefixes, and HTTP statuses. On git-bash\u002FMSYS, use `curl`\nfor TLS calls — MSYS `python3` urllib frequently fails with\n`SSL: CERTIFICATE_VERIFY_FAILED` (no CA bundle); curl ships with proper certs.\n\n## Detecting \"API returns a subset\" limitations\n\nWhen the user suspects the poller missed subscribers, compare two live calls:\n\n```bash\n# Public truth: channels.list statistics\nGET \u002Fchannels?part=statistics&id=\u003Cchannel>  → subscriberCount=1310\n# What the poller can see: subscriptions pageInfo\nGET \u002Fsubscriptions?part=snippet&mySubscribers=true&maxResults=1 → totalResults=172\n```\n\nIf `totalResults` \u003C\u003C `subscriberCount`, the endpoint only exposes recent\nsubscribers (ongoing capture works, historical backfill is impossible). This\nis a platform limitation, not a code bug — report it via meeting minute, don't\ntry to \"fix\" the client.\n\n## Pitfalls\n\n- **API spec example URLs may be factually wrong — verify live.** The Deerngo\n  API spec said `GET \u002Fsubscriptions?channelId=X&order=date`. Live testing\n  proved: `channelId=` returns the channels the owner FOLLOWS (not its\n  subscribers), and `order=date` is not a valid enum for subscriptions.list\n  (400 INVALID_ARGUMENT). The correct call is `mySubscribers=true`. When real\n  credentials exist, empirically probe the endpoint (curl with a fresh access\n  token) BEFORE trusting spec query params. See\n  `references\u002Fyoutube-subscriptions-api.md`.\n- **List endpoints may return IDs only — budget a second enrichment call.**\n  `subscriptions?mySubscribers=true` returns only subscriber channel IDs +\n  timestamps (`subscriberSnippet` is empty). Display name + @handle require a\n  second batched call (`GET \u002Fchannels?part=snippet&id=\u003Ccomma-separated>`, 50\n  per call, 1 quota unit each). Account for the extra call in quota math, and\n  fall back to the ID as the handle when a channel has no customUrl.\n- **Parallel business logic in the scheduler** — the scheduler must call the\n  same service method as the HTTP handler. Do not duplicate validation,\n  normalization, or upsert SQL in the scheduler.\n- **Hardcoded poll interval** — always make it configurable; tests need fast\n  intervals and the production default (15 min) is too slow for CI.\n- **Unexported error types** — if `apiError` is unexported, tests in other\n  packages cannot construct it. Export `NewAPIError()` as a test helper.\n- **Missing skip-cycle reset** — after skipping one cycle, `skipNext` must be\n  reset to `false` so the third cycle runs normally.\n- **Token in env vars** — the spec says `oauth_tokens` table. Use the database.\n  The env var is only for the CLI's `DATABASE_URL`.\n- **OAuth credentials in Git** — the credentials JSON must be in `.gitignore`.\n  Never read it into source files or commit it.\n- **No graceful shutdown** — the ticker goroutine must respect `ctx.Done()`\n  or it leaks on process exit.\n- **Testing with real timers** — `PollOnce(ctx)` is the testable entry point.\n  Do not test `Start(ctx)` with real `time.Ticker` waits.\n- **Subscriber lists are subsets** — `mySubscribers=true` returns only the\n  most recent ~N subscribers (Deerngo: 172 of 1,310 public), not the full\n  list. Ongoing capture works; historical backfill is impossible. Detect via\n  `channels.list statistics.subscriberCount` vs `pageInfo.totalResults`.\n- **Platform limitation affecting acceptance criteria → meeting minute, not\n  chat.** When a live finding invalidates what an AC implies (e.g., \"capture\n  all subscribers\" is impossible), notify PO\u002FQA via a meeting minute in the\n  project's `07_pm\u002F` directory following the local MM format (finding →\n  evidence → impact on affected ACs → options → action items), and keep Dev\n  work unblocked with a fix branch. User explicitly requested this\n  (\"create meeting minute to notice the PO\u002FQA instant\").\n- **gofmt on Windows marks every file modified** — `make fmt` (gofmt -w)\n  rewrites files with LF; git status shows all .go files as `M` while\n  `git diff` is EMPTY (CRLF\u002FLF artifact). Verify the diff is empty, then\n  `git restore .` — never commit the line-ending noise.\n- **`git restore` can silently delete uncommitted work** — cleaning the\n  gofmt noise with a broad `git restore cmd internal` also reverted an\n  UNCOMMITTED new test file in the working tree (it was only flagged as\n  `M` by the same CRLF artifact, so it looked like noise). Rules: (1)\n  commit all intended changes BEFORE restoring line-ending noise; (2) if\n  you must restore before committing, restore only the specific noise\n  files, and `grep -c` your new symbol afterward to confirm it survived.\n","# Go Background Scheduler — External API Poller\n\n## Trigger\n\nUse when implementing a Go background scheduler goroutine that periodically\npolls an external API (YouTube Data API, EasyDonate REST API, etc.) with:\n- OAuth 2.0 refresh-token exchange for access tokens\n- Structured error classification (403 quota, 401 auth, empty response)\n- Skip-cycle or alert-operator behavior on specific API errors\n- Integration with an existing service layer for data persistence\n\nThis pattern recurs across multiple schedulers in spec-driven projects\n(e.g., the Deerngo Bot SAD defines three: YouTube poller 15 min, EasyDonate\nsync 5 min, name matcher 2 min). Build the first one right and the rest follow\nthe same shape.\n\n## Architecture\n\n```\ncmd\u002Fserver\u002Fmain.go          → wires scheduler with config + DB + service\ninternal\u002Fyoutube\u002Fclient.go   → external API client (OAuth + endpoint)\ninternal\u002Fscheduler\u002Fpoller.go → ticker goroutine, error classification\ninternal\u002Frepository\u002Ftoken.go → OAuth token CRUD on oauth_tokens table\ninternal\u002Fservice\u002F*.go         → existing business logic (reused, not duplicated)\n```\n\n### Key design rules\n\n1. **The scheduler does NOT contain business logic.** It calls the existing\n   service layer (`SubscriberService.Register()`) — same code path as the HTTP\n   handler. No parallel validation, no separate upsert SQL.\n\n2. **The API client is a separate package** (`internal\u002Fyoutube\u002F` or\n   `internal\u002Feasydonate\u002F`). It handles: OAuth token exchange, HTTP request\n   construction, response parsing, and error classification. It knows nothing\n   about the database or service layer.\n\n3. **The scheduler orchestrates**: load token → call client → classify errors\n   → call service for each result. The `PollOnce(ctx)` method is the\n   unit-testable entry point. `Start(ctx)` wraps it in a ticker goroutine.\n\n4. **OAuth tokens live in the database** (`oauth_tokens` table), not in\n   environment variables. The scheduler loads the refresh token at startup from\n   a `TokenRepository`. A separate CLI (`cmd\u002Foauth-init`) performs the one-time\n   consent flow and seeds the token.\n\n## TDD approach — vertical tracer bullets\n\nDo NOT write all tests first, then all implementation. Build one behavior slice\nat a time:\n\n### Slice 1: API client happy path (mock HTTP server)\n\n```go\n\u002F\u002F RED: Write test against httptest.Server that returns 200 + subscriber JSON\nfunc TestFetchSubscribersReturnsSubscribersOnSuccess(t *testing.T) { ... }\n\n\u002F\u002F GREEN: Implement FetchSubscribers with:\n\u002F\u002F   exchangeRefreshToken(ctx) → access token\n\u002F\u002F   GET \u002Fsubscriptions with Bearer header\n\u002F\u002F   parse JSON response → []Subscriber\n```\n\n### Slice 2: Empty response\n\n```go\nfunc TestFetchSubscribersReturnsEmptyOnEmptyResponse(t *testing.T) { ... }\n```\n\n### Slice 3: Error classification (403\u002F401)\n\n```go\nfunc TestFetchSubscribersReturnsQuotaExceededOn403(t *testing.T) { ... }\nfunc TestFetchSubscribersReturnsUnauthorizedOn401(t *testing.T) { ... }\n```\n\n### Slice 4: Scheduler poll cycle (mock fetcher + mock registrar)\n\n```go\nfunc TestPollOnceCreatesSubscribersFromAPI(t *testing.T) { ... }\nfunc TestPollOnceHandlesEmptyResponse(t *testing.T) { ... }\nfunc TestPollOnceQuotaExceededSetsSkipFlag(t *testing.T) { ... }\nfunc TestPollOnceUnauthorizedAlertsOperator(t *testing.T) { ... }\n```\n\n### Slice 5: Token repository (PostgreSQL integration)\n\n```go\nfunc TestPostgresTokenRepositoryUpsertAndLoad(t *testing.T) { ... }\n```\n\n## Error classification pattern\n\nExport typed error checkers so the scheduler can branch without knowing\nHTTP details:\n\n```go\n\u002F\u002F In the API client package:\nfunc IsQuotaExceeded(err error) bool {\n    var ae *apiError\n    return errors.As(err, &ae) && ae.Code == 403 && ae.Reason == \"quotaExceeded\"\n}\n\nfunc IsUnauthorized(err error) bool {\n    var ae *apiError\n    return errors.As(err, &ae) && ae.Code == 401\n}\n\n\u002F\u002F Exported constructor for test use (avoids needing HTTP in unit tests):\nfunc NewAPIError(statusCode int, reason, message string) error {\n    return &apiError{Code: statusCode, Reason: reason, Message: message}\n}\n```\n\nThe scheduler branches on these:\n\n```go\nif youtube.IsQuotaExceeded(err) {\n    p.logger.Error(\"quota exceeded, skipping next cycle\", \"error\", err)\n    p.skipNext = true\n    return nil  \u002F\u002F handled, not an error\n}\nif youtube.IsUnauthorized(err) {\n    p.logger.Error(\"unauthorized — operator must re-authenticate\",\n        \"error\", err, \"action\", \"manual_reauth_required\")\n    return nil  \u002F\u002F handled\n}\nreturn err  \u002F\u002F unexpected — propagate\n```\n\n## Skip-cycle pattern\n\nFor quota errors, use a `skipNext bool` field on the poller. `PollOnce` checks\nit at the top:\n\n```go\nif p.skipNext {\n    p.logger.Info(\"skipping poll cycle due to previous quota error\")\n    p.skipNext = false\n    return nil\n}\n```\n\nThis is testable without waiting for a real timer — call `PollOnce` three times\nand verify the second call is skipped.\n\n## Configurable interval\n\nThe poll interval must be configurable for tests via env var, with a production\ndefault:\n\n```go\n\u002F\u002F config.go\npollMinutes, err := strconv.Atoi(getEnv(\"YOUTUBE_POLL_INTERVAL_MINUTES\", \"15\"))\nif err != nil || pollMinutes \u003C= 0 {\n    pollMinutes = 15\n}\ncfg.YouTubePollInterval = time.Duration(pollMinutes) * time.Minute\n```\n\nNever hardcode `15 * time.Minute` in the scheduler — the constructor should\napply the default if the config value is zero.\n\n## OAuth one-time consent CLI\n\nBuild a separate `cmd\u002Foauth-init` binary that reads the Google credentials\nJSON (gitignored, not in code) and stores a refresh token in `oauth_tokens`\nvia `TokenRepository.UpsertToken`. Two flows exist — pick based on WHERE the\nauthorizing user sits:\n\n**Flow A — operator is local (owns the account):** start a local HTTP\nlistener (e.g., `127.0.0.1:18090\u002Fcallback`), print the consent URL, receive\nthe code via redirect, exchange.\n\n**Flow B — authorizer is a REMOTE person (channel owner ≠ developer):** the\nlocalhost callback FAILS for them — Google redirects to\n`http:\u002F\u002Flocalhost:18090\u002Fcallback?code=...` on THEIR machine, no server is\nlistening, the page won't load. That's expected: they copy the FULL URL from\nthe browser address bar and send it back; you paste it into the CLI, which\nextracts `?code=...`, exchanges it, and stores the token. No public callback\nendpoint needed. (This was the deciding factor in the Deerngo project: the\nYouTube channel owner and the developer are different people.)\n\nThe main server binary loads the token at startup — if missing, it logs a\nwarning with a hint to run the CLI, but the HTTP API still works.\n\n### Google Cloud Console setup\n\nIf the OAuth client is a **Desktop\u002Finstalled app** (`\"installed\"` type in the\ncredentials JSON), **no redirect URI registration is needed.** Google accepts\nloopback redirects (`http:\u002F\u002Flocalhost:\u003Cport>` \u002F `http:\u002F\u002F127.0.0.1:\u003Cport>`)\nwith ANY port for installed apps. Only Web-app clients require the redirect\nURI to be registered. Use `prompt=consent` and `access_type=offline` to\nguarantee a refresh token is returned. If the owner previously granted\naccess, they must revoke the app at https:\u002F\u002Fmyaccount.google.com\u002Fpermissions\nfirst, or Google may not issue a refresh_token.\n\n**Check the OAuth consent screen app status:** if the app is in \"Testing\"\nmode, Google issues refresh tokens that **expire after 7 days** — the poller\nbreaks weekly. Publish the app (\"In production\") before running the consent\nflow (personal projects with a single test user need no verification).\n\n## Mock HTTP server pattern for API client tests\n\nUse `httptest.NewServer` to simulate the external API and token endpoint\nwithout network calls:\n\n```go\nfunc mockTokenServer() *httptest.Server {\n    return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n        w.Header().Set(\"Content-Type\", \"application\u002Fjson\")\n        json.NewEncoder(w).Encode(map[string]string{\"access_token\": \"test-token\"})\n    }))\n}\n\nfunc mockYouTubeAPI(t *testing.T, statusCode int, body string) *httptest.Server {\n    return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n        \u002F\u002F Assert Authorization header and query params\n        w.WriteHeader(statusCode)\n        w.Write([]byte(body))\n    }))\n}\n```\n\nInject the test server URLs via `ClientConfig.TokenURL` and `ClientConfig.APIBaseURL`.\n\n## Scheduler stub pattern for poller tests\n\nThe scheduler test uses two mocks — no HTTP, no database:\n\n```go\ntype mockFetcher struct {\n    subscribers []youtube.Subscriber\n    err         error\n    callCount   int\n}\nfunc (m *mockFetcher) FetchSubscribers(_ context.Context) ([]youtube.Subscriber, error) {\n    m.callCount++\n    return m.subscribers, m.err\n}\n\ntype mockRegistrar struct {\n    registered []service.RegisterSubscriberInput\n    \u002F\u002F ... results slice for per-call return values\n}\n```\n\nInject `youtube.NewAPIError(403, \"quotaExceeded\", \"...\")` as the fetcher error\nto test skip-cycle behavior without a live HTTP server.\n\n## Wiring into main.go\n\nThe scheduler starts as a background goroutine with context cancellation:\n\n```go\nctx, cancel := context.WithCancel(context.Background())\ndefer cancel()\n\n\u002F\u002F Start poller only if credentials are configured.\nstartYouTubePoller(ctx, cfg, db, subscriberService, logger)\n\n\u002F\u002F HTTP server runs in main goroutine.\ngo func() { app.Listen(\":\" + cfg.Port) }()\n\n\u002F\u002F Graceful shutdown.\nquit := make(chan os.Signal, 1)\nsignal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)\n\u003C-quit\ncancel()\n```\n\n`startYouTubePoller` checks for missing credentials and logs a warning —\nthe HTTP API should still work even if the poller is disabled.\n\n## Verification\n\n```bash\nmake fmt\nmake test\nmake vet\nmake build\ngo test -race -count=1 .\u002F...\ngo build -trimpath -o bin\u002Foauth-init .\u002Fcmd\u002Foauth-init\n```\n\nIntegration tests for the token repository run via `make test-integration`\nagainst an isolated PostgreSQL database. On a Windows host with PostgreSQL in\nDocker, cross-compile the test binaries and run them inside the container —\nsee `references\u002Fwindows-docker-postgres-integration-testing.md` for the full\nrecipe (cross-compile → `docker cp` → Unix-socket DSN) plus cross-package\nisolation rules (unique UUID handles, `-p=1`) and the CI PostgreSQL-service\nworkflow.\n\n## Live end-to-end verification (before shipping a poller)\n\nMock tests prove the code paths; a live run proves the integration. When real\ncredentials exist, run the actual poller against the real API + local DB:\n\n1. Start the server with the real `.env` (background process, watch for the\n   poll log): the poller fires an **immediate poll on startup**.\n2. Confirm the log line: `youtube poll completed fetched=N created=N upserted=0`.\n3. Query the DB to confirm rows exist with the expected `source` and real data.\n4. **Restart the server** — the startup poll now exercises the UPSERT path:\n   expect `fetched=N created=0 upserted=N` and the DB row count unchanged\n   (proves AC \"no duplicates\" live, without waiting for the real interval).\n\nThis pattern catches contract bugs that mocks cannot: wrong query parameters,\nresponse field mismatches, and auth flow breaks. In the Deerngo session it\ncaught that the spec's endpoint URL was wrong (see Pitfalls).\n\n## Verifying secrets exist WITHOUT printing them\n\nWhen the user says \"the token is in the DB, check it\", never print the secret.\nProve presence + liveness with masked checks:\n\n```bash\n# 1. Row exists, correct shape, value masked:\ndocker exec local-postgres psql -U postgres -d deerngo -Atc \\\n  \"SELECT provider, youtube_channel_id, created_at, LENGTH(refresh_token), LEFT(refresh_token,3) FROM oauth_tokens\"\n\n# 2. Cross-check the channel ID matches .env (length\u002Fprefix only):\nCH=$(grep '^YOUTUBE_CHANNEL_ID=' .env | cut -d= -f2); echo \"${#CH} ${CH:0:4}\"\n\n# 3. LIVE token-exchange probe — values stay in shell vars, only statuses print:\nREFRESH_TOKEN=$(docker exec ... psql -Atc \"SELECT refresh_token FROM oauth_tokens LIMIT 1;\")\nACCESS_TOKEN=$(curl -sS -X POST \"$TOKEN_URI\" \\\n  -d \"client_id=$CLIENT_ID&client_secret=$CLIENT_SECRET&refresh_token=$REFRESH_TOKEN&grant_type=refresh_token\" \\\n  | python3 -c \"import json,sys;print(json.load(sys.stdin)['access_token'])\")\ncurl -sS -o \u002Fdev\u002Fnull -w '%{http_code}\\n' -H \"Authorization: Bearer $ACCESS_TOKEN\" \\\n  \"https:\u002F\u002Fwww.googleapis.com\u002Fyoutube\u002Fv3\u002Fchannels?part=statistics&id=$CHANNEL_ID\"\n```\n\nPrint only lengths, prefixes, and HTTP statuses. On git-bash\u002FMSYS, use `curl`\nfor TLS calls — MSYS `python3` urllib frequently fails with\n`SSL: CERTIFICATE_VERIFY_FAILED` (no CA bundle); curl ships with proper certs.\n\n## Detecting \"API returns a subset\" limitations\n\nWhen the user suspects the poller missed subscribers, compare two live calls:\n\n```bash\n# Public truth: channels.list statistics\nGET \u002Fchannels?part=statistics&id=\u003Cchannel>  → subscriberCount=1310\n# What the poller can see: subscriptions pageInfo\nGET \u002Fsubscriptions?part=snippet&mySubscribers=true&maxResults=1 → totalResults=172\n```\n\nIf `totalResults` \u003C\u003C `subscriberCount`, the endpoint only exposes recent\nsubscribers (ongoing capture works, historical backfill is impossible). This\nis a platform limitation, not a code bug — report it via meeting minute, don't\ntry to \"fix\" the client.\n\n## Pitfalls\n\n- **API spec example URLs may be factually wrong — verify live.** The Deerngo\n  API spec said `GET \u002Fsubscriptions?channelId=X&order=date`. Live testing\n  proved: `channelId=` returns the channels the owner FOLLOWS (not its\n  subscribers), and `order=date` is not a valid enum for subscriptions.list\n  (400 INVALID_ARGUMENT). The correct call is `mySubscribers=true`. When real\n  credentials exist, empirically probe the endpoint (curl with a fresh access\n  token) BEFORE trusting spec query params. See\n  `references\u002Fyoutube-subscriptions-api.md`.\n- **List endpoints may return IDs only — budget a second enrichment call.**\n  `subscriptions?mySubscribers=true` returns only subscriber channel IDs +\n  timestamps (`subscriberSnippet` is empty). Display name + @handle require a\n  second batched call (`GET \u002Fchannels?part=snippet&id=\u003Ccomma-separated>`, 50\n  per call, 1 quota unit each). Account for the extra call in quota math, and\n  fall back to the ID as the handle when a channel has no customUrl.\n- **Parallel business logic in the scheduler** — the scheduler must call the\n  same service method as the HTTP handler. Do not duplicate validation,\n  normalization, or upsert SQL in the scheduler.\n- **Hardcoded poll interval** — always make it configurable; tests need fast\n  intervals and the production default (15 min) is too slow for CI.\n- **Unexported error types** — if `apiError` is unexported, tests in other\n  packages cannot construct it. Export `NewAPIError()` as a test helper.\n- **Missing skip-cycle reset** — after skipping one cycle, `skipNext` must be\n  reset to `false` so the third cycle runs normally.\n- **Token in env vars** — the spec says `oauth_tokens` table. Use the database.\n  The env var is only for the CLI's `DATABASE_URL`.\n- **OAuth credentials in Git** — the credentials JSON must be in `.gitignore`.\n  Never read it into source files or commit it.\n- **No graceful shutdown** — the ticker goroutine must respect `ctx.Done()`\n  or it leaks on process exit.\n- **Testing with real timers** — `PollOnce(ctx)` is the testable entry point.\n  Do not test `Start(ctx)` with real `time.Ticker` waits.\n- **Subscriber lists are subsets** — `mySubscribers=true` returns only the\n  most recent ~N subscribers (Deerngo: 172 of 1,310 public), not the full\n  list. Ongoing capture works; historical backfill is impossible. Detect via\n  `channels.list statistics.subscriberCount` vs `pageInfo.totalResults`.\n- **Platform limitation affecting acceptance criteria → meeting minute, not\n  chat.** When a live finding invalidates what an AC implies (e.g., \"capture\n  all subscribers\" is impossible), notify PO\u002FQA via a meeting minute in the\n  project's `07_pm\u002F` directory following the local MM format (finding →\n  evidence → impact on affected ACs → options → action items), and keep Dev\n  work unblocked with a fix branch. User explicitly requested this\n  (\"create meeting minute to notice the PO\u002FQA instant\").\n- **gofmt on Windows marks every file modified** — `make fmt` (gofmt -w)\n  rewrites files with LF; git status shows all .go files as `M` while\n  `git diff` is EMPTY (CRLF\u002FLF artifact). Verify the diff is empty, then\n  `git restore .` — never commit the line-ending noise.\n- **`git restore` can silently delete uncommitted work** — cleaning the\n  gofmt noise with a broad `git restore cmd internal` also reverted an\n  UNCOMMITTED new test file in the working tree (it was only flagged as\n  `M` by the same CRLF artifact, so it looked like noise). Rules: (1)\n  commit all intended changes BEFORE restoring line-ending noise; (2) if\n  you must restore before committing, restore only the specific noise\n  files, and `grep -c` your new symbol afterward to confirm it survived.\n",{"name":5,"author":24,"license":15,"version":25,"metadata":26,"platforms":40,"description":7},"Hermes Agent","1.0.0",{"hermes":27},{"tags":28,"related_skills":36},[29,30,31,32,33,34,35],"go","scheduler","background-goroutine","api-poller","oauth","external-integration","tdd",[37,38,39],"test-driven-development","github-pr-workflow","systematic-debugging",[41,42,43],"windows","macos","linux","main","2988869c5a7d7be2225c9ea7a54a4a56a59b0d45","workflow\u002Ffull-stack\u002Fgo-background-scheduler-api-poller",0,"https:\u002F\u002Fgithub.com\u002Foat431\u002Fhermes_config_backup","https:\u002F\u002Fgithub.com\u002Foat431","https:\u002F\u002Fpanomete.com\u002F","Hope and Luck is not a part of the strategy, \r\n\r\nSoftskill produces plan Hard skill produce product.","2026-11-03 00:43:08",{"source":8,"skillName":5,"commands":54,"prompt":64,"zipAvailable":65},[55,58,61],{"tool":56,"command":57},"npx","npx skills add oat431\u002Fhermes_config_backup --skill go-background-scheduler-api-poller",{"tool":59,"command":60},"bunx","bunx skills add oat431\u002Fhermes_config_backup --skill go-background-scheduler-api-poller",{"tool":62,"command":63},"pnpm","pnpm dlx skills add oat431\u002Fhermes_config_backup --skill go-background-scheduler-api-poller","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Foat431\u002Fhermes_config_backup\u002Fblob\u002Fmain\u002Fworkflow\u002Ffull-stack\u002Fgo-background-scheduler-api-poller\u002FSKILL.md",true,[67,73,77],{"path":68,"resourceType":69,"resourceTypeDesc":70,"sizeBytes":71,"sourceHtmlUrl":72},"references\u002Fdeerngo-youtube-poller-example.md","REFERENCE","参考文档",7867,"https:\u002F\u002Fgithub.com\u002Foat431\u002Fhermes_config_backup\u002Fblob\u002Fmain\u002Fworkflow\u002Ffull-stack\u002Fgo-background-scheduler-api-poller\u002Freferences\u002Fdeerngo-youtube-poller-example.md",{"path":74,"resourceType":69,"resourceTypeDesc":70,"sizeBytes":75,"sourceHtmlUrl":76},"references\u002Fwindows-docker-postgres-integration-testing.md",4538,"https:\u002F\u002Fgithub.com\u002Foat431\u002Fhermes_config_backup\u002Fblob\u002Fmain\u002Fworkflow\u002Ffull-stack\u002Fgo-background-scheduler-api-poller\u002Freferences\u002Fwindows-docker-postgres-integration-testing.md",{"path":78,"resourceType":69,"resourceTypeDesc":70,"sizeBytes":79,"sourceHtmlUrl":80},"references\u002Fyoutube-subscriptions-api.md",5740,"https:\u002F\u002Fgithub.com\u002Foat431\u002Fhermes_config_backup\u002Fblob\u002Fmain\u002Fworkflow\u002Ffull-stack\u002Fgo-background-scheduler-api-poller\u002Freferences\u002Fyoutube-subscriptions-api.md",[82,89,96,104,111,118],{"skillNo":83,"name":84,"nameZh":6,"description":85,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":86,"categories":87,"keywords":88,"publishedAt":19},"01M7AYZ2JY3NFKAPQSC39N5F3F","project-spec-docs","Fill\u002Fupdate project_spec docs (templates, MM handoffs).","https:\u002F\u002Fgithub.com\u002Foat431\u002Fhermes_config_backup\u002Fblob\u002Fmain\u002Fworkflow\u002Fui-ux\u002Fproject-spec-docs\u002FSKILL.md",[],[],{"skillNo":90,"name":91,"nameZh":6,"description":92,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":93,"categories":94,"keywords":95,"publishedAt":19},"01M7AYYRZPE7HQX7778558X52S","penpot-mcp","Penpot MCP: connect, verify, and fix streaming via nginx.","https:\u002F\u002Fgithub.com\u002Foat431\u002Fhermes_config_backup\u002Fblob\u002Fmain\u002Fworkflow\u002Fui-ux\u002Fpenpot-mcp\u002FSKILL.md",[],[],{"skillNo":97,"name":98,"nameZh":6,"description":99,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":100,"licenseFileUrl":6,"sourceHtmlUrl":101,"categories":102,"keywords":103,"publishedAt":19},"01M7AYYNKP61CN2281VMJDXMB5","nginx-streaming-proxy","Configure nginx for streaming endpoints (SSE, MCP, WS).","Unlicense","https:\u002F\u002Fgithub.com\u002Foat431\u002Fhermes_config_backup\u002Fblob\u002Fmain\u002Fworkflow\u002Fui-ux\u002Fnginx-streaming-proxy\u002FSKILL.md",[],[],{"skillNo":105,"name":106,"nameZh":6,"description":107,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":108,"categories":109,"keywords":110,"publishedAt":19},"01M7AYYJP0MDV1D3WVEEZB3SGA","branding-ci","Use for brand\u002FCI identity, style guides, and brand docs.","https:\u002F\u002Fgithub.com\u002Foat431\u002Fhermes_config_backup\u002Fblob\u002Fmain\u002Fworkflow\u002Fui-ux\u002Fbranding-ci\u002FSKILL.md",[],[],{"skillNo":112,"name":113,"nameZh":6,"description":114,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":100,"licenseFileUrl":6,"sourceHtmlUrl":115,"categories":116,"keywords":117,"publishedAt":19},"01M7AYYGCXVT97DDTCM0ZJT6F6","yuanbao","Yuanbao (元宝) groups: @mention users, query info\u002Fmembers.","https:\u002F\u002Fgithub.com\u002Foat431\u002Fhermes_config_backup\u002Fblob\u002Fmain\u002Fworkflow\u002Fshared-skills\u002Fyuanbao\u002FSKILL.md",[],[],{"skillNo":119,"name":120,"nameZh":6,"description":121,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":100,"licenseFileUrl":6,"sourceHtmlUrl":122,"categories":123,"keywords":124,"publishedAt":19},"01M7AYYC2Y65NMGMD4GQXAZMMS","slidev","Create and present web-based slidedecks for developers using Slidev with Markdown, Vue components, code highlighting, animations, and interactive features. Use when building technical presentations, conference talks, code walkthroughs, teaching materials, or developer decks.","https:\u002F\u002Fgithub.com\u002Foat431\u002Fhermes_config_backup\u002Fblob\u002Fmain\u002Fworkflow\u002Fshared-skills\u002Fslidev\u002FSKILL.md",[],[]]