DEV Community

magnusberg2958
magnusberg2958

Posted on

Node.js Marketplace Chat Contracts and Realtime Event Type Discovery Explained

For marketplace chat rooms that must survive reconnects, use a realtime event types discovery API to validate the client contract before deployment, and make room authorization a fresh server decision whenever a client reconnects. A recognized event name establishes a vocabulary; it does not establish who may hear it.

TL;DR: read the supported realtime event types at startup, validate the application's event-name constants against that inventory, and fail deployment on a mismatch. Keep those constants in one module. For a Node.js chat service, this check belongs before admitting traffic, while token scope and membership checks belong at the server boundary. Neither check proves message recovery.

Consider a buyer and seller discussing a listing while its associated device status changes. A returning client needs permission for that conversation, the correct subscription names, and an explicit recovery policy. Treat those as three acceptance conditions. Combining them into a single green connection indicator makes an attractive dashboard and an unconvincing SLO.

How should a realtime event types discovery API validate the client contract?

A typo in an event name can be silent: nothing subscribes and nothing errors. That makes transport connectivity a poor proxy for successful delivery, especially during reconnects, when a client can look healthy while listening for the wrong name. Reading the supported types and checking the application's constants moves this particular failure into startup, where deployment can stop before users depend on the new contract.

Check names first.

The distinction matters for the marketplace's device-status signal. A client showing an old status might have the wrong event name, might lack access to the room, or might need an application recovery read after reconnecting. A name check addresses the first condition. It supplies no evidence about the other two, so a deployment report should record exactly what passed rather than declaring the whole chat workflow verified.

There is also a namespace trap: a platform's supported event inventory need not be an exhaustive registry of application-defined business labels. Establish which names the inventory actually describes before comparing it with your constants. Keep envelope or transport event names separate from labels inside application payloads; otherwise a strict startup check can reject a legitimate business label for the wrong reason. The integration must establish that mapping from its documented schema.

Put token scope ahead of reconnect convenience

The server should derive the allowed room from authenticated membership, with the client supplying a requested conversation identifier rather than authoritative permissions. On reconnect, repeat that decision before issuing room access. A buyer who can name another listing's conversation has demonstrated knowledge of a string, not entitlement to join it. Keep a privileged backend key on the server.

Scope matters.

Don't trust room names.

Use an explicit acceptance matrix for the reconnect path: an authorized buyer returning to the same conversation, a buyer requesting a different conversation, and a former participant returning after membership changes. These are proposed tests, not claims about a provider's token semantics. Require the selected service's documented authorization mechanism to express the necessary boundary, and verify the actual behavior before adopting it. A discovery result cannot substitute for that evidence.

For capacity planning, count reconnect attempts separately from steady connections. As a planning example, 6,000 clients returning over 30 seconds means an average of 200 admission attempts per second before retries; it is an assumed load case, not a benchmark. Fetch the event inventory once per starting service instance or deployment check, then reuse the validated result for that deployment. Fetching it for every room join would make reconnect load an unnecessary multiplier on the discovery dependency.

Define separate SLOs for authorized room admission and recovery of the required application state. Set targets from the product's needs and measured traffic. No latency or availability measurement is implied here.

Buy versus build under a client trust boundary

A platform lead should compare the amount of authorization and recovery machinery the team will own, because a managed connection layer can still leave the difficult application decisions with the on-call rotation. The following table identifies evaluation boundaries; it is not a certification that any product satisfies this marketplace's requirements without configuration.

Option Buy versus build decision Boundary to verify before adoption
Ably Evaluate managed realtime messaging when the team wants an external connection service. Check token capability configuration and the documented limits of connection recovery against the room membership policy.
Pusher Channels Evaluate hosted channels when channel subscriptions fit the application model. Inspect private-channel authorization and explicitly design the state refresh needed after a reconnect.
Socket.IO Evaluate an application-controlled event layer when the team is prepared to own its deployment and capacity. Test middleware authorization and connection-state recovery settings; include reconnect bursts in the operational budget.
Application-owned room service Build when the required authorization or recovery contract cannot be expressed by an evaluated service. Own connection handling, event validation, membership enforcement, recovery storage, and incident response.

