VrpcClient
VrpcClient ⇐ EventEmitter
Client capable of creating proxy objects and remotely calling functions as provided through one or more (distributed) agents.
Kind: global class
Extends: EventEmitter
- VrpcClient ⇐
EventEmitter- new VrpcClient(options)
- .getClientId() ⇒
String - .getConnectionId() ⇒
String - .connect([options]) ⇒
Promise - .updateCredentials(credentials)
- .create(options) ⇒
Promise.<Proxy> - .getInstance(instance, [options]) ⇒
Promise.<Proxy> - .delete(instance, [options]) ⇒
Promise.<Boolean> - .callStatic(options) ⇒
Promise.<Any> - .callAll(options) ⇒
Promise.<Array.<Object>> - .unsubscribe(target, [options]) ⇒
Promise.<Boolean> - .getSubscriptions([filter]) ⇒
Array.<Object> - .setSubscriberLabel(callback, label)
- .getRegistrations(options) ⇒
Promise.<Array.<Object>> - .endRegistration(options) ⇒
Promise.<Boolean> - .getSystemInformation() ⇒
Object - .getAvailableAgents([options]) ⇒
Array - .getAvailableClasses([options]) ⇒
Array - .getAvailableInstances([options]) ⇒
Array - .getAvailableMemberFunctions([options]) ⇒
Array - .getAvailableStaticFunctions([options]) ⇒
Array - .reconnectWithToken(token, [options]) ⇒
Promise - .unregisterAgent(agent) ⇒
Promise.<Boolean> - .end() ⇒
Promise - "agent" (info)
- "class" (info)
- "instanceNew" (addedInstances, info)
- "instanceGone" (removedInstances, info)
- "ended" (id, reason, by, info)
- "undelivered" (id, error, info)
- "lost" (id, reason, info)
- "healed" (id, info)
- "connect"
- "reconnect"
- "close"
- "offline"
- "error"
- "end"
new VrpcClient(options)
Constructs a remote client, able to communicate with any distributed agents
NOTE: Each instance creates its own physical connection to the broker.
Params
- options
Object- [.username]
String- MQTT username - [.password]
String- MQTT password (if no token is provided) - [.token]
String- Access token - .domain
String- Sets the domain - [.agent]
String= "*"- Sets default agent - [.broker]
String= "mqtts://broker.hivemq.com:8883"- Broker url in form:<scheme>://<host>:<port> - [.timeout]
Number= 12000- Maximum time in ms to wait for a RPC answer - [.log]
Object= console- Log object (must support debug, info, warn, and error level) - [.bestEffort]
Boolean= true- If true, message will be sent with best effort, i.e. no caching if offline - [.mqttClientId]
String= '<generated()>'- Explicitly sets the mqtt client id - [.identity]
String- Explicitly sets a vrpc client identity - [.keepalive]
String- Sets the MQTT keepalive interval (in seconds). In browsers the ping runs on a Web Worker timer, so a hidden tab keeps its session - [.requiresSchema]
Boolean= false- If true, any available schema information is shipped - [.tls]
Object- TLS settings for a secure broker:{ ca, rejectUnauthorized }. Without it the broker's certificate is not verified (the historical behaviour); withcathe broker must present a chain the given certificates anchor.
- [.username]
Example
const client = new VrpcClient({
domain: 'vrpc',
broker: 'mqtts://broker.hivemq.com:8883'
})
vrpcClient.getClientId() ⇒ String
Provides the identity-derived id of this client
Every client constructed with the same domain, host and identity
reports the same client id: it names the principal, not the
connection. Agents receive it as clientId in the presence messages
and can group the connections (e.g. browser tabs) of one identity by
it. See getConnectionId() for the id that is unique per instance.
Kind: instance method of VrpcClient
Returns: String - clientId
vrpcClient.getConnectionId() ⇒ String
Provides the unique id of this connection
Unique per VrpcClient instance: two clients sharing one identity still have distinct connection ids. Agents key all their bookkeeping by it (response routing, event listeners, isolated instances, presence), so one connection ending never disturbs the others of the same identity.
It reads <domain>/<mqttClientId>/<secret>: the mqtt client id is
what the broker knows this connection by, so a broker can confine the
client to its own topics, and the secret is random per connection, so
nobody who cannot read those topics can impersonate the connection
towards an agent. Treat it as a credential: do not log or share it.
Kind: instance method of VrpcClient
Returns: String - connectionId
vrpcClient.connect([options]) ⇒ Promise
Actually connects to the MQTT broker.
A refused connection is retried with a growing wait (doubling up to 30 s, back to the start once connected), and every refusal is emitted as 'error', so a caller can renew its credentials (see updateCredentials).
Kind: instance method of VrpcClient
Returns: Promise - Resolves once connected within [timeout], rejects otherwise
Emits: event:connected
Params
- [options]
Object- [.keepTrying]
Boolean= false- If true, a connection that is not made within [timeout] still rejects the returned promise, but keeps trying until end() and emits 'connect' once it stands, and a further connect({ keepTrying: true }) while it is trying waits for it instead of opening a second connection. If false (the default), nothing changes: the client gives up at the timeout and must be connected again.
- [.keepTrying]
Example
try {
await client.connect()
} catch (err) {
console.error(`Could not connect because: ${err.message}`)
}
vrpcClient.updateCredentials(credentials)
Replaces the credentials the connection logs in with
The broker checks credentials when a connection is made: a live connection carries on undisturbed, and the next one - after a network loss, a broker restart - logs in with these. A connection that is being refused right now tries again with them within a second, instead of waiting out its back-off.
Kind: instance method of VrpcClient
Params
- credentials
Object- Only the given fields change- [.username]
String- MQTT username - [.password]
String- MQTT password (if no token is used) - [.token]
String- Access token
- [.username]
vrpcClient.create(options) ⇒ Promise.<Proxy>
Creates a new remote instance and provides a proxy to it.
Remote instances can be "shared" or "isolated". Shared instances are
visible and re-attachable across clients as long as they are not
explicitly deleted. Life-cycle changes of shared instances are available
under the class, instanceNew, and instanceGone events. A shared
instance is created by default (isIsolated: false).
When the isIsolated option is true, the remote instance stays invisible
to other clients and the corresponding proxy object is the only way to
issue commands.
NOTE When creating an instance that already exists, the new proxy will
simply attach to (and not re-create) it - just like getInstance() was
called.
Kind: instance method of VrpcClient
Returns: Promise.<Proxy> - Object reflecting a proxy to the original object
which is handled by the agent
Params
- options
Object- .className
String- Name of the class which should be instantiated - [.instance]
String- Name of the created instance. If not provided an id will be generated - [.args]
Array- Positional arguments for the constructor call - [.agent]
String- Agent name. If not provided class default is used - [.cacheProxy]
bool= false- If true the proxy object for a given instance is cached and (re-)used in subsequent calls - [.isIsolated]
bool= false- If true the created proxy will be visible only to the client who created it
- .className
Example
// create isolated instance
const proxy1 = await client.create({
className: 'Foo',
instance: 'myPersonalInstance',
isIsolated: true
})
// create shared instance
const proxy2 = await client.create({
className: 'Foo',
instance: 'aSharedFooInstance'
})
// create shared instance providing three constructor arguments
const proxy3 = await client.create({
className: 'Bar',
instance: 'mySharedBarInstance',
args: [42, "second argument", { some: 'option' }]
})
vrpcClient.getInstance(instance, [options]) ⇒ Promise.<Proxy>
Get a remotely existing instance.
Either provide a string only, then VRPC tries to find the instance using client information, or additionally provide an object with explicit meta data.
Kind: instance method of VrpcClient
Returns: Promise.<Proxy> - Proxy object reflecting the remotely existing instance
Params
- instance
String- The instance to be retrieved - [options]
Object- Explicitly define agent and class- [.className]
String- Name of the instance's class - [.agent]
String- Agent name. If not provided class default is used as priority hit - [.noWait]
bool= false- If true immediately fail if instance could not be found in local cache
- [.className]
vrpcClient.delete(instance, [options]) ⇒ Promise.<Boolean>
Delete a remotely existing instance
Either provide a string only, then VRPC tries to find the instance using client information, or provide an object with explicit meta data.
Kind: instance method of VrpcClient
Returns: Promise.<Boolean> - true if successful, false otherwise
Params
- instance
String- The instance to be deleted - [options]
Object- Explicitly define agent and class- .className
String- Name of the instance's class - .agent
String- Agent name. If not provided class default is used as priority hit
- .className
vrpcClient.callStatic(options) ⇒ Promise.<Any>
Calls a static function on a remote class
Kind: instance method of VrpcClient
Returns: Promise.<Any> - Return value of the remotely called function
Params
- options
Object- .className
String- Name of the static function's class - .functionName
String- Name of the static function to be called - [.args]
Array- Positional arguments of the static function call - [.agent]
String- Agent name. If not provided class default is used
- .className
vrpcClient.callAll(options) ⇒ Promise.<Array.<Object>>
Calls the same function on all instances of a given class and returns an aggregated result. It as well allows for batch event and callback registrations. In this case the instanceId of the emitter is injected as first argument of any event callback.
instances selects the instances: a name pattern (line-*, where *
matches any run of characters) or a list of names and patterns. The
agent calls the selected ones only and answers for those - one request,
however many instances. An agent that does not select instances
(before protocol 4) gets one call per selected instance instead; a
subscription cannot be split like that and is refused there.
agent may name several agents as well: a pattern (edge-*, * by
default) asks every online agent that offers the class and matches, a
list asks each agent listed. They are asked all at once, and every
entry names its agent; an agent that fails as a whole answers an error
for each of its instances the client knows - or one entry with the
error alone when it knows none - and the other agents' answers stand.
Kind: instance method of VrpcClient
Returns: Promise.<Array.<Object>> - An array of objects { id, val } or
{ id, err } carrying the instance id and its return value or error,
and agent when the call addressed several agents
Params
- options
Object- .className
String- Name of the class - .functionName
String- Name of the member function - [.args]
Array- Positional arguments of the call - [.agent]
String|Array.<String>- Agent name, pattern or list of names. If not provided class default is used - [.instances]
String|Array.<String>- The instances to call: a name pattern, or a list of names and patterns (all if not provided)
- .className
vrpcClient.unsubscribe(target, [options]) ⇒ Promise.<Boolean>
Withdraws subscriptions.
A subscription is what an event function call (or on) declared with a
callback: one per target, function, arguments and callback, named by
its subscription id (see getSubscriptions). Withdrawing it stops its events at once, and
every agent holding it is told by id - however it was declared (a proxy,
callStatic, callAll on one agent or on all of them). The agent releases
the registration when the last subscription leaves.
With instance, only what is held on that instance is withdrawn: a
subscription declared there ends, and a callAll subscription - one id
on every instance of its class - stops at that instance alone while
the others keep delivering. The client remembers such a withdrawal and
applies it again after its own reconnect, until the subscription is
declared anew (a declaration names what is wanted now).
Agents before protocol 4 cannot withdraw by id: an on subscription is
removed there as before (removeListener), an on<Name> one through its
off<Name> twin when the class has one; anything else ends locally
(a callAll subscription withdrawn at one instance stops delivering its
events there).
Kind: instance method of VrpcClient
Returns: Promise.<Boolean> - true if anything was withdrawn
Params
- target
String|Array.<String>|function|Object- A subscription id (or several), a callback (all its subscriptions), or an{ emitter, event }contract (all of its subscriptions) - [options]
Object- [.instance]
String- Withdraw at this instance only
- [.instance]
vrpcClient.getSubscriptions([filter]) ⇒ Array.<Object>
Lists the subscriptions this client holds.
Kind: instance method of VrpcClient
Returns: Array.<Object> - { id, agent, className, instance, functionName, event, callAll, confirmed, lost } per subscription;
confirmed once a protocol-4 agent answered that it holds it, lost
while its agent is offline (it is declared again once the agent is back)
Params
- [filter]
Object- [.callback]
function|Object- Only the subscriptions of this callback, or of this{ emitter, event }contract
- [.callback]
vrpcClient.setSubscriberLabel(callback, label)
Gives the subscriptions of a callback a label, which agents list with
their registrations (__registrations__), e.g. who listens.
Kind: instance method of VrpcClient
Params
- callback
function|Object- The callback, or an{ emitter, event }contract (labelled before or after it subscribes) - label
String- The label (sent with every declaration)
vrpcClient.getRegistrations(options) ⇒ Promise.<Array.<Object>>
Lists the registrations of an instance (or, without an instance, the static ones of a class): function, arguments, subscriptions with their labels, events and events per second. Needs a protocol-4 agent.
Kind: instance method of VrpcClient
Returns: Promise.<Array.<Object>> - The registrations
Params
- options
Object- .className
String- Class name - [.instance]
String- Instance name - [.agent]
String- Agent name. If not provided class default is used
- .className
vrpcClient.endRegistration(options) ⇒ Promise.<Boolean>
Ends a registration for all its subscriptions; each subscriber learns that it ended and by whom ('ended' event). Needs a protocol-4 agent.
Kind: instance method of VrpcClient
Returns: Promise.<Boolean> - Whether such a registration existed
Params
- options
Object- .className
String- Class name - [.instance]
String- Instance name (static registration without) - [.agent]
String- Agent name. If not provided class default is used - .functionName
String- The event function - [.args]
Array- Its arguments without the handlers, as listed - [.by]
String- Who ends it, told to every subscriber
- .className
vrpcClient.getSystemInformation() ⇒ Object
Retrieves all information about the currently available components.
Kind: instance method of VrpcClient
Returns: Object - SystemInformation
type SystemInformation = {
[agent].status: string, // 'offline' or 'online'
[agent].hostname: string,
[agent].version: string,
[agent].classes[className].instances: string[],
[agent].classes[className].memberFunctions: string[],
[agent].classes[className].staticFunctions: string[],
[agent].classes[className].meta?: MetaData
}
vrpcClient.getAvailableAgents([options]) ⇒ Array
Retrieves all available agents.
Kind: instance method of VrpcClient
Returns: Array - Array of agent names.
Params
- [options]
Object- [.mustBeOnline]
Boolean= true- Only retrieve currently online agents
- [.mustBeOnline]
vrpcClient.getAvailableClasses([options]) ⇒ Array
Retrieves all available classes on specific agent.
Kind: instance method of VrpcClient
Returns: Array - Array of class names.
Params
- [options]
Object- [.agent]
String- Agent name. If not provided class default is used. - [.mustBeOnline]
Boolean= true- Only retrieve currently online classes
- [.agent]
vrpcClient.getAvailableInstances([options]) ⇒ Array
Retrieves all (shared) instances on specific class and agent.
Kind: instance method of VrpcClient
Returns: Array - Array of instance names
Params
- [options]
Object- .className
String- Class name - [.agent]
String- Agent name. If not provided class default is used - [.mustBeOnline]
Boolean= true- Only retrieve currently online classes
- .className
vrpcClient.getAvailableMemberFunctions([options]) ⇒ Array
Retrieves all member functions of specific class and agent.
Kind: instance method of VrpcClient
Returns: Array - Array of member function names
Params
- [options]
Object- .className
String- Class name - [.agent]
String- Agent name. If not provided class default is used - [.mustBeOnline]
Boolean= true- Only retrieve currently online classes
- .className
vrpcClient.getAvailableStaticFunctions([options]) ⇒ Array
Retrieves all static functions of specific class and agent.
Kind: instance method of VrpcClient
Returns: Array - Array of static function names
Params
- [options]
Object- .className
String- Class name - [.agent]
String- Agent name. If not provided class default is used - [.mustBeOnline]
Boolean= true- Only retrieve currently online classes
- .className
vrpcClient.reconnectWithToken(token, [options]) ⇒ Promise
Reconnects to the broker by using a different token
Kind: instance method of VrpcClient
Returns: Promise - Promise that resolves once re-connected
Params
- token
String- Access token - [options]
Object- .agent
String- Agent name. If not provided class default is used
- .agent
vrpcClient.unregisterAgent(agent) ⇒ Promise.<Boolean>
Unregisters (= removal of persisted information) an offline agent
Kind: instance method of VrpcClient
Returns: Promise.<Boolean> - Resolves to true in case of success, false otherwise
Params
- agent - The agent to be unregistered
vrpcClient.end() ⇒ Promise
Ends the connection to the broker
Kind: instance method of VrpcClient
Returns: Promise - Resolves when ended
"agent" (info)
Event 'agent'
This event is fired whenever an agent is added or removed, or whenever an agent changes its status (switches between online or offline).
Kind: event emitted by VrpcClient
Params
- info
Object- .domain
String- Domain name - .agent
String- Agent name - .status
String- Agent status, can be 'offline' or 'online' - .hostname
String- Name of the host running the agent - .version
String- User-defined version of the agent
- .domain
"class" (info)
Event 'class'
Emitted whenever a class is added or removed, or when instances or functions of this class have changed.
Kind: event emitted by VrpcClient
Params
- info
Object- .domain
String- Domain name - .agent
String- Agent name - .className
String- Class name - .instances
Array.<String>- Array of instances - .memberFunctions
Array.<String>- Array of member functions - .staticFunctions
Array.<String>- Array of static functions - .meta
MetaData- Object associating further information to functions
- .domain
"instanceNew" (addedInstances, info)
Event 'instanceNew'
Emitted whenever a new instance was created.
Kind: event emitted by VrpcClient
Params
- addedInstances
Array.<String>- An array of newly added instances - info
Object- .domain
String- Domain name - .agent
String- Agent name - .className
String- Class name
- .domain
"instanceGone" (removedInstances, info)
Event 'instanceGone'
Emitted whenever a new instance was removed.
Kind: event emitted by VrpcClient
Params
- removedInstances
Array.<String>- An array of removed instances - info
Object- .domain
String- Domain name - .agent
String- Agent name - .className
String- Class name
- .domain
"ended" (id, reason, by, info)
Event 'ended'
Emitted when a registration a subscription held ended for a reason the
subscriber did not cause: its source ended it, or a member did
(endRegistration). The subscription is gone; it never reaches the
callback. A callAll subscription lives on at its other instances.
Kind: event emitted by VrpcClient
Params
- id
String- The subscription id - reason
String- Why it ended (an error message when it failed) - by
String|null- Who ended it ('source', or what the member said) - info
Object- The subscription (agent, className, instance, functionName, event, callAll),context(the instance or class) andfailed
"undelivered" (id, error, info)
Event 'undelivered'
Emitted instead of an event, or a one-shot callback, whose arguments the agent could not encode as JSON (a BigInt, say). The callback is not called for it; a subscription stays and receives the next event. Agents before protocol 4 drop such events without telling.
Kind: event emitted by VrpcClient
Params
- id
String- The subscription id, or the one-shot callback's id - error
Object- What the agent says,{ message } - info
Object- The subscription (agent, className, instance, functionName, event, callAll), or for a one-shot callback its agent, className, instance and functionName
"lost" (id, reason, info)
Event 'lost'
Emitted when a subscription is lost: its agent went offline
('agentOffline'), its instance went away ('instanceGone'), or a
declaration again failed (the error's message). A subscription on an agent
of protocol 4 that went offline is declared again once the agent is back
('healed'); every other lost subscription is gone, and declaring it again
is the consumer's.
Kind: event emitted by VrpcClient
Params
- id
String- The subscription id - reason
String-'agentOffline','instanceGone'or an error message - info
Object- The subscription (agent, className, instance, functionName, event, callAll)
"healed" (id, info)
Event 'healed'
Emitted when a subscription lost with its agent is back: the agent serves again and holds it.
Kind: event emitted by VrpcClient
Params
- id
String- The subscription id - info
Object- The subscription (agent, className, instance, functionName, event, callAll)
"connect"
Event 'connect'
Emitted on successful (re)connection (i.e. connack rc=0).
Kind: event emitted by VrpcClient
Properties
| Name | Type | Description |
|---|---|---|
| sessionPresent | Boolean | A session from a previous connection is already present |
"reconnect"
Event 'reconnect'
Emitted when a reconnect starts.
Kind: event emitted by VrpcClient
"close"
Event 'close'
Emitted after a disconnection.
Kind: event emitted by VrpcClient
"offline"
Event 'offline'
Emitted when the client goes offline.
Kind: event emitted by VrpcClient
"error"
Event 'error'
Emitted when the client cannot connect (i.e. connack rc != 0) or when a parsing error occurs. The following TLS errors will be emitted as an error event:
- ECONNREFUSED
- ECONNRESET
- EADDRINUSE
- ENOTFOUND
Kind: event emitted by VrpcClient
"end"
Event 'end'
Emitted when mqtt.Client#end() is called. If a callback was passed to mqtt.Client#end(), this event is emitted once the callback returns.
Kind: event emitted by VrpcClient