Skip to content

feat(cli): expose handler hook for injecting SDK options#3755

Merged
ronelliott merged 1 commit into
mainfrom
feat/otdfctl-handler-extra-opts
Jul 20, 2026
Merged

feat(cli): expose handler hook for injecting SDK options#3755
ronelliott merged 1 commit into
mainfrom
feat/otdfctl-handler-extra-opts

Conversation

@ronelliott

@ronelliott ronelliott commented Jul 17, 2026

Copy link
Copy Markdown
Contributor

Proposed Changes

  • Add a Hook extension point to pkg/handlers so callers can inject SDK options that depend on the resolved profile without replicating any of the profile resolution or credential validation flow.
  • Rename the internal handlerOptsFunc to the exported HandlerOption so downstream packages can name the option type when composing calls to handlers.New.
  • Extend cmd/common.NewHandler with an optional variadic ...handlers.Hook. Every existing zero-hook call site keeps working unchanged.

The hook runs after every HandlerOption has been applied and before sdk.New is called. Hooks compose in registration order and receive a HookContext with the fully resolved endpoint, TLS flag, and profile.

Motivation

A Virtru CLI built on top of otdfctl (tructl) currently duplicates common.NewHandler wholesale, about 130 lines of profile resolution, flag validation, and credential error handling, purely so it can attach a client-side connect interceptor to the SDK for license status header capture. With this hook that downstream call collapses to:

h := common.NewHandler(c, func(hookCtx handlers.HookContext) []sdk.Option {
    return []sdk.Option{sdk.WithExtraClientOptions(
        connect.WithInterceptors(premium.NewLicenseStatusInterceptor()),
    )}
})

and otdfctl stays the single owner of the profile and auth flow.

Checklist

  • I have added or updated unit tests
  • I have added or updated integration tests (if appropriate)
  • I have added or updated documentation

Testing Instructions

  • cd otdfctl && go test ./... -race
  • New tests live in pkg/handlers/sdk_test.go and cover:
    • hook registration order
    • HookContext content matches the resolved handler config
    • hook-returned options append to sdkOpts
    • applyHooks is a no-op when no hooks are registered

Summary by CodeRabbit

  • New Features

    • Added an extensibility mechanism for customizing SDK setup through handler hooks.
    • Added support for supplying custom SDK options when creating handlers.
    • Hooks can access resolved endpoint, TLS, and profile settings before SDK initialization.
    • Multiple hooks are supported in registration order, while nil hooks are safely ignored.
  • Tests

    • Expanded coverage for hook registration, execution order, configuration context, and edge cases.

@ronelliott
ronelliott requested a review from a team as a code owner July 17, 2026 16:03
@gemini-code-assist

Copy link
Copy Markdown
Contributor

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request introduces a hook-based extension point to the handler initialization flow. By allowing downstream consumers to inject SDK options after profile resolution, it eliminates the need for redundant code in secondary CLI tools while maintaining centralized control over authentication and profile management.

Highlights

  • Extension Point Added: Introduced a Hook mechanism in pkg/handlers to allow callers to inject SDK options dynamically based on resolved profile configurations.
  • API Refinement: Renamed handlerOptsFunc to HandlerOption to improve readability and allow downstream packages to explicitly reference the option type.
  • CLI Integration: Updated cmd/common.NewHandler to accept variadic handlers.Hook arguments, enabling flexible SDK configuration without duplicating core logic.
New Features

🧠 You can now enable Memory (public preview) to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize the Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counterproductive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.


Hooks are set in order true, / To help the SDK get through. / Profile resolved and context clear, / The extra options now appear.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@coderabbitai

coderabbitai Bot commented Jul 17, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@ronelliott, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 27 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Repository UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: c09a9f1e-93b4-4e34-8de6-36226b66c596

📥 Commits

Reviewing files that changed from the base of the PR and between 9dcafcc and 6f5db67.

📒 Files selected for processing (3)
  • otdfctl/cmd/common/common.go
  • otdfctl/pkg/handlers/sdk.go
  • otdfctl/pkg/handlers/sdk_test.go
📝 Walkthrough

Walkthrough

Changes

Handler Hook Extension

Layer / File(s) Summary
Hook API and SDK option application
otdfctl/pkg/handlers/sdk.go, otdfctl/pkg/handlers/sdk_test.go
Exported handler options and pre-SDK hooks register ordered hooks, pass resolved configuration, append returned SDK options, and test nil, unknown, and no-hook behavior.
Command-level hook wiring
otdfctl/cmd/common/common.go
NewHandler accepts variadic hooks and forwards them with the resolved profile option.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Sequence Diagram(s)

sequenceDiagram
  participant NewHandler
  participant handlers.New
  participant applyHooks
  participant PreSDKHook
  participant SDK
  NewHandler->>handlers.New: pass profile and hooks
  handlers.New->>applyHooks: apply registered hooks
  applyHooks->>PreSDKHook: pass resolved context
  PreSDKHook-->>applyHooks: return SDK options
  applyHooks-->>handlers.New: append options
  handlers.New->>SDK: construct SDK
