Skip to content

chore: simplify, modernize (Go 1.26), update deps#116

Merged
rustatian merged 4 commits into
masterfrom
chore/cleanup-modernize-deps
May 31, 2026
Merged

chore: simplify, modernize (Go 1.26), update deps#116
rustatian merged 4 commits into
masterfrom
chore/cleanup-modernize-deps

Conversation

@rustatian
Copy link
Copy Markdown
Member

@rustatian rustatian commented May 29, 2026

Fixed (applied)

Simplify (S) — 5 findings:

  • handler/events.go: clarify comment — []byte vars are package-level mutable globals, not Go consts; replaced misleading // immutable with accurate explanation
  • handler/handler.go: single defer putPayload(pld) in Start() replaces two manual calls in separate branches
  • handler/helpers.go: log the discarded wPool error in sendClose instead of silencing it with _, _
  • handler/handler.go: document Release() as a no-op placeholder (was bare comment)
  • plugin.go: removed redundant *staticPool.Pool type-assert in Stop; Destroy is already on the Pool interface

Modernize (M) — 3 findings:

  • plugin.go: drop explicit string type on pluginName and RrMode consts
  • config.go: replace unsafe.Slice(unsafe.StringData(data), len(data)) with plain []byte(data); drop unsafe import
  • handler/pool.go: reset Codec and Flags fields in putPayload to prevent pool contamination

Review/Low (R) — 1 finding:

  • plugin.go: defer mu.RUnlock() in Exec; eliminate four scattered manual RUnlock calls that make future edits fragile

Not applied (needs manual review)

  • R/High handler/handler.go:103: double sendClose() on partial-EOF path — subtle stream handling; needs test coverage
  • R/High handler/handler.go:131: delimiter check only on current chunk — framing breaks across reads; requires protocol-level refactor
  • R/Med plugin.go:172: Stop goroutine holds mu across Destroy; context-cancel → potential deadlock with Reset
  • R/Med plugin.go:128: errCh cap 1 with multiple listeners — second failure blocks and leaks a goroutine

Verification

go build ./..., go vet ./..., golangci-lint run — all clean.

Summary by CodeRabbit

Release Notes

  • Bug Fixes

    • Improved memory safety by removing unsafe pointer operations
    • Enhanced error handling and logging for worker communication failures
    • Improved payload cleanup and state management in connection handling
  • Documentation

    • Clarified internal sentinel value documentation
  • Chores

    • Optimized memory pooling behavior
    • Simplified internal code paths for better maintainability

Review Change Stack

- Drop explicit string type from pluginName/RrMode consts
- Replace unsafe strToBytes with []byte(s) in config.go
- Reset Codec/Flags in putPayload to avoid pool contamination
- Remove redundant *staticPool.Pool type-assert in Stop; call Destroy via Pool interface
- Defer RUnlock in Exec; eliminate scattered manual RUnlock calls
- Use single defer putPayload in Handler.Start
- Log discarded sendClose wPool error instead of silencing it
- Clarify events.go comment: []byte vars are mutable globals, not Go consts
- Document Release() as a no-op placeholder
Copilot AI review requested due to automatic review settings May 29, 2026 12:46
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 29, 2026

Warning

Review limit reached

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

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

Your organization has run out of usage credits. Purchase more in the billing tab.

⌛ 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: b27ea1cc-b182-4ee8-ab42-3b2dc5a4644c

📥 Commits

Reviewing files that changed from the base of the PR and between 6efd0ec and dd9e96e.

⛔ Files ignored due to path filters (2)
  • go.work.sum is excluded by !**/*.sum
  • tests/go.sum is excluded by !**/*.sum
📒 Files selected for processing (2)
  • handler/helpers.go
  • tests/go.mod
📝 Walkthrough

Walkthrough

The PR removes the unsafe package dependency, improves payload pooling across handler and plugin components, refactors plugin pool lifecycle management, and simplifies execution locking. Changes span configuration, handler, and plugin orchestration to enhance resource reuse and code safety.

Changes

Resource Management and Cleanup

Layer / File(s) Summary
Remove unsafe code dependency
config.go
The unsafe package import and strToBytes helper function are removed. Delimiter byte initialization now uses direct []byte(v.Delimiter) conversion instead of unsafe string-to-slice views.
Improve payload lifecycle management
handler/handler.go, handler/helpers.go, handler/pool.go
In Start(), payloads are returned to the pool immediately after wPool() and before error checking. sendClose() defers payload cleanup and captures wPool() errors for warning logs. putPayload() now clears Codec and Flags fields in addition to existing resets. Release() comment is updated.
Refactor plugin pool initialization and teardown
plugin.go
Serve() assigns p.wPool only after successful pool creation via a temporary variable, avoiding nil-interface wrapping. Stop() calls p.wPool.Destroy() directly instead of type-switching on *staticPool.Pool.
Simplify Exec lock handling
plugin.go
Exec() uses deferred RUnlock() after acquiring the read lock, simplifying early-return paths and reducing intermediate variables while preserving error forwarding and response validation.
Documentation and type annotation updates
handler/events.go, plugin.go
Sentinel []byte documentation clarifies read-only usage and explains why they are package variables rather than constants. The RrMode exported constant drops its explicit string type annotation.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

A rabbit hops through unsafe code so grand,
Removing pointers with a steady hand.
Pooling payloads now with clearer care,
Locks deferred gently through the air.
Safety blooms where unsafe used to stand! 🐰✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description is comprehensive and well-structured, covering all applied fixes, unapplied items flagged for manual review, verification steps, and detailed commit messages. However, it does not follow the template structure with explicit sections for 'Reason for This PR', 'Description of Changes', 'License Acceptance', and 'PR Checklist' as required. Restructure the description to match the template: add explicit 'Reason for This PR' section with issue reference, use 'Description of Changes' heading, include the License Acceptance statement, and complete the PR Checklist with checkboxes for all required criteria.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main changes: simplifications, modernizations for Go 1.26, and dependency updates across multiple files.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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 chore/cleanup-modernize-deps

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.

