From 45ac4fa56b6e5c31a28fd08eaad14a09bf3934f6 Mon Sep 17 00:00:00 2001 From: gdamore Date: Sun, 27 Oct 2024 18:55:51 +0000 Subject: deploy: ffeb31c64ea72c4eb287f75b641ca2a707df90b0 --- ref/api/aio.html | 558 ++++++++++++++++++++++++++++++++++++++++++++++++++ ref/api/cmd_opts.html | 454 ++++++++++++++++++++++++++++++++++++++++ ref/api/errors.html | 370 +++++++++++++++++++++++++++++++++ ref/api/id_map.html | 423 ++++++++++++++++++++++++++++++++++++++ ref/api/index.html | 311 ++++++++++++++++++++++++++++ ref/api/logging.html | 437 +++++++++++++++++++++++++++++++++++++++ ref/api/memory.html | 351 +++++++++++++++++++++++++++++++ ref/api/misc.html | 350 +++++++++++++++++++++++++++++++ ref/api/msg.html | 511 +++++++++++++++++++++++++++++++++++++++++++++ ref/api/stats.html | 471 ++++++++++++++++++++++++++++++++++++++++++ ref/api/synch.html | 438 +++++++++++++++++++++++++++++++++++++++ ref/api/thread.html | 374 +++++++++++++++++++++++++++++++++ ref/api/time.html | 381 ++++++++++++++++++++++++++++++++++ ref/api/url.html | 370 +++++++++++++++++++++++++++++++++ 14 files changed, 5799 insertions(+) create mode 100644 ref/api/aio.html create mode 100644 ref/api/cmd_opts.html create mode 100644 ref/api/errors.html create mode 100644 ref/api/id_map.html create mode 100644 ref/api/index.html create mode 100644 ref/api/logging.html create mode 100644 ref/api/memory.html create mode 100644 ref/api/misc.html create mode 100644 ref/api/msg.html create mode 100644 ref/api/stats.html create mode 100644 ref/api/synch.html create mode 100644 ref/api/thread.html create mode 100644 ref/api/time.html create mode 100644 ref/api/url.html (limited to 'ref/api') diff --git a/ref/api/aio.html b/ref/api/aio.html new file mode 100644 index 00000000..fa90d946 --- /dev/null +++ b/ref/api/aio.html @@ -0,0 +1,558 @@ + + + + + + Asynchronous I/O - NNG Reference Manual (DRAFT) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + + + + + + + + + + +
+ +
+ + + + + + + + +
+
+ +

Asynchronous Operations

+

In order to obtain significant scalability, with low-latency, and minimal +overheads, NNG supports performing operations asynchronously.

+

One way that applications can perform work asynchronously and concurrently +is by using threads, but threads carry significant resource overheads +and frequently there are limits on the number that can easily be created.

+

Additionally, with most network applications, the flow of execution will spend +the bulk of its time waiting for traffic from a peer.

+

For these kinds of applications, it is far more efficient to use asynchronous operations +using the mechanisms described in this chapter.

+
+

+ + tip +

+

To get the highest performance with the least overhead, applications should use +asynchronous operations described in this chapter whenever possible.

+
+

Asynchronous I/O Handle

+
typedef struct nng_aio nng_aio;
+
+

An nng_aio is an opaque structure used in conjunction with +asynchronous I/O operations. +Every asynchronous operation uses one of these structures, each of which +can only be used with a single operation at a time.

+

Asynchronous operations are performed without blocking calling application threads. +Instead the application registers a callback function to be executed +when the operation is complete (whether successfully or not). +This callback will be executed exactly once.

+

The asynchronous I/O framework also supports cancellation of +operations that are already in progress as well setting a maximum +timeout for them to complete.

+

It is also possible to initiate an asynchronous operation, and wait for it to +complete, creating a synchronous flow from an asynchronous one.

+

Create Handle

+
int nng_aio_alloc(nng_aio **aiop, void (*callb)(void *), void *arg);
+
+

The nng_aio_alloc function creates an nng_aio object, with the +callback callb taking the argument arg, and returns it in aiop.

+

If this succeeds, the function returns zero. Otherwise it may return NNG_ENOMEM.

+
+

+ + tip +

+

The arg should normally be a structure that contains a pointer to the aiop, +or from which it can be located. This allows callb to check the handle for +success using nng_aio_result, as well access other properties of aiop.

+
+
+

+ + tip +

+

The callb may be executed on another thread, so it may be necessary to use +synchronization methods in callb to avoid data races.

+
+

Destroy Handle

+
void nng_aio_free(nng_aio *aio);
+void nng_aio_reap(nng_aio *aio);
+
+

The nng_aio_free handle destroys the handle aio, waiting for any operations +and associated callbacks to complete before doing so.

+

The nng_aio_reap handle destroys the handle aio asynchronously, using a reaper +thread to do so. It does not wait for the object to be destroyed. Thus this function +is safe to call from aio’s own callback.

+
+

+ + note +

+

The nng_aio_free function must never be called from an aio callback. +Use nng_aio_reap instead if an object must be destroyed from a callback.

+
+

Cancellation

+
void nng_aio_abort(nng_aio *aio, int err);
+void nng_aio_cancel(nng_aio *aio);
+void nng_aio_stop(nng_aio *aio);
+
+

These functions are used to stop a previously submitted asynchronous +I/O operation. The operation may be canceled, or may continue to +completion. If no operation is in progress (perhaps because it has +already completed), then these operations have no effect. +If the operation is successfully canceled or aborted, then the callback +will still be called.

+

The nng_aio_abort function aborts the operation associated with aio +and returns immediately without waiting. If cancellation was successful, +then nng_aio_result will return err.

+

The nng_aio_cancel function acts like nng_aio_abort, but uses the error code +NNG_ECANCELED.

+

The nng_aio_stop function aborts the aio operation with NNG_ECANCELED, +and then waits the operation and any associated callback to complete. +This function also marks aio itself permanently stopped, so that any +new operations scheduled by I/O providers using nng_aio_begin +return false. Thus this function should be used to teardown operations.

+
+

+ + tip +

+

When multiple asynchronous I/O handles are in use and need to be +deallocated, it is safest to stop all of them using nng_aio_stop, +before deallocating any of them with nng_aio_free, +particularly if the callbacks might attempt to reschedule further operations.

+
+

Set Timeout

+
void nng_aio_set_timeout(nng_aio *aio, nng_duration timeout);
+void nng_aio_set_expire(nng_aio *aio, nng_time expiration);
+
+

The nng_aio_set_timeout function sets a timeout +for the asynchronous operation associated with aio. +This causes a timer to be started when the operation is actually started. +If the timer expires before the operation is completed, then it is +aborted with an error of NNG_ETIMEDOUT. +The timeout duration is specified as a relative number of milliseconds.

+

If the timeout is NNG_DURATION_INFINITE, then no timeout is used. +If the timeout is NNG_DURATION_DEFAULT, then a “default” or socket-specific +timeout is used. +(This is frequently the same as NNG_DURATION_INFINITE.)

+

The nng_aio_set_expire function is similar to nng_aio_set_timeout, but sets +an expiration time based on the system clock. The expiration +time is a clock timestamp, such as would be returned by nng_clock.

+

Wait for Completion

+
void nng_aio_wait(nng_aio *aio);
+
+

The nng_aio_wait function waits for an asynchronous I/O operation to complete. +If the operation has not been started, or has already completed, then it returns immediately.

+

If a callback was set with aio when it was allocated, then this +function will not be called until the callback has completed.

+
+

+ + important +

+

The nng_aio_wait function should never be called from a function that itself +is a callback of an nng_aio, either this one or any other. +Doing so may result in a deadlock.

+
+

Test for Completion

+
bool nng_aio_busy(nng_aio *aio);
+
+

The nng_aio_busy function returns true if the aio is currently busy performing an +operation or is executing a completion callback. Otherwise it return false. +This is the same test used internally by nng_aio_wait.

+
+

+ + important +

+

The caller is responsible for coordinating any use of this with any reuse of the aio. +Because the aio can be reused use of this function can be racy.

+
+

Result of Operation

+
int nng_aio_result(nng_aio *aio);
+size_t nng_aio_count(nng_aio *aio);
+
+

The nng_aio_result function returns the result of the operation associated +with the handle aio. +If the operation was successful, then 0 is returned. +Otherwise a non-zero error code, such as NNG_ECANCELED or NNG_ETIMEDOUT, is returned.

+

For operations that transfer data, nng_aio_count returns the +number of bytes transferred by the operation associated with the handle aio. +Operations that do not transfer data, or do not keep a count, may return zero for this function.

+
+

+ + note +

+

The return value from these functions is undefined if the operation has not completed yet. +Either call these from the handle’s completion callback, or after waiting for the +operation to complete with nng_aio_wait.

+
+

Messages

+
nng_msg *nng_aio_get_msg(nng_aio *aio);
+void nng_aio_set_msg(nng_aio *aio, nng_msg *msg);
+
+

The nng_aio_get_msg and nng_aio_set_msg functions retrieve and store a message +in aio. +For example, if a function to receive data is called, that function can generally be expected +to store a message on the asssociated aio, for the application to retrieve with +nng_aio_get_msg. +Conversely an application desiring to send a message msg will store it in the aio using +nng_aio_set_msg. The function implementing the send operation will retrieve the message +and arrange for it to be sent.

+

Message Ownership

+

For send or transmit operations, the rule of thumb is that implementation of the operation +is responsible for taking ownership of the message (and releasing resources when it is complete), +if it will return success. If the operation will end in error, then the message will be +retained and it is the consuming application’s responsibility to dispose of the message. +This allows an application the opportunity to reuse the message to try again, if it so desires.

+

For receive operations, the implementation of the operation will set the message on the aio +on success, and the consuming application hasa responsibility to retrieve and dispose of the +message. Failure to do so will leak the message. If the operation does not complete successfully, +then no message is stored on the aio.

+

I/O Vector

+
typedef struct nng_iov {
+    void * iov_buf;
+    size_t iov_len;
+};
+
+int nng_aio_set_iov(nng_aio *aio, unsigned int niov, nng_iov *iov);
+
+

For some operations, the unit of data transferred is not a message, but +rather a stream of bytes.

+

For these operations, an array of niov nng_iov structures can be passed to +the nng_aio_set_iov function to provide a scatter/gather array of +elements describing the location (iov_buf) and length (iov_len) of data, +to transfer.

+

The iov vector is copied into storage in the aio itself, so that callers may use stack allocated nng_iov structures. +The values pointed to by the iov_buf members are not copied by this function though.

+

A maximum of four (4) nng_iov members may be supplied.

+
+

+ + tip +

+

Most functions using nng_iov do not guarantee to transfer all of the data that they +are requested to. To be sure that correct amount of data is transferred, as well as to +start an attempt to complete any partial transfer, check the amount of data transferred by +calling nng_aio_count.

+
+

Inputs and Outputs

+
void nng_aio_set_input(nng_aio *aio, unsigned int index, void *param);
+void *nng_aio_get_output(nng_aio *aio, unsigned int index);
+
+

Asynchronous operations can take additional input parameters, and +provide additional result outputs besides the result code.

+

The nng_aio_set_input function sets the input parameter at index +to param for the operation associated with aio.

+

The nng_aio_get_output function returns the output result at index +for the operation associated with aio.

+

The type and semantics of input parameters and output results are determined by specific +operations. The documentation for the operation should provide details.

+

The valid values of index range from zero (0) to three (3), as no operation +currently defined can accept more than four parameters or return more than four additional +results.

+
+

+ + note +

+

If the index does not correspond to a defined input for the operation, +then nng_aio_set_input will have no effect, and nng_aio_get_output will +return NULL.

+
+
+

+ + important +

+

It is an error to call this function while the aio is currently +in use by an active asynchronous operation.

+
+

See Also

+

Synchronization, +Threads, +Time

+ + + + + + +
+ + +
+
+ + + +
+ + + + + + + + + + + + + + + + + + + +
+ + diff --git a/ref/api/cmd_opts.html b/ref/api/cmd_opts.html new file mode 100644 index 00000000..fff75be4 --- /dev/null +++ b/ref/api/cmd_opts.html @@ -0,0 +1,454 @@ + + + + + + Command Options - NNG Reference Manual (DRAFT) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + + + + + + + + + + +
+ +
+ + + + + + + + +
+
+ +

Command Options

+

Some NNG utilities need to parse command line options, +and the supplementary function here allows applications that +need the same support to benefit from this.

+

To make use of this, the supplemental header <nng/supplemental/util/options.h> +must be included.

+

Parse Command Line Options

+
typedef struct nng_optspec {
+    const char *o_name;  // Long style name (may be NULL for short only)
+    int         o_short; // Short option (no clustering!)
+    int         o_val;   // Value stored on a good parse (>0)
+    bool        o_arg;   // Option takes an argument if true
+} nng_optspec;
+
+int nng_opts_parse(int argc, char *const *argv,
+                   const nng_optspec *spec, int *val, char **arg, int *idx);
+
+

The nng_opts_parse function is a intended to facilitate parsing +command-line arguments. +This function exists largely to stand in for getopt from POSIX systems, +but it is available everywhere that NNG is, and it includes +some capabilities missing from getopt.

+

The function parses arguments from +main1 +(using argc and argv), +starting at the index referenced by idx. +(New invocations typically set the value pointed to by idx to 1.)

+

Options are parsed as specified by spec (see Option Specification.) +The value of the parsed option will be stored at the address indicated by +val, and the value of idx will be incremented to reflect the next +option to parse.

+
+

+ + tip +

+

For using this to parse command-line like strings that do not include +the command name itself, set the value referenced by idx to zero instead of one.

+
+

If the option had an argument, a pointer to that is returned at the address +referenced by arg.

+

This function should be called repeatedly, until it returns either -1 +(indicating the end of options is reached) or a non-zero error code is +returned.

+

This function may return the following errors:

+
    +
  • NNG_EAMBIGUOUS: Parsed option matches more than one specification.
  • +
  • NNG_ENOARG: Option requires an argument, but one is not present.
  • +
  • NNG_EINVAL: An invalid (unknown) argument is present.
  • +
+

Option Specification

+

The calling program must first create an array of nng_optspec structures +describing the options to be supported. +This structure has the following members:

+
    +
  • +

    o_name:

    +

    The long style name for the option, such as “verbose”. +This will be parsed as a long option on the command line when it is prefixed with two dashes. +It may be NULL if only a short option is to be supported.

    +
  • +
  • +

    o_short:

    +

    This is a single letter (at present only ASCII letters are supported). +These options appear as just a single letter, and are prefixed with a single dash on the command line. +The use of a slash in lieu of the dash is not supported, in order to avoid confusion with path name arguments. +This value may be set to 0 if no short option is needed.

    +
  • +
  • +

    o_val:

    +

    This is a numeric value that is unique to this option. +This value is assigned by the application program, and must be non-zero for a valid option. +If this is zero, then it indicates the end of the specifications, and the +rest of this structure is ignored. +The value will be returned to the caller in val by nng_opts_parse when +this option is parsed from the command line.

    +
  • +
  • +

    o_arg:

    +

    This value should be set to true if the option should take an argument.

    +
  • +
+

Long Options

+

Long options are parsed from the argv array, and are indicated when +the element being scanned starts with two dashes. +For example, the “verbose” option would be specified as --verbose on +the command line. +If a long option takes an argument, it can either immediately follow +the option as the next element in argv, or it can be appended to +the option, separated from the option by an equals sign (=) or a +colon (:).

+

Short Options

+

Short options appear by themselves in an argv element, prefixed by a dash (-). +If the short option takes an argument, it can either be appended in the +same element of argv, or may appear in the next argv element.

+
+

+ + note +

+

Option clustering, where multiple options can be crammed together in +a single argv element, is not supported by this function (yet).

+
+

Prefix Matching

+

When using long options, the parser will match if it is equal to a prefix +of the o_name member of a option specification, provided that it do so +unambiguously (meaning it must not match any other option specification.)

+

Example

+

The following program fragment demonstrates this function.

+
    enum { OPT_LOGFILE, OPT_VERBOSE };
+    char *logfile; // options to be set
+    bool verbose;
+
+    static nng_optspec specs[] = {
+        {
+            .o_name = "logfile",
+            .o_short = 'D',
+            .o_val = OPT_LOGFILE,
+            .o_arg = true,
+        }, {
+            .o_name = "verbose",
+            .o_short = 'V',
+            .o_val = OPT_VERBOSE,
+            .o_arg = false,
+        }, {
+            .o_val = 0; // Terminate array
+        }
+    };
+
+    for (int idx = 1;;) {
+        int rv, opt;
+        char *arg;
+        rv = nng_opts_parse(argc, argv, specs, &opt, &arg, &idx);
+        if (rv != 0) {
+            break;
+        }
+        switch (opt) {
+        case OPT_LOGFILE:
+            logfile = arg;
+            break;
+        case OPT_VERBOSE:
+            verbose = true;
+            break;
+        }
+    }
+    if (rv != -1) {
+        printf("Options error: %s\n", nng_strerror(rv));
+        exit(1);
+    }
+
+ + + + + +


+

1: Parsing argument strings from other sources can be done as well, +although usually then idx will be initialized to zero.

+ +
+ + +
+
+ + + +
+ + + + + + + + + + + + + + + + + + + +
+ + diff --git a/ref/api/errors.html b/ref/api/errors.html new file mode 100644 index 00000000..b928bbf5 --- /dev/null +++ b/ref/api/errors.html @@ -0,0 +1,370 @@ + + + + + + Errors - NNG Reference Manual (DRAFT) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + + + + + + + + + + +
+ +
+ + + + + + + + +
+
+ +

Errors

+

Many NNG functions can fail for a variety of reasons. +These functions tend to return either zero on success, +or a non-zero error code to indicate failure. +1

+

All these error codes are int.

+

Not every possible error code is defined here, as sometimes +an underlying system or library error code is “wrapped”.

+

Human Readable Error Message

+
const char *nng_strerror(int err);
+
+

The nng_strerror returns the human-readable description of the +given error in err.

+

The error message returned is a fixed NUL-terminated string and may be located in +read-only memory.

+

The returned error message is provided in US English, but in the +future locale-specific strings may be presented instead.

+
+

+ + note +

+

The specific strings associated with specific error messages are +subject to change. +Therefore applications must not depend on the message, +but may use them verbatim when supplying information to end-users, such +as in diagnostic messages or log entries.

+
+

List of Errors

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ErrorValueDescription
NNG_EINTR1Operation interrupted.
NNG_ENOMEM2Out of memory, or other resource exahusted.
NNG_EINVAL3Invalid argument. The arguments are invalid or malformed somehow.
NNG_EBUSY4Resource busy.
NNG_ETIMEDOUT5Timed out. The operation took longer than the allotted time.
NNG_ECONNREFUSED6Connection refused. Usually indicates the wrong address or a server is running.
NNG_ECLOSED7Object closed. Typically the socket is closed.
NNG_EAGAIN8Try again. Typcally for a non-blocking operation that might succeed later.
NNG_ENOTSUP9Not supported. Perhaps the protocol or transport is not supported, or the operation is not not supported with the transport or protocol.
NNG_EADDRINUSE10Address in use. The network address is already used by another process. Most often this is seen for listeners.
NNG_ESTATE11Incorrect state. The operation cannot be performed in the current state, such as trying to send a response when no request has yet been received.
NNG_ENOENT12Entry not found (no such object.) Can also indicate that a file does not exist.
NNG_EPROTO13Protocol error. Typically this indicates incorrect messages over a network.
NNG_EUNREACHABLE14Destination unreachable.
NNG_EADDRINVAL15Address invalid. Like NNG_EINVAL, but only for network addresses.
NNG_EPERM16Permission denied.
NNG_EMSGSIZE17Message too large.
NNG_ECONNABORTED18Connection aborted. A connection attempt was aborted locally.
NNG_ECONNRESET19Connection reset. The remote peer reset the connection unexpectedly.
NNG_ECANCELED20Operation canceled. Typically as a result of nng_aio_cancel or similar.
NNG_ENOFILES21Out of files. Either the destination file system cannot store files, or all available file handles are used.
NNG_ENOSPC22Out of space. Destination table or filesystem is full.
NNG_EEXIST23Resource already exists.
NNG_EREADONLY24Read only resource. An attempt to modify a read-only file or other object.
NNG_EWRITEONLY25Write only resource. A read operation failed because the object only supports writes.
NNG_ECRYPTO26Cryptographic error. Usually indicates an invalid key was used for TLS.
NNG_EPEERAUTH27Peer could not be authenticated.
NNG_ENOARG28Option requires argument. A command-line option was supplied without an argument. Only used with nng_opts_parse.
NNG_EAMBIGUOUS29Ambiguous option. The command line option could not be unambiguously resolved. Only used with nng_opts_parse.
NNG_EBADTYPE30Incorrect type. A type-specific function was used for an object of the wrong type.
NNG_ECONNSHUT31Connection shutdown. The connection was shut down and cannot be used.
NNG_EINTERNAL1000An unidentifier internal error occurred.
NNG_ESYSERR0x10000000 - 0x1FFFFFFFAn unidentified system error occurred. These are errors reported by the operating system.
NNG_ETRANERR0x20000000 - 0x2FFFFFFFAn unidentified transport error occurred.
+
+ + + + +


+

1: This convention goes back to UNIX system calls, +which behave the same way, but NNG does not use a separate +errno variable.

+ +
+ + +
+
+ + + +
+ + + + + + + + + + + + + + + + + + + +
+ + diff --git a/ref/api/id_map.html b/ref/api/id_map.html new file mode 100644 index 00000000..26970d26 --- /dev/null +++ b/ref/api/id_map.html @@ -0,0 +1,423 @@ + + + + + + ID Map - NNG Reference Manual (DRAFT) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + + + + + + + + + + +
+ +
+ + + + + + + + +
+
+ +

ID Map

+

Internally, NNG uses a map of numeric identifiers to data structures. +This feature is also exposed for application use, as a “supplemental” feature.

+

When using these functions, it is necessary to add the #include <nng/supplemental/util/idhash.h> +include file to list of includes.

+

ID Map Structure

+
#include <nng/nng.h>
+#include <nng/supplemental/util/idhash.h>
+
+typedef struct nng_id_map_s nng_id_map;
+
+

The ID map structure, nng_id_map provides a table of identifiers mapping +to user-supplied pointers (which must not be NULL). The identifiers can be +thought of as indices into the table, with the pointers providing the reference +for the user supplied data.

+

The values of identifiers can be supplied by the user, or can be allocated automatically +by nng_id_map from a predefined range. The starting point for allocations +can also be randomly within the range.

+

The identifiers are 64-bit unsigned integers and can be sparse; the structure +will use space efficiently even if identifiers are very far apart. +1

+
+

+ + important +

+

The function available for nng_id_map are not thread-safe. +Callers should use a mutex or similar approach when thread-safety is needed.

+
+

Create ID Map

+
#define NNG_MAP_RANDOM 1
+
+int nng_id_map_alloc(nng_id_map **map_p, uint64_t lo, uint64_t hi, int flags);
+
+

The nng_id_map_alloc function allocates a map without any data in it, +and returns a pointer to it in map_p. When allocating identifiers dynamically, +the values will be chosen from the range defined by lo and hi, inclusive.

+

The flags argument is a bit mask of flags that can adjust behavior of the map. +The only flag defined at present +is NNG_MAP_RANDOM, which causes the first identifier allocation to start at a random +point within the range. +This is useful to reduce the odds of different instances of an application using +the same identifiers at the same time.

+

If both lo and hi are zero, then the values 0 and 0xffffffff are substituted +in their place, giving a full range of 32-bit identifiers.

+

This function can return NNG_ENOMEM if it is unable to allocate resources, otherwise +it returns zero on success.

+

Destroy Map

+
void nng_id_map_free(nng_id_map *map);
+
+

The nng_id_map_free function destroys map, releasing any resources associated +with it.

+
+

+ + note +

+

The nng_id_map_free frees the map itself, but will not free memory associated with +any strctures contained within it.

+
+

Store a Value

+
int nng_id_set(nng_id_map *map, uint64_t id, void *value);
+
+

The nng_id_map_set function is used to store the value in the map at +index id.

+

If another value is already stored at that same location, then it is overwritten with +value.

+
+

+ + note +

+

The value must not be NULL.

+
+

If the table has to grow to accommodate this value, it may fail if insufficient +memory is available, returning NNG_ENOMEM. Otherwise it returns zero.

+

Lookup a Value

+
void *nng_id_get(nng_id_map *map, uint64_t id);
+
+

The nng_id_get function looks up the entry for id in map, returning the +associated value if present, or NULL if no such entry exists.

+

Allocate an ID

+
int nng_id_alloc(nng_id_map *map, uint64_t *id_p, void *value);
+
+

The nng_id_alloc stores the value in the map, at a newly allocated index, +and returns the index in id_p.

+

Identifiers are allocated in increasing order, without reusing old identifiers until the +largest possible identifier is allocated. After wrapping, only identifiers that are no longer +in use will be considered. +No effort is made to order the availability of identifiers based on +when they were freed.2

+

As with nng_id_set, this may need to allocate memory and can thus +fail with NNG_ENOMEM.

+

Additionally, if there are no more free identifiers within the range specified +when map was created, then it will return NNG_ENOSPC.

+

Otherwise it returns zero, indicating success.

+

Remove an ID

+
int nng_id_remove(nng_id_map *map, uint64_t id);
+
+

The nng_id_remove removes the entry at index id from map.

+

If no such entry exist, it will return NNG_ENOENT. Otherwise it returns zero.

+

Iterating IDs

+
bool nng_id_visit(nng_id_map *map, uint64_t *id_p, void **value_p, uint32_t *cursor);
+
+

The nng_id_visit function is used to iterate over all items in the table. +The caller starts the iteration by setting the cursor to 0 before calling it. +For each call, the associated key and value of the next item will be returned in id_p, +and value_p and the cursor will be updated. +When all items have been iterated, the function returns false. +The order of items returned is not guaranteed to be sequential. +The caller must not attempt to derive any value of the cursor as it refers to internal table indices.

+

Entries may be safely removed from map while iterating.

+

However, if new entries are added to the table while iterating, the result of +iteration is undefined; entries may be repeated or omitted during such an iteration.

+

The caller must not attempt to derive any value of the cursor as it refers to internal +table indices.

+ + + + + +


+

1: The ID map is capable of storing at most 232 identifiers, even though the identifers may +themselves be much larger than this.

+

2: The concern about possibly reusing a +recently released identifier comes into consideration after the range has wrapped. +Given a sufficiently large range, this is unlikely to be a concern.

+ +
+ + +
+
+ + + +
+ + + + + + + + + + + + + + + + + + + +
+ + diff --git a/ref/api/index.html b/ref/api/index.html new file mode 100644 index 00000000..61df6062 --- /dev/null +++ b/ref/api/index.html @@ -0,0 +1,311 @@ + + + + + + API Reference - NNG Reference Manual (DRAFT) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + + + + + + + + + + +
+ +
+ + + + + + + + +
+
+ +

API Reference

+

This section is a reference guide for the NNG programming interfaces. +It is meant to serve as a refernce, rather than as a tutorial.

+

The material here is organized by major areas of functionality.

+

Note that unless indicated otherwise, consumers of these interfaces must +include the nng/nng.h header file like so:

+
#include <nng/nng.h>
+
+

Chapters

+ + +
+ + +
+
+ + + +
+ + + + + + + + + + + + + + + + + + + +
+ + diff --git a/ref/api/logging.html b/ref/api/logging.html new file mode 100644 index 00000000..4402ff40 --- /dev/null +++ b/ref/api/logging.html @@ -0,0 +1,437 @@ + + + + + + Logging - NNG Reference Manual (DRAFT) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + + + + + + + + + + +
+ +
+ + + + + + + + +
+
+ +

Logging

+

This chapter describes the support for message logs. +Both applications and NNG itself can emit logs, which can be useful +for application field support and debugging. Additionally applications +can customize the handling of this logging as needed.

+

Note that logging is disabled by default unless an application +configures a suitable logger with nng_log_set_logger.

+

Submitting Logs

+
void nng_log_err(const char *msgid, const char *msg, ...);
+void nng_log_warn(const char *msgid, const char *msg, ...);
+void nng_log_notice(const char *msgid, const char *msg, ...);
+void nng_log_info(const char *msgid, const char *msg, ...);
+void nng_log_debug(const char *msgid, const char *msg, ...);
+
+

These functions inject a a message into the +logging system, where it will be processed and potentially go to +system logs, standard output, or procssed further.

+

The msgid is a short prefix that should uniquely identify the message, +possibly also with some kind of category. It is recommended that +strings between 8 and 16 charactes be used. As this may, but will not necessarily +be displayed to the user, the content of the message should not appear +solely in this field. A NULL value is permitted here, but that may +make filtering the message or other automatic processing more difficult.

+

The msg is a printf-style format string, which is used to format the +message content. The following arguments are consumed in the +same manner as printf.

+
+

+ + tip +

+

Applications should take care to limit the use of higher severity levels, as message logs +are potentially expensive, increase stress for end users and administrators, and further may +mask real problems if incorrectly over used.

+

Warnings and error messages should be concise and actionable, and notices should only +really be those things that are worthy of attention.

+

Informational and debug messages used during development should be removed when no longer +needed, as these messages can overwhelm logging subsystems and can reduce the +signal-to-noise value for the message logs, impairing the diagnostic value of the logs.

+
+

Auth Logs

+
void nng_log_auth(nng_log_level level, const char *msgid, const char *msg, ...);
+
+

The nng_log_auth function formats and injects a security related log message. +(“Auth” can indicate either “authentication” or “authorization”.) +The level is a log level. +The msgid, msg, and any remaining arguments are processed in a fashion +similar to the other logging functions, except that the +logs may be are logged using the NNG_LOG_AUTH facility, and thus may be +redirected or receive other special treatment.

+

Log Levels

+
typedef enum nng_log_level nng_log_level;
+
+void nng_log_set_level(nng_log_level level);
+nng_log_level nng_log_get_level(void);
+
+

The nng_log_level type represents a severity for logged messages. +These levels correspond to those found in the UNIX syslog subsystem, +although applications should not depend upon the values being identical.

+

The nng_log_set_level function sets the log level. +Messages with a severity that is numerically greater than this (less-severe) +will be discarded.

+

The nng_log_get_level function returns the log level most recently +set by nng_log_set_level or the default +if that function has not been called.

+

The log levels are defined as follows:

+
typedef enum nng_log_level {
+	NNG_LOG_NONE   = 0, // used for filters only, NNG suppresses these
+	NNG_LOG_ERR    = 3,
+	NNG_LOG_WARN   = 4,
+	NNG_LOG_NOTICE = 5,
+	NNG_LOG_INFO   = 6,
+	NNG_LOG_DEBUG  = 7
+} nng_log_level;
+
+

The value NNG_LOG_NONE may be useful to suppress message logs altogether.

+

The default level is typically NNG_LOG_NOTICE, but applications should +select a value rather than relying upon the default.

+

Log Facilities

+
typedef enum nng_log_facility
+
+void nng_log_set_facility(nng_log_facility facility);
+
+

Logging facilities are used to indicate the source of a log message, +and may be useful in routing and processing these logs. +Traditionally these are used with the UNIX syslog system, and +the values here represent some (but not all) of the values found there.

+

The following values are defined:

+
typedef enum nng_log_facility {
+	NNG_LOG_USER   = 1,
+	NNG_LOG_DAEMON = 3,
+	NNG_LOG_AUTH   = 10,
+	NNG_LOG_LOCAL0 = 16,
+	NNG_LOG_LOCAL1 = 17,
+	NNG_LOG_LOCAL2 = 18,
+	NNG_LOG_LOCAL3 = 19,
+	NNG_LOG_LOCAL4 = 20,
+	NNG_LOG_LOCAL5 = 21,
+	NNG_LOG_LOCAL6 = 22,
+	NNG_LOG_LOCAL7 = 23,
+} nng_log_facility;
+
+

The nng_log_set_facility function can be used to +set the facility that the application will use when emitting log +messages. This should be called as part of initialization of the +application, if logging is to be used.

+

The default facility is typically NNG_LOG_USER, but applications should +select a value rather than relying upon the default.

+

Log Handlers

+
typedef void (*nng_logger)(nng_log_level level, nng_log_facility facility,
+    const char *msgid, const char *msg);
+
+void nng_null_logger(nng_log_level, nng_log_facility, const char *, const char *);
+void nng_stderr_logger(nng_log_level, nng_log_facility, const char *, const char *);
+void nng_system_logger(nng_log_level, nng_log_facility, const char *, const char *);
+
+void nng_log_set_logger(nng_logger logger);
+
+

Log handlers are responsible for actually processing the logged messages.

+

The nng_log_set_logger function installs the named logger, of type nng_logger, +as the log handler. The function logger will be called when any message is meant to +be processed. (Messages are first filtered by severity, then formatted, +before calling the logger.)

+

Any previously installed logger is replaced by logger.

+

The nng_null_logger function is an implementation of nng_logger that simply discards the content. +This is the default logger, so logging is disabled by default.

+

The nng_stderr_logger function is an implementation that logs messages to the standard error stream. +It will attempt to colorize messages by the severity, if the standard error is a terminal device. +This can be suppressed by setting either the NO_COLOR or NNG_LOG_NO_COLOR environment variables.

+

The nng_system_logger attempts to use an appropriate system facility to log messages. +For POSIX systems, this means using syslog to process the messages. +For other systems the defauilt behavior may be the same as nng_stderr_logger.

+

See Also

+

The Syslog Protocol upon which this is based is documented in the following two IETF +RFCS,

+
    +
  • R. Gerhards, RFC 5424, The Syslog Protocol, +March 2009
  • +
  • C. Lonvick, RFC 3164, The BSD syslog Protocol, +August 2001
  • +
+ +
+ + +
+
+ + + +
+ + + + + + + + + + + + + + + + + + + +
+ + diff --git a/ref/api/memory.html b/ref/api/memory.html new file mode 100644 index 00000000..3d58726f --- /dev/null +++ b/ref/api/memory.html @@ -0,0 +1,351 @@ + + + + + + Memory - NNG Reference Manual (DRAFT) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + + + + + + + + + + +
+ +
+ + + + + + + + +
+
+ +

Memory

+

Managing memory and allocations is something that every C program has to deal with. +In the case of NNG, it can be more complicated because the underlying platform +code can provide different allocators that might not be compatible with the use +system allocator used by malloc and free.

+

Allocate Memory

+
void *nng_alloc(size_t size);
+
+

The nng_alloc function allocates a contiguous memory region of +at least size bytes, and returns a pointer to it. +The memory will be 64-bit aligned. +Note that the memory may have random data in it, just like with malloc.

+

If memory cannot be allocated for any reason, then NULL will be returned. +Applications that experience this should treat this like NNG_ENOMEM.

+

Memory returned by nng_alloc can be used to hold message buffers, in which +case it can be directly passed to nng_send using the flag NNG_FLAG_ALLOC. +Alternatively, it can be freed when no longer needed using nng_free.

+
+

+ + important +

+

Do not use the system free function (or the C++ delete operator) to release this memory. +On some configurations this may work, but on others it will lead to a crash or +other unpredictable behavior.

+
+

Deallocate Memory

+
void nng_free(void *ptr, size_t size);
+
+

The nng_free function deallocates memory previously allocated by nng_alloc.

+

The size argument must exactly match the size argument that was supplied to +nng_alloc when the memory was allocated.

+

Duplicate String

+
char *nng_strdup(const char *src);
+
+

The nng_strdup duplicates the string src and returns it.

+

This is logically equivalent to using nng_alloc +to allocate a region of memory of strlen(s) + 1 bytes, and then +using strcpy to copy the string into the destination before +returning it.

+

The returned string should be deallocated with +nng_strfree, or may be deallocated using the +nng_free using the length of the returned string plus +one (for the NUL terminating byte).

+

Free String

+
void nng_strfree(char *str);
+
+

The nng_strfree function is a convenience function that +can be used to deallocate strings allocated with nng_strdup.

+

It is effectively the same as nng_free(strlen(str) + 1).

+ + + + + + +
+ + +
+
+ + + +
+ + + + + + + + + + + + + + + + + + + +
+ + diff --git a/ref/api/misc.html b/ref/api/misc.html new file mode 100644 index 00000000..3968b7ff --- /dev/null +++ b/ref/api/misc.html @@ -0,0 +1,350 @@ + + + + + + Miscellaneous - NNG Reference Manual (DRAFT) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + + + + + + + + + + +
+ +
+ + + + + + + + +
+
+ +

Miscellaneous

+

This chapter discusses some interfaces that don’t really +fit anywhere else.

+

Get Random Number

+
uint32_t nng_random(void);
+
+

The nng_random returns a random number. +The value returned is suitable for use with cryptographic functions such as +key generation, and is obtained using platform-specific cryptographically strong random +number facilities when available.

+

Create Socket Pair

+
int nng_socket_pair(int fds[2]);
+
+

The nng_socket_pair function creates a pair of connected file descriptors. +These file descriptors, which are returned in the fds array, are suitable for +use with the Socket transport.

+

On POSIX platforms, this is a thin wrapper around the standard socketpair function, +using the AF_UNIX family and the SOCK_STREAM socket type. +1

+

This will return zero on success, or an error number. On platforms that lack this +capability, such as Windows, it will return NNG_ENOTSUP.

+
+

+ + tip +

+

This function may be useful for creating a shared connection between a parent process and +a child process on UNIX platforms, without requiring the processes use a shared filesystem or TCP connection.

+
+

Report Library Version

+
const char * nng_version(void);
+
+

The nng_version function returns a human readable version number +for NNG, formatted as a NUL-terminated string.

+

Additionally, compile time version information is available +via some predefined macros:

+
    +
  • NNG_MAJOR_VERSION: Major version number.
  • +
  • NNG_MINOR_VERSION: Minor version number.
  • +
  • NNG_PATCH_VERSION: Patch version number.
  • +
+

NNG is developed and released using +Semantic Versioning 2.0, and +the version numbers reported refer to both the API and the library itself. +(The ABI – application binary interface – between the +library and the application is controlled in a similar, but different +manner depending upon the link options and how the library is built.)

+ + + + + +


+

1: At present only POSIX platforms implementing socketpair support this function.

+ +
+ + +
+
+ + + +
+ + + + + + + + + + + + + + + + + + + +
+ + diff --git a/ref/api/msg.html b/ref/api/msg.html new file mode 100644 index 00000000..ff9a1cad --- /dev/null +++ b/ref/api/msg.html @@ -0,0 +1,511 @@ + + + + + + Messages - NNG Reference Manual (DRAFT) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + + + + + + + + + + +
+ +
+ + + + + + + + +
+
+ +

Messages

+

Messages in Scalability Protocols are the fundamental unit of +transmission and reception, as these protocols are fundamentally message-oriented.

+

Messages have a [body][nng_msg_body], containing the application-supplied +payload, and a [header][nng_msg_header], containing protocol specific routing and similar +related information.

+
+

+ + tip +

+

Only applications using raw mode need to access the message header. +Very few NNG applications do this.

+
+

Message Structure

+
typedef struct nng_msg nng_msg;
+
+

The nng_msg structure represents a single message. It carries a body +and a header.

+

Create a Message

+
int nng_msg_alloc(nng_msg **msgp, size_t size);
+
+

The nng_msg_alloc function allocates a new message. +It takes a size argument, and returns a message +with a preallocated body of that size in the msgp parameter.

+

If it succeeds, it returns zero, otherwise this function may return NNG_ENOMEM, +indicating that insufficient memory is available to allocate a new message.

+

Destroy a Message

+
void nng_msg_free(nng_msg *msg);
+
+

The nng_msg_free function deallocates a message.

+

Duplicate a Message

+
int nng_msg_dup(nng_msg **dup, nng_msg *msg);
+
+

The nng_msg_dup function duplicates the message msg, storing a pointer +to the new duplicate in dup. This function also returns zero on succes, or NNG_ENOMEM +if memory is exhausted.

+

Message Size and Capacity

+
size_t nng_msg_capacity(nng_msg *msg);
+int nng_msg_realloc(nng_msg *msg, size_t size);
+int nng_msg_reserve(nng_msg *msg, size_t capacity);
+
+

Messages have a certain amount of pre-reserved space, which may exceed the total +size of the message. This allows for content to be added to the message later, +without necessarily performing a reallocation.

+

The nng_msg_capacity function returns the amount of prereserved space. +If a message size change is required, and the new size will fit within the capacity +reported by this function, then change will be done without a reallocation, and +likely without a data copy as well.

+
+

+ + tip +

+

The capacity reported by nng_msg_capacity may not include reserved headroom, which +is present to allow a very limited amount of content to be inserted in front of the +message without requiring the rest of the message to be copied.

+
+

The message size may be changed by use of the nng_msg_realloc function. This +function will reallocate the underlying memory for the message msg, +preserving contents while doing so. +If the new size is smaller than the original message, it will +truncate the message, but not perform any allocations. +If reallocation fails due to insufficient memory, then the original is left intact.

+

The nng_msg_reserve function ensures that the total message capacity +is at least capacity bytes. Use of this function to ensure the total anticipated +capacity is present in the message may help prevent many small allocations.

+

Both nng_msg_realloc and nng_msg_reserve return zero on success, or may return +NNG_ENOMEM if insufficient memory exists to preform allocation.

+
+

+ + important +

+

Any pointers to message content obtained before a call to nng_msg_realloc or +nng_msg_reserve (or any other function that changes the message size) should be +treated as invalid, as the locations pointed to may be deallocated by these functions.

+
+

Message Body

+
void *nng_msg_body(nng_msg *msg);
+size_t nng_msg_len(nng_msg *msg);
+
+

The body and body length of msg are returned by nng_msg_body and +nng_msg_len, respectively.

+

Clear the Body

+
void *nng_msg_clear(nng_msg *msg);
+
+

The nng_msg_clear simply resets the total message body length to zero, but does +not affect the capacity. It does not change the underlying bytes of the message.

+

Add to Body

+
int nng_msg_append(nng_msg *msg, const void *val, size_t size);
+int nng_msg_append_u16(nng_msg *msg, uint16_t val16);
+int nng_msg_append_u32(nng_msg *msg, uint32_t val32);
+int nng_msg_append_u64(nng_msg *msg, uint64_t val64);
+
+int nng_msg_insert(nng_msg *msg, const void *val, size_t size);
+int nng_msg_insert_u16(nng_msg *msg, uint16_t val16);
+int nng_msg_insert_u32(nng_msg *msg, uint32_t val32);
+int nng_msg_insert_u64(nng_msg *msg, uint64_t val64);
+
+

Appending data to a message body is done by using the nng_msg_append functions. +The base nng_msg_append function appends size bytes of untyped data to the end of the +message.

+

Use of the typed versions, ending in suffixes _u16, _u32, and _u64 allows +for unsigned integers to be appended directly. The integers are encoded in network byte order, with +the most significant byte appearing first. The message body will by two, four, or eight +bytes accordingly.

+

Data may inserted before the rest of the message body by using the nng_msg_insert functions. +This will attempt to use “headroom” in the message to avoid a data copy. +Otherwise they are like the nng_msg_append functions except that the put the data in front +of the messages instead of at the end.

+
+

+ + tip +

+

Message headroom is limited, so nng_msg_insert is best used sparingly. +It is much more efficient to build the message content from start to end +using nng_msg_append.

+
+

Consume From Body

+
int nng_msg_chop(nng_msg *msg, size_t size);
+int nng_msg_chop_u16(nng_msg *msg, uint16_t *val16);
+int nng_msg_chop_u32(nng_msg *msg, uint32_t *val32);
+int nng_msg_chop_u64(nng_msg *msg, uint64_t *val64);
+
+int nng_msg_trim(nng_msg *msg, size_t size);
+int nng_msg_trim_u16(nng_msg *msg, uint16_t *val16);
+int nng_msg_trim_u32(nng_msg *msg, uint32_t *val32);
+int nng_msg_trim_u64(nng_msg *msg, uint64_t *val64);
+
+

The nng_msg_chop functions remove data from the end of the body of message msg, +reducing the message length by either size, or the appropriate value size.

+

The nng_msg_trim functions remove data from the beginning of the message body of msg. +but are otherwise just like the nng_msg_chop functions.

+

If the message is not big enough to remove requisite amount of bytes, these functions +return NNG_EINVAL. Otherwise they return zero.

+

Additionally, functions with typed suffixes (_u16, _u32, _u64) decode the data and return it +through the appropriate val pointer.

+

The data is assumed to have been in network byte order in the message, but is returned in +the native machine byte order. The appropriate number of bytes is consumed for each of these types, +so two bytes for _u16, four bytes for _u32, and eight bytes for _u64.

+

Message Header

+
void *nng_msg_header(nng_msg *msg);
+size_t nng_msg_header_len(nng_msg *msg);
+
+

The header and header length of msg are returned by nng_msg_header and +nng_msg_header_len, respectively.

+

The message headers are generally intended for limited use, to store protocol headers.

+
+

+ + important +

+

The message headers are for protocol and transport headers, and not for general +application payloads. Misuse of the header may prevent the application from functioning +properly.

+
+

Clear the Header

+
void *nng_msg_header_clear(nng_msg *msg);
+
+

The nng_msg_header_clear simply resets the total message header length to zero.

+

Append or Insert Header

+

Appending data to a message header is done by using the nng_msg_header_append functions, +and inserting data in the header is done using the nng_msg_header_insert functions.

+

These functions act just like the nng_msg_append and nng_msg_insert functions, +except that they operate on the message header rather than the message body.

+

Consume from Header

+

The nng_msg_header_trim functions remove data from the beginning of the message header, +and the nng_msg_header_chop functions remove data from the end of the message header.

+

These functions act just like the nng_msg_trim and nng_msg_chop functions, +except that they operate the message header rather than the message body.

+

Message Pipe

+
nng_pipe nng_msg_get_pipe(nng_msg *msg);
+void nng_msg_get_pipe(nng_msg *msg, nng_pipe p);
+
+

The nng_msg_set_pipe function sets the pipe associated with msg to p. +This is most often useful when used with protocols that support directing +a message to a specific peer. +For example the PAIR version 1 protocol can do +this when NNG_OPT_PAIR1_POLY mode is set.

+

The nng_msg_get_pipe function returns the pipe that was previously set on the message m, +either directly by the application, or when the message was received by the protocol.

+
+

+ + note +

+

Not all protocols support overriding the destination pipe.

+
+

Examples

+

Example 1: Preparing a message for use

+
    #include <nng/nng.h>
+
+    nng_msg *m;
+    if (nng_msg_alloc(&m, strlen("content") + 1) != 0) {
+       // handle error
+    }
+    strcpy(nng_msg_body(m), "content");
+
+

Example 2: Preallocating message content

+
    if (nng_msg_alloc(&m, 1024) != 0) {
+        // handle error
+    }
+    while ((val64 = next_datum()) != 0) P
+        if (nng_msg_append_u64(m, val64) != 0) {
+            // handle error
+        }
+    }
+
+ + + + + + +
+ + +
+
+ + + +
+ + + + + + + + + + + + + + + + + + + +
+ + diff --git a/ref/api/stats.html b/ref/api/stats.html new file mode 100644 index 00000000..6c483ac6 --- /dev/null +++ b/ref/api/stats.html @@ -0,0 +1,471 @@ + + + + + + Statistics - NNG Reference Manual (DRAFT) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + + + + + + + + + + +
+ +
+ + + + + + + + +
+
+ +

Statistics

+

To facilitate debugging and support situations, the NNG library +provides for collection and reporting of numerous statistics.

+

These statistics are organized in a tree, and include both values, +and metadata describing the statistics. In order to be efficient and +minimize the impact of maintaining statistics, an explicit snapshot +of statistics must be taken, and that snapshot can then be processed.

+
+

+ + note +

+

Statistics may be disabled by build-time configuration options, +in order to reduce program size and run-time overheads.

+
+

Statistic Structure

+
typedef struct nng_stat nng_stat;
+
+

The nng_stat structure represents a statistic, which is a single value +collected at a specific point in time.

+

This structure has meta-data describing the value, the value itself, and links +to any sibling or child statistics.

+
+

+ + note +

+

The presence, name, and semantics of any given statistic are +subject to change at any time and without notice.

+
+

Collecting a Snapshot

+
int nng_stats_get(nng_stat **statsp);
+
+

The nng_stats_get function takes a snapshot of the statistics for +the system and returns it through the pointer statsp. +This function may return NNG_ENOMEM if memory is exhausted, or NNG_ENOTSUP if the statistics +support is not enabled in the build, but is otherwise expected to return zero.

+

Freeing a Snapshot

+
void nng_stats_free(nng_stat *stat);
+
+

The nng_stats_free function deallocates the snapshot referenced by stat.

+
+

+ + important +

+

The stat must be root of the statistics tree, i.e. the value that was returned +through statsp using the function nng_stats_get.

+
+

Traversing the Tree

+
const nng_stat *nng_stat_child(const nng_stat *stat);
+const nng_stat *nng_stat_next(const nng_stat *stat);
+
+

Traversing the tree of statistics is done using the nng_stat_child and +nng_stat_next functions.

+

The nng_stat_child function returns either the first child of stat, +or NULL if the stat has no children.

+

The nng_stat_next function returns the nearest sibling to the right of stat, +or NULL if stat has no more siblings to the right.

+

Finding a Statistic

+
const nng_stat *nng_stat_find(const nng_stat *stat, const char *name);
+const nng_stat *nng_stat_find_dialer(const nng_stat *stat, nng_dialer dialer);
+const nng_stat *nng_stat_find_listener(const nng_stat *stat, nng_dialer listener);
+const nng_stat *nng_stat_find_socket(const nng_stat *stat, nng_dialer socket);
+
+

Sometimes it is easiest to search for a specific statistic, matching by name, +or possibly to find the tree of statistics associated iwth a specific socket, +dialer, or listener.

+

The nng_stat_find functions are provided for this purpose.

+

The nng_stat_find function returns the first statistic within the subtree of +statistics stat, with the given name. If no such statistic can be found, NULL +is returned.

+

The nng_stat_find_dialer, nng_stat_find_listener, and nng_stat_find_socket +return the statistics subtree for the given dialer, listener, or socket object. If no such +statistic can be found, then they return NULL. +These functions should be provided the root of the statistic tree, in order to ensure +that they can find the desired object.

+

Statistic Identification

+
const char *nng_stat_name(const nng_stat *stat);
+const char *nng_stat_desc(const nng_stat *stat);
+
+

Every statistic has a name, returned by nng_stat_name, and a description, returned by +nng_stat_desc. Descriptions are human-readable text, which might be useful for display.

+

Statistic Type

+
int nng_stat_type(const nng_stat *stat);
+
+

The function nng_stat_type returns the type of the statistic. +The type of a statistic determines the nature of the value, and which +function can be used to obtain that value.

+
    +
  • +

    NNG_STAT_SCOPE: +The statistic does not carry any real value, but is +used for grouping related statistics together. This is a nexus in the +statistics tree.

    +
  • +
  • +

    NNG_STAT_COUNTER: +The statistic is a counter that only increments. +Usually the change in the value of the statistic is more interesting +(as a rate) than the absolute value at any given time. The value should +be obtained using nng_stat_value. +The units will be given by the value returned from nng_stat_unit.

    +
  • +
  • +

    NNG_STAT_LEVEL: +The statistic represnts a measured value which corresponds +to a specific value at a specific time. For example, this may represent the +number of messages currently queued for some operation, or the link speed +of a network interface. Most often the absolute value is more interesting +than the change in the value over time. Again the value can be obtained with +nng_stat_value, and any appropriate unit of measurement +with nng_stat_unit.

    +
  • +
  • +

    NNG_STAT_STRING: +The statistic is a string, such as a name. The value +of the string can be obtained with nng_stat_string. +The value of this string +will remain valid until the snapshot is deallocated with nng_stats_free.

    +
  • +
  • +

    NNG_STAT_BOOLEAN: +The value of the statistic is a truth value (either true +or false) and can be obtained with nng_stat_bool.

    +
  • +
  • +

    NNG_STAT_ID: +The value of the statistic is a numeric identifier, such as a socket +identifier. The value can be obtained with nng_stat_value, +and will be fixed for the life of the statistic.

    +
  • +
+

Statistic Value

+
uint64_t nng_stat_value(const nng_stat *stat);
+const char *nng_stat_string(const nng_stat *stat);
+bool nng_stat_bool(const nng_stat *stat);
+
+

These functions return the value associated with the statistic.

+

The nng_stat_value function returns the the numeric value for the statistic stat +of type NNG_STAT_COUNTER, NNG_STAT_LEVEL, or NNG_STAT_ID. +If stat is not one of these types, then it returns zero.

+

The nng_stat_bool function returns the Boolean value (either true or false) for the statistic stat of +type NNG_STAT_BOOLEAN. If the statistics is not of this type, then it returns false.

+

The nng_stat_string function returns a pointer to a string value for the statistic stat, +of type NNG_STAT_STRING. This string will remain valud until the snapshot that +stat was collected with is deallocated with nng_stats_free. If the statistic +is not of type NNG_STAT_STRING, then NULL is returned.

+

Statistic Units

+
int nng_stat_unit(const nng_stat *stat);
+
+

For statistics of type NNG_STAT_COUNTER or NNG_STAT_LEVEL, +it is often useful to know what that quantity being reported measures. +The following units may be returned from nng_stat_unit for such a statistic:

+
    +
  • NNG_UNIT_NONE: No unit is known or applies.
  • +
  • NNG_UNIT_BYTES: A count of bytes.
  • +
  • NNG_UNIT_MESSAGES: A count of messages.
  • +
  • NNG_UNIT_MILLIS: A count of milliseconds.
  • +
  • NNG_UNIT_EVENTS: A count of events of some type.
  • +
+

Statistic Timestamp

+
uint64_t nng_stat_timestamp(const nng_stat *stat);
+
+

Statistics have a timestamp indicating when the value was sampled, +obtained via nng_stat_timestamp. The timestamp is given in +in milliseconds since a reference time, and the reference time used +here is the same reference time used for nng_clock.

+

See Also

+

nng_clock

+ + + + + + +
+ + +
+
+ + + +
+ + + + + + + + + + + + + + + + + + + +
+ + diff --git a/ref/api/synch.html b/ref/api/synch.html new file mode 100644 index 00000000..1ac1cd57 --- /dev/null +++ b/ref/api/synch.html @@ -0,0 +1,438 @@ + + + + + + Synchronization - NNG Reference Manual (DRAFT) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + + + + + + + + + + +
+ +
+ + + + + + + + +
+
+ +

Synchronization Primitives

+

In order to allow safely accessing shared state, or to allow coordination between +different threads, NNG provides synchronization primitives in the +form of mutual exclusion locks and condition variables.

+

Correct use of these primitives will be needed when accessing shared state from +threads, or from callback functions associated with asynchronous operations. +(The need to do this in callbacks is because the callback may be executed under +a task thread other than the submitting thread.)

+

Mutual Exclusion Lock

+
typedef struct nng_mtx nng_mtx;
+
+

Mutual exclusion locks, or mutex locks, represented by the nng_mtx structure, +allow only a single thread to lock “own” the lock, acquired by nng_mtx_lock. +Any other thread trying to acquire the same mutex will wait until the owner has released the mutex +by calling nng_mtx_unlock.

+

Creating a Mutex

+
int nng_mutx_alloc(nng_mt **mtxp);
+
+

A mutex can be created by allocating one with nng_mtx_lock. +On success, a pointer to the mutex is returned through mtxp. +This function can fail due to insufficient memory or resources, in which +case it will return NNG_ENOMEM. Otherwise it will succceed and return zero.

+

Destroying a Mutex

+
void nng_mtx_free(nng_mtx *mtx);
+
+

When no longer needed, a mutex can be deallocated and its resources returned +to the caller, by calling nng_mtx_free. The mutex must not be locked +by any thread when calling this function.

+

Acquiring a Mutex

+
void nng_mtx_lock(nng_mtx *mtx);
+
+

The nng_mtx_lock function acquires ownership of a mutex, waiting for it to +unowned by any other threads if necessary.

+
+

+ + important +

+

A thread must not attempt to reqacuire the same mutex while it already “owns” the mutex. +If it does attempt to do so, the result will be a single party deadlock.

+
+

Releasing a Mutex

+
void nng_mtx_unlock(nng_mtx *mtx);
+
+

The nng_mtx_unlock function releases a mutex that the calling thread has previously +acquired with nng_mtx_lock.

+
+

+ + important +

+

A thread must not attempt to release (unlock) a mutex if it was not the thread +that acquired the mutex to begin with.

+
+

Condition Variable

+
typedef struct nng_cv nng_cv;
+
+

The nng_cv structure implements a condition variable, associated with the +the mutex mtx which was supplied when it was created.

+

Condition variables provide for a way to wait on an arbitrary condition, and to be woken +when the condition is signaled. +The mutex is dropped while the caller is asleep, and reacquired atomically when the caller +is woken.

+
+

+ + important +

+

The caller of nng_cv_until, nng_cv_wait, nng_cv_wake, and nng_cv_wake1 must +have ownership of the mutex mtx when calling these functions.

+
+

Creating a Condition Variable

+
int nng_cv_alloc(nng_cv **cvp, nng_mtx *mtx);
+
+

The nng_cv_alloc function allocates a condition variable, and associated with the mutex mtx, +and returns a pointer to it in cvp.

+

Destroy a Condition Variable

+
void nng_cv_free(nng_cv *cv);
+
+

The nng_cv_free function deallocates the condition variable cv.

+

Waiting for the Condition

+
int nng_cv_until(nng_cv *cv, nng_time when);
+void nng_cv_wait(nng_cv *cv);
+
+

The nng_cv_until and nng_cv_wait functions put the caller to sleep until the condition +variable cv is signaled, or (in the case of nng_cv_until), the specified time when +(as determined by nng_clock is reached.

+

While nng_cv_wait never fails and so has no return value, the nng_cv_until function can +return NNG_ETIMEDOUT if the time is reached before condition cv is signaled by +either nng_cv_wake or nng_cv_wake1.

+

Signaling the Condition

+
void nng_cv_wake(nng_cv *cv);
+void nng_cv_wake1(nng_cv *cv);
+
+

The nng_cv_wake and nng_cv_wake1 functions wake threads waiting in +nng_cv_until or nng_cv_wait. +The difference between these functions is that +nng_cv_wake will wake every thread, whereas nng_cv_wake1 will wake up exactly +one thread (which may be chosen randomly).

+
+

+ + tip +

+

Use of nng_cv_wake1 may be used to reduce the “thundering herd” syndrom of waking +all threads concurrently, but should only be used in circumstances where the application +does not depend on which thread will be woken. When in doubt, nng_cv_wake is safer.

+
+

Examples

+

Example 1: Allocating the condition variable

+
	nng_mtx *m;
+	nng_cv *cv;
+	nng_mtx_alloc(&m); // error checks elided
+	nng_cv_alloc(&cv, m);
+
+

Example 2: Waiting for the condition

+
    expire = nng_clock() + 1000; // 1 second in the future
+    nng_mtx_lock(m);  // assume cv was allocated using m
+    while (!condition_true) {
+        if (nng_cv_until(cv, expire) == NNG_ETIMEDOUT) {
+            printf("Time out reached!\n");
+            break;
+        }
+    }
+    // condition_true is true
+    nng_mtx_unlock(m);
+
+

Example 3: Signaling the condition

+
    nng_mtx_lock(m);
+    condition_true = true;
+    nng_cv_wake(cv);
+    nng_mtx_unlock(m);
+
+ + + + + +

See Also

+

Threads, +Time, +Asynchronous I/O

+ +
+ + +
+
+ + + +
+ + + + + + + + + + + + + + + + + + + +
+ + diff --git a/ref/api/thread.html b/ref/api/thread.html new file mode 100644 index 00000000..0f9e0ac7 --- /dev/null +++ b/ref/api/thread.html @@ -0,0 +1,374 @@ + + + + + + Threads - NNG Reference Manual (DRAFT) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + + + + + + + + + + +
+ +
+ + + + + + + + +
+
+ +

Threads

+

Threads provide a means of representing multiple parallel execution contexts. +NNG makes use of this concept internally, but also provides for user applications +to utilize the same thread facilities. This allows one form of concurrency for +applications.

+
+

+ + note +

+

Threads in NNG are built upon platform support, which may be based upon operating +system supplied threads, process, or coroutines. The appearance of concurrency does +not guarantee true concurrency, and scheduling between threads may not necessarily be +pre-emptive. While this will not adversely impact applications that use this facility +for I/O bound concurrency, it may not provide good results for purely CPU-bound operations.

+
+
+

+ + important +

+

Thread objects created by this function may not be real system-level +threads capable of performing blocking I/O operations using normal blocking system calls. +If use of blocking system calls is required (not including APIs provided +by the NNG library itself of course), then real OS-specific threads +should be created instead (such as with pthread_create or similar functions.) +Blocking NNG library calls can however be made safely from NNG threads.

+
+
+

+ + tip +

+

The system may impose limits on the number of threads that can be created. +Typically applications should not create more than a dozen of these. +If greater concurrency or scalability is needed, consider instead using +an asynchronous model using nng_aio structures.

+
+

Thread Structure

+
typedef struct nng_thread nng_thread;
+
+

The nng_thread structure represnts a thread, which is a single execution context. +A given thread will have its own stack, and CPU registers. However global state, as well +as values allocated on the heap, will be shared and accessible to all threads in the system +(See the Synchronization chapter for functions to help with data sharing between different threads.)

+

Multiple threads can be thought of as running concurrently, even though +they might not actually do so.

+

I/O operations that block (i.e. wait for completion) will block the +thread, while allowing other threads to proceed.

+

Creating a Thread

+
int nng_thread_create(nng_thread **thrp, void (*func)(void *), void *arg);
+
+

The nng_thread_create function creates a thread, which will execute func, with +the given argument arg, and returns a pointer to it in thrp.

+

The thread may begin execution immediately.

+

The thread will persist until func returns.

+

This function returns zero on success, but may return NNG_ENOMEM if insufficient +resources to create a thread are available.

+

Destroying a Thread

+
void nng_thread_destroy(nng_thread *thr);
+
+

The nng_thread_destroy function waits for the thread thr to finish execution. +This function should be called to reclaim any resources associated with the thread when done. +It also has the effect of blocking execution in the caller until thr has completed executing.

+

Thread Names

+
void nng_thread_set_name(nng_thread *thr, const char *name);
+
+

In order to facilitate debugging, nng_thread_set_name may be called +to provide a name for the thread. This may change how the thread is represented +in debuggers. Not all platforms support setting the thread name.

+

See Also

+

Synchronization, +Asynchronous Operations

+ + + + + + +
+ + +
+
+ + + +
+ + + + + + + + + + + + + + + + + + + +
+ + diff --git a/ref/api/time.html b/ref/api/time.html new file mode 100644 index 00000000..f3bf9685 --- /dev/null +++ b/ref/api/time.html @@ -0,0 +1,381 @@ + + + + + + Time - NNG Reference Manual (DRAFT) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + + + + + + + + + + +
+ +
+ + + + + + + + +
+
+ +

Time

+

NNG supports has support for time in the form of access to a +system clock, and supporting timeouts for certain operations.

+

Time Type

+
typedef uint64_t nng_time;
+
+

The nng_time type is used to represent a clock offset from a common base time, +measured in milliseconds.

+

The reference, or zero value, is some arbitrary point in time, most often sytem boot, but can +be process start time or any other convenient reference.

+

All threads within a process will use the same reference time, but be aware that different processes +may use a different reference time.

+

Duration Type

+
typedef int64_t nng_duration;
+
+#define NNG_DURATION_INFINITE (-1)
+#define NNG_DURATION_DEFAULT  (-2)
+#define NNG_DURATION_ZERO     (0)
+
+

The nng_duration time measures a time duration in milliseconds. +Normally durations are positive, but some specific negative values are reserved.

+
    +
  • +

    NNG_DURATION_INFINITE: The duration essentially means forever. +This is most often used with a timeout to indicate that there is no timeout, the +operation should wait until it is complete, even forever.

    +
  • +
  • +

    NNG_DURATION_DEFAULT: This special value is used in some circumstances to +prevent overriding a default timeout. Some operations have a default maximum time, +and this value means that the previously established default should be used. +The precise meaning is context-specific.

    +
  • +
  • +

    NNG_DURATION_ZERO: A zero length duration is used to performan an immediate +poll.

    +
  • +
+

Get the Current Time

+
nng_time nng_clock(void);
+
+

The nng_clock function returns the number of elapsed +milliseconds since some arbitrary time in the past. +The resolution of the clock depends on the underlying timing facilities of the system. +This function may be used for timing, but applications should not expect +very fine-grained values.

+

Wait for Duration

+
void nng_msleep(nng_duration msec);
+
+

The nng_msleep function blocks the calling thread for at least the specified +number of milliseconds.

+
+

+ + tip +

+

This function may block for longer than requested. +The actual wait time is determined by the capabilities of the +underlying system.

+
+

Wait Asynchronously

+
void nng_sleep_aio(nng_duration msec, nng_aio *aio);
+
+

It is possible to wait as the action on an nng_aio, which in effect +acts like scheduling a callback to run after a specified period of time.

+

The nng_sleep_aio function provides this capability. +After msec milliseconds have passed, then aio’s callback will be executed. +If this sleep waits without interruption, and then completes, the result from +nng_aio_result will be zero.

+
+

+ + note +

+

If a timeout shorter than msec is set on aio using nng_aio_set_timeout, +then the sleep will wake up early, with a result code of NNG_ETIMEDOUT.

+
+

See Also

+

Asynchronous Operations, +Synchronization

+ + + + + + +
+ + +
+
+ + + +
+ + + + + + + + + + + + + + + + + + + +
+ + diff --git a/ref/api/url.html b/ref/api/url.html new file mode 100644 index 00000000..3f13797f --- /dev/null +++ b/ref/api/url.html @@ -0,0 +1,370 @@ + + + + + + URLs - NNG Reference Manual (DRAFT) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + + + + + + + + + + +
+ +
+ + + + + + + + +
+
+ +

URLs

+

Universal Resource Locators, or URLs for short, are a standardized +way of representing a network resource, +defined in RFC 1738, +and RFC 3968.

+

In Scalability Protocols, this concept is extended, although it includes schemes +that are not part of the IETF standards.

+

URL Structure

+
typedef struct nng_url {
+    char *u_rawurl;
+    char *u_scheme;
+    char *u_userinfo;
+    char *u_host;
+    char *u_hostname;
+    char *u_port;
+    char *u_path;
+    char *u_query;
+    char *u_fragment;
+    char *u_requri;
+} nng_url;
+
+

URL Fields

+

Applications may access individual fields, but must not free or +alter them, as the underlying memory is managed by the library.

+

The fields of an nng_url object are as follows:

+
    +
  • u_rawurl: The unparsed URL string. This will never be NULL.
  • +
  • u_scheme: The URL scheme, such as “http” or “inproc”. Always lower case. This will never be NULL.
  • +
  • u_userinfo: This username and password if supplied in the URL string. Will be NULL when not present.
  • +
  • u_host: The full host part of the URL, including the port if present (separated by a colon.)
  • +
  • u_hostname: The name of the host, and may be the empty string in some cases.
  • +
  • u_port: The port. May be empty if irrelevant or not specified.
  • +
  • u_path: The path, typically used with HTTP or WebSockets. Will be empty string if not specified.
  • +
  • u_query: The query info (typically following ? in the URL.) Will be NULL if not present.
  • +
  • u_fragment: This is used for specifying an anchor, the part after # in a URL. Will be NULL if not present.
  • +
  • u_requri: The full Request-URI. Will be the empty string if not specified.
  • +
+
+

+ + note +

+

Other fields may also be present, but only those documented here are safe for application use.

+
+

Parse a URL

+
int nng_url_parse(nng_url **urlp, const char *str);
+
+

The nng_url_parse function parses a URL string (in str), +and creates a dynamically allocated nng_url, returning it in urlp.

+
+

+ + important +

+

Only nng_url_free should be used to deallocate nng_url objects.

+
+

Clone a URL

+
int nng_url_clone(nng_url **dup, nng_url *url);
+
+

The nng_url_clone function creates a copy of url, and returns it in dup.

+

Destroy a URL

+
void nng_url_free(nng_url *url);
+
+

The nng_url_free function destroy an nng_url object created with +either nng_url_parse or nng_url_free.

+

This is the only correct way to destroy an nng_url object.

+

See Also

+

More information about Universal Resource Locators can be found in +RFC 3986.

+ + + + + + +
+ + +
+
+ + + +
+ + + + + + + + + + + + + + + + + + + +
+ + -- cgit v1.2.3-70-g09d2