Skip to content

🔥feat: Add storage backed SharedState for prefork applications#4243

Open
gaby wants to merge 3 commits intomainfrom
implement-shared-state-component-using-fiber.storage
Open

🔥feat: Add storage backed SharedState for prefork applications#4243
gaby wants to merge 3 commits intomainfrom
implement-shared-state-component-using-fiber.storage

Conversation

@gaby
Copy link
Copy Markdown
Member

@gaby gaby commented Apr 28, 2026

Motivation

  • Provide a storage-backed, prefork-safe key–value state store for data that must be shared across workers or processes.
  • Allow apps to namespace shared keys to avoid collisions (with sensible default prefixing that can include AppName) and reuse app-configured encoders/decoders for JSON/MsgPack/CBOR/XML.

Description

  • Add SharedState implementation (shared_state.go) exposing raw and encoded helpers such as Set, Get, SetJSON, GetJSON, SetMsgPack, GetMsgPack, SetCBOR, GetCBOR, SetXML, GetXML, Delete, Has, and context-aware variants.
  • Wire SharedState into the app by adding Config.SharedStorage and Config.SharedStatePrefix, initializing app.sharedState in New(...), and exposing App.SharedState() while clarifying that App.State() remains process-local.
  • Implement predictable key namespacing (defaultSharedStatePrefix + optional AppName) and ensure the SharedState uses the app-provided encoder/decoder hooks.
  • Update documentation (docs/api/app.md, docs/api/state.md, docs/whats_new.md) and add comprehensive unit tests in shared_state_test.go covering configuration, context propagation, serialization, codec usage, namespacing, and error propagation.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Apr 28, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 2ea473fa-9643-4417-8bc2-8b5c100daada

📥 Commits

Reviewing files that changed from the base of the PR and between f6ecd99 and a72c503.

📒 Files selected for processing (6)
  • app.go
  • docs/api/app.md
  • docs/api/state.md
  • docs/whats_new.md
  • shared_state.go
  • shared_state_test.go

Walkthrough

Introduces a new storage-backed SharedState capability to the Fiber App struct for prefork/multi-process coordination. Adds configurable prefix and storage backend options in Config, implements the SharedState type with byte-level and serialization-aware operations (JSON, MsgPack, CBOR, XML) with context support, and includes comprehensive documentation and test coverage.

Changes

Cohort / File(s) Summary
Core Implementation
app.go, shared_state.go
Adds SharedStorage and SharedStatePrefix configuration fields to Config; initializes sharedState in New() with default prefix logic; introduces SharedState() method; implements SharedState type with byte-level Set/Get/Delete/Has operations, format-specific helpers (JSON/MsgPack/CBOR/XML), and context-aware variants.
Tests
shared_state_test.go
Comprehensive test suite covering unconfigured storage scenarios, serialization error handling, context validation, namespace isolation via AppName, prefix defaults, byte copy semantics, and codec integration for all supported formats.
Documentation
docs/api/app.md, docs/api/state.md, docs/whats_new.md
Adds "State / SharedState" section distinguishing in-process State() from storage-backed SharedState(); documents configuration, API surface including context variants, and provides usage examples for JSON and context-based operations.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Suggested labels

✏️ Feature

Suggested reviewers

  • sixcolors
  • ReneWerner87
  • efectn

Poem

🐰 Hoppy news! A SharedState arrived,
Cross-process magic, prefork thrives,
With JSON, MsgPack, CBOR so bright,
Context-aware ops, everything's tight! 🎉

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 4.55% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ❓ Inconclusive The description covers motivation, technical implementation details, and documentation/testing updates. However, critical template sections lack explicit completion markers (checklist items unchecked, no explicit benchmarks/migration guide discussion, no Express alignment statement). Complete the template checklist by checking applicable items (e.g., New feature, Documentation update), explicitly address benchmarks, migration, and Express alignment, or clarify why sections are not applicable.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: introducing a storage-backed SharedState feature for prefork applications, which aligns with the core changeset.
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 docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch implement-shared-state-component-using-fiber.storage

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 golangci-lint (2.11.4)

