Skip to content

fix: align thread-safety docs and add CI test coverage#37

Merged
kooksee merged 8 commits into
v2from
fix/review-followups
Jun 16, 2026
Merged

fix: align thread-safety docs and add CI test coverage#37
kooksee merged 8 commits into
v2from
fix/review-followups

Conversation

@kooksee

@kooksee kooksee commented Jun 16, 2026

Copy link
Copy Markdown
Collaborator

Clarify non-thread-safe container behavior, expose top-level Try* APIs, and run full test suite in task/CI with added smoke tests for public wrappers.

Summary by CodeRabbit

  • New Features
    • Added error-returning TryProvide, TryInject, and TryInjectContext helpers for dependency operations.
  • Documentation
    • Expanded Quick Start and API guidance, including detailed thread-safety limitations and recommended startup patterns.
    • Updated diagnostics and dixhttp security guidance (including a reverse-proxy auth example).
  • Tests
    • Added/expanded unit tests for context-aware injection, generic panic behavior, and dixcontext helpers.
  • CI / Chores
    • Updated CI workflow to include a test job (runs go test ./... with -race), and broadened the test task to all packages.

Clarify non-thread-safe container behavior, expose top-level Try* APIs, and run full test suite in task/CI with added smoke tests for public wrappers.

Co-authored-by: Cursor <cursoragent@cursor.com>
@coderabbitai

coderabbitai Bot commented Jun 16, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@kooksee, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 20 minutes and 14 seconds. Learn how PR review limits work.

Your organization has used up its prepaid credits, and credit purchases are no longer available. Enable the review add-on in the billing tab to keep reviews running — you're only billed for reviews past your plan's rate limits ($0.25/file).

⌛ How to resolve this issue?

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.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: d733926d-2d6b-48cb-8c9c-9bf5c1bb1118

📥 Commits

Reviewing files that changed from the base of the PR and between 354d17d and 8273aec.

📒 Files selected for processing (17)
  • README.md
  • README_zh.md
  • dixglobal/global_test.go
  • example/_.go
  • example/cycle/main.go
  • example/func/main.go
  • example/handler/main.go
  • example/http/main.go
  • example/inject_method/main.go
  • example/lazy/main.go
  • example/list-nil/main.go
  • example/list/main.go
  • example/map-nil/main.go
  • example/map/main.go
  • example/struct-in/main.go
  • example/struct-out/main.go
  • example/test-return-error/main.go
📝 Walkthrough

Walkthrough

Adds three error-returning exported helpers (TryProvide, TryInject, TryInjectContext) to the dix package with matching thread-safety clarifications in comments and documentation. Comprehensive test coverage is added for the core functions, context injection patterns, and module-specific functionality. Both English and Chinese READMEs are expanded with production startup guidance, thread-safety constraints, core API tables, module documentation, and diagnostics. Security documentation with reverse-proxy authentication examples and checklists is added to dixhttp README files. Finally, the CI workflow is renamed and gains a race-enabled go test job, the Taskfile test task is broadened to all packages, and a PR description template is introduced.

Changes

Try* API, Thread-Safety Clarification, and Core Tests

Layer / File(s) Summary
Try* functions and thread-safety comments
dix.go, dixinternal/dix.go
Exports TryProvide, TryInject, and TryInjectContext as error-returning wrappers in dix.go; updates inject and provide method NOTE comments in dixinternal/dix.go to state that Dix containers are not thread-safe and Provide/Inject must not be called concurrently.
Core function tests and Version check
dix_test.go
Adds TestVersion, TestTryProvide, TestTryInject, and TestTryInjectContext covering success and error paths for the new exported helpers and context-aware injection.
Extended test coverage for injection patterns and panic cases
dix_test.go, dixcontext/context_test.go, dixglobal/global_test.go
Adds TestInjectContextWithStructValue and panic-expectation tests with assertPanics helper in dix_test.go; introduces comprehensive tests for dixcontext (Create, Get, GetOrNil, panic behavior) and dixglobal (Provide/Inject and generic InjectT).

Documentation Updates and Security Guidance

