Loading...
Searching...
No Matches
ServerSentEventClient::ServerSentEventClient Class Reference

the main sse client class More...

`#include <ServerSentEventClient.qc.dox.h>`

## Public Member Functions

| clearStats ()
| Clears performance statistics.
| clearWarningQueue ()
| Removes any warning Queue object from the Socket.
hash< auto > | connect (*hash< auto > opts, *reference< hash< auto > > info)
| Connects to the sse server.
| constructor (hash< auto > opts)
| Creates the ServerSentEvent client object from the arguments.
| destructor ()
| disconnects the connection and stops the event thread if connected
| disconnect ()
| Disconnect with the given close code.
int | getConnectionId ()
| returns the unique connection ID
*hash< auto > | getConnectionInfo ()
| Returns information about the current connection.
*string | getPassword ()
| Returns any password set for the connection.
bool | getReconnect ()
| Returns the value of the reconnect flag.
string | getSafeUrl ()
| Returns a "safe" URL, without any password info.
hash< auto > | getSchemes ()
| returns a hash of URL scheme information for URL schemes supported by this object
string | getSerialization ()
| Returns the data serialization value (`"none"`, `"json"`)
string | getUrl ()
| returns the URL given in the constructor
hash< auto > | getUsageInfo ()
| Returns performance statistics for the socket.
*string | getUsername ()
| Returns any username set for the connection.
bool | isOpen ()
| returns True if the connection is currently open and active, False if not
bool | isReconnecting ()
| Returns True if the client is reconnecting.
| observersReady ()
| Called when all observers have been added to the object.
bool | reconnect ()
| Initiate a server reconnect immediately.
| setEventQueue ()
| Removes any Queue object so that socket events are no longer added to the Queue.
| setEventQueue (Qore::Thread::Queue queue, auto arg, *bool with_data)
| Sets a Queue object to receive socket events.
| setWarningQueue (int warning_ms, int warning_bs, Queue queue, auto arg, timeout min_ms=1s)
| Sets a Queue object to receive socket warnings.
| stopEvents ()
| Called to stop generating events.

## Public Attributes

const | DataSerializationSupport = ...
| Data serialization support.
const | DefaultTimeout = 15s
| Default socket I/O operation timeout: 15 seconds.
const | DefaultUserAgent = sprintf("Qore-SSE-Client/%s", ServerSentEventClient::Version)
| default user agent string for HTTP requests
const | MaxReconnectRetries = -1
| Max reconnect retries; negative numbers = infinite.
const | ReconnectDelay = 2s
| Reconnect retry delay.
const | Version = "1.0"
| Client version.

## Protected Member Functions

| clearTid ()
| Clears the tid and stop variables and wakes up any waiting threads.
| closingConnection ()
| Called when the connection is closed.
hash< auto > | connectIntern (*hash< auto > opts, *reference< hash< auto > > info, *bool reconnect)
| Connects to the sse server.
hash< auto > | connectUnlocked (*hash< auto > hdr0, *reference< hash< auto > > info, *bool reconnect)
| Performs the HTTP socket connection to the ServerSentEvent server.
| constructorInit (hash< auto > opts)
| Common constructor code.
auto | deserializeData (string buf)
| Deserializes data received.
| disconnectIntern (*bool destroy)
| Disconnect with the given close code.
| doReconnect ()
| Handles reconnections.
int | handleEvent (hash< SseMessageInfo > event)
| Handles messages.
| raiseError (string fmt,...)
| throsse an exception due to an error
| reconnectPostamble ()
| Executes after a reconnect.
| reconnectPreamble ()
| Executes before a reconnect.
| reestablishConnection (reference< hash< auto > > info)
| Connects to the server when reconnecting.
| start ()
| Connects and starts receiving messages.
| startReconnect ()
| Starts a reconnect.
Condition | tid_cond ()
| Event thread condition variable.
| unsupportedSerialization ()
| Throws an UNSUPPORTED-SERIALIZATION error.

## Static Protected Member Functions

static Sequence | seq ()
| Connection sequence.

## Protected Attributes

bool | chunked
| Flag indicating chunked transfer encoding.
int | cid = -1
| Unique sse connection ID; -1 when not connected.
string | content_encoding
| The content encoding used by the server.
bool | do_reconnect
| Flag for a user-initiated reconnect.
TransformOutputStream | dstream
| The decompression transform stream.
string | last_event_id
| Request Last-Event-Id when connecting.
int | num_connects
| Total number of connections made.
StringOutputStream | ostream
| The decompression output stream.
bool | reconnect = False
| Reconnect flag.
string | serialization
| data serialization option: json or none
const | SSEEDC_BREAK = 2
| Event disposition code: break event loop.
const | SSEEDC_CONTINUE = 1
| Event disposition code: continue processing event loop.
*code | start_thread
| callable value to start a new thread; must take a callable object as a parameter and return an integer TID
int | tid
| TID of the event thread; only changed in the log.
int | tid_waiting
| Event thread waiting count.
string | url
| URL string.
*code | yield
| callable object to yield the current thread's execution

