Unique name for the client (important for queues and sow). It is strongly recommended to set a client name, but if it's not set, it'll be assigned automatically.
When a transaction log is present, AMPS requires the Client Name for a publisher to be:
60East recommends always using consistent, unique client names.
This method ACKs a message queue message using the message object.
client.ack(queueMessage);
AMPS message object.
A comma separated list of values indicating additional options, such as cancel
,
expire
, or lease_extension=60s
.
This method ACKs a message queue message using the topic and bookmark values.
client.ack('queue-topic', '12290412031115262887|1484244707000000008|');
The topic of the message to ack.
The bookmark of the message to ack.
A comma separated list of values indicating additional options, such as cancel
,
expire
, or lease_extension=60s
.
This method is a setter/getter for the acknowledgement batch size of the client.
Batching acknowledgements reduces the number of round-trips to AMPS, which reduces network traffic and improves overall performance. AMPS sends the batch of acknowledgements when the number of acknowledgements exceeds a specified size. By default, if not specified otherwise, it is equal to 0. If the batch size value is greater than 1, the automatic ack timeout will be assigned with the default value of 1000 ms, if not already set. To override this behavior and disable ack timeouts with the batch size > 1, explicitly set ack timeout value to 0 after setting the batch size.
// create a client and assign a publish store to it
const client = new Client().ackBatchSize(100);
// ... get the ack batch size later
if (client.ackBatchSize() > 10) { ... }
The client if a setter is called. The acknowledgement batch size otherwise.
This method is a setter/getter for the acknowledgement batch timeout of the client.
Batching acknowledgements reduces the number of round-trips to AMPS, which reduces network traffic and improves overall performance. AMPS sends the batch of acknowledgements when the amount of time since the last batch was sent exceeds a specified timeout.
// create a client and assign a acknowledgment batch timeout to it
const client = new Client().ackTimeout(100);
// ... get the ack batch timeout later
if (client.ackTimeout() > 1000) { ... }
The client if a setter is called. The acknowledgement batch timeout value (if any) otherwise.
This method adds a connection state listener that will be called every time a connection state has been changed.
const client = new Client();
const listenerId = client.addConnectionStateListener(state => {
console.log('state: ', state);
});
// ... later
client.removeConnectionStateListener(listenerId);
The callback function that will be invoked in case of a connection state change.
The unique monotonically increasing listener id that can be used to remove the listener later.
This method is a setter/getter for the autoAck option of the client. The AMPS client allows you to specify that messages should be automatically acknowledged. When this mode is on, AMPS acknowledges the message automatically if the message handler returns without throwing an exception. It is false by default.
// create a client and set autoAck to true
const client = new Client().autoAck(true);
// ... check the autoAck option value later
if (client.autoAck()) {
console.log('Auto Ack is enabled!');
}
The client if a setter is called. The autoAck option value otherwise.
This method is a setter/getter for the BookmarkStore object of the client. BookmarkStore interface is being used to provide resumable subscriptions and client-side duplicate message handling.
// create a client and assign a bookmark store to it
const bookmarkStore = new MemoryBookmarkStore();
const client = new Client().bookmarkStore(bookmarkStore);
// ... access the bookmark store later
client.bookmarkStore().purge();
The client if a setter is called. The BookmarkStore object (if any) otherwise.
This method connects the AMPS client to the server. It automatically calls logon() upon successful connection. If the ServerChooser is set, arguments are ignored.
const client = new Client('my-application');
try {
await client.connect('ws://localhost:9100/amps/json');
// now the client is ready to send and receive any commands
// ...
}
catch (err) {
console.error('Connection error: ', err);
}
The URI containing all required credentials/addresses/types.
The authenticator object for custom authentication scenarios.
The logon options, such as `pretty``.
The promise object with the result of fulfilling/failing the connection promise.
This method is a setter/getter for the DelayStrategy object of the client. AMPS provides FixedDelayStrategy and ExponentialDelayStrategy strategies that are used to define a delay between reconnection attempts. It is possible to implement a custom DelayStrategy. If it is not set, but the server chooser is used, the client will use ExponentialDelayStrategy with default settings.
// create a client and assign a delay strategy to it
const strategy = new ExponentialDelayStrategy();
const client = new Client().delayStrategy(strategy);
// ... access the delay strategy object later
client.delayStrategy().reset();
The client if a setter is called. The DelayStrategy object (if any) otherwise.
This method delta publishes a message to a SOW topic. If the client has a PublishStore set, then the client will store the message before forwarding the message to AMPS. This method does not wait for a response from the AMPS server. To detect failure, set a Client.failedWriteHandler. If a disconnection occurs, the message is still stored in the publish store.
client.deltaPublish('topic', {id: 1, text: 'Hello, World'});
the topic to publish data.
the data to publish to a topic.
an object with params, like: {expiration: 30, ...}
This method performs the delta_subscribe command. The delta_subscribe command is like the subscribe command except that subscriptions placed through delta_subscribe will receive only messages that have changed between the SOW record and the new update. If delta_subscribe is used on a record which does not currently exist in the SOW or if it is used on a topic which does not have a SOW-topic store defined, then delta_subscribe behaves like a subscribe command.
try {
const subId = await client.deltaSubscribe(message => console.log(message.data), 'topic');
console.log(subId);
}
catch (err) {
console.error('err: ', err);
}
a message handler that will be called each time a message is received.
The topic argument in sow.
The filter argument in sow.
The params like ackType, bookmark, commandId, etc in an object.
The Promise object with the subscription id of the command.
This method disconnects the client from an AMPS server (if the connection existed).
The promise object fulfilled once disconnection is finished.
This method sets/gets the disconnect handler that is in case of an unintentional disconnection.
const disconnectHandler = (client, err) => {
// when the Client unintentionally disconnects, this method is invoked.
console.error('err: ', err);
};
const client = new Client().disconnectHandler(disconnectHandler);
The client if a setter called, the disconnect handler (if any) otherwise.
This method sets/gets the error handler for all general errors such as connection issues, exceptions, etc.
const client = new Client().errorHandler(err => console.error('err: ', err));
The client if a setter called, the error handler (if any) otherwise.
This is the command execution interface method that allows to send commands that don't have a convenience method or require additional settings that are not provided by the convenience methods. The purpose of the method is to execute Command objects.
const subCommand = new Command('subscribe')
.topic('messages')
.filter('/id > 20');
const commandId = await client.execute(subCommand, message => {
console.log('message: ', message.data);
});
console.log('commandId: ', commandId);
a Command object.
a callback to report the messages (including ack messages if they were requested).
a timeout value for the command execution in milliseconds.
The promise object fulfilled with the command id created.
This method sets/gets the failed write handler for reporting failed publishes to AMPS, for example, due to insufficient entitlements.
const client = new Client().failedWriteHandler((message, reason) => {
console.log('Failed to publish -- reason:', reason);
console.log('Failed to publish -- message data: ', message.data);
});
The client if a setter called, the failed write handler (if any) otherwise.
This method performs the flush command. It sends a command to AMPS that returns an acknowledgement when all previous messages from this client have been received and processed or persisted. This command helps applications that use AMPS determine when AMPS has received all of the messages that have been sent, making it safe for the client to exit.
client.publish('topic', {id: 1});
client.publish('topic', {id: 2});
await client.flush('persisted');
the flush timeout in milliseconds. Default value is 0.
The Promise object with the results of execution of the command.
This method sets up the heartbeat mode with the server. It sends a command to AMPS that starts or refreshes a heartbeat timer. When a heartbeat timer is active, AMPS publishes periodic heartbeat messages to AMPS and expects the client to respond with a heartbeat message. If the client does not provide a heartbeat within the time specified, AMPS logs an error and disconnects the connection.
// Initialize a client with the heartbeat of 5 seconds
const client = new Client().heartbeat(5);
the heartbeat value in seconds.
the timeout value in seconds. By default it is the heartbeat interval value times 2.
The Client object.
This method sets/gets the last chance message handler that is invoked when no other handler matches.
const client = new Client().lastChanceMessageHandler(message => {
console.log('Last chance to handle the message: ', message.data);
});
The client if a setter called, the last chance message handler (if any) otherwise.
This method is a setter/getter for the logon correlation id of the client. It must be a valid Base64 string.
// assign a logon correlation id to the client object
const client = new Client().logonCorrelationId('L2p0vkn2');
// ... access the logon correlation id later
console.log(client.logonCorrelationId());
The client if a setter is called. The logon correlation id (if any) otherwise.
This method is a setter/getter for the logon options of the client. Logon options can also be set via the connect() method as an optional argument. Logon options can't be set after the client is connected and logged on.
// create a client and set the logon options
const client = new Client().logonOptions('pretty,ack_conflation=300ms');
// ... access the logon options later
console.log(client.logonOptions());
The client if a setter is called. The logon options (if any) otherwise.
This method is a setter/getter for the client's name. If logon has not been performed yet and the name was not set, returns null.
When a transaction log is present, AMPS requires the Client Name for a publisher to be:
60East recommends always using consistent, unique client names.
The name of the AMPS client instance.
The client object if the setter is called. The name of the AMPS client instance (if any) otherwise.
This method is a getter for the client's name hash value. If logon has not been performed yet and the name hash value was not set, returns null.
Here's an example of a name hash value: 5934099655320710513
. This corresponds to the name Test
.
The name hash value of this client instance.
Publish a message to an AMPS topic. If the client has a PublishStore set, then the client will store the message before forwarding the message to AMPS. This method does not wait for a response from the AMPS server. To detect failure, set a Client.failedWriteHandler. If a disconnection occurs, the message is still stored in the publish store.
client.publish('topic', {id: 1}); // publish data as a native object
client.publish('topic', '{"id":1}'); // publish data as a string
Depending on the available TypeHelper for the message type used, data can be published as a native object or a string -- the type helper can take care of the serializing it before sending, if needed.
the topic to publish data.
the data to publish to a topic.
an object with params, like: {expiration: 30, ...}
This method is a setter/getter for the PublishStore object of the client. PublishStore interface is being used to provide consistent publish functionality with guaranteed delivery.
// create a client and assign a publish store to it
const publishStore = new MemoryPublishStore();
const client = new Client().publishStore(publishStore);
// ... access the publish store later
if (client.publishStore().unpersistedCount() === 0) {
client.disconnect();
}
The client if a setter is called. The PublishStore object (if any) otherwise.
This method sets a reconnection delay for the client. This is a convenience method that sets up a FixedDelayStrategy with a requested delay value.
// create a client and set a reconnect delay
const client = new Client().reconnectDelay(5000);
The client object.
This method removes a connection state listener with the id provided.
const client = new Client();
const listenerId = client.addConnectionStateListener(state => {
console.log('state: ', state);
});
// ... later
client.removeConnectionStateListener(listenerId);
This method is a setter/getter for the server chooser object of the client. ServerChooser interface is used to obtain a URI to connect. The chooser can only be set before the client is connected. Once a server chooser is set, the client is working in the High Availability mode and uses a DelayStrategy object to determine a delay between reconnection attempts. If no delay strategy was provided, the client will use ExponentialDelayStrategy with default settings. AMPS provides the DefaultServerChooser implementation.
// create a server chooser and assign URIs
const chooser = new DefaultServerChooser();
chooser.add('wss://localhost:9000/amps/json');
chooser.add('wss://localhost:9100/amps/json');
// create a client and assign a server chooser to it
const client = new Client().serverChooser(chooser);
// ... access the chooser object later
client.serverChooser().add('wss://backup_host:9200/amps/json');
The client if a setter is called. The server chooser(if any) otherwise.
This method returns the server version returned by the AMPS server in the logon acknowledgement. If logon has not been performed yet, returns null.
The version of the AMPS server.
This method returns the server version returned by the AMPS server in the logon acknowledgement in a form
of an integer XXYYZZWWW. For example, for 5.2.1.22 will be represented as 050201022
.
If logon has not been performed yet, returns 0.
The version of the AMPS server.
This method performs the sow command. The sow command is use to query the contents of a previously defined SOW Topic. A sow command can be used to query an entire SOW Topic, or a filter can be used to further refine the results found inside a SOW Topic. For more information, see the State of the World and SOW Queries chapters in the AMPS User Guide.
const sowHandler = message => {
switch (message.header.command()) {
case 'group_begin':
console.log('--- Begin SOW Results ---');
break;
case 'sow':
console.log(message.data);
break;
case 'group_end':
console.log('--- End SOW Results ---');
break;
}
};
try {
const queryId = await client.sow(sowHandler, 'sow-topic');
console.log(queryId);
}
catch (err) {
console.error('err: ', err);
}
a message handler that will be called each time a message is received.
The topic argument in sow.
The filter argument in sow.
The params like ackType, bookmark, commandId, etc in an object.
The Promise object with the query id of the command.
This method performs the sow_and_delta_subscribe command. A sow_and_delta_subscribe command is used to combine the functionality of commands sow and a delta_subscribe in a single command. The sow_and_delta_subscribe command is used
As with the delta_subscribe command, publish messages representing updates to SOW records will contain only the information that has changed. If a sow_and_delta_subscribe is issued on a record that does not currently exist in the SOW topic, or if it is used on a topic that does not have a SOW-topic store defined, then a sow_and_delta_subscribe will behave like a sow_and_subscribe command.
try {
const queryId = await client.sowAndDeltaSubscribe(
message => console.log(message),
'sow-topic'
);
console.log(queryId);
}
catch (err) {
console.error('err: ', err);
}
a message handler that will be called each time a message is received.
The topic argument in sow.
The filter argument in sow.
The params like ackType, bookmark, commandId, etc in an object.
The Promise object with the query id of the command.
This method performs the sow_and_subscribe command. A sow_and_subscribe command is used to combine the functionality of sow and a subscribe command in a single command. The sow_and_subscribe command is used
try {
const queryId = await client.sowAndSubscribe(
message => console.log(message),
'sow-topic'
);
console.log(queryId);
}
catch (err) {
console.error('err: ', err);
}
a message handler that will be called each time a message is received.
The topic argument in sow.
The filter argument in sow.
The params like ackType, bookmark, commandId, etc in an object.
The Promise object with the query id of the command.
This method executes a SOW delete with a filter.
const result = await client.sowDelete('sow-topic', '/status = "obsolete"');
console.log(result.header.ackType(), ': ', result.header.status());
The topic to execute the SOW delete against.
The filter. To delete all records, set a filter that is always true: 1=1
A comma separated list of values indicating additional processing options.
The promise object with the results of execution of the command.
This method deletes a message from a SOW, using data supplied to locate a SOW entry with matching keys.
const topic = sowMessage.header.topic();
const data = sowMessage.data;
const result = await client.sowDeleteByData(topic, data);
console.log(result.header.ackType(), ': ', result.header.status());
The topic to execute the SOW delete against.
The A message data whose keys match the message to be deleted in the server’s SOW.
The promise object with the results of execution of the command.
This method executes a SOW delete with sow keys (supplied as a comma-separated values in a string). SOW keys are provided in the header of a SOW message, and are the internal identifier AMPS uses for that SOW message.
const topic = sowMessage1.header.topic();
const keys = sowMessage1.header.sowKey() + ',' + sowMessage2.header.sowKey();
const result = await client.sowDeleteByKeys(topic, keys);
console.log(result.header.ackType(), ': ', result.header.status());
The topic to execute the SOW delete against.
A comma separated list of SOW keys to be deleted. SOW keys are provided in the header of a SOW message, and are the internal identifier AMPS uses for that SOW message.
The promise object with the results of execution of the command.
This method performs the subscribe command. The subscribe command is the primary way to retrieve messages from the AMPS processing stream. A client can issue a subscribe command on a topic to receive all published messages to that topic in the future. Additionally, content filtering can be used to choose which messages the client is interested in receiving.
try {
const subId = await client.subscribe(message => console.log(message.data), 'topic');
console.log(subId);
}
catch (err) {
console.error('err: ', err);
}
a message handler that will be called each time a message is received.
The topic argument in subscribe.
The filter argument in subscribe.
The params like ackType, bookmark, commandId, etc in an object.
The Promise object with the subscription id of the command.
This method is a setter/getter for the SubscriptionManager object of the client. AMPS provides DefaultSubscriptionManager that is used to restore subscriptions after an unintended disconnection. It is not set by default.
// create a client and assign a subscription manager to it
const subscriptionManager = new DefaultSubscriptionManager();
const client = new Client().subscriptionManager(subscriptionManager);
// ... access the subscription manager object later
client.subscriptionManager().clear();
The client if a setter is called. The SubscriptionManager object (if any) otherwise.
This method sets/gets the transport filter to observe incoming and outgoing messages in the format they are sent and received on the network. This allows you to inspect or modify outgoing messages before they are sent to the network, and incoming messages as they arrive from the network. This can be especially useful when using SSL connections, since this gives you a way to monitor outgoing network traffic before it is encrypted, and incoming network traffic after it is decrypted.
const printingFilter = (data, outgoing) => {
if (outgoing) {
console.log('OUTGOING ---> ', data);
}
else {
console.log('INCOMING ---> ', data);
}
};
const client = new Client().transportFilter(printingFilter);
The client if a setter called, the transport filter method (if any) otherwise.
This method performs the unsubscribe command. The unsubscribe command unsubscribes the client from the topic which messages the client is no more interested in receiving. If not subscription id is provided, the client will unsubscribe from all subscriptions.
await client.unsubscribe(); // unsubscribe from all
await client.unsubscribe('123'); // unsubscribe for the subscription with id "123"
The id of the subscription.
The Promise object with the command id of the command.
This is a convenience static method that creates a memory-backed client that tracks bookmarks and subscriptions in memory. Subscriptions are automatically restored after a reconnection using DefaultSubscriptionManager object. MemoryBookmarkStore is enabled for bookmarks, MemoryPublishStore is enabled for publishing messages.
Unique name for the client (important for queues and sow). It is strongly recommended to set a client name, but if it's not set, it'll be assigned automatically.
a highly available Client instance.
This static method returns a version of the AMPS client.
The version of this AMPS client.