Repository navigation
refactor(drogon): flatten GitHubController::login callback hell - #18
Merged
Merged
Conversation
- Survey how industry handles nested-callback async (Future/Promise .then(), async/await coroutines, Rx) with one-line citations from Google C++ Style Tips, folly (Meta), C++ Core Guidelines, Drogon官方 - Quantify the current pain in authforge: GitHubController::login is a 564-line method with 7 nested lambdas, two near-verbatim issueTokens copies, and 9 duplicated DrogonDbException error callbacks; pure-callback model with zero Future/Promise/coroutine abstraction, locked to C++17 - Compare three remediation paths (A: pure structural refactor in C++17; B: self-built Future/Promise in C++17; C: C++20 coroutine + CoroMapper) via a side-by-side matrix covering deps, spec impact, interface break, indent reduction, effort, risk, reversibility - Recommend path A as the immediate, zero-risk landing (single file, GitHubController.cc) with a concrete pre/post pseudo-code preview, and retain B/C as longer-term evolution with explicit trigger conditions - Per decision: coroutines excluded this round (TECH_SPECS §一 bans CoroMapper); C++17 std::future also unused repo-wide
Lift the 564-line login() body with up to 7 nested async lambdas into 8
named private member methods, one per step of the OAuth flow. Behaviour
is identical to the pre-refactor implementation; only structure changes.
- Merge the two near-verbatim issueTokens lambdas (WITH_SOCIAL path +
fallback path) into a single issueTokensForUser() member; split its
two-step DB insert into persistAccessToken()/persistRefreshToken()
- Split the fallback path into a linear step chain: exchangeCodeForToken
-> fetchGitHubUserInfo -> resolveSubjectMapping -> {linkExistingUser,
createNewLinkedUser} -> issueTokensForUser; each step is a single-level
async callback that hands off to the next
- Add a CallbackPtr type alias (shared_ptr<function<void(HttpResponsePtr)>)
on the controller so all step helpers share one callback-lifetime type
without re-spelling it (TECH_SPECS §一 Callback 生命周期 convention)
- Preserve every behavioural detail verbatim: linkExistingUser keeps the
original no-op-on-empty-row behaviour (username was read but unused),
UserRoles insert stays best-effort (success/error both proceed to token
issuance), and try/catch scope around the Mapper insert call is unchanged
- No new deps, no interface-signature changes, no CMake/TECH_SPECS edits
Verified locally: cmake --preset windows-msvc builds authforge-drogon
with zero warnings; the OpenAPI endpoint-set baseline test (15 assertions)
and the route fingerprint baseline test both pass, confirming
POST/OPTIONS /api/github/login registration is unchanged.
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
…iff baseline api-diff flagged 55 additive declaration lines in GitHubController.h (the CallbackPtr alias + 8 new private step-helper methods introduced by the login() callback-flattening refactor). All additions are private members inaccessible to SDK consumers, so this is purely additive with no version bump required. Regenerated via: python tools/api-diff/api_diff.py --update-baseline Now reports "OK (164 headers match baseline)".
…+ cleanup) Address the should-fix and minor items from PR #18 review. The two 🔴 items are pre-existing robustness gaps (present in the original code, faithfully carried over by the refactor) now fixed in passing; none of these change behaviour on the happy or normal-error paths. 🔴 Should-fix - Wrap the 4 Mapper constructions that run inside async success callbacks in their own try/catch: persistRefreshToken, linkExistingUser, and the SubjectMappings + UserRoles inserts inside createNewLinkedUser. The outer try/catch (issueTokensForUser, resolveSubjectMapping) cannot reach across the async boundary, so a synchronous throw from Mapper construction (e.g. DbClient in a bad state) previously escaped into the Drogon event loop and would abort the process; now converted to a normal DB_QUERY_ERROR response. NB: this gap existed identically in the pre-refactor code -- the refactor preserved it, this commit fixes it. - fetchGitHubUserInfo: null-check getJsonObject() before dereferencing, matching the check already done in exchangeCodeForToken. A non-JSON body (e.g. GitHub 5xx returning HTML) yields an empty shared_ptr and would have crashed on dereference. 🟡 Minor - Add a respondDbError(req, cb, ctx, e) helper (DrogonDbException and std::exception overloads) and route every DB error path through it, removing ~6 inline copies of the "github login: <ctx>: " + e.what() template (assessment doc path-A item 2). - Document the intentional [this] capture at the top of the private section, pointing at the canonical TokenEndpointController.cc:1306 rationale, so future reviewers/static analysers don't re-flag it. - Strengthen the linkExistingUser comment explaining why the (result- unused) findBy is preserved verbatim (equivalence + it doubles as the "user row exists" guard). ⚪ Not actioned (with rationale) - Review item 6 (INSERT ... ON CONFLICT as a semantic change): verified against f500f57 -- the ON CONFLICT clause was already present in the original code; no change introduced by the refactor. - Review item 7 (api-baseline including private symbols): this is the api-diff tool's mechanical, file-level behaviour and matches repo convention (see 4a5c73e); left as-is. Verified locally: cmake --preset windows-msvc builds authforge-drogon with zero warnings (MSVC 19.4, C++17, Release, /W4); api-diff reports "OK (164 headers match baseline)"; route fingerprint baseline test passes -- POST/OPTIONS /api/github/login registration unchanged.
Resolve the "rule file not found" gap surfaced during the GitHubController review: the async/DB rules live in .claude/rules/ but no project-level instruction file pointed at them, so non-Claude tools (e.g. ZCode) had no way to discover the canonical source. AGENTS.md (new, project-level instruction file): - Index + navigation form -- does NOT copy rule bodies, so there remains a single source of truth in .claude/rules/ and no drift risk - Rule index table linking the 4 rule files (db-operations, data-access, orm-models, dev-workflow) with one-line summaries and applicable paths - Pointer to db-operations.md for async/DB detail without restating it - Clarifies the [this]-capture rule that differs by layer (Domain services must use shared_from_this; controllers may use [this] -- HttpController is a process singleton). The old TECH_SPECS.md listed [this] as a global ban, conflicting with controller-layer practice (TokenEndpointController.cc:1306); corrected here - Documents the role of each AI-tool directory (.claude as source of truth; .codebuddy/.qoder as mirrors; .zcode/.workbuddy as config/memory) TECH_SPECS.md (slimmed, 129 -> 99 lines): - Replace the duplicated "async programming" and "data access" sections (whose tables were a subset of .claude/rules/db-operations.md) with short pointers to that file - Remove the inaccurate [this]-capture ban (layer-specific, see AGENTS.md) - KEEP sections that have no rules-file equivalent: architecture, code quality (C++17/Google style/100-col/clang-format/ASCII), security (RFC 6749/Token TTL/SHA-256/log redaction) - Drop the [MUST] tag from the two slimmed sections -- they are pointers now, not normative text; the [MUST] lives in db-operations.md
wangrh0909
approved these changes
Aug 5, 2026
voidvec
added a commit
that referenced
this pull request
Aug 5, 2026
…+ cleanup) Address the should-fix and minor items from PR #18 review. The two 🔴 items are pre-existing robustness gaps (present in the original code, faithfully carried over by the refactor) now fixed in passing; none of these change behaviour on the happy or normal-error paths. 🔴 Should-fix - Wrap the 4 Mapper constructions that run inside async success callbacks in their own try/catch: persistRefreshToken, linkExistingUser, and the SubjectMappings + UserRoles inserts inside createNewLinkedUser. The outer try/catch (issueTokensForUser, resolveSubjectMapping) cannot reach across the async boundary, so a synchronous throw from Mapper construction (e.g. DbClient in a bad state) previously escaped into the Drogon event loop and would abort the process; now converted to a normal DB_QUERY_ERROR response. NB: this gap existed identically in the pre-refactor code -- the refactor preserved it, this commit fixes it. - fetchGitHubUserInfo: null-check getJsonObject() before dereferencing, matching the check already done in exchangeCodeForToken. A non-JSON body (e.g. GitHub 5xx returning HTML) yields an empty shared_ptr and would have crashed on dereference. 🟡 Minor - Add a respondDbError(req, cb, ctx, e) helper (DrogonDbException and std::exception overloads) and route every DB error path through it, removing ~6 inline copies of the "github login: <ctx>: " + e.what() template (assessment doc path-A item 2). - Document the intentional [this] capture at the top of the private section, pointing at the canonical TokenEndpointController.cc:1306 rationale, so future reviewers/static analysers don't re-flag it. - Strengthen the linkExistingUser comment explaining why the (result- unused) findBy is preserved verbatim (equivalence + it doubles as the "user row exists" guard). ⚪ Not actioned (with rationale) - Review item 6 (INSERT ... ON CONFLICT as a semantic change): verified against f500f57 -- the ON CONFLICT clause was already present in the original code; no change introduced by the refactor. - Review item 7 (api-baseline including private symbols): this is the api-diff tool's mechanical, file-level behaviour and matches repo convention (see 4a5c73e); left as-is. Verified locally: cmake --preset windows-msvc builds authforge-drogon with zero warnings (MSVC 19.4, C++17, Release, /W4); api-diff reports "OK (164 headers match baseline)"; route fingerprint baseline test passes -- POST/OPTIONS /api/github/login registration unchanged.
voidvec
added a commit
that referenced
this pull request
Aug 30, 2026
…loor, bootstrap self-heal, review cleanups Address PR #141 review (1 must-fix, 8 should-fix, quick considers): - #1 consent_csrf declared as a required query parameter in openapi.yaml and the C++ endpoint doc registration; apps/server/docs/api/openapi.json regenerated from a live server run; Python/Go clients regenerated. - #2 nonce one-shot is now atomic: the find/verify/erase sequence is serialized by a process-wide mutex (consent traffic is tiny; in-process session storage). - #3 identity AuthService no longer captures this in the async validateUser callback — the legacy-hash policy flag is value-captured (db-operations rule 4). - #4/#12 AdminBootstrapper reworked as ensure-* steps: an existing admin user row is reused and role/mapping completed (partial failures self-heal on restart); the random password is printed only after the insert succeeded; a mapping failure no longer reports created=true. - #5 POST /api/admin/users enforces auth.min_password_length (VALIDATION_PASSWORD_TOO_SHORT) — closing the admin bypass. - #6 consent integration tests reworked: missing-nonce now drives the real authorize-minted slot (400), deny-to-unregistered-uri (400, no Location) and deny-to-registered-uri (302 access_denied) branches are covered. - #7/#8 deployment.md: auto-bootstrap wording fixed, bogus ADMIN_SALT removed (PBKDF2 keeps salt empty); website i18n error table mirrored (3014/4007). - #9 main.cc bootstrap probes with backoff (5 attempts) and LOG_WARN on failure instead of a single silent 2s probe. - #13 unique-violation detection layered (SqlError 23505 -> constraint name -> english/zh localized text), mirroring the PostgresSocialAccountRepository pattern. - #11 gate-4 comment corrected; #15 CHANGELOG duplicate Unreleased merged; #17 AGENTS.md consent.csp entry removed. Considered-but-not-taken: #10 multi-slot nonces (tracked follow-up), #14 admin UI hardcode (server now enforces; hint stays), #18 MFA-pending session through consent (pre-existing authorize behavior, tracked).
voidvec
added a commit
that referenced
this pull request
Aug 30, 2026
…loor, bootstrap self-heal, review cleanups Address PR #141 review (1 must-fix, 8 should-fix, quick considers): - #1 consent_csrf declared as a required query parameter in openapi.yaml and the C++ endpoint doc registration; apps/server/docs/api/openapi.json regenerated from a live server run; Python/Go clients regenerated. - #2 nonce one-shot is now atomic: the find/verify/erase sequence is serialized by a process-wide mutex (consent traffic is tiny; in-process session storage). - #3 identity AuthService no longer captures this in the async validateUser callback — the legacy-hash policy flag is value-captured (db-operations rule 4). - #4/#12 AdminBootstrapper reworked as ensure-* steps: an existing admin user row is reused and role/mapping completed (partial failures self-heal on restart); the random password is printed only after the insert succeeded; a mapping failure no longer reports created=true. - #5 POST /api/admin/users enforces auth.min_password_length (VALIDATION_PASSWORD_TOO_SHORT) — closing the admin bypass. - #6 consent integration tests reworked: missing-nonce now drives the real authorize-minted slot (400), deny-to-unregistered-uri (400, no Location) and deny-to-registered-uri (302 access_denied) branches are covered. - #7/#8 deployment.md: auto-bootstrap wording fixed, bogus ADMIN_SALT removed (PBKDF2 keeps salt empty); website i18n error table mirrored (3014/4007). - #9 main.cc bootstrap probes with backoff (5 attempts) and LOG_WARN on failure instead of a single silent 2s probe. - #13 unique-violation detection layered (SqlError 23505 -> constraint name -> english/zh localized text), mirroring the PostgresSocialAccountRepository pattern. - #11 gate-4 comment corrected; #15 CHANGELOG duplicate Unreleased merged; #17 AGENTS.md consent.csp entry removed. Considered-but-not-taken: #10 multi-slot nonces (tracked follow-up), #14 admin UI hardcode (server now enforces; hint stays), #18 MFA-pending session through consent (pre-existing authorize behavior, tracked).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Flatten the 564-line
GitHubController::loginmethod with up to 7 nested async lambdas into 8 named private member methods, one per step of the OAuth flow. Behaviour is identical to the pre-refactor implementation — only structure changes.This is the path-A landing from
docs/async-refactor-assessment.md(also in this PR): the lowest-risk, zero-dependency, zero-spec-change remediation for the callback-hell pattern surveyed there.Changes
GitHubController.h(+92)CallbackPtrtype alias (shared_ptr<function<void(HttpResponsePtr)>>) as a private member typedef so all step helpers share one callback-lifetime type (TECH_SPECS §一 Callback 生命周期 convention).GitHubController.cc(net +23)issueTokenslambdas (WITH_SOCIAL path + fallback path) into a singleissueTokensForUser()member; split its two-step DB insert intopersistAccessToken()/persistRefreshToken().exchangeCodeForToken→fetchGitHubUserInfo→resolveSubjectMapping→ {linkExistingUser,createNewLinkedUser} →issueTokensForUser. Each step is a single-level async callback that hands off to the next.login()shrinks from 564 lines / 7 nesting levels to ~85 lines / single-level orchestration.docs/async-refactor-assessment.md(+324, new).then(), coroutines, Rx) with citations from Google C++ Style Tips, folly, C++ Core Guidelines, Drogon官方.Behaviour-equivalence guarantees
Every detail preserved verbatim (verified by reviewer + git diff against
f500f57):issueTokensForUserkeeps theresolvePlugin()guard (present in both original copies).linkExistingUserkeeps the original no-op-on-empty-row behaviour (username was read but unused;(void)users;thenissueTokensForUser).createNewLinkedUserkeeps the best-effortUserRolesinsert (success and error callbacks both proceed to token issuance).clientId=\"vue-client\",scope=\"openid profile email\",expiresAt=now+3600(access) /now+2592000(refresh).DrogonDbExceptionasync error callbacks traced; the 2 that disappear (access/refresh token inserts in the now-removed duplicate copy B) are exact duplicates of copy A's callbacks — no error branch lost.NET_CONNECTION_FAILED/VALIDATION_INVALID_INPUT/DB_QUERY_ERROR/INTERNAL_ERRORwith identical detail strings.Verification
cmake --preset windows-msvcbuildsauthforge-drogonwith zero warnings (MSVC 19.4, C++17, Release, /W4).Unit_P1_InitOrder_1_1_OpenApiEndpointSet_Complete_Baselinepasses (15 assertions) —POST/OPTIONS /api/github/loginregistration intact.Integration_P1_OpenApiSpec_Property4_3_1_PathMethodFingerprint_Baselinepasses — route manifest byte-identical to pre-refactor.GitHubController::loginexists in the repo (only assembly/route tests cover it); equivalence was verified by line-by-line review againstf500f57.Out of scope (deliberately)
CoroMapper).HttpClientshared_ptr capture inexchangeCodeForToken/fetchGitHubUserInfoleft as-is to keep the refactor purely equivalence-preserving (matches original; siblings Google/WeChat capture it — a separate style cleanup).