Layer / File(s) Summary
README reorganization with Table of Contents and production startup guidance
README.md
Adds comprehensive Table of Contents with anchor links; adds production startup section recommending TryProvide/TryInject patterns; updates Core API section with API summary and container options tables; adds Generic Helpers documentation.
Thread Safety documentation and module updates
README.md
Adds explicit Thread Safety section clarifying non-concurrent Provide/Inject constraints and recommending single-goroutine startup with per-goroutine containers; updates dixcontext docs with GetOrNil; adds dixhttp security note; expands Diagnostics section with env-var table and Development section with task commands and CI race-detection note.
Chinese README with production guidance and core documentation
README_zh.md
Adds Table of Contents and production startup section with TryProvide/TryInject examples; updates Core API table and container options; adds Generic Helpers and Thread Safety sections explaining non-concurrent usage constraints in Chinese.
Chinese README module documentation and diagnostics
README_zh.md
Updates dixcontext documentation with GetOrNil usage; revises dixhttp security guidance and diagnostic sections with environment variable table and development/CI command updates in Chinese.
dixhttp security documentation and access control guidance
dixhttp/README.md, dixhttp/README_zh.md
Adds Reverse Proxy Auth Example sections with Nginx Basic Auth configuration and security checklists covering access restriction, IP/CIDR limitation, and avoiding public exposure of diagnostic endpoints in both English and Chinese.
PR description template
docs/pr_description_template.md
Introduces PR description template with predefined sections for Summary, Changes, Test Plan, Risk & Rollback, and Checklist.

CI and Build Infrastructure

Layer / File(s) Summary
CI workflow and test task expansion
.github/workflows/lint.yml, Taskfile.yml
Renames GitHub Actions workflow from Lint to CI; adds new test job running go test ./... -count=1 -race with checkout and Go setup steps; expands Taskfile test task from ./dixinternal/... to ./... for comprehensive package coverage.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

🐇 Three Try calls hop into the light,
Returning errors when things aren't right.
Tests bloom like clover, thick and deep,
Thread-safety warnings make reviewers sleep.
CI races through all the packages with cheer—
What a productive PR we have here! 🌟

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 4.76% 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 'fix: align thread-safety docs and add CI test coverage' directly reflects the main changes: documenting thread-safety limitations and expanding test coverage in CI.
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.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/review-followups

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 and usage tips.

@gemini-code-assist gemini-code-assist 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.

Code Review

This pull request exposes new TryProvide, TryInject, and TryInjectContext helper functions, updates the test suite and Taskfile to cover all packages, and documents that Dix containers are not thread-safe. The reviewer suggests completing the new API suite by also adding TryInjectT and TryInjectTContext helper functions to allow struct-targeted dependency injection with error handling.

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 dix.go
Comment on lines +84 to +90
func TryInject(di *Dix, data any, opts ...Option) error {
return di.TryInject(data, opts...)
}

