• English
  • Socket

    Planned APIs: This page documents the final socket workflow. commflow@0.0.2 does not export a socket runtime; do not use its imports as current production imports. See Current Release Quick Start for runnable exports.

    When To Use It

    socket fits long-lived bidirectional realtime communication:

    ScenarioFit
    Chat, collaboration, room messagesYes
    Realtime state syncYes
    Both client and server actively send messagesYes
    Server-to-client one-way eventsConsider SSE
    One-shot request/responseUse Request

    Create A Socket Client

    import { createCommflowSocketClient } from 'commflow';
    
    const socket = createCommflowSocketClient({
      url: 'wss://socket.example.com',
      heartbeatInterval: 30000,
      reconnect: {
        attempts: 5,
        delay: 1000
      }
    });
    OptionUser meaning
    urlWebSocket service URL.
    heartbeatIntervalHeartbeat interval.
    reconnectReconnect policy after disconnect.

    Connect And Close

    await socket.connect();
    
    // ...use the connection
    
    await socket.close();

    The lifecycle must be explicit. Users should know when the connection starts, when it closes, and whether reconnect is still active after close.

    Send Messages

    await socket.send({
      type: 'chat.message',
      payload: {
        roomId: 'room-a',
        text: 'hello'
      }
    });

    Recommended message shape:

    FieldMeaning
    typeMessage type.
    payloadBusiness data.
    requestIdOptional correlation or diagnostics id.

    Ordering and backpressure:

    ScenarioTarget behavior
    Send before openQueue the message by default, or fail immediately by user config.
    Send during reconnectPreserve order and flush after reconnect.
    Server or browser buffer is too highExpose drain or backpressure state to avoid unbounded memory growth.
    User manually closesClear the queue and do not resend.

    Listen To Events

    const unsubscribe = socket.on('message', (message) => {
      console.log(message.type, message.payload);
    });
    
    unsubscribe();

    Listeners must be releasable to avoid leaks after page switches, service shutdown, or repeated subscriptions.

    Heartbeat And Reconnect

    ScenarioGuidance
    Heartbeat timeoutTreat connection as unavailable and reconnect or fail.
    Short network breakReconnect by policy.
    Server closed connectionCheck close reason before reconnecting.
    User closed connectionDo not reconnect automatically.

    Resubscribe:

    const socket = createCommflowSocketClient({
      url: 'wss://socket.example.com',
      reconnect: { attempts: 5, delay: 1000 },
      resubscribeOnReconnect: true
    });
    
    await socket.subscribe('room-a');

    Whether reconnect automatically resubscribes must be configurable. By default, do not replay business messages that can cause side effects; only restore subscriptions, presence, or read-only state sync when it is safe.

    Auth And Session

    Socket connections often require token or session data:

    const socket = createCommflowSocketClient({
      url: 'wss://socket.example.com',
      auth() {
        return {
          token: getAccessToken()
        };
      }
    });

    When auth expires, users should be able to refresh the token and reconnect instead of retrying forever.

    Cleanup

    Resources that must be released:

    • message listeners;
    • reconnect timers;
    • heartbeat timers;
    • pending request/response correlation;
    • socket connection.

    Error Handling

    ErrorHandling
    Network disconnectReconnect if policy allows.
    Auth failureRefresh token or ask user to sign in again.
    Protocol errorRecord message and close reason.
    Manual closeDo not reconnect.

    See Errors And Retries for the broader error model.