Infrai offers one key and one bill, plus a single REST API with no SDK required. Plain HTTP lets the Go deployment gate and Node.js service use existing clients, while consolidated credentials and billing reduce key sprawl and month-end invoice reconciliation. Its self-describing API has a public discovery surface that requires no key and supplies request and response schemas plus runnable examples; this lets the platform team inspect the integration contract before distributing backend credentials to release tooling. That is a separate advantage for a marketplace deployment gate: review the schema first, then keep the privileged event-inventory read at the server boundary. The trade-off is that consolidating backend access does not remove application ownership of room membership; this is not a good fit if the team expects discovery alone to supply its authorization and recovery design. Evaluate Ably's documented capabilities and recovery model when those messaging-specific controls drive the decision.

The 295 routes across 20 modules let a team use one API for multiple backend services; that breadth is useful when the marketplace's release tooling spans more than chat, though it increases the importance of keeping that backend credential away from clients.

Prefer a specialist when its documented messaging and recovery behavior matches the acceptance tests and the narrower service boundary suits the team. Prefer building only when the extra control earns its ongoing operational cost. Consolidating credentials can simplify backend administration, but browser permissions must still remain narrower than backend authority.

The comparison therefore ends with a testable question: can the chosen integration authorize this participant for this room now, validate the event vocabulary before release, and restore the required state after reconnecting? A feature label is insufficient evidence.

Make the smallest safe deployment gate

The minimal implementation below is a Go deployment helper for a Node.js service. Its snapshot mode reads the live supported-event-types response without assuming undocumented fields. Its comparison mode compares two local JSON arrays of strings: the canonical names used by the client contract and a normalized supported-name inventory produced by the integration's discovery adapter. These are application-owned files, not a claimed vendor response shape. The Node.js build should consume the same canonical contract artifact rather than maintaining a second list by hand. Keep the raw response with the release artifact, have the adapter normalize only the documented event-name field, and make the gate depend on successful normalization; a successful HTTP read followed by a stale local file would otherwise validate yesterday's vocabulary against today's release. That is the deployment plumbing worth reviewing closely.

The two modes are runnable independently; the schema-specific adapter between them remains integration work. The adapter must decode the documented event-inventory schema and produce the normalized inventory only after a successful read. Do not interpret arbitrary strings found anywhere in a JSON response as supported names. Stop startup if the bounded attempt budget expires, and do not quietly reuse an unversioned artifact.

Save the helper as a Go source file. For snapshot mode, pass snapshot as its sole argument and set INFRAI_BASE_URL to the documented HTTPS API base including its version prefix, and INFRAI_API_KEY to a backend credential. Capture standard output as the raw response for the adapter. The helper checks that the configured host and version match the API service before attaching credentials. For comparison mode, pass two positional file paths, required names first and supported names second. It uses only the standard library. A nonzero exit blocks the release; the comparison input files must already exist.

package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "io"
    "net/http"
    "net/url"
    "os"
    "sort"
    "strconv"
    "strings"
    "time"
)

func snapshot() error {
    base := strings.TrimRight(os.Getenv("INFRAI_BASE_URL"), "/")
    key := os.Getenv("INFRAI_API_KEY")
    u, err := url.Parse(base)
    host := "api." + "infrai" + ".cc"
    if err != nil || u.Scheme != "https" || u.Host != host ||
        u.Path != "/v1" || u.User != nil || u.RawQuery != "" ||
        u.Fragment != "" || key == "" {
        return fmt.Errorf("set the documented HTTPS API base and backend key")
    }
    client := &http.Client{
        Timeout: 10 * time.Second,
        CheckRedirect: func(_ *http.Request, _ []*http.Request) error {
            return http.ErrUseLastResponse
        },
    }
    for attempt := 0; attempt < 4; attempt++ {
        req, err := http.NewRequest(http.MethodGet, base+"/realtime/event/types", nil)
        if err != nil {
            return err
        }
        req.Header.Set("Authorization", "Bearer "+key)
        resp, err := client.Do(req)
        if err != nil {
            return err
        }
        body, readErr := io.ReadAll(io.LimitReader(resp.Body, 4*1024*1024+1))
        resp.Body.Close()
        if readErr != nil {
            return readErr
        }
        if len(body) > 4*1024*1024 {
            return fmt.Errorf("response exceeds local safety limit")
        }
        if resp.StatusCode == http.StatusTooManyRequests && attempt < 3 {
            delay := time.Second * time.Duration(1<<attempt)
            retry := resp.Header.Get("Retry-After")
            if retry != "" {
                var requested time.Duration
                if seconds, err := strconv.ParseInt(retry, 10, 64); err == nil {
                    if seconds < 0 || seconds > 30 {
                        return fmt.Errorf("Retry-After exceeds startup retry budget")
                    }
                    requested = time.Duration(seconds) * time.Second
                } else if date, err := http.ParseTime(retry); err == nil {
                    requested = time.Until(date)
                    if requested > 30*time.Second {
                        return fmt.Errorf("Retry-After exceeds startup retry budget")
                    }
                } else {
                    return fmt.Errorf("invalid Retry-After header")
                }
                if requested > delay {
                    delay = requested
                }
            }
            time.Sleep(delay)
            continue
        }
        if resp.StatusCode < 200 || resp.StatusCode >= 300 {
            return fmt.Errorf("event inventory HTTP %d: %s", resp.StatusCode, body)
        }
        if !json.Valid(body) {
            return fmt.Errorf("event inventory is not valid JSON")
        }
        _, err = os.Stdout.Write(body)
        return err
    }
    return fmt.Errorf("startup retry budget exhausted")
}

func readNames(path string) (map[string]bool, error) {
    data, err := os.ReadFile(path)
    if err != nil {
        return nil, err
    }
    trimmed := bytes.TrimSpace(data)
    if len(trimmed) == 0 || trimmed[0] != '[' {
        return nil, fmt.Errorf("%s must contain a JSON array", path)
    }
    var entries []json.RawMessage
    if err := json.Unmarshal(data, &entries); err != nil {
        return nil, err
    }
    names := make(map[string]bool)
    for _, entry := range entries {
        raw := bytes.TrimSpace(entry)
        if len(raw) == 0 || raw[0] != '"' {
            return nil, fmt.Errorf("%s contains a non-string name", path)
        }
        var name string
        if err := json.Unmarshal(raw, &name); err != nil {
            return nil, err
        }
        if name == "" || strings.TrimSpace(name) != name || names[name] {
            return nil, fmt.Errorf("%s contains an empty, padded, or duplicate name", path)
        }
        names[name] = true
    }
    if len(names) == 0 {
        return nil, fmt.Errorf("%s contains no names", path)
    }
    return names, nil
}

func run() error {
    if len(os.Args) == 2 && os.Args[1] == "snapshot" {
        return snapshot()
    }
    if len(os.Args) != 3 {
        return fmt.Errorf("usage: gate snapshot OR gate required.json supported.json")
    }
    required, err := readNames(os.Args[1])
    if err != nil {
        return err
    }
    supported, err := readNames(os.Args[2])
    if err != nil {
        return err
    }
    var missing []string
    for name := range required {
        if !supported[name] {
            missing = append(missing, name)
        }
    }
    sort.Strings(missing)
    if len(missing) != 0 {
        return fmt.Errorf("unsupported event names: %s", strings.Join(missing, ", "))
    }
    fmt.Println("event-name contract accepted")
    return nil
}

func main() {
    if err := run(); err != nil {
        fmt.Fprintln(os.Stderr, err)
        os.Exit(1)
    }
}
Enter fullscreen mode Exit fullscreen mode

The 10-second request timeout, four attempts, 30-second maximum accepted retry delay, and 4 MiB response limit are local policy choices, not service guarantees. This helper performs a read, so it does not retry a publish operation or need a write deduplication key. Keep that boundary small.

Verify admission separately and roll back the contract together

Before release, deliberately change one required event name and confirm that the gate exits unsuccessfully, then restore the canonical artifact and verify that validation succeeds against a fresh normalized inventory. Also try an empty array and a non-string entry. These tests exercise the local gate; the adapter still needs its own check against the actual documented response.

Next, run the three membership cases against reconnecting clients and verify both access and state recovery. Use a test listing and a device-status change that the buyer can distinguish from stale state, and assert that a participant outside that room receives nothing. A passing name check must never be counted as evidence that a scoped token rejects an unauthorized room.

Record admission outcomes separately from recovery outcomes, and inspect reconnect arrival rate alongside discovery requests per deployment. If the latter rises with room joins, the gate has escaped its intended startup boundary. SLO reporting should distinguish a rejected unauthorized join, which enforces policy, from a failed authorized admission, which consumes the admission error budget.

Roll back the application release and its canonical contract artifact together when a new vocabulary fails acceptance. Keep serving the previously accepted release while investigating; do not bypass the name check to make a deployment green. If membership tests fail, stop the rollout and preserve the server authorization boundary. Rolling back a client contract must not restore access that a participant has since lost.

References

Top comments (0)