func TryInjectContext(ctx context.Context, di *Dix, data any, opts ...Option) error {
return di.TryInjectContext(ctx, data, opts...)
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

To complete the newly exposed Try* API suite and match the existing InjectT and InjectTContext helpers, consider adding TryInjectT and TryInjectTContext functions.

Currently, there is no safe way to inject into a struct of type T and return it along with an error without writing verbose boilerplate. Adding these helpers provides a clean, safe, and consistent way to perform struct-targeted dependency injection.

func TryInject(di *Dix, data any, opts ...Option) error {
	return di.TryInject(data, opts...)
}

func TryInjectContext(ctx context.Context, di *Dix, data any, opts ...Option) error {
	return di.TryInjectContext(ctx, data, opts...)
}

func TryInjectT[T any](di *Dix, opts ...Option) (T, error) {
	var data T
	typ := reflect.TypeOf(&data).Elem()
	if typ.Kind() != reflect.Struct {
		return data, fmt.Errorf("<T> type kind is not struct")
	}

	err := di.TryInject(&data, opts...)
	return data, err
}

func TryInjectTContext[T any](ctx context.Context, di *Dix, opts ...Option) (T, error) {
	var data T
	typ := reflect.TypeOf(&data).Elem()
	if typ.Kind() != reflect.Struct {
		return data, fmt.Errorf("<T> type kind is not struct")
	}

	err := di.TryInjectContext(ctx, &data, opts...)
	return data, err
}

Add unit tests for dixcontext panic/nil handling and dixglobal provide/inject flows to improve wrapper-module coverage.

Co-authored-by: Cursor <cursoragent@cursor.com>

@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

🧹 Nitpick comments (3)
.github/workflows/lint.yml (3)

14-15: ⚖️ Poor tradeoff

Pin actions to commit hashes for supply-chain security.

Both actions/checkout@v4 and actions/setup-go@v5 should be pinned to specific commit hashes rather than tags. Tag-based references can be moved by attackers who compromise the action repository, creating a supply-chain attack vector.

🔒 Recommended fix to pin actions
-      - uses: actions/checkout@v4
-      - uses: actions/setup-go@v5
+      - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683  # v4.2.2
+      - uses: actions/setup-go@3041bf56c941b39c61721a86cd11f3bb1338122a  # v5.2.0
🤖 Prompt for 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.

In @.github/workflows/lint.yml around lines 14 - 15, Pin the GitHub Actions to
specific commit hashes instead of version tags for improved supply-chain
security. Replace `actions/checkout@v4` with the full commit hash of that action
version and replace `actions/setup-go@v5` with its corresponding full commit
hash. This prevents potential attacks where tag references could be manipulated
if the action repositories are compromised.

Source: Linters/SAST tools


14-14: ⚡ Quick win

Disable credential persistence to prevent leakage.

By default, actions/checkout persists GitHub credentials in the local git config, which can be inadvertently exposed by subsequent steps. Setting persist-credentials: false removes this risk.

🛡️ Recommended fix
-      - uses: actions/checkout@v4
+      - uses: actions/checkout@v4
+        with:
+          persist-credentials: false
🤖 Prompt for 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.

In @.github/workflows/lint.yml at line 14, The actions/checkout@v4 action at the
specified location persists GitHub credentials in the local git config by
default, creating a potential security risk if these credentials are exposed by
subsequent workflow steps. Add the `persist-credentials: false` option to the
actions/checkout action configuration to disable this credential persistence and
mitigate the leakage risk.

Source: Linters/SAST tools


10-21: ⚡ Quick win

Consider setting explicit minimal permissions for the test job.

The test job inherits default repository permissions, which may be broader than necessary. Explicitly setting permissions: {} or minimal read permissions follows the principle of least privilege.

🔐 Recommended permissions block
 test:
   runs-on: ubuntu-latest
+  permissions:
+    contents: read

   steps:
🤖 Prompt for 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.

In @.github/workflows/lint.yml around lines 10 - 21, The test job in the
lint.yml workflow inherits overly broad default repository permissions. Add an
explicit permissions field to the test job definition with either permissions:
{} (no permissions) or minimal read-only permissions such as permissions: {
contents: read } to follow the principle of least privilege. This should be
added at the job level under the test job, before the steps section.

Source: Linters/SAST tools

🤖 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 `@dix_test.go`:
- Around line 27-47: The test suite is missing coverage for the TryInjectContext
API, which is one of the new public wrapper APIs introduced in this PR. Add a
new test function (such as TestTryInjectContext) that provides smoke-test
coverage for this API, following the same testing pattern as the existing
TestTryInject function. The new test should verify that TryInjectContext can
successfully inject dependencies with context, validate that callbacks are
invoked correctly, and confirm that appropriate errors are returned when
required dependencies are missing.

---

Nitpick comments:
In @.github/workflows/lint.yml:
- Around line 14-15: Pin the GitHub Actions to specific commit hashes instead of
version tags for improved supply-chain security. Replace `actions/checkout@v4`
with the full commit hash of that action version and replace
`actions/setup-go@v5` with its corresponding full commit hash. This prevents
potential attacks where tag references could be manipulated if the action
repositories are compromised.
- Line 14: The actions/checkout@v4 action at the specified location persists
GitHub credentials in the local git config by default, creating a potential
security risk if these credentials are exposed by subsequent workflow steps. Add
the `persist-credentials: false` option to the actions/checkout action
configuration to disable this credential persistence and mitigate the leakage
risk.
- Around line 10-21: The test job in the lint.yml workflow inherits overly broad
default repository permissions. Add an explicit permissions field to the test
job definition with either permissions: {} (no permissions) or minimal read-only
permissions such as permissions: { contents: read } to follow the principle of
least privilege. This should be added at the job level under the test job,
before the steps section.
🪄 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: defaults

Review profile: CHILL

Plan: Pro

Run ID: 2c31dcf0-a1e1-4c95-8d42-7f713193e371

📥 Commits

Reviewing files that changed from the base of the PR and between 43e393e and c254831.

📒 Files selected for processing (7)
  • .github/workflows/lint.yml
  • README.md
  • README_zh.md
  • Taskfile.yml
  • dix.go
  • dix_test.go
  • dixinternal/dix.go

Comment thread dix_test.go
kooksee and others added 4 commits June 16, 2026 20:54
Improve bilingual READMEs with clearer onboarding, API/option quick references, production-safe examples, and condensed diagnostics guidance linked to detailed dixhttp docs.

Co-authored-by: Cursor <cursoragent@cursor.com>
Add dix wrapper edge-case tests and a README local-link checker wired into task and CI docs job.

Co-authored-by: Cursor <cursoragent@cursor.com>
Document reverse-proxy authentication practices for dixhttp and add a reusable PR description template for review-ready changes.

Co-authored-by: Cursor <cursoragent@cursor.com>
Drop the optional readme-check script and its CI/task wiring since it is not needed for day-to-day development.

Co-authored-by: Cursor <cursoragent@cursor.com>

@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 `@dixglobal/global_test.go`:
- Around line 24-32: The TestInjectT test function relies on global state from
another test to have testGlobalDep already registered, causing order-dependent
and flaky behavior. Make TestInjectT self-contained by registering the
testGlobalDep dependency at the beginning of the test itself, before calling
InjectT[app](), so the test has no external dependencies on execution order or
prior test state.

In `@README.md`:
- Around line 112-121: Add a row for the exported function InjectTContext[T] to
the API table in README.md, documenting that it allocates a struct and injects
exported fields with trace context propagation, and indicate its panic behavior
(yes, similar to InjectT[T]). Additionally, review the parameter names used in
the table (fn and target) to verify if they should be updated to match the
actual implementation parameter names (data), and consider whether the other
exported functions SetLog, WithValuesNull, WithProviderTimeout, and
WithSlowProviderThreshold should also be documented in the API table for
completeness.
🪄 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: defaults

Review profile: CHILL

Plan: Pro

Run ID: 8b46ebb4-bf3e-4c3b-b364-390b30ebc8b6

📥 Commits

Reviewing files that changed from the base of the PR and between c254831 and 354d17d.

📒 Files selected for processing (8)
  • README.md
  • README_zh.md
  • dix_test.go
  • dixcontext/context_test.go
  • dixglobal/global_test.go
  • dixhttp/README.md
  • dixhttp/README_zh.md
  • docs/pr_description_template.md
✅ Files skipped from review due to trivial changes (3)
  • dixhttp/README.md
  • docs/pr_description_template.md
  • README_zh.md

Comment thread dixglobal/global_test.go
Comment thread README.md
kooksee and others added 2 commits June 16, 2026 22:28
Rewrite example programs with clearer scenarios, dix.New usage, run instructions, and Try* error-handling patterns aligned with the public API docs.

Co-authored-by: Cursor <cursoragent@cursor.com>
Make dixglobal InjectT test self-contained to avoid order-dependent state and document InjectTContext in both README API tables.

Co-authored-by: Cursor <cursoragent@cursor.com>
@kooksee kooksee merged commit 1e76e8f into v2 Jun 16, 2026
3 checks passed
@kooksee kooksee deleted the fix/review-followups branch June 16, 2026 15:02
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant