Standardize comment format for parameters and return values in socketapi package

- Updated `pkg/protocol/socketapi/socketapi.go` with "# Expected Behaviour" section using British spelling
- Enhanced `pkg/protocol/socketapi/handleEvent.go` parameter documentation with context type annotations
- Standardized return value formatting with consistent bracket placement
- Improved error message phrasing to use "can't" instead of "cannot" for consistency
- Added detailed implementation notes for event deletion validation logic
This commit is contained in:
2025-07-19 14:45:55 +01:00
parent 681cdb3a64
commit 93d6871488
9 changed files with 145 additions and 63 deletions

View File

@@ -10,6 +10,29 @@ import (
"orly.dev/pkg/utils/log"
)
// 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 *A) HandleAuth(b []byte, srv server.I) (msg []byte) {
if a.I.AuthRequired() {
log.I.F("AUTH:\n%s", b)

View File

@@ -7,27 +7,29 @@ import (
"orly.dev/pkg/utils/log"
)
// HandleClose processes a CLOSE envelope, intended to cancel a specific
// subscription, and notifies the server to handle the cancellation.
// 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: A byte slice containing the raw CLOSE envelope data to process.
// - req ([]byte): The raw byte slice containing the CLOSE envelope data.
//
// - srv: The server instance responsible for managing subscription
// operations, such as cancellation.
// - srv (server.I): A reference to the server interface used to access
// publishing capabilities.
//
// # Return Values
//
// - note: A byte slice containing an error message if issues occur during
// processing; otherwise, an empty slice.
// - note ([]byte): An empty byte slice if successful, or an error message
// if the envelope is invalid or missing required fields.
//
// Expected behavior:
// # Expected behaviour
//
// The method parses and validates the CLOSE envelope. If valid, it cancels the
// corresponding subscription by notifying the server's publisher. If the
// envelope is malformed or the subscription ID is missing, an error message is
// returned instead. Logs any remaining unprocessed data for diagnostics.
// 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 *A) HandleClose(
req []byte,
srv server.I,

View File

@@ -18,33 +18,31 @@ import (
"orly.dev/pkg/utils/log"
)
// HandleEvent processes an incoming event request, validates its structure,
// checks its signature, and performs necessary actions such as storing,
// deleting, or responding to the event.
// HandleEvent processes an incoming event by validating its signature, verifying
// its integrity, and handling deletion operations based on event tags.
//
// # Parameters
//
// - c: a context object used for managing deadlines, cancellation signals,
// and other request-scoped values.
// - c (context.T): The context for the current operation, used for logging and
// cancellation.
//
// - req: a byte slice representing the raw request containing the event
// details to be processed.
// - req ([]byte): The raw byte representation of the event to be processed.
//
// - srv: an interface representing the server context, providing access to
// storage and other server-level utilities.
// - srv (server.I): The server interface providing access to storage and relay
// functionalities required during event handling.
//
// # Return Values
//
// - msg: a byte slice representing the response message generated by the
// method. The content depends on the processing outcome.
// - msg ([]byte): A byte slice representing a response message, typically empty
// on success or containing error details if processing fails.
//
// Expected behavior:
// # Expected behaviour
//
// The method validates the event's ID, checks its signature, and verifies its
// type. It ensures only authorized users can delete events and manages
// conflicts effectively. It interacts with storage for querying, updating, or
// deleting events while responding to the client based on the evaluation
// results. Returns immediately if any verification or operation fails.
// 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 *A) HandleEvent(
c context.T, req []byte, srv server.I,
) (msg []byte) {
@@ -206,7 +204,7 @@ func (a *A) HandleEvent(
if !kk.IsParameterizedReplaceable() {
if err = Ok.Error(
a, env,
"delete tags with a tags containing non-parameterized-replaceable events cannot be processed",
"delete tags with a tags containing non-parameterized-replaceable events can't be processed",
); chk.E(err) {
return
}
@@ -215,7 +213,7 @@ func (a *A) HandleEvent(
if !bytes.Equal(pk, env.E.Pubkey) {
if err = Ok.Blocked(
a, env,
"cannot delete other users' events (delete by a tag)",
"can't delete other users' events (delete by a tag)",
); chk.E(err) {
return
}

View File

@@ -12,20 +12,19 @@ import (
"orly.dev/pkg/utils/log"
)
// HandleMessage processes an incoming message, identifies its type, and
// delegates handling to the appropriate method based on the message's envelope
// type.
// 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: A byte slice representing the raw message to be processed.
// - msg ([]byte): The incoming message data to be processed.
//
// Expected behavior:
// # Expected behaviour
//
// The method identifies the message type by examining its envelope label and
// passes the message payload to the corresponding handler function. If the type
// is unrecognized, it logs an error and generates an appropriate notice
// message. Handles errors in message identification or writing responses.
// 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 *A) HandleMessage(msg []byte) {
var notice []byte
var err error

View File

@@ -22,25 +22,25 @@ import (
//
// # Parameters
//
// - c: A context object used for managing deadlines, cancellation signals,
// - 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.
// - 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
// - r: a byte slice containing the response or error message generated
// during processing.
//
// Expected behavior:
// # 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 canceled due to completed query results, it
// If the subscription should be cancelled due to completed query results, it
// generates and sends a closure envelope.
func (a *A) HandleReq(
c context.T, req []byte, srv server.I,

View File

@@ -6,8 +6,15 @@ import (
"orly.dev/pkg/interfaces/eventId"
)
// 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 OK func(a *A, env eventId.Ider, format string, params ...any) (err error)
// 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 OKs struct {
AuthRequired OK
PoW OK
@@ -20,6 +27,10 @@ type OKs struct {
Restricted OK
}
// 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 Ok = OKs{
AuthRequired: func(
a *A, env eventId.Ider, format string, params ...any,

View File

@@ -9,29 +9,30 @@ import (
"github.com/fasthttp/websocket"
)
// Pinger sends periodic WebSocket ping messages to ensure the connection is
// alive and responsive. It terminates the connection if pings fail or the
// context is canceled.
// 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: A context object used to monitor cancellation signals and
// manage termination of the method execution.
// - ctx (context.T): The context controlling the operation lifecycle, used to
// detect cancellation or completion signals.
//
// - ticker: A time.Ticker object that triggers periodic pings based on
// its configured interval.
// - ticker (*time.Ticker): A timer that triggers periodic ping messages at
// regular intervals.
//
// - cancel: A context.CancelFunc called to gracefully terminate operations
// associated with the WebSocket connection.
// - cancel (context.F): A function to cancel the context when the operation
// should terminate, typically called on shutdown or error.
//
// - s: An interface representing the server context, allowing interactions
// related to the connection.
// - s (server.I): The server interface provides contextual information for the
// connection, though not directly used within this method.
//
// Expected behavior:
// # Expected behaviour
//
// The method writes ping messages to the WebSocket connection at intervals
// dictated by the ticker. If the ping write fails or the context is canceled,
// it stops the ticker, invokes the cancel function, and closes the connection.
// 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 *A) Pinger(
ctx context.T, ticker *time.Ticker, cancel context.F, s server.I,
) {

View File

@@ -24,13 +24,22 @@ type Map map[*ws.Listener]map[string]*filters.T
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
Id string
// The Receiver holds the event channel for receiving notifications or data
// relevant to this WebSocket connection.
Receiver event.C
Filters *filters.T
// 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
}
func (w *W) Type() (typeName string) { return Type }
@@ -40,6 +49,9 @@ type Close struct {
Id string
}
// 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.
type S struct {
// Mx is the mutex for the Map.
Mx sync.Mutex
@@ -53,6 +65,23 @@ func New() (publisher *S) { return &S{Map: make(Map)} }
func (p *S) Type() (typeName string) { return Type }
// 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.
func (p *S) Receive(msg publisher.Message) {
if m, ok := msg.(*W); ok {
if m.Cancel {
@@ -87,6 +116,25 @@ func (p *S) Receive(msg publisher.Message) {
}
}
// Deliver sends an event to all subscribers whose filters match the event
//
// # Parameters
//
// - ev (*event.E): The event to deliver to matching subscribers
//
// # Expected behaviour
//
// # Locks the mutex to synchronize access to subscriber data
//
// # Iterates over all websocket connections and their associated subscriptions
//
// # Checks if each subscription's filter matches the event being delivered
//
// # Creates an event envelope result for matching subscriptions
//
// # Writes the result to the corresponding websocket connection
//
// Logs details about event delivery and any errors encountered
func (p *S) Deliver(ev *event.E) {
log.T.F("delivering event %0x to subscribers", ev.Id)
var err error

View File

@@ -46,7 +46,7 @@ type A struct {
//
// - s: The server context object that manages request lifecycle and state.
//
// Expected behavior:
// # 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