@codecov
Copy link
Copy Markdown

codecov Bot commented May 29, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 63.05%. Comparing base (2f656a8) to head (dd9e96e).

Additional details and impacted files
@@            Coverage Diff             @@
##           master     #116      +/-   ##
==========================================
+ Coverage   62.57%   63.05%   +0.48%     
==========================================
  Files           4        4              
  Lines         171      157      -14     
==========================================
- Hits          107       99       -8     
+ Misses         52       47       -5     
+ Partials       12       11       -1     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Copy link
Copy Markdown

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

This PR simplifies several control-flow and cleanup paths in the TCP plugin/handler, removes an unsafe string→bytes conversion in config initialization, and makes pooled payload reuse safer by resetting additional fields.

Changes:

  • Simplify lock/unlock and cleanup patterns (e.g., defer for RUnlock, remove redundant pool type-assertion in Stop).
  • Remove unsafe-based string-to-bytes conversion in config delimiter initialization.
  • Harden payload pooling by resetting additional payload.Payload fields on return to the pool.

Reviewed changes

Copilot reviewed 6 out of 6 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
plugin.go Simplifies constants, Stop() pool teardown, and Exec() lock handling.
handler/pool.go Resets additional payload.Payload fields before returning to the pool.
handler/helpers.go Ensures payload is returned to pool via defer and logs close-event send failures.
handler/handler.go Simplifies connected-event payload cleanup and clarifies Release() as a no-op placeholder.
handler/events.go Replaces misleading comment about []byte “immutability” with accurate explanation.
config.go Removes unsafe helper and uses []byte(string) for delimiter bytes.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread handler/handler.go
Comment thread plugin.go
rustatian added 2 commits May 29, 2026 23:30
…l call

The payload used for the EventConnected call was deferred until Start()
returned, keeping it checked out across the entire readLoop() lifetime
and defeating pool reuse for long-lived connections.
NewPool returns a concrete *static_pool.Pool that is nil on error.
Assigning it straight into the Pool interface field boxed a typed nil,
so the p.wPool != nil guard in Stop passed and Destroy dereferenced a
nil receiver. Assign the interface only after a successful NewPool.
Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
plugin.go (1)

127-149: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Avoid blocking listener startup goroutines on errCh.

Line 128 allocates errCh with capacity 1, but every listener goroutine in Lines 143-148 can send into it. If two listeners fail before the caller drains the first error, the later goroutine blocks forever on errCh <- err.

💡 Suggested fix
 func (p *Plugin) Serve() chan error {
-	errCh := make(chan error, 1)
+	errCh := make(chan error, len(p.cfg.Servers)+1)
+	sendErr := func(err error) {
+		select {
+		case errCh <- err:
+		default:
+			p.log.Error("failed to report serve error", "error", err)
+		}
+	}
 
 	// NewPool returns a concrete *static_pool.Pool; on error it is a nil
 	// pointer. Assigning it directly to the Pool interface field would produce
 	// a non-nil interface wrapping a nil pointer, so Stop's `p.wPool != nil`
 	// guard would pass and Destroy would panic on a nil receiver. Assign the
 	// interface only after a successful NewPool.
 	wp, err := p.server.NewPool(context.Background(), p.cfg.Pool, map[string]string{RrMode: pluginName}, nil)
 	if err != nil {
-		errCh <- err
+		sendErr(err)
 		return errCh
 	}
 	p.wPool = wp
@@
 			l, err := tcplisten.CreateListener(addr)
 			if err != nil {
-				errCh <- err
+				sendErr(err)
 				return
 			}
🤖 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 `@plugin.go` around lines 127 - 149, The listener goroutines can block on
sending errors to errCh because it's created with capacity 1; change the
creation of errCh in Serve to be buffered to accommodate all potential listener
errors (e.g., errCh := make(chan error, len(p.cfg.Servers)+1) or similar), so
multiple tcplisten.CreateListener failures from the goroutines won't block; keep
the rest of the logic (sends to errCh in the goroutines) unchanged and ensure
p.wPool assignment and error handling around p.server.NewPool remain as-is.
🤖 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.

Outside diff comments:
In `@plugin.go`:
- Around line 127-149: The listener goroutines can block on sending errors to
errCh because it's created with capacity 1; change the creation of errCh in
Serve to be buffered to accommodate all potential listener errors (e.g., errCh
:= make(chan error, len(p.cfg.Servers)+1) or similar), so multiple
tcplisten.CreateListener failures from the goroutines won't block; keep the rest
of the logic (sends to errCh in the goroutines) unchanged and ensure p.wPool
assignment and error handling around p.server.NewPool remain as-is.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 7cab6af1-b4d4-4a89-9cd4-04b07dd95dd7

📥 Commits

Reviewing files that changed from the base of the PR and between 2f656a8 and 6efd0ec.

📒 Files selected for processing (6)
  • config.go
  • handler/events.go
  • handler/handler.go
  • handler/helpers.go
  • handler/pool.go
  • plugin.go

Signed-off-by: Valery Piashchynski <piashchynski.valery@gmail.com>
@rustatian rustatian self-assigned this May 31, 2026
@rustatian rustatian merged commit b0e5c3b into master May 31, 2026
9 checks passed
@rustatian rustatian deleted the chore/cleanup-modernize-deps branch May 31, 2026 17:06
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.

2 participants