level=error msg="[linters_context] typechecking error: pattern ./...: directory prefix . does not contain main module or its selected dependencies"


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.

@ReneWerner87 ReneWerner87 added this to v3 Apr 28, 2026
@ReneWerner87 ReneWerner87 added this to the v3 milestone Apr 28, 2026
@gaby gaby changed the title Introduce SharedState: storage-backed, prefork-safe app state with codecs and tests 🔥feat: Add storage backed SharedState for prefork applications Apr 28, 2026
@gaby gaby moved this to In Progress in v3 Apr 28, 2026
@codecov
Copy link
Copy Markdown

codecov Bot commented Apr 28, 2026

Codecov Report

❌ Patch coverage is 92.89941% with 12 lines in your changes missing coverage. Please review.
✅ Project coverage is 91.15%. Comparing base (9b47da0) to head (a72c503).
⚠️ Report is 137 commits behind head on main.

Files with missing lines Patch % Lines
shared_state.go 92.00% 6 Missing and 6 partials ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #4243      +/-   ##
==========================================
- Coverage   91.26%   91.15%   -0.11%     
==========================================
  Files         123      124       +1     
  Lines       11877    12253     +376     
==========================================
+ Hits        10839    11169     +330     
- Misses        653      679      +26     
- Partials      385      405      +20     
Flag Coverage Δ
unittests 91.15% <92.89%> (-0.11%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ 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
Contributor

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

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 SharedState, a storage-backed state management system for Fiber designed to be safe for prefork workers and multi-process environments. It adds new configuration fields to Config, implements a variety of data access methods with support for multiple encoding formats (JSON, MsgPack, CBOR, XML), and provides comprehensive documentation and tests. Review feedback suggests removing a redundant string copy in the key generation logic and highlights potential concerns regarding key length and readability when using hex encoding.

Comment thread shared_state.go Outdated
Comment thread shared_state.go Outdated
Copy link
Copy Markdown
Contributor

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

Adds a new storage-backed SharedState API to Fiber apps to support prefork-safe / multi-process shared key–value state, with configurable namespacing and codec helpers aligned with app-configured encoders/decoders.

Changes:

  • Introduces SharedState with raw (Set/Get) and encoded (SetJSON/GetJSON, SetMsgPack/GetMsgPack, SetCBOR/GetCBOR, SetXML/GetXML) operations, plus context-aware variants.
  • Wires shared state into App via Config.SharedStorage and Config.SharedStatePrefix, and exposes App.SharedState() alongside clarified App.State() semantics.
  • Adds documentation and a comprehensive unit test suite covering configuration, namespacing, context propagation, and error handling.

Reviewed changes

Copilot reviewed 6 out of 6 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
shared_state.go Implements the SharedState API over fiber.Storage, including prefixing and codec helpers.
app.go Adds shared-state configuration, initializes shared state in New(), and exposes App.SharedState().
shared_state_test.go Adds unit tests for shared-state behavior (storage config, namespacing, codecs, context, error propagation).
docs/api/state.md Documents prefork-safe SharedState, configuration, method signatures, and examples.
docs/api/app.md Updates app API docs to distinguish State() (process-local) vs SharedState() (storage-backed).
docs/whats_new.md Notes SharedState as a new v3 app feature.

Comment thread shared_state.go
@gaby gaby marked this pull request as ready for review April 28, 2026 13:36
@gaby gaby requested a review from a team as a code owner April 28, 2026 13:36
Copy link
Copy Markdown
Contributor

@github-actions github-actions Bot left a comment

Choose a reason for hiding this comment

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

⚠️ Performance Alert ⚠️

Possible performance regression was detected for benchmark.
Benchmark result of this commit is worse than the previous benchmark result exceeding threshold 1.50.

Benchmark suite Current: a72c503 Previous: f6ecd99 Ratio
Benchmark_Compress_Levels/Zstd_LevelDefault (github.com/gofiber/fiber/v3/middleware/compress) - B/op 1 B/op 0 B/op +∞

This comment was automatically generated by workflow using github-action-benchmark.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

Status: In Progress

Development

Successfully merging this pull request may close these issues.

3 participants