Documentation
¶
Overview ¶
Package server provides utilities for creating fully spec-compliant HTML5 server-sent events streams.
The central piece of this package is the Provider interface. A Provider describes a publish-subscribe system that can be used to implement messaging for the SSE protocol. This package already has an implementation, called Joe, that is the default provider for any server. Abstracting the messaging system implementation away allows servers to use any arbitrary provider under the same interface. The default provider will work for simple use-cases, but where scalability is required, one will look at a more suitable solution. Adapters that satisfy the Provider interface can easily be created, and then plugged into the server instance.
The events themselves are represented as an object that's under package event, see its documentation for info on how to create events.
Index ¶
- Constants
- Variables
- type Connection
- type FiniteReplayProvider
- type Joe
- type JoeConfig
- type Message
- type Provider
- type ReplayProvider
- type Server
- func (s *Server) Provider() Provider
- func (s *Server) Publish(e *event.Event, topic ...string) error
- func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (s *Server) Shutdown() error
- func (s *Server) Subscribe(ctx context.Context, ch chan<- *event.Event, lastEventID event.ID, ...) error
- type Subscription
- type ValidReplayProvider
Constants ¶
const DefaultTopic = ""
DefaultTopic is the identifier for the topic that is implied when no topics are specified for a Subscription or a Message. Providers are required to implement this behavior to ensure handlers don't break if providers are changed.
Variables ¶
var ErrProviderClosed = errors.New("go-sse.server: provider is closed")
ErrProviderClosed is a sentinel error returned by providers when any operation is attempted after the provider is closed.
var ErrUnsupported = errors.New("go-sse.server.connection: unsupported")
ErrUnsupported is returned when a request can't be upgraded to support server-sent events.
Functions ¶
This section is empty.
Types ¶
type Connection ¶
type Connection struct {
// contains filtered or unexported fields
}
A Connection is an upgraded request. Use it to send events to the client.
func NewConnection ¶
func NewConnection(w http.ResponseWriter) (*Connection, error)
NewConnection upgrades an HTTP request to support server-sent events. It returns a Connection that's used to send events to the client or an error if the upgrade failed.
type FiniteReplayProvider ¶
type FiniteReplayProvider struct {
// contains filtered or unexported fields
}
FiniteReplayProvider is a replay provider that replays at maximum a certain number of events. GC is a no-op for this provider, as when the maximum number of values is reached and a new value has to be appended, old values are removed from the buffer.
func NewFiniteReplayProvider ¶
func NewFiniteReplayProvider(count int, autoIDs ...bool) *FiniteReplayProvider
NewFiniteReplayProvider creates a replay provider that can hold a maximum number of events at once. The events' expiry times are not considered, as the oldest events are removed anyway when the provider has buffered the maximum number of events. The events must have an ID unless the provider is constructed with the autoIDs flag.
func (*FiniteReplayProvider) GC ¶
func (f *FiniteReplayProvider) GC() error
GC is a no-op for this provider.
func (*FiniteReplayProvider) Put ¶
func (f *FiniteReplayProvider) Put(message *Message)
Put puts a message into the provider's buffer. If there are more messages than the maximum number, the oldest message is removed.
func (*FiniteReplayProvider) Replay ¶
func (f *FiniteReplayProvider) Replay(subscription Subscription)
Replay replays the messages in the buffer to the subscription. It doesn't take into account the messages' expiry times.
type Joe ¶
type Joe struct {
// contains filtered or unexported fields
}
Joe is a basic server provider that synchronously executes operations by queueing them in channels. Events are also sent synchronously to subscribers, and Joe waits for them to be received - if a subscriber is misbehaving Joe might wait forever! Make sure the subscription channels are always open for receiving.
Joe supports event replaying with the help of a replay provider. As operations are executed synchronously, it is guaranteed that no new events will be omitted from sending to a new subscriber because older events are still replaying when the event is sent to Joe.
If due to some unexpected scenario (the replay provider has a bug, for example) a panic occurs, Joe will close all the subscribers' channels, so requests aren't closed abruptly.
He serves simple use-cases well, as he's light on resources, and does not require any external services. Also, he is the default provider for Servers.
type JoeConfig ¶
type JoeConfig struct {
// An optional replay provider that Joe uses to resend older messages to new subscribers.
ReplayProvider ReplayProvider
// An optional interval at which Joe triggers a cleanup of expired messages, if the replay provider supports it.
// See the desired provider's documentation to determine if periodic cleanup is necessary.
ReplayGCInterval time.Duration
}
JoeConfig is used to tune Joe to preference.
type Message ¶
type Message struct {
// The event to publish.
Event *event.Event
// The topic to publish the event to. If no topic is specified the default topic is implied.
Topic string
}
The Message struct is used to publish a message to a given provider.
type Provider ¶
type Provider interface {
// Subscribe to the provider. The context is used to remove the subscription automatically
// when the subscriber stops receiving messages.
Subscribe(ctx context.Context, subscription Subscription) error
// Publish a message to all the subscribers that are subscribed to the message's topic.
Publish(message Message) error
// Stop the provider. Calling Stop will clean up all the provider's resources and
// make Subscribe and Publish fail with an error. All the subscription channels will be
// closed and any ongoing publishes will be aborted.
//
// Calling Stop multiple times does nothing but return ErrProviderClosed.
Stop() error
}
A Provider is a publish-subscribe system that can be used to implement a HTML5 server-sent events protocol. A standard interface is required so HTTP request handlers are agnostic to the provider's implementation.
Providers are required to be thread-safe.
After Stop is called, trying to call any method of the provider must return ErrProviderClosed. The providers may return other implementation-specific errors too, but the close error is guaranteed to be the same across providers.
type ReplayProvider ¶
type ReplayProvider interface {
// Put adds a new event to the replay buffer. The message's event may be modified by
// the provider, if it sets an ID.
//
// The Put operation may be executed by the replay provider in another goroutine only if
// it can ensure that any Replay operation called after the Put goroutine is started
// can replay the new received message. This also requires the replay provider implementation
// to be thread-safe.
//
// Replay providers are not required to guarantee that after Put returns the new events
// can be replayed. If an error occurs and retrying the operation would block for too
// long, it can be aborted. The errors aren't returned as the server providers won't be able
// to handle them in a useful manner anyway.
Put(message *Message)
// Replay sends to a new subscriber all the valid events received by the provider
// since the event with the subscription's ID. If the ID the subscription provides
// is invalid, the provider should not replay any events.
//
// Replay operations must be executed in the same goroutine as the one it is called in.
// Other goroutines may be launched from inside the Replay method, but the events must
// be sent to the subscription in the same goroutine that Replay is called in.
Replay(subscription Subscription)
// GC triggers a cleanup. After GC returns, all the events that are invalid according
// to the provider's criteria should be impossible to replay again.
//
// If GC returns an error, the provider is not required to try to trigger another
// GC ever again. Make sure that before you return a non-nil value you handle
// temporary errors accordingly, with blocking as shortly as possible.
// If your implementation does not require GC, return a non-nil error from this method.
// This way server providers won't try to GC at all, improving their performance.
//
// If the replay provider implementation is thread-safe the GC operation can be executed in another goroutine.
GC() error
}
A ReplayProvider is a type that can replay older published events to new subscribers. Replay providers use event IDs, the topics the events were published to and optionally the events' expiration times or any other criteria to determine which are valid for replay.
While providers can require events to have IDs beforehand, they can also set the IDs themselves, automatically - it's up to the implementation. Providers should ignore events without IDs, if they require IDs to be set.
Replay providers are not required to be thread-safe - server providers are required to ensure only one operation is executed on the replay provider at any given time. Server providers may not execute replay operation concurrently with other operations, so make sure any action on the replay provider blocks for as little as possible. If a replay provider is thread-safe, some operations may be run in a separate goroutine - see the interface's method documentation.
Executing actions that require waiting for a long time on I/O, such as HTTP requests or database calls must be handled with great care, so the server provider is not blocked. Reducing them to the minimum by using techniques such as caching or by executing them in separate goroutines is recommended, as long as the implementation fulfills the requirements.
If not specified otherwise, the errors returned are implementation-specific.
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
A Server is mostly a convenience wrapper around a provider. It implements the http.Handler interface and has some methods for calling the underlying provider's methods.
func New ¶
New creates a new server using the specified provider. If no provider is given, Joe with no replay provider is used.
func (*Server) Publish ¶
Publish sends the event to all subscribes that are subscribed to the topic the event is published to. The topic is optional - if none is specified, the event is published to the default topic.
func (*Server) ServeHTTP ¶
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP implements a default HTTP handler for a server.
This handler upgrades the request, subscribes it to the server's provider and starts sending incoming events to the client, while logging any write errors. It also sends the Last-Event-ID header's value, if present.
If the request isn't upgradeable, it writes a message to the client along with an 500 Internal Server Error response code. If on subscribe the provider returns an error, it writes the error message to the client and a 500 Internal Server Error response code.
If you need different behavior, you can create a custom handler.
func (*Server) Shutdown ¶
Shutdown closes all the connections and stops the server. Publish operations will fail with the error sent by the underlying provider. New requests will be ignored.
Call this method when shutting down the HTTP server using http.Server's RegisterOnShutdown method. Not doing this will result in the server never shutting down or connections being abruptly stopped.
The error returned is the one returned by the underlying provider's Stop method.
func (*Server) Subscribe ¶
func (s *Server) Subscribe(ctx context.Context, ch chan<- *event.Event, lastEventID event.ID, topics ...string) error
Subscribe subscribes the given channel to the specified topics. It is unsubscribed when the context is closed or the server is shut down. If no topic is specified, the channel is subscribed to the default topic.
type Subscription ¶
type Subscription struct {
// A non-nil, open channel to send events on. The provider may wait when sending on this channel
// until the event is received, so start receiving immediately after the provider's Subscribe
// method returned.
//
// Subsequent subscriptions that use the same channel are ignored by providers.
//
// Only the provider is allowed to close this channel. Closing it yourself may cause the program to panic!
Channel chan<- *event.Event
// An optional last event ID indicating the event to resume the stream from.
// The events will replay starting from the first valid event sent after the one with the given ID.
// If the ID is invalid replaying events will be omitted and new events will be sent as normal.
LastEventID event.ID
// The topics to receive message from. If no topic is specified, a default topic is implied.
// Topics are orthogonal to event names. They are used to filter what the server sends to each client.
Topics []string
}
The Subscription struct is used to subscribe to a given provider.
type ValidReplayProvider ¶
type ValidReplayProvider struct {
// contains filtered or unexported fields
}
ValidReplayProvider is a replay provider that replays all the valid (not expired) previous events.
func NewValidReplayProvider ¶
func NewValidReplayProvider(autoIDs ...bool) *ValidReplayProvider
NewValidReplayProvider creates a replay Provider that replays all the buffered non-expired events. Call its GC method periodically to remove expired events from the buffer and release resources. You can use this provider for replaying an infinite number of events, if the events never expire. The events must have an ID unless the provider is constructed with autoIDs flag as true.
func (*ValidReplayProvider) GC ¶
func (v *ValidReplayProvider) GC() error
GC removes all the expired messages from the provider's buffer.
func (*ValidReplayProvider) Put ¶
func (v *ValidReplayProvider) Put(message *Message)
Put puts the message into the provider's buffer.
func (*ValidReplayProvider) Replay ¶
func (v *ValidReplayProvider) Replay(subscription Subscription)
Replay replays all the valid messages to the subscription.