Loading

Poem

A rabbit hops through options bright,
Hooks line up in ordered flight.
Profiles guide the SDK’s way,
Nil ones vanish without delay.
“Build,” squeaks Bunny, “clean and neat!” 🐇

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 36.36% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly matches the main change: exposing a handler hook to inject SDK options.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/otdfctl-handler-extra-opts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a hook mechanism during handler construction, allowing downstream CLI extensions to inject SDK options after profile resolution. It renames handlerOptsFunc to HandlerOption, adds the Hook and HookContext types, and implements the WithHook option along with comprehensive unit tests. The review feedback suggests adding defensive nil checks in WithProfile and WithHook to prevent potential nil pointer dereference panics.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment thread otdfctl/pkg/handlers/sdk.go
Comment thread otdfctl/pkg/handlers/sdk.go Outdated
@github-actions

Copy link
Copy Markdown
Contributor
Benchmark results, click to expand

Benchmark authorization.GetDecisions Results:

Metric Value
Approved Decision Requests 1000
Denied Decision Requests 0
Total Time 196.166622ms

Benchmark authorization.v2.GetMultiResourceDecision Results:

Metric Value
Approved Decision Requests 1000
Denied Decision Requests 0
Total Time 102.645991ms

Benchmark Statistics

Name № Requests Avg Duration Min Duration Max Duration

Bulk Benchmark Results

Metric Value
Total Decrypts 100
Successful Decrypts 100
Failed Decrypts 0
Total Time 447.958867ms
Throughput 223.23 requests/second

TDF3 Benchmark Results:

Metric Value
Total Requests 5000
Successful Requests 5000
Failed Requests 0
Concurrent Requests 50
Total Time 43.951282706s
Average Latency 437.891922ms
Throughput 113.76 requests/second

@coderabbitai

coderabbitai Bot commented Jul 17, 2026

Copy link
Copy Markdown

Caution

Review failed

An error occurred during the review process. Please try again later.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/otdfctl-handler-extra-opts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai

coderabbitai Bot commented Jul 17, 2026

Copy link
Copy Markdown

Caution

Failed to replace (edit) comment. This is likely due to insufficient permissions or the comment being deleted.

Error details
putComment timed out

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@otdfctl/pkg/handlers/sdk.go`:
- Around line 92-97: Update WithHook to ignore a nil hook before appending it to
c.hooks. Preserve the existing append-and-return behavior for non-nil hooks so
applyHooks only receives executable hooks.
- Around line 81-86: Update WithSDKOpts to append the supplied opts to the
existing c.sdkOpts slice rather than replacing it, preserving previously
configured SDK options when HandlerOption values are composed or applied
repeatedly.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 85584680-95b7-43aa-aabf-93718b89ac6b

📥 Commits

Reviewing files that changed from the base of the PR and between 21e95e0 and a9bda63.

📒 Files selected for processing (3)
  • otdfctl/cmd/common/common.go
  • otdfctl/pkg/handlers/sdk.go
  • otdfctl/pkg/handlers/sdk_test.go

Comment thread otdfctl/pkg/handlers/sdk.go
Comment thread otdfctl/pkg/handlers/sdk.go Outdated
@ronelliott
ronelliott force-pushed the feat/otdfctl-handler-extra-opts branch from a9bda63 to 19c6378 Compare July 17, 2026 16:15
@ronelliott ronelliott changed the title feat(otdfctl): expose handler hook for injecting SDK options feat(cli): expose handler hook for injecting SDK options Jul 17, 2026
@github-actions

Copy link
Copy Markdown
Contributor
Benchmark results, click to expand

Benchmark authorization.GetDecisions Results:

Metric Value
Approved Decision Requests 1000
Denied Decision Requests 0
Total Time 200.424536ms

Benchmark authorization.v2.GetMultiResourceDecision Results:

Metric Value
Approved Decision Requests 1000
Denied Decision Requests 0
Total Time 107.522723ms

Benchmark Statistics

Name № Requests Avg Duration Min Duration Max Duration

Bulk Benchmark Results

Metric Value
Total Decrypts 100
Successful Decrypts 100
Failed Decrypts 0
Total Time 448.328406ms
Throughput 223.05 requests/second

TDF3 Benchmark Results:

Metric Value
Total Requests 5000
Successful Requests 5000
Failed Requests 0
Concurrent Requests 50
Total Time 45.589289388s
Average Latency 453.356219ms
Throughput 109.67 requests/second

@ronelliott
ronelliott force-pushed the feat/otdfctl-handler-extra-opts branch from 19c6378 to 9dcafcc Compare July 17, 2026 21:00

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@otdfctl/pkg/handlers/sdk.go`:
- Around line 106-116: Update WithHook to detect and skip typed-nil Hook values,
including a nil PreSDKHook stored in the Hook interface, before appending to
c.hooks. Preserve registration of non-nil hooks and ensure the typed-nil case
does not reach later invocation.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 2a25b30b-b907-48b2-8ba0-aaa8e82052c1

📥 Commits

Reviewing files that changed from the base of the PR and between a9bda63 and 9dcafcc.

