Documentation
¶
Overview ¶
Package stream implements the SSE and WebSocket streams that push flag changes to clients.
Index ¶
- Constants
- func Behind(lastEventID, current string) bool
- func ContextWithState(ctx context.Context, state State) context.Context
- type ConfigIdentity
- type KeyRoutes
- type KeyedWebsocketService
- type Limiter
- type Option
- func WithClock(now func() time.Time) Option
- func WithFlagDetails(include bool) Option
- func WithJitter(source func() float64) Option
- func WithLogger(logger *slog.Logger) Option
- func WithMaxStreams(limit int) Option
- func WithReconnectWindow(minDelay, maxDelay time.Duration) Option
- func WithSSEHeartbeatInterval(interval time.Duration) Option
- func WithWriteTimeout(timeout time.Duration) Option
- func WithWriteTimer(...) Option
- type Reason
- type SSEService
- type SSEServiceImpl
- func (s *SSEServiceImpl) BroadcastConfigChange(flagsetName string, config ConfigIdentity) error
- func (s *SSEServiceImpl) BroadcastFlagChanges(flagsetName string, _ notifier.DiffCache) error
- func (s *SSEServiceImpl) Close()
- func (s *SSEServiceImpl) Connections() int
- func (s *SSEServiceImpl) DisconnectAnonymous(keep string)
- func (s *SSEServiceImpl) DisconnectRevoked(routes KeyRoutes)
- func (s *SSEServiceImpl) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (s *SSEServiceImpl) ServeKeyed(w http.ResponseWriter, r *http.Request, apiKey string, stillValid func() bool)
- func (s *SSEServiceImpl) SetOnSubscribe(fn func(streamID string))
- type Slot
- type State
- type Stats
- type Transport
- type WebsocketConnector
- type WebsocketService
- type WebsocketServiceImpl
- func (w *WebsocketServiceImpl) Activate(conn WebsocketConnector) bool
- func (w *WebsocketServiceImpl) BroadcastFlagChanges(flagsetName string, diff notifier.DiffCache)
- func (w *WebsocketServiceImpl) Close()
- func (w *WebsocketServiceImpl) Connections() int
- func (w *WebsocketServiceImpl) Deregister(conn WebsocketConnector)
- func (w *WebsocketServiceImpl) DisconnectAnonymous(keep string)
- func (w *WebsocketServiceImpl) DisconnectRevoked(routes KeyRoutes) []func()
- func (w *WebsocketServiceImpl) Register(c WebsocketConnector, flagsetName string)
- func (w *WebsocketServiceImpl) RegisterAnonymous(c WebsocketConnector, flagsetName string)
- func (w *WebsocketServiceImpl) RegisterKeyed(conn WebsocketConnector, flagsetName, apiKey string)
- func (w *WebsocketServiceImpl) WaitForCleanup(timeout time.Duration) error
Constants ¶
const AnonymousStreamPrefix = "anonymous:"
AnonymousStreamPrefix starts the stream ID of the clients that have no API key: they have a stream of their own next to the one of the flag set, so that the relay can close them when the anonymous access ends.
const ( // MaxLastEventIDLength is the longest Last-Event-ID the service reads: an ETag is 16 characters at most, a longer // value is not one of ours and is treated as unknown (the client is behind). MaxLastEventIDLength = 128 )
Variables ¶
This section is empty.
Functions ¶
func Behind ¶ added in v0.3.0
Behind reports whether a client whose last event id is lastEventID has to fetch again, when the flag set serves the configuration with the ETag current. The id is the ETag of the configuration the client was told of: any other value (empty, unknown, malformed, over-long, from another flag set or from a format that is retired) is behind. It never fails, and it tells nothing about a configuration but the current one.
func ContextWithState ¶ added in v0.3.0
ContextWithState returns a context that makes the stream of the request resumable: the service compares the Last-Event-ID of the client with the configuration that state reports, once the client is subscribed.
Types ¶
type ConfigIdentity ¶ added in v0.2.0
ConfigIdentity names the configuration of a flag set that a change leads to: the ETag the OFREP bulk evaluation compares with the one a replica serves, and the date the configuration was built.
type KeyRoutes ¶ added in v0.2.0
KeyRoutes lists the API keys that route to a flag set now, with the name of the flag set. It is a sequence, so that a service that has no client with a key never reads it.
type KeyedWebsocketService ¶ added in v0.2.0
type KeyedWebsocketService interface {
// RegisterKeyed is Register for a connection that authenticated with an API key: the service keeps an identifier of
// the key (never the key), so that [WebsocketService.DisconnectRevoked] can close the connection when the key does
// not route to the flag set anymore. The connection is inactive: it receives nothing until
// [WebsocketService.Activate]. The caller checks the key again between the two, so that a key that was revoked by a
// swap that ran before the registration never receives a change.
RegisterKeyed(c WebsocketConnector, flagsetName, apiKey string)
// Activate makes a connection of RegisterKeyed receive the changes of its flag set. It returns false when the
// connection is not waiting anymore (its key was revoked or it left): the caller ends the connection.
Activate(c WebsocketConnector) bool
// DisconnectRevoked takes out of the list, before it returns, the connections whose key is not in routes anymore or
// routes to another flag set than the one of the connection, and returns what closes them: the caller runs it away
// from the swap, a close can take time. Connections without a key are not touched.
DisconnectRevoked(routes KeyRoutes) []func()
}
KeyedWebsocketService is what a websocket service does for the connections that authenticated with an API key.
type Limiter ¶ added in v1.0.0
type Limiter struct {
// contains filtered or unexported fields
}
Limiter caps the open change streams of a replica and tells the clients when to come back. A stream takes a slot (Limiter.Acquire) for as long as it is open and gives it back (Slot.Release); a refusal reads and writes atomics only: it takes no lock and allocates nothing. The zero value is not usable, build it with NewLimiter.
func NewLimiter ¶ added in v1.0.0
NewLimiter returns the limiter that the options describe: WithMaxStreams, WithReconnectWindow, WithJitter and WithLogger.
func (*Limiter) Acquire ¶ added in v1.0.0
Acquire takes a slot for a stream of the transport, or says why it can not: the replica is draining, or it has as many open streams as its cap. ctx is the request, for the log. The count is exact: the cap is checked and the slot is taken under one lock, so that N+1 streams that ask together never get more than N slots.
func (*Limiter) Drain ¶ added in v1.0.0
func (l *Limiter) Drain( ctx context.Context, window time.Duration, wait func(context.Context, time.Duration) error, ) error
Drain makes the replica refuse new streams and ends the open ones one by one, spread over the window: each stream gets a moment within it from the jitter source, so that the clients reconnect to other replicas over the window and not at the same instant. wait is the wait of the shutdown (it returns an error when its context ends); the waits add up to the window. A window of zero or less ends no stream: the streams close with the server. It returns when the window is over or ctx ended; a stream that is still open then is closed with the server.
func (*Limiter) RetryAfter ¶ added in v1.0.0
RetryAfter is the Retry-After header value of a refusal: a delay within the reconnect window rounded up to whole seconds, so it can pass the upper bound by less than a second (one second when the window is off), drawn from the jitter source. The slice is shared, a caller must not change it.
type Option ¶
type Option func(*options)
Option configures flag change streams.
func WithClock ¶ added in v0.2.0
WithClock sets the clock that the write deadlines of an SSE stream are computed from. The default is the real time: a network deadline is enforced by the runtime, so a stream that runs against the network keeps the default.
func WithFlagDetails ¶
WithFlagDetails controls whether stream payloads include flag definitions.
func WithJitter ¶ added in v1.0.0
WithJitter sets the source of the reconnect delays: a function that returns a value in [0, 1), safe for concurrent use. The default is the random source of the operating system; a test gives a fixed one.
func WithLogger ¶ added in v1.0.0
WithLogger sets the logger of the Limiter: it writes one line per minute at most, whatever the number of refusals.
func WithMaxStreams ¶ added in v1.0.0
WithMaxStreams sets the cap of open change streams (SSE and websocket together) of the Limiter. A value <= 0 means no cap.
func WithReconnectWindow ¶ added in v1.0.0
WithReconnectWindow sets the window of the reconnect delay: every SSE stream tells its client a delay within it (the retry field), and a refusal tells one in its Retry-After header. A max <= 0 turns the hint off; a min above max is taken as max.
func WithSSEHeartbeatInterval ¶
WithSSEHeartbeatInterval sets the interval between two SSE heartbeat comments, sent to keep idle connections open through proxies. A value <= 0 disables the heartbeat.
func WithWriteTimeout ¶ added in v0.2.0
WithWriteTimeout sets the time a websocket client has to take a message before it is closed and removed, and the write deadline of every write of an SSE stream. A value <= 0 keeps the default.
func WithWriteTimer ¶ added in v1.0.0
func WithWriteTimer(start func(conn WebsocketConnector, timeout time.Duration) (<-chan time.Time, func())) Option
WithWriteTimer sets how the timeout of a websocket write is started: it returns the channel that tells the write is late, and the function that stops the timer. The default is a timer of the runtime that fires after the write timeout. A caller that needs to end a write by its own action gives a channel that it closes.
type Reason ¶ added in v1.0.0
type Reason uint8
Reason is why a stream was refused.
type SSEService ¶
type SSEService interface {
// BroadcastFlagChanges sends an OFREP refetchEvaluation event to all clients
// subscribed to the given flagset stream.
BroadcastFlagChanges(flagsetName string, diff notifier.DiffCache) error
// BroadcastConfigChange is BroadcastFlagChanges for a change whose configuration is known: the event carries
// its identity, which a provider names in the re-fetch.
BroadcastConfigChange(flagsetName string, config ConfigIdentity) error
// ServeHTTP handles incoming SSE client connections. The request must
// carry a "stream" query parameter set to the target flagset name.
ServeHTTP(w http.ResponseWriter, r *http.Request)
// ServeKeyed is ServeHTTP for a client that authenticated with an API key: the service keeps an identifier of the
// key (never the key), so that [SSEService.DisconnectRevoked] can end the stream when the key does not route to the
// flag set anymore. The stream is still shared by every client of the flag set: a message is published once.
// stillValid is called once the client is registered: a key that was revoked while the request was being set up is
// then refused (a revalidation that ran before the registration could not see the client).
ServeKeyed(w http.ResponseWriter, r *http.Request, apiKey string, stillValid func() bool)
// DisconnectRevoked ends the streams of the clients whose key is not in routes anymore or routes to another flag
// set than the one of the stream. It cancels their requests and never waits for a client.
DisconnectRevoked(routes KeyRoutes)
// DisconnectAnonymous closes the streams of the clients without a key whose flag set is not keep; an empty keep
// closes all of them. A client with a key is never touched.
DisconnectAnonymous(keep string)
// Connections is the number of connected clients.
Connections() int
// SetOnSubscribe registers a callback invoked when a client subscribes to
// any stream. The streamID matches the flagset name used in BroadcastFlagChanges.
SetOnSubscribe(fn func(streamID string))
// Close shuts down the SSE server and disconnects all clients.
Close()
}
SSEService is the service interface that handles SSE connections. It dispatches OFREP flag change events (OpenFeature ADR-0008) scoped to specific flagset names so that only clients connected with an API key belonging to a given flagset receive the corresponding events.
type SSEServiceImpl ¶ added in v0.2.0
type SSEServiceImpl struct {
// contains filtered or unexported fields
}
SSEServiceImpl is the implementation of SSEService backed by r3labs/sse.
func NewSSEService ¶
func NewSSEService(opts ...Option) *SSEServiceImpl
NewSSEService creates a new SSEService backed by r3labs/sse.
func (*SSEServiceImpl) BroadcastConfigChange ¶ added in v0.2.0
func (s *SSEServiceImpl) BroadcastConfigChange(flagsetName string, config ConfigIdentity) error
BroadcastConfigChange sends the refetchEvaluation event with the identity of the configuration. The event id is the ETag of the configuration (see [eventFrame]), so a client can resume with it on any replica.
func (*SSEServiceImpl) BroadcastFlagChanges ¶ added in v0.2.0
func (s *SSEServiceImpl) BroadcastFlagChanges(flagsetName string, _ notifier.DiffCache) error
BroadcastFlagChanges only notifies that the flags changed, the diff is not sent: providers re-fetch their evaluations when they receive the event.
func (*SSEServiceImpl) Close ¶ added in v0.2.0
func (s *SSEServiceImpl) Close()
Close closes all the SSE streams.
func (*SSEServiceImpl) Connections ¶ added in v0.2.0
func (s *SSEServiceImpl) Connections() int
Connections is the number of connected clients.
func (*SSEServiceImpl) DisconnectAnonymous ¶ added in v0.2.0
func (s *SSEServiceImpl) DisconnectAnonymous(keep string)
DisconnectAnonymous ends the requests of the clients without a key whose flag set is not keep. It cancels their request contexts, so the library ends each subscription itself: removing the stream under them would leave one goroutine of the library blocked per client.
func (*SSEServiceImpl) DisconnectRevoked ¶ added in v0.2.0
func (s *SSEServiceImpl) DisconnectRevoked(routes KeyRoutes)
DisconnectRevoked ends the requests of the clients whose key does not route to their flag set anymore. The requests are cancelled after the lock is released, and a cancel never waits for the client.
func (*SSEServiceImpl) ServeHTTP ¶ added in v0.2.0
func (s *SSEServiceImpl) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP serves a client without a key.
func (*SSEServiceImpl) ServeKeyed ¶ added in v0.2.0
func (s *SSEServiceImpl) ServeKeyed(w http.ResponseWriter, r *http.Request, apiKey string, stillValid func() bool)
ServeKeyed serves a client that authenticated with an API key.
func (*SSEServiceImpl) SetOnSubscribe ¶ added in v0.2.0
func (s *SSEServiceImpl) SetOnSubscribe(fn func(streamID string))
SetOnSubscribe sets the callback called when a client subscribes to a stream.
type Slot ¶ added in v1.0.0
type Slot struct {
// contains filtered or unexported fields
}
Slot is the place of one open stream. Give it back with Slot.Release: it is idempotent.
func (*Slot) Bind ¶ added in v1.0.0
func (s *Slot) Bind(cancel context.CancelFunc)
Bind gives the slot the function that ends its stream: Limiter.Drain calls it. When the slot was closed before the bind, it is called at once.
type State ¶ added in v0.3.0
type State func() (ConfigIdentity, bool)
State reads the configuration the flag set of a stream serves right now; false when the flag set is not known anymore (the revalidation of the relay then ends the stream).
type Stats ¶ added in v1.0.0
type Stats struct {
// Open are the open streams by transport, in the order of [Transport].
Open [transports]int64
// Refused are the refusals by transport and reason, in the order of [Transport] and [Reason].
Refused [transports][reasons]uint64
// Max is the cap, zero for none.
Max int64
}
Stats are the counts that the metrics read.
type Transport ¶ added in v1.0.0
type Transport uint8
Transport is the kind of a change stream, the only label of the stream metrics next to the reason of a refusal.
type WebsocketConnector ¶
WebsocketConnector is an interface to be able to mock websocket.Conn.
type WebsocketService ¶
type WebsocketService interface {
KeyedWebsocketService
// Register is adding the connection to the list of open connection of the flagset.
Register(c WebsocketConnector, flagsetName string)
// RegisterAnonymous is Register for a connection that has no API key: the flag set is the public flag set of
// the relay, and [WebsocketService.DisconnectAnonymous] closes the connection when it is not anymore.
RegisterAnonymous(c WebsocketConnector, flagsetName string)
// DisconnectAnonymous closes the connections without a key whose flag set is not keep; an empty keep closes all
// of them. A connection with a key is never touched.
DisconnectAnonymous(keep string)
// Deregister is removing the connection from the list of open connection.
Deregister(c WebsocketConnector)
// Connections is the number of open connections.
Connections() int
// BroadcastFlagChanges is sending the diff cache struct to the clients of the flagset.
BroadcastFlagChanges(flagsetName string, diff notifier.DiffCache)
// Close deregister all open connections.
Close()
// WaitForCleanup waits for all connections to be properly closed
WaitForCleanup(timeout time.Duration) error
}
WebsocketService is the service interface that handle the websocket connections This service is able to broadcast a notification to all the open websockets.
type WebsocketServiceImpl ¶ added in v0.2.0
type WebsocketServiceImpl struct {
// contains filtered or unexported fields
}
WebsocketServiceImpl is the implementation of the interface.
func NewWebsocketService ¶
func NewWebsocketService(opts ...Option) *WebsocketServiceImpl
NewWebsocketService is a constructor to create a new WebsocketServiceImpl.
func (*WebsocketServiceImpl) Activate ¶ added in v0.2.0
func (w *WebsocketServiceImpl) Activate(conn WebsocketConnector) bool
Activate puts a connection that waited into the list the broadcasts read.
func (*WebsocketServiceImpl) BroadcastFlagChanges ¶ added in v0.2.0
func (w *WebsocketServiceImpl) BroadcastFlagChanges(flagsetName string, diff notifier.DiffCache)
BroadcastFlagChanges is sending the diff to all the open connection of the flagset. No lock is held while a client is written to: the recipients are taken under the lock, then every one is written to on its own, and one that does not take the message within the write timeout is closed and removed. The others still get the change.
func (*WebsocketServiceImpl) Close ¶ added in v0.2.0
func (w *WebsocketServiceImpl) Close()
Close deregister all open connections.
func (*WebsocketServiceImpl) Connections ¶ added in v0.2.0
func (w *WebsocketServiceImpl) Connections() int
Connections is the number of open connections.
func (*WebsocketServiceImpl) Deregister ¶ added in v0.2.0
func (w *WebsocketServiceImpl) Deregister(conn WebsocketConnector)
Deregister is removing the connection from the list of open connection.
func (*WebsocketServiceImpl) DisconnectAnonymous ¶ added in v0.2.0
func (w *WebsocketServiceImpl) DisconnectAnonymous(keep string)
DisconnectAnonymous closes the connections without a key whose flag set is not keep. They are out of the list before it returns, so no change reaches them anymore.
func (*WebsocketServiceImpl) DisconnectRevoked ¶ added in v0.2.0
func (w *WebsocketServiceImpl) DisconnectRevoked(routes KeyRoutes) []func()
DisconnectRevoked takes the connections of the keys that do not route to their flag set anymore out of the list, and returns the closes. Nothing is written to a socket under the lock, and a service with no keyed connection does not read the routes.
func (*WebsocketServiceImpl) Register ¶ added in v0.2.0
func (w *WebsocketServiceImpl) Register(c WebsocketConnector, flagsetName string)
Register is adding the connection to the list of open connection of the flagset.
func (*WebsocketServiceImpl) RegisterAnonymous ¶ added in v0.2.0
func (w *WebsocketServiceImpl) RegisterAnonymous(c WebsocketConnector, flagsetName string)
RegisterAnonymous is Register for a connection that has no API key.
func (*WebsocketServiceImpl) RegisterKeyed ¶ added in v0.2.0
func (w *WebsocketServiceImpl) RegisterKeyed(conn WebsocketConnector, flagsetName, apiKey string)
RegisterKeyed is Register for a connection that has an API key.
func (*WebsocketServiceImpl) WaitForCleanup ¶ added in v0.2.0
func (w *WebsocketServiceImpl) WaitForCleanup(timeout time.Duration) error
WaitForCleanup waits for all connections to be properly closed.