## Detailed Description

the main sse client class

To use this class, create a ServerSentEventClient object and the call ServerSentEventClient::connect().

The ServerSentEventClient::connect() method starts a background thread to receive messages, which are then raised as observable events.

To stop listening for SSE events, call ServerSentEventClient::disconnect().

The ServerSentEventClient class includes support for running in sandboxed Program objects with the following parse options set:

- `PO_NO_PROCESS_CONTROL:` in this case the `"yield"` option is required in ServerSentEventClient::constructor()

## Member Function Documentation

## clearStats()

ServerSentEventClient::ServerSentEventClient::clearStats | ( |  | ) |

Clears performance statistics.

Example:
  sse.clearStats();

Since
  ServerSentEventClient 1.1

See also
  ServerSentEventClient::getUsageInfo()

## clearWarningQueue()

ServerSentEventClient::ServerSentEventClient::clearWarningQueue | ( |  | ) |

Removes any warning Queue object from the Socket.

Example:
  sse.clearWarningQueue();

See also
  ServerSentEventClient::setWarningQueue()

Since
  ServerSentEventClient 1.1

## connect()

hash< auto > ServerSentEventClient::ServerSentEventClient::connect | ( | *hash< auto > | opts,
|  | *reference< hash< auto > > | info )

Connects to the sse server.

Example:
  sub event(*data msg) {
  if (!msg) {
  printf("connection closed\n");
  } else {
  printf("%s msg: %y\n", now_us().format("YYYY-MM-DD HH:mm:SS.xx"), msg);
  }
  }
  ServerSentEventClient sse(\event(), {
  "url": "sse://example.com:8080/path",
  });
  sse.connect();

This method starts a background thread to receive messages, which are rasied as observable events. If the server disconnects the SSE connection, the event thread also terminates and the ServerSentEventClient object will be in a disconnected state.

To stop listening for SSE events, call ServerSentEventClient::disconnect().

If this method is called while a connection is already in progress, then the existing connection is first implicitly disconnected.

Parameters

  opts

  a hash with the following keys:
  - `hdr:` (optional) a hash giving header values for the connection request to the SSE server

  info | a reference to a hash which will be set to information about the call setup

Returns
  a hash with information about the HTTP response from the HTTP server corresponding to the return value of Qore::Socket::readHTTPHeader()

Exceptions

  SSE-ERROR | the option hash is missing either the 'url' key or there is type error in the option hash

## constructor()

ServerSentEventClient::ServerSentEventClient::constructor | ( | hash< auto > | opts | ) |

Creates the ServerSentEvent client object from the arguments.

Example:
  sub event(*data msg) {
  if (!msg) {
  printf("connection closed\n");
  } else {
  printf("%s msg: %y\n", now_us().format("YYYY-MM-DD HH:mm:SS.xx"), msg);
  }
  }
  ServerSentEventClient sse(\event(), {
  "url": "sse://example.com:8080/path",
  });

Parameters

  opts

  an option hash for the HTTPClient constructor plus the following keys:
  - `last_event_id:` Request to the server to resend messages starting after this ID
  - `logger:` an optional LoggerInterface object for internal logging
  - `reconnect:` try to reconnect when the connection is closed or lost (default False)
  - `yield:` an options closure or call reference for yielding the current thread's execution to another thread (default value: Qore::Threads::thread_yield()); required if Qore::PO_NO_PROCESS_CONTROL is set in the current execution context

Exceptions

  SSE-ERROR | unknown scheme, missing 'url' key in option hash; invalid option value

## getConnectionInfo()

*hash< auto > ServerSentEventClient::ServerSentEventClient::getConnectionInfo | ( |  | ) |

Returns information about the current connection.

Returns
  a hash with the following keys:
  - `cid:` the ServerSentEvent client connection ID
  - `num_connects:` how many times has the client connected to the server
  - `peer:` information about the connected server socket (see Socket::getPeerInfo())
  - `socket:` information about the connected local socket (see Socket::getSocketInfo())

## getPassword()

*string ServerSentEventClient::ServerSentEventClient::getPassword | ( |  | ) |

Returns any password set for the connection.

Returns
  any password set for the connection

## getUsageInfo()

hash< auto > ServerSentEventClient::ServerSentEventClient::getUsageInfo | ( |  | ) |

Returns performance statistics for the socket.

Example:
  hash<auto> h = sse.getUsageInfo();

Returns
  a hash with the following keys:
  - `"bytes_sent"`: an integer giving the total amount of bytes sent
  - `"bytes_recv"`: an integer giving the total amount of bytes received
  - `"us_sent"`: an integer giving the total number of microseconds spent sending data
  - `"us_recv"`: an integer giving the total number of microseconds spent receiving data
  - `"arg"`: (only if warning values have been set with ServerSentEventClient::setWarningQueue()) the optional argument for warning hashes
  - `"timeout"`: (only if warning values have been set with ServerSentEventClient::setWarningQueue()) the warning timeout in microseconds
  - `"min_throughput"`: (only if warning values have been set with ServerSentEventClient::setWarningQueue()) the minimum warning throughput in bytes/sec

Since
  ServerSentEventClient 1.1

See also
  ServerSentEventClient::clearStats()

## getUsername()

*string ServerSentEventClient::ServerSentEventClient::getUsername | ( |  | ) |

Returns any username set for the connection.

Returns
  any username set for the connection

## observersReady()

ServerSentEventClient::ServerSentEventClient::observersReady | ( |  | ) |

Called when all observers have been added to the object.

This method is meant to trigger event generation

## reconnect()

bool ServerSentEventClient::ServerSentEventClient::reconnect | ( |  | ) |

Initiate a server reconnect immediately.

Returns
  True if the reconnect was started

## setEventQueue() [1/2]

ServerSentEventClient::ServerSentEventClient::setEventQueue | ( |  | ) |

Removes any Queue object so that socket events are no longer added to the Queue.

Example:
  sse.setEventQueue();

See also
  event_handling for more information

Since
  ServerSentEventClient 1.8

## setEventQueue() [2/2]

ServerSentEventClient::ServerSentEventClient::setEventQueue | ( | Qore::Thread::Queue | queue,
|  | auto | arg,
|  | *bool | with_data )

Sets a Queue object to receive socket events.

Example:
  sse.setEventQueue(queue);

Parameters

  queue | the Queue object to receive socket events; note that the Queue passed cannot have any maximum size set or a QUEUE-ERROR will be thrown
  arg | an argument that will be included in each event hash in the arg key
  with_data | if True, then the actual raw data transferred / received is also included in the events

Exceptions

  QUEUE-ERROR | the Queue passed has a maximum size set

See also
  event_handling for more information

Since
  ServerSentEventClient 1.8

## setWarningQueue()

ServerSentEventClient::ServerSentEventClient::setWarningQueue | ( | int | warning_ms,
|  | int | warning_bs,
|  | Queue | queue,
|  | auto | arg,
|  | timeout | min_ms = 1s )

Sets a Queue object to receive socket warnings.

Example:
  sse.setWarningQueue(5000, 5000, queue, "socket-1");

Parameters

  warning_ms

  the threshold in milliseconds for individual socket actions (send, receive, connect), if exceeded, a socket warning is placed on the warning queue with the following keys:
  - `"type"`: a string with the constant value `"SOCKET-OPERATION-WARNING"`
  - `"operation"`: a string giving the operation that caused the warning (ex: `"connect"`)
  - `"us"`: an integer giving the number of microseconds for the operation
  - `"timeout"`: an integer giving the warning threshold in microseconds
  - `"arg"`: if any `"arg"` argument is passed to the ServerSentEventClient::setWarningQueue() method, it will be included in the warning hash here

  warning_bs

  value in bytes per second; if any call has performance below this threshold, a socket warning is placed on the warning queue with the following keys:
  - `"type"`: a string with the constant value `"SOCKET-THROUGHPUT-WARNING"`
  - `"dir"`: either `"send"` or `"recv"` depending on the direction of the data flow
  - `"bytes"`: the amount of bytes sent
  - `"us"`: an integer giving the number of microseconds for the operation
  - `"bytes_sec"`: a float giving the transfer speed in bytes per second
  - `"threshold"`: an integer giving the warning threshold in bytes per second
  - `"arg"`: if any `"arg"` argument is passed to the ServerSentEventClient::setWarningQueue() method, it will be included in the warning hash here

  queue | the Queue object to receive warning events
  arg | an optional argument to be placed in the `"arg"` key in each warning hash (could be used to identify the socket for example)
  min_ms | the minimum transfer time with a resolution of milliseconds for a transfer to be eligible for triggering a warning; transfers that take less than this period of time are not eligible for raising a warning

Exceptions

  QUEUE-ERROR | the Queue passed has a maximum size set
  SOCKET-SETWARNINGQUEUE-ERROR | at least one of warning_ms and warning_bs must be > 0

See also
  ServerSentEventClient::clearWarningQueue()

Since
  ServerSentEventClient 1.1

## stopEvents()

ServerSentEventClient::ServerSentEventClient::stopEvents | ( |  | ) |

Called to stop generating events.

Disconnects from the server

## Member Data Documentation

## tid

int ServerSentEventClient::ServerSentEventClient::tid

protected

TID of the event thread; only changed in the log.

Threads can wait for it to be cleared using tid_waiting and tid_cond