Documentation
¶
Index ¶
- Constants
- Variables
- type A
- func (a *A) HandleAuth(b []byte, srv server.I) (msg []byte)
- func (a *A) HandleClose(req []byte, srv server.I) (note []byte)
- func (a *A) HandleEvent(c context.T, req []byte, srv server.I) (msg []byte)
- func (a *A) HandleMessage(msg, authedPubkey []byte)
- func (a *A) HandleReq(c context.T, req []byte, srv server.I) (r []byte)
- func (a *A) Pinger(ctx context.T, ticker *time.Ticker, cancel context.F, s server.I)
- func (a *A) Serve(w http.ResponseWriter, r *http.Request, s server.I)
- type Close
- type Map
- type OK
- type OKs
- type S
- type W
Constants ¶
const ( DefaultWriteWait = 10 * time.Second DefaultPongWait = 60 * time.Second DefaultPingWait = DefaultPongWait / 2 DefaultMaxMessageSize = 1 * units.Mb )
const Type = "socketapi"
Variables ¶
var Ok = OKs{ Ok: func( a *A, env eventId.Ider, format string, params ...any, ) (err error) { return okenvelope.NewFrom( env.Id(), true, nil, ).Write(a.Listener) }, AuthRequired: func( a *A, env eventId.Ider, format string, params ...any, ) (err error) { return okenvelope.NewFrom( env.Id(), false, reason.AuthRequired.F(format, params...), ).Write(a.Listener) }, PoW: func( a *A, env eventId.Ider, format string, params ...any, ) (err error) { return okenvelope.NewFrom( env.Id(), false, reason.PoW.F(format, params...), ).Write(a.Listener) }, Duplicate: func( a *A, env eventId.Ider, format string, params ...any, ) (err error) { return okenvelope.NewFrom( env.Id(), false, reason.Duplicate.F(format, params...), ).Write(a.Listener) }, Blocked: func( a *A, env eventId.Ider, format string, params ...any, ) (err error) { return okenvelope.NewFrom( env.Id(), false, reason.Blocked.F(format, params...), ).Write(a.Listener) }, RateLimited: func( a *A, env eventId.Ider, format string, params ...any, ) (err error) { return okenvelope.NewFrom( env.Id(), false, reason.RateLimited.F(format, params...), ).Write(a.Listener) }, Invalid: func( a *A, env eventId.Ider, format string, params ...any, ) (err error) { return okenvelope.NewFrom( env.Id(), false, reason.Invalid.F(format, params...), ).Write(a.Listener) }, Error: func( a *A, env eventId.Ider, format string, params ...any, ) (err error) { return okenvelope.NewFrom( env.Id(), false, reason.Error.F(format, params...), ).Write(a.Listener) }, Unsupported: func( a *A, env eventId.Ider, format string, params ...any, ) (err error) { return okenvelope.NewFrom( env.Id(), false, reason.Unsupported.F(format, params...), ).Write(a.Listener) }, Restricted: func( a *A, env eventId.Ider, format string, params ...any, ) (err error) { return okenvelope.NewFrom( env.Id(), false, reason.Restricted.F(format, params...), ).Write(a.Listener) }, }
Ok provides a collection of handler functions for managing different types of operational outcomes, each corresponding to specific error or status conditions such as authentication requirements, rate limiting, and invalid inputs.
var Upgrader = websocket.Upgrader{ ReadBufferSize: 1024, WriteBufferSize: 1024, CheckOrigin: func(r *http.Request) bool { return true }, }
Upgrader is a preconfigured instance of websocket.Upgrader used to upgrade HTTP connections to WebSocket connections with specific buffer sizes and a permissive origin-checking function.
Functions ¶
This section is empty.
Types ¶
type A ¶
A is a composite type that integrates a context, a websocket Listener, and a server interface to manage WebSocket-based server communication. It is designed to handle message processing, authentication, and event dispatching in its operations.
func (*A) HandleAuth ¶
HandleAuth processes authentication data received from a remote client, validates it against the server's challenge, and sets up authentication if successful.
Parameters ¶
- b ([]byte): The raw byte slice containing the authentication response to be processed.
- srv (server.I): A reference to the server interface that provides context for the authentication process.
Return Values ¶
- msg ([]byte): An optional message returned if the authentication fails or requires further action.
Expected behaviour ¶
Handles the authentication process by checking if authentication is required, unmarshalling and validating the response against a challenge, logging relevant information, and setting up the authenticated state on successful validation.
func (*A) HandleClose ¶
HandleClose processes a CLOSE envelope by unmarshalling the request, validates the presence of an <id> field, and signals cancellation for the associated listener through the server's publisher mechanism.
Parameters ¶
req ([]byte): The raw byte slice containing the CLOSE envelope data.
srv (server.I): A reference to the server interface used to access publishing capabilities.
Return Values ¶
- note ([]byte): An empty byte slice if successful, or an error message if the envelope is invalid or missing required fields.
Expected behaviour ¶
Processes the CLOSE envelope by unmarshalling it into a structured format, checks for remaining data after unmarshalling, verifies the presence of a non-empty <id> field, and sends a cancellation signal to the publisher with the associated listener and ID. Returns an error message if the envelope lacks a valid <id>.
func (*A) HandleEvent ¶
HandleEvent processes an incoming event by validating its signature, verifying its integrity, and handling deletion operations based on event tags.
Parameters ¶
c (context.T): The context for the current operation, used for logging and cancellation.
req ([]byte): The raw byte representation of the event to be processed.
srv (server.I): The server interface providing access to storage and relay functionalities required during event handling.
Return Values ¶
- msg ([]byte): A byte slice representing a response message, typically empty on success or containing error details if processing fails.
Expected behaviour ¶
Processes the event by unmarshalling it into an envelope and validating its signature. If the event is a deletion, it checks tags to determine which events should be deleted, ensuring authorship matches before performing deletions in storage. Logs relevant information during processing and returns appropriate responses.
func (*A) HandleMessage ¶
HandleMessage processes an incoming byte slice message by identifying its type and routing it to the appropriate handler method, generating and sending a notice response if necessary.
Parameters ¶
- msg ([]byte): The incoming message data to be processed.
Expected behaviour ¶
Processes the message by identifying its envelope type, routes it to the corresponding handler method, generates a notice for errors or unknown types, logs the notice, and writes it back to the listener if required.
func (*A) HandleReq ¶
HandleReq processes a raw request, parses its envelope, validates filters, and interacts with the server storage and subscription mechanisms to query events or manage subscriptions.
Parameters ¶
c: a context object used for managing deadlines, cancellation signals, and other request-scoped values.
req: a byte slice representing the raw request data to be processed.
srv: An interface representing the server, providing access to storage and subscription management.
Return Values ¶
- r: a byte slice containing the response or error message generated during processing.
Expected behaviour ¶
The method parses and validates the incoming request envelope, querying events from the server storage based on filters provided. It sends results through the associated subscription or writes error messages to the listener. If the subscription should be cancelled due to completed query results, it generates and sends a closure envelope.
func (*A) Pinger ¶
Pinger sends periodic WebSocket ping messages to maintain an active connection and handles clean-up when the context is cancelled or the ticker triggers.
Parameters ¶
ctx (context.T): The context controlling the operation lifecycle, used to detect cancellation or completion signals.
ticker (*time.Ticker): A timer that triggers periodic ping messages at regular intervals.
cancel (context.F): A function to cancel the context when the operation should terminate, typically called on shutdown or error.
s (server.I): The server interface provides contextual information for the connection, though not directly used within this method.
Expected behaviour ¶
Sends WebSocket ping messages at intervals defined by the ticker. If an error occurs during transmission, logs the failure and closes the underlying connection. Cleans up resources by stopping the ticker and cancelling the context when the operation completes or is interrupted.
func (*A) Serve ¶
Serve handles an incoming WebSocket request by upgrading the HTTP request, managing the WebSocket connection, and delegating received messages for processing.
Parameters ¶
w: The HTTP response writer used to manage the connection upgrade.
r: The HTTP request object that is being upgraded to a WebSocket connection.
s: The server context object that manages request lifecycle and state.
Expected Behaviour ¶
The method upgrades the HTTP connection to a WebSocket connection, sets up read and write limits, handles pings and pongs for keeping the connection alive, and processes incoming messages. It ensures proper cleanup of resources on connection termination or cancellation, adhering to the given context's lifecycle.
type OK ¶
OK represents a function that processes events or operations, using provided parameters to generate formatted messages and return errors if any issues occur during processing.
type OKs ¶
type OKs struct {
Ok OK
AuthRequired OK
PoW OK
Duplicate OK
Blocked OK
RateLimited OK
Invalid OK
Error OK
Unsupported OK
Restricted OK
}
OKs provides a collection of handler functions for managing different types of operational outcomes, each corresponding to specific error or status conditions such as authentication requirements, rate limiting, and invalid inputs.
type S ¶
type S struct {
// Mx is the mutex for the Map.
Mx sync.Mutex
// Map is the map of subscribers and subscriptions from the websocket api.
Map
// Server is an interface to the server.
Server server.I
}
S is a structure that manages subscriptions and associated filters for websocket listeners. It uses a mutex to synchronize access to a map storing subscriber connections and their filter configurations.
func (*S) Deliver ¶
Deliver processes and distributes an event to all matching subscribers based on their filter configurations.
Parameters ¶
- ev (*event.E): The event to be delivered to subscribed clients.
Expected behaviour ¶
Delivers the event to all subscribers whose filters match the event. It applies authentication checks if required by the server and skips delivery for unauthenticated users when events are privileged.
func (*S) Receive ¶
Receive handles incoming messages to manage websocket listener subscriptions and associated filters.
Parameters ¶
- msg (publisher.Message): The incoming message to process; expected to be of type *W to trigger subscription management actions.
Expected behaviour ¶
- Checks if the message is of type *W.
- If Cancel is true, removes a subscriber by ID or the entire listener.
- Otherwise, adds the subscription to the map under a mutex lock.
- Logs actions related to subscription creation or removal.
type W ¶
type W struct {
*ws.Listener
// If Cancel is true, this is a close command.
Cancel bool
// Id is the subscription Id. If Cancel is true, cancel the named
// subscription, otherwise, cancel the publisher for the socket.
Id string
// The Receiver holds the event channel for receiving notifications or data
// relevant to this WebSocket connection.
Receiver event.C
// Filters holds a collection of filters used to match or process events
// associated with this WebSocket connection. It is used to determine which
// notifications or data should be received by the subscriber.
Filters *filters.T
}