📒 Files selected for processing (3)
  • otdfctl/cmd/common/common.go
  • otdfctl/pkg/handlers/sdk.go
  • otdfctl/pkg/handlers/sdk_test.go

Comment thread otdfctl/pkg/handlers/sdk.go
@github-actions

Copy link
Copy Markdown
Contributor
Benchmark results, click to expand

Benchmark authorization.GetDecisions Results:

Metric Value
Approved Decision Requests 1000
Denied Decision Requests 0
Total Time 168.737005ms

Benchmark authorization.v2.GetMultiResourceDecision Results:

Metric Value
Approved Decision Requests 1000
Denied Decision Requests 0
Total Time 91.657894ms

Benchmark Statistics

Name № Requests Avg Duration Min Duration Max Duration

Bulk Benchmark Results

Metric Value
Total Decrypts 100
Successful Decrypts 100
Failed Decrypts 0
Total Time 370.053184ms
Throughput 270.23 requests/second

TDF3 Benchmark Results:

Metric Value
Total Requests 5000
Successful Requests 5000
Failed Requests 0
Concurrent Requests 50
Total Time 40.990842589s
Average Latency 408.226079ms
Throughput 121.98 requests/second

Adds a Hook extension point so downstream CLIs built on otdfctl's
common.NewHandler can inject SDK options that depend on the resolved
profile (for example, a client-side connect interceptor) without
having to replicate the profile resolution, flag validation, and
credential error handling that lives inside NewHandler today.

Changes:

- pkg/handlers: rename handlerOptsFunc to exported HandlerOption so
  downstream packages can name the option type when composing calls to
  handlers.New. Introduce Hook as a marker interface and PreSDKHook as
  the first concrete variant; PreSDKHook runs after every
  HandlerOption has been applied and before sdk.New so it observes the
  fully resolved endpoint, TLS flag, and profile via
  PreSDKHookContext. Future point-specific hooks (post-build,
  auth-error, etc.) land as sibling named types with an
  isHandlerHook receiver and a new case in the applyHooks dispatch
  switch, so no new exported registration function is needed. WithHook
  is variadic and skips nil entries, and WithProfile skips nil
  profiles so it cannot deref GetEndpoint. applyHooks drops unknown
  Hook variants rather than panicking, so future variants can land
  ahead of the corresponding dispatch update.
- cmd/common: NewHandler accepts an optional variadic list of
  handlers.Hook values and forwards them into handlers.New via
  WithHook. Zero-hook callers are unchanged, so every existing
  common.NewHandler(c) call site continues to compile and behave the
  same way.

Motivation: a Virtru CLI that wraps otdfctl currently duplicates
common.NewHandler wholesale (~130 lines of profile resolution, flag
validation, and credential error handling) purely to attach a
license-status capture interceptor to the SDK. With this hook the
downstream call collapses to a single
common.NewHandler(c, handlers.PreSDKHook(fn)) and otdfctl remains the
single owner of profile and auth flow logic.

Test plan:

- pkg/handlers/sdk_test.go covers hook registration order (including
  the variadic form), PreSDKHookContext content, option append
  behavior, the no-hooks no-op path, the nil-input guards on WithHook
  (single and variadic) and WithProfile, and the unknown-variant
  drop path.
- otdfctl `go test ./... -race` passes.

Signed-off-by: Ron Elliott <ron.elliott@virtru.com>
@ronelliott
ronelliott force-pushed the feat/otdfctl-handler-extra-opts branch from 9dcafcc to 6f5db67 Compare July 17, 2026 21:32
@github-actions

Copy link
Copy Markdown
Contributor
Benchmark results, click to expand

Benchmark authorization.GetDecisions Results:

Metric Value
Approved Decision Requests 1000
Denied Decision Requests 0
Total Time 201.363025ms

Benchmark authorization.v2.GetMultiResourceDecision Results:

Metric Value
Approved Decision Requests 1000
Denied Decision Requests 0
Total Time 110.905086ms

Benchmark Statistics

Name № Requests Avg Duration Min Duration Max Duration

Bulk Benchmark Results

Metric Value
Total Decrypts 100
Successful Decrypts 100
Failed Decrypts 0
Total Time 453.204075ms
Throughput 220.65 requests/second

TDF3 Benchmark Results:

Metric Value
Total Requests 5000
Successful Requests 5000
Failed Requests 0
Concurrent Requests 50
Total Time 46.457907145s
Average Latency 463.075229ms
Throughput 107.62 requests/second

@github-actions

Copy link
Copy Markdown
Contributor

⚠️ Govulncheck found vulnerabilities ⚠️

The following modules have known vulnerabilities:

  • examples
  • otdfctl
  • sdk
  • service
  • lib/fixtures
  • tests-bdd

See the workflow run for details.

@ronelliott
ronelliott added this pull request to the merge queue Jul 20, 2026
Merged via the queue into main with commit 76305b0 Jul 20, 2026
45 checks passed
@ronelliott
ronelliott deleted the feat/otdfctl-handler-extra-opts branch July 20, 2026 14:44
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants