pubsubfx

package module
v0.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 19, 2026 License: Apache-2.0 Imports: 8 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Contributors Forks Stargazers Issues Apache 2.0 License


pubsubfx

Uber Fx module for publish/subscribe messaging with in-process and Redis backends selected by URL.

Report Bug · Request Feature

Table of Contents


About The Project

pubsubfx is an Uber Fx module that provides a pubsub.PubSub for fan-out messaging. It supports:

  • URL-selected backends — memory:// for in-process messaging, redis:// for cross-process messaging through a Redis server
  • Fan-out delivery — every subscriber of a topic receives every published message
  • Per-subscription buffering — BufferSize caps how far a subscriber may lag before Publish blocks (memory backend)
  • Topic namespacing — Prefix isolates applications sharing one Redis server
  • Fail-fast startup — an invalid URL or scheme fails app startup, not first publish
  • Close on stop — the Fx module closes the instance during graceful shutdown

Built With

  • Go
  • Uber Fx
  • go-redis

(back to top)


Getting Started

Prerequisites

  • Go 1.26+ (go.mod requires go 1.26.0)
  • An application using Uber Fx for dependency injection (for Module(); the package also works without Fx)

Installation

go get github.com/go-core-fx/pubsubfx@latest

Until the first tag is cut, pin a commit instead:

go get github.com/go-core-fx/pubsubfx@<commit-sha>

(back to top)


Usage

Module Setup

import (
    "github.com/go-core-fx/logger"
    "github.com/go-core-fx/pubsubfx"
    "go.uber.org/fx"
)

func main() {
    fx.New(
        logger.Module(),
        fx.Provide(func() pubsubfx.Config {
            return pubsubfx.Config{
                URL:        "redis://localhost:6379/0",
                BufferSize: 64,
                Prefix:     "myapp:",
            }
        }),
        pubsubfx.Module(),
        // ... other modules
    ).Run()
}

Module() provides pubsub.PubSub for the Config in the container, decorates the *zap.Logger with pubsubfx, and closes the instance when the app stops. An invalid URL or scheme makes startup fail with pubsubfx.ErrInvalidConfig. The container must already contain a *zap.Logger — logger.Module() from go-core-fx/logger provides one.

Consumers inject the interface:

func Handler(ps pubsub.PubSub) error {
    sub, err := ps.Subscribe(context.Background(), "events")
    if err != nil {
        return err
    }
    defer sub.Close()

    go func() {
        for msg := range sub.Receive() {
            log.Printf("%s: %s", msg.Topic, msg.Data)
        }
    }()

    return ps.Publish(context.Background(), "events", []byte("hello"))
}

Configuration Reference

Field Type Default Description
URL string "" Backend URL. Empty defaults to memory://. redis:// connects to Redis; any other scheme fails with ErrInvalidConfig.
BufferSize uint 0 Capacity of the channel behind each subscription. 0 makes the memory backend's Publish block until every subscriber has accepted.
Prefix string "" Prepended to every topic name (a trailing : is added automatically). Isolates apps sharing one Redis server. Ignored by memory://.

Direct Construction

The package works without Fx:

ps, err := pubsubfx.New(pubsubfx.Config{
    URL:    "memory://",
    Prefix: "myapp:",
})
if err != nil {
    log.Fatal(err)
}
defer ps.Close()

Individual backends from the pubsub package can be built directly — pubsub.NewMemory(opts...) and pubsub.NewRedis(pubsub.RedisConfig{...}, opts...) — with pubsub.WithBufferSize(n) for buffering.

Backends

memory:// — in-process fan-out. Publish blocks until every subscriber has received the message or a context is cancelled; BufferSize gives subscribers slack so a slow consumer does not stall publishers. Topics are scoped per instance; Prefix is ignored.

redis:// — publishes through a Redis server; subscribers receive via Redis pub/sub, so messaging works across processes. Prefix namespaces the topics. The Fx module and New create and own the Redis client; a client passed directly to pubsub.NewRedis stays owned by the caller and is never closed by the pubsub.

Errors

Error Meaning
pubsubfx.ErrInvalidConfig Config.URL is unparseable or selects an unknown scheme
pubsub.ErrInvalidConfig RedisConfig has neither a client nor a URL
pubsub.ErrPubSubClosed Operation on a closed pubsub instance
pubsub.ErrInvalidTopic Empty topic name

(back to top)


Development

Make Targets

Target Description
make all Run all checks: fmt, lint, coverage
make version Display the current version (from git describe, defaults to 0.0.0)
make fmt Run go generate ./..., then golangci-lint fmt
make lint Run golangci-lint run --timeout=5m
make test Run tests with race detector, shuffle and atomic coverage
make coverage Produce coverage.out and an HTML report (coverage.html)
make benchmark Run benchmarks into benchmark.txt
make deps Download module dependencies
make clean Remove coverage output, benchmarks and build artifacts
make help List all available targets

Continuous Integration

The Go workflow runs on pushes to master and on pull requests (path-filtered to Go sources, go.mod/go.sum, the lint config and the workflows themselves):

  • Lint — golangci-lint with the repository config
  • Test — race-enabled, shuffled tests with coverage uploaded to Codecov; the Redis tests run against a redis:8-alpine testcontainer and fail the job if Docker is unavailable in CI
  • Benchmark — runs go test -bench, keeps history in the Actions cache and only alerts when benchmarks exist

(back to top)


Contributing

Contributions are what make the open source community such an amazing place to learn, inspire, and create. Any contributions you make are greatly appreciated.

  1. Fork the Project
  2. Create your Feature Branch (git checkout -b feature/AmazingFeature)
  3. Commit your Changes (git commit -m 'Add some AmazingFeature')
  4. Push to the Branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

(back to top)


License

Distributed under the Apache License 2.0. See LICENSE for more information.

(back to top)


Acknowledgments

(back to top)

Documentation

Index

Constants

View Source
const ModuleName = "pubsubfx"

ModuleName is the fx module and logger name.

Variables

View Source
var ErrInvalidConfig = errors.New("invalid config")

ErrInvalidConfig indicates an invalid configuration.

Functions

func Module

func Module() fx.Option

Module provides the PubSub selected by Config and closes it when the app stops, so a Redis-backed instance releases its subscriptions and client even on graceful shutdown paths that never call Close themselves.

func New

func New(config Config) (pubsub.PubSub, error)

New creates a PubSub for the backend selected by config.URL.

The default and "memory://" select the in-process backend; "redis://" selects Redis, where Prefix namespaces the topics. Any other scheme, or a URL the backend rejects, fails with ErrInvalidConfig.

Types

type Config

type Config struct {
	// URL selects and configures the backend. It is passed to the backend
	// unchanged: "memory://" serves an in-process fan-out pubsub, and
	// "redis://" publishes through a Redis server. The backend parses the
	// URL, so a malformed one fails when the pubsub is created (typically at
	// app startup) instead of at first use.
	URL string

	// BufferSize is the capacity of the channel behind each subscription.
	// With the memory backend, a zero value makes Publish block until every
	// subscriber has accepted the message, and a positive value lets a
	// subscriber lag by up to BufferSize messages before Publish blocks. The
	// redis backend does not apply this backpressure: a successful Publish
	// means the Redis server accepted the message, not that subscribers have
	// received it.
	BufferSize uint

	// Prefix is prepended to every topic name, so independent applications
	// sharing one Redis server do not see each other's messages. An empty
	// value publishes to unprefixed topics. Ignored by the memory backend,
	// which scopes topics per instance.
	Prefix string
}

Config controls the pubsub backend via a URL (e.g., "memory://", "redis://...") and the subscription buffer.

Directories

Path Synopsis
Package pubsub provides a lightweight publish/subscribe abstraction with in-memory and Redis backends.
Package pubsub provides a lightweight publish/subscribe abstraction with in-memory and Redis backends.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址