...

Package amps

import "github.com/60East/amps-client-go/amps"
Overview
Index

Overview ▾

Package amps contains the AMPS Go client that makes it easy to build reliable, high performance messaging applications in Go.

AMPS Go Client

The AMPS Go Client lets you write blazing fast messaging applications that use the powerful AMPS technology.

This is the detailed reference for the client. For an overview and introduction, see the Go Development Guide that came with the client download, or the Go Developer's page on the 60East website.

Features

- Connecting and logging on to the AMPS Server 5.2 or higher;

- Authenticator interface support;

- Command interface support (any command can be built and sent via Client.ExecuteAsync or Client.Execute method)

- Publishing, either via convenience methods or using the Command interface;

- Subscriptions, SOW queries, and other commands using the Command interface and ExecuteAsync method;

- Experimental: Subscriptions, SOW queries, and other commands using synchronous MessageStream interface.

Quick Start

Once the client is installed, it can be used in your Go projects:

package main

import (
    "amps"
    "fmt"
)

func main() {
    fmt.Println(amps.ClientVersion)
}

You are now ready to use AMPS in your project! Here are a few Go examples to get you started:

Connect and Subscribe

In this example, we connect to an AMPS server running locally and initiate a subscription to the "orders" topic. As new orders are posted, the message handler is invoked with each message, and prints the data of each order to the console:

package main

import (
    "amps"
    "fmt"
)

func main() {
    client := amps.NewClient("my-application")

    err := client.Connect("tcp://localhost:9000/amps/json")
    if err != nil { fmt.Println(err); return }

    err = client.Logon()
    if err != nil { fmt.Println(err); return }

    // Connected, let's subscribe to a topic now
    subID, err := client.Subscribe(func(message *amps.Message) (msgError error) {
        fmt.Println(string(message.Data()))
	return
    }, "orders")

    // Now we can publish to the above subscription
    err = client.Publish("orders", `{"order": "Tesla 3", "qty": 10}`)
}

Publish a Message

With AMPS, publishing is simple, as shown in this example. We connect to an AMPS server running locally, and publish a single message to the messages topic. To simply publish a message, there is no need to predeclare the topic or configure complex routing. Any subscription that has asked for XML messages on the messages topic will receive the message. Alternatively, the PublishBytes() method is available -- it works great with the built-in Go libraries such as json.

package main

import (
    "amps"
    "fmt"
)

func main() {
    client := amps.NewClient("publish-example")

    err := client.Connect("tcp://localhost:9000/amps/xml")
    if err != nil { fmt.Println(err); return }

    err = client.Logon()
    if err != nil { fmt.Println(err); return }

    err = client.Publish("messages", "<hi>Hello, world!</hi>")
}

Disconnect Handling

When AMPS detects a disconnection, the reconnect function is called from DisconnectHandler to re-establish connection, and our connectToNextURI method reconnects to the next URI available in the list. Notice that the DisconnectHandler is only called after a successful connection has been established, otherwise a connection error is returned by the Connect method of the Client.

package main

import (
	"fmt"
	"time"
	"amps"
)

// The currently selected URI index (0 by default)
var currentURI int

// A list of URIs to connect
var uris = []string{
    "tcp://localhost:9000/amps/json",
    "tcp://localhost:9001/amps/json",
    "tcp://localhost:9002/amps/json",
}

/*
  This function is invoked by the disconnect handler,
  with a URI to connect.
*/
func connectToNextURI(client *amps.Client, uri string) {
    fmt.Println("Connecting to", uri, "...")

    err := client.Connect(uri)
    // Can't establish connection
    if err != nil {
        time.Sleep(time.Second)
        currentURI = (currentURI + 1) % len(uris);
        connectToNextURI(client, uris[currentURI])
        return
    }

    err = client.Logon()
    // Can't logon
    if err !=  nil {
        fmt.Println("Failed to logon")
        return
    }

    // Successfully connected
    fmt.Println("Connected!")
}

func main() {
    var client = amps.NewClient("failover-demo")

    /*
     In our disconnect handler, we invoke connectToNextURI(),
     with the next URI in our array of URIs and display
     a warning message. This simplistic handler never gives up,
     but in a typical implementation, you would likely stop
     attempting to reconnect at some point.
    */
    client.SetDisconnectHandler(func(cl *amps.Client, err error) {
        fmt.Println("Switching to the next URI...")

        currentURI = (currentURI + 1) % len(uris);
        connectToNextURI(client, uris[currentURI]);
    })

    // We begin by connecting to the first URI
    connectToNextURI(client, uris[currentURI]);
}

Query the Contents of a SOW Topic

State-of-the-World ("SOW") topics in AMPS combine the power of a database table with the performance of a publish-subscribe system. Use the AMPS Go client to query the contents of a SOW topic:

package main

import (
    "amps"
    "fmt"
)

func main() {
    client := amps.NewClient("my-application")

    err := client.Connect("tcp://localhost:9000/amps/json")
    if err != nil { fmt.Println(err); return }

    err = client.Logon()
    if err != nil { fmt.Println(err); return }

    _, err := client.Sow(func(message *amps.Message) (msgErr error) {
        if command, _ := message.Command(); command == amps.CommandSOW {
            // Print the message data
            fmt.Println(string(message.Data()))
        }
        return
    }, "orders", "/symbol = 'ROL'")

    if err != nil { fmt.Println("SOW Query Error:", err); return }
}

Command Interface

Even though AMPS clients provide the above named convenience methods for core AMPS functionality, you can use the Command object to customize the messages that AMPS sends. This is useful for more advanced scenarios where you need precise control over the command, or in cases where you need to use an earlier version of the client to communicate with a more recent version of AMPS, or in cases where a named method is not available.

package main

import (
    "amps"
    "fmt"
)

func main() {
    client := amps.NewClient("my-application")

    err := client.Connect("tcp://localhost:9001/amps/json")
    if err != nil { fmt.Println(err); return }

    err = client.Logon()
    if err != nil { fmt.Println(err); return }

    var subscribeCommand = amps.NewCommand("subscribe").SetTopic("messages").SetFilter("/id > 20")

    _, err = client.ExecuteAsync(subscribeCommand, func(message *amps.Message) (msgErr error) {
        // Print the message data
        fmt.Println(string(message.Data()))
        return
    })

    if err != nil { fmt.Println("Subscribe Error:", err); return }
}

This example provides the subscription to a 'messages' topic with a filter applied.

Everything You Need

If you need more help getting started, the 60East Technologies support and services team is ready to provide the support you need to help you CRANK UP THE AMPS.

Index ▾

Constants
func NewError(errorCode int, message ...interface{}) error
type Authenticator
type Client
    func NewClient(clientName ...string) *Client
    func (client *Client) ClientName() string
    func (client *Client) Close() error
    func (client *Client) Connect(uri string) error
    func (client *Client) DeltaPublish(topic string, data string, expiration ...uint) error
    func (client *Client) DeltaPublishBytes(topic string, data []byte, expiration ...uint) error
    func (client *Client) DeltaSubscribe(topic string, filter ...string) (*MessageStream, error)
    func (client *Client) DeltaSubscribeAsync(messageHandler func(*Message) error, topic string, filter ...string) (string, error)
    func (client *Client) Disconnect() (err error)
    func (client *Client) DisconnectHandler() func(*Client, error)
    func (client *Client) ErrorHandler() func(error)
    func (client *Client) Execute(command *Command) (*MessageStream, error)
    func (client *Client) ExecuteAsync(command *Command, messageHandler func(message *Message) error) (string, error)
    func (client *Client) Flush() (err error)
    func (client *Client) Logon(optionalParams ...LogonParams) (err error)
    func (client *Client) LogonCorrelationID() string
    func (client *Client) Publish(topic string, data string, expiration ...uint) error
    func (client *Client) PublishBytes(topic string, data []byte, expiration ...uint) error
    func (client *Client) ServerVersion() string
    func (client *Client) SetClientName(clientName string) *Client
    func (client *Client) SetDisconnectHandler(disconnectHandler func(*Client, error)) *Client
    func (client *Client) SetErrorHandler(errorHandler func(error)) *Client
    func (client *Client) SetHeartbeat(interval uint, providedTimeout ...uint) *Client
    func (client *Client) SetLogonCorrelationID(logonCorrelationID string) *Client
    func (client *Client) SetTLSConfig(config *tls.Config) *Client
    func (client *Client) Sow(topic string, filter ...string) (*MessageStream, error)
    func (client *Client) SowAndDeltaSubscribe(topic string, filter ...string) (*MessageStream, error)
    func (client *Client) SowAndDeltaSubscribeAsync(messageHandler func(*Message) error, topic string, filter ...string) (string, error)
    func (client *Client) SowAndSubscribe(topic string, filter ...string) (*MessageStream, error)
    func (client *Client) SowAndSubscribeAsync(messageHandler func(*Message) error, topic string, filter ...string) (string, error)
    func (client *Client) SowAsync(messageHandler func(*Message) error, topic string, filter ...string) (string, error)
    func (client *Client) SowDelete(topic string, filter string) (*Message, error)
    func (client *Client) SowDeleteByData(topic string, data []byte) (*Message, error)
    func (client *Client) SowDeleteByKeys(topic string, keys string) (*Message, error)
    func (client *Client) Subscribe(topic string, filter ...string) (*MessageStream, error)
    func (client *Client) SubscribeAsync(messageHandler func(*Message) error, topic string, filter ...string) (string, error)
    func (client *Client) Unsubscribe(subID ...string) error
type Command
    func NewCommand(commandName string) *Command
    func (com *Command) AckType() (int, bool)
    func (com *Command) AddAckType(ackType int) *Command
    func (com *Command) BatchSize() (uint, bool)
    func (com *Command) Bookmark() (string, bool)
    func (com *Command) Command() (string, bool)
    func (com *Command) CommandID() (string, bool)
    func (com *Command) CorrelationID() (string, bool)
    func (com *Command) Data() []byte
    func (com *Command) Expiration() (uint, bool)
    func (com *Command) Filter() (string, bool)
    func (com *Command) Options() (string, bool)
    func (com *Command) OrderBy() (string, bool)
    func (com *Command) QueryID() (string, bool)
    func (com *Command) SequenceID() (uint64, bool)
    func (com *Command) SetAckType(ackType int) *Command
    func (com *Command) SetBatchSize(batchSize uint) *Command
    func (com *Command) SetBookmark(bookmark string) *Command
    func (com *Command) SetCommand(command string) *Command
    func (com *Command) SetCommandID(commandID string) *Command
    func (com *Command) SetCorrelationID(correlationID string) *Command
    func (com *Command) SetData(data []byte) *Command
    func (com *Command) SetExpiration(expiration uint) *Command
    func (com *Command) SetFilter(filter string) *Command
    func (com *Command) SetOptions(options string) *Command
    func (com *Command) SetOrderBy(orderBy string) *Command
    func (com *Command) SetQueryID(queryID string) *Command
    func (com *Command) SetSequenceID(sequenceID uint64) *Command
    func (com *Command) SetSowKey(sowKey string) *Command
    func (com *Command) SetSowKeys(sowKeys string) *Command
    func (com *Command) SetSubID(subID string) *Command
    func (com *Command) SetSubIDs(subIDs string) *Command
    func (com *Command) SetTopN(topN uint) *Command
    func (com *Command) SetTopic(topic string) *Command
    func (com *Command) SowKey() (string, bool)
    func (com *Command) SowKeys() (string, bool)
    func (com *Command) SubID() (string, bool)
    func (com *Command) SubIDs() (string, bool)
    func (com *Command) TopN() (uint, bool)
    func (com *Command) Topic() (string, bool)
type CompositeMessageBuilder
    func NewCompositeMessageBuilder() *CompositeMessageBuilder
    func (cmb *CompositeMessageBuilder) Append(data string) error
    func (cmb *CompositeMessageBuilder) AppendBytes(data []byte, offset int, length int) error
    func (cmb *CompositeMessageBuilder) Clear()
    func (cmb *CompositeMessageBuilder) GetBytes() []byte
    func (cmb *CompositeMessageBuilder) GetData() string
type CompositeMessageParser
    func NewCompositeMessageParser() *CompositeMessageParser
    func (cmp *CompositeMessageParser) Parse(data []byte) (int, error)
    func (cmp *CompositeMessageParser) ParseMessage(message *Message) (int, error)
    func (cmp *CompositeMessageParser) Part(index int) ([]byte, error)
    func (cmp *CompositeMessageParser) Size() int
type FixMessageBuilder
    func NewFIXBuilder(fieldSep ...byte) *FixMessageBuilder
    func (fmb *FixMessageBuilder) Append(tag int, value string) error
    func (fmb *FixMessageBuilder) AppendBytes(tag int, value []byte, offset int, length int) error
    func (fmb *FixMessageBuilder) Bytes() []byte
    func (fmb *FixMessageBuilder) Clear()
    func (fmb *FixMessageBuilder) Data() string
    func (fmb *FixMessageBuilder) Size() int
type FixMessageShredder
    func NewFIXShredder(fieldSep ...byte) *FixMessageShredder
    func (fms *FixMessageShredder) ToMap(fix []byte) map[int]string
type LogonParams
type Message
    func (msg *Message) AckType() (int, bool)
    func (msg *Message) BatchSize() (uint, bool)
    func (msg *Message) Bookmark() (string, bool)
    func (msg *Message) Command() (int, bool)
    func (msg *Message) CommandID() (string, bool)
    func (msg *Message) Copy() *Message
    func (msg *Message) CorrelationID() (string, bool)
    func (msg *Message) Data() []byte
    func (msg *Message) Expiration() (uint, bool)
    func (msg *Message) Filter() (string, bool)
    func (msg *Message) GroupSequenceNumber() (uint, bool)
    func (msg *Message) LeasePeriod() (string, bool)
    func (msg *Message) Matches() (uint, bool)
    func (msg *Message) MessageLength() (uint, bool)
    func (msg *Message) Options() (string, bool)
    func (msg *Message) OrderBy() (string, bool)
    func (msg *Message) QueryID() (string, bool)
    func (msg *Message) Reason() (string, bool)
    func (msg *Message) RecordsDeleted() (uint, bool)
    func (msg *Message) RecordsInserted() (uint, bool)
    func (msg *Message) RecordsReturned() (uint, bool)
    func (msg *Message) RecordsUpdated() (uint, bool)
    func (msg *Message) SequenceID() (uint64, bool)
    func (msg *Message) SowKey() (string, bool)
    func (msg *Message) SowKeys() (string, bool)
    func (msg *Message) Status() (string, bool)
    func (msg *Message) SubID() (string, bool)
    func (msg *Message) SubIDs() (string, bool)
    func (msg *Message) Timestamp() (string, bool)
    func (msg *Message) TopN() (uint, bool)
    func (msg *Message) Topic() (string, bool)
    func (msg *Message) TopicMatches() (uint, bool)
    func (msg *Message) UserID() (string, bool)
type MessageRoute
type MessageRouter
    func (msgRouter *MessageRouter) AddRoute(commandID string, messageHandler func(*Message) error, requestedAcks int, systemAcks int, isSubscribe bool, isReplace bool)
    func (msgRouter *MessageRouter) Clear()
    func (msgRouter *MessageRouter) DeliverAck(ackMessage *Message, ackType int) int
    func (msgRouter *MessageRouter) DeliverData(dataMessage *Message) int
    func (msgRouter *MessageRouter) DeliverDataWithID(dataMessage *Message, cmdID string) int
    func (msgRouter *MessageRouter) FindRoute(commandID string) func(*Message) error
    func (msgRouter *MessageRouter) RemoveRoute(commandID string)
    func (msgRouter *MessageRouter) UnsubscribeAll()
type MessageStream
    func (ms *MessageStream) Close() (err error)
    func (ms *MessageStream) Conflate()
    func (ms *MessageStream) Depth() uint64
    func (ms *MessageStream) HasNext() bool
    func (ms *MessageStream) MaxDepth() uint64
    func (ms *MessageStream) Next() (message *Message)
    func (ms *MessageStream) SetMaxDepth(depth uint64) *MessageStream
    func (ms *MessageStream) SetTimeout(timeout uint64) *MessageStream
    func (ms *MessageStream) Timeout() uint64
type NvfixMessageBuilder
    func NewNVFIXBuilder(fieldSep ...byte) *NvfixMessageBuilder
    func (nmb *NvfixMessageBuilder) AppendBytes(tag []byte, value []byte, valOffset int, valLength int) error
    func (nmb *NvfixMessageBuilder) AppendStrings(tag string, value string) error
    func (nmb *NvfixMessageBuilder) Bytes() []byte
    func (nmb *NvfixMessageBuilder) Clear()
    func (nmb *NvfixMessageBuilder) Data() string
    func (nmb *NvfixMessageBuilder) Size() int
type NvfixMessageShredder
    func NewNVFIXShredder(fieldSep ...byte) *NvfixMessageShredder
    func (nfs *NvfixMessageShredder) ToMap(nvfix []byte) map[string]string

Package files

authenticator.go client.go command.go composite_message_builder.go composite_message_parser.go errors.go fix_builder.go fix_shredder.go header.go message.go message_router.go message_stream.go nvfix_builder.go nvfix_shredder.go

Constants

Client constants

const (
    ClientVersion = "9.9.9.9.999999.fffff:golang"

    // Bookmarks
    BookmarksEPOCH  = "0"
    BookmarksRECENT = "recent"
    BookmarksNOW    = "1|0|"

    // Acks
    AckTypeNone      = 0
    AckTypeReceived  = 1
    AckTypeParsed    = 2
    AckTypeProcessed = 4
    AckTypePersisted = 8
    AckTypeCompleted = 16
    AckTypeStats     = 32
)

Command Types

const (
    CommandAck = iota
    CommandDeltaPublish
    CommandDeltaSubscribe
    CommandFlush
    CommandGroupBegin
    CommandGroupEnd

    CommandOOF
    CommandPublish
    CommandSOW
    CommandSOWAndDeltaSubscribe
    CommandSOWAndSubscribe
    CommandSOWDelete

    CommandSubscribe
    CommandUnsubscribe
    CommandUnknown
)

AMPS Error constants

const (
    // AlreadyConnectedError - Connect() is called while there is already an active connection to AMPS.
    AlreadyConnectedError = iota

    // AuthenticationError - returned when the authentication was unsuccessful
    AuthenticationError

    // BadFilterError - returned when the AMPS server reports that a filter could not be successfully processed.
    BadFilterError

    // BadRegexTopicError - returned when the AMPS server reports that the regex provided as the topic for a
    // subscription or query could not be processed. This most often indicates a syntax error in the regular expression.
    BadRegexTopicError

    // CommandError - returned when an error occurs in an AMPS command.
    CommandError

    // ConnectionError - returned when a general connection error occurred.
    ConnectionError

    // ConnectionRefusedError - returned when the server is not available or refused to establish the connection.
    ConnectionRefusedError

    // DisconnectedError - returned when the client is not connected while attempting to perform an action
    // that requires a working connection.
    DisconnectedError

    // ProtocolError - returned when a general AMPS protocol error occurred.
    ProtocolError

    // InvalidTopicError - returned when the AMPS server reports that the command requested is not valid for the topic
    // specified.
    InvalidTopicError

    // InvalidURIError - returned when the provided URI is not valid.
    InvalidURIError

    // NotEntitledError - returned when the provided username is not entitled to perform the action.
    NotEntitledError

    // RetryOperationError - returned when the attempt to retry to connect to AMPS using an Authenticator has failed.
    RetryOperationError

    // SubidInUseError - returned when the specified subscription ID is already in use for this client.
    SubidInUseError

    // SubscriptionAlreadyExistsError - returned when a client attempts to register a subscription that already exists.
    SubscriptionAlreadyExistsError

    // TimedOutError - returned when the time out occurs before getting the result of an action.
    TimedOutError

    // MessageHandlerError - returned when the message hander returned an error after processing the message.
    MessageHandlerError

    // UnknownError -  when AMPS reports an error of an unknown type, for example, when running an older version of
    // the AMPS Go client against a more recent version of AMPS.
    UnknownError
)

func NewError

func NewError(errorCode int, message ...interface{}) error

NewError generates a new AMPS error, with optional description.

type Authenticator

The Authenticator interface is used by the client during the logging on. It provides the authentication for custom authentication scenarios when external actions are required before logging on.

Methods:

Authenticate(username string, password string) (string, error)

Authenticate() is called by the Client, just before the logon command is sent. Returns the value that should be placed into the Password header for the logon attempt will be passed, and the error object (nil by default) with information about the error occurred while executing the method.

Retry(username string, password string) (string, error)

Retry() is called when a logon "ack" is received with a status of "retry". AMPS will continue trying to logon as long as the server returns "retry", and this method continues to succeed. Returns the value that should be placed into the Password header for the logon attempt will be passed, and the error object (nil by default) with information about the error occurred while executing the method.

Completed(username string, password string, reason string)

Completed() is called when a logon completes successfully. Once a logon has completed, this method is called with the username and password that caused a successful logon, and optionally, with the reason for this successful completion.

type Authenticator interface {
    Authenticate(username string, password string) (string, error)
    Retry(username string, password string) (string, error)
    Completed(username string, password string, reason string)
}

type Client

Client struct

type Client struct {
    // contains filtered or unexported fields
}

func NewClient

func NewClient(clientName ...string) *Client

NewClient creates a new Client object and returns it.

Arguments:

clientName [string] (optional)

The client name is the optional parameter. Unique name for the client is required (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.

func (*Client) ClientName

func (client *Client) ClientName() string

ClientName is a getter for the client's name. If logon has not been performed yet and the name was not set, returns the empty string.

func (*Client) Close

func (client *Client) Close() error

Close disconnects the client from an AMPS server (if the connection existed).

func (*Client) Connect

func (client *Client) Connect(uri string) error

Connect connects the AMPS client to the server using the URI containing all required credentials/addresses/types. After successful connection, the Logon() method must be called, unless the implicit logon is enabled on the server.

func (*Client) DeltaPublish

func (client *Client) DeltaPublish(topic string, data string, expiration ...uint) error

DeltaPublish delta publishes a message to a SOW topic:

client.DeltaPublish("topic", "{\"id\": 1, \"text\": \"Hello, World\"}");

For regular topics, DeltaPublish() behaves like regular Publish().

Arguments:

topic [string] - The topic to publish data.

data [string] - The data to publish to a topic.

expiration [uint] (optional) - An optional parameter that sets the expiration value on the message (for SOW topics with expiration enabled).

func (*Client) DeltaPublishBytes

func (client *Client) DeltaPublishBytes(topic string, data []byte, expiration ...uint) error

DeltaPublishBytes is the same as DeltaPublish() but is more optimized for Go's native parsing libraries which almost exclusively utilize slices of bytes ([]byte) as the output format.

func (*Client) DeltaSubscribe

func (client *Client) DeltaSubscribe(topic string, filter ...string) (*MessageStream, error)

DeltaSubscribe is the synchronous version of the DeltaSubscribeAsync() method that returns the MessageStream object which can be iterated over in a for loop. Executed in the main thread context.

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.

Example:

messages, err := client.DeltaSubscribe("orders", "/id > 20")
if err != nil { fmt.Println(err); return }

for message := messages.Next(); message != nil; message = messages.Next() {
    fmt.Println("Message Data:", string(message.Data()))
}

Arguments:

topic [string] - The topic argument in SOW.

filter [string] (optional) - An optional content filter value.

func (*Client) DeltaSubscribeAsync

func (client *Client) DeltaSubscribeAsync(messageHandler func(*Message) error, topic string, filter ...string) (string, error)

DeltaSubscribeAsync 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.

Example:

subID, err := client.DeltaSubscribeAsync(func(message *amps.Message) error {
	fmt.Println("Message Data:", string(message.Data()))
	return nil
}, "orders")

Arguments:

messageHandler [func(*Message) error] - The message handler that will be called each time a message is received. Message handler is called from the background thread context.

topic [string] - The topic argument in SOW.

filter [string] (optional) - An optional content filter value.

func (*Client) Disconnect

func (client *Client) Disconnect() (err error)

Disconnect disconnects the client from an AMPS server (if the connection existed). Same as Close()

func (*Client) DisconnectHandler

func (client *Client) DisconnectHandler() func(*Client, error)

DisconnectHandler gets the disconnect handler that is called in case of an unintentional disconnection.

func (*Client) ErrorHandler

func (client *Client) ErrorHandler() func(error)

ErrorHandler gets the error handler for all general errors such as connection issues, exceptions, etc.

func (*Client) Execute

func (client *Client) Execute(command *Command) (*MessageStream, error)

Execute is the synchronous version of the ExecuteAsync() method which returns the MessageStream object to iterate over in a for loop. Iteration occurs in the main thread context.

Example:

messages, err := client.Execute(amps.NewCommand("sow").SetTopic("orders"))
if err != nil { fmt.Println(err); return }

for message := messages.Next(); message != nil; message = messages.Next() {
    fmt.Println("Message Data:", string(message.Data()))
}

Arguments:

command [*Command] - the Command object that will be executed, resulting in a MessageStream object.

func (*Client) ExecuteAsync

func (client *Client) ExecuteAsync(command *Command, messageHandler func(message *Message) error) (string, error)

ExecuteAsync 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.

Example:

cmdID, err := client.ExecuteAsync(amps.NewCommand("sow").SetTopic("orders"), func(message *amps.Message) error {
	fmt.Println("Message Data:", string(message.Data()))
	return nil
})

Arguments:

command [*Command] - A command object to execute.

messageHandler [func(*Message) error] (optional) - The message handler that will be called each time a message is received. Message handler is called from the background thread context. If no message handler is needed, provide nil as the second argument.

func (*Client) Flush

func (client *Client) Flush() (err error)

Flush ...

func (*Client) Logon

func (client *Client) Logon(optionalParams ...LogonParams) (err error)

Logon logs into AMPS with the parameters provided in the connect method, if any, that is set. Optional parameters can be supplied using the LogonParams struct, such as Timeout, Authenticator, and logon CorrelationID.

func (*Client) LogonCorrelationID

func (client *Client) LogonCorrelationID() string

LogonCorrelationID gets the uninterpreted logon correlation information a client sends at logon to aid in searching server log files for specific clients. If it was not set, returns the empty string.

func (*Client) Publish

func (client *Client) Publish(topic string, data string, expiration ...uint) error

Publish method performs the publish command. The publish command is the primary way to inject messages into the AMPS processing stream. A publish command received by AMPS will be forwarded to other connected clients with matching subscriptions.

Example:

client.Publish("topic", "{\"id\": 1}")

Arguments:

topic [string] - The topic to publish data.

data [string] - The data to publish to a topic.

expiration [uint] (optional) - An optional parameter that sets the expiration value on the message (for SOW topics with expiration enabled).

func (*Client) PublishBytes

func (client *Client) PublishBytes(topic string, data []byte, expiration ...uint) error

PublishBytes is the same as Publish() but is more optimized for Go's native parsing libraries which almost exclusively utilize slices of bytes ([]byte) as the output format.

func (*Client) ServerVersion

func (client *Client) ServerVersion() string

ServerVersion returns the server version returned by the AMPS server in the logon acknowledgement. If logon has not been performed yet, returns an empty string.

func (*Client) SetClientName

func (client *Client) SetClientName(clientName string) *Client

SetClientName is a setter for the client's name.

func (*Client) SetDisconnectHandler

func (client *Client) SetDisconnectHandler(disconnectHandler func(*Client, error)) *Client

SetDisconnectHandler sets the disconnect handler that is called in case of an unintentional disconnection.

Example:

client.SetDisconnectHandler(func(cl *amps.Client, err error) {
    fmt.Println("Switching to the next URI...")
    connectToNextURI(client);
})

func (*Client) SetErrorHandler

func (client *Client) SetErrorHandler(errorHandler func(error)) *Client

SetErrorHandler sets the error handler for all general errors such as connection issues, exceptions, etc.

Example:

client.SetErrorHandler(func(err error) {
    fmt.Println(time.Now().Local().String() + " [" + client.ClientName() + "] >>>", err)
})

func (*Client) SetHeartbeat

func (client *Client) SetHeartbeat(interval uint, providedTimeout ...uint) *Client

SetHeartbeat ...

func (*Client) SetLogonCorrelationID

func (client *Client) SetLogonCorrelationID(logonCorrelationID string) *Client

SetLogonCorrelationID sets the uninterpreted logon correlation information a client sends at logon to aid in searching server log files for specific clients. Can also be set in the LogonParams object supplied to the Logon() method.

func (*Client) SetTLSConfig

func (client *Client) SetTLSConfig(config *tls.Config) *Client

SetTLSConfig is an optional setter for the secure TCP connection configuration parameters, such as Certificates. It must be set before the Connect() and Logon() methods are called. This configuration, is ignored if connecting to a standard non-secure TCP transport.

Example:

  client.SetTLSConfig(&tls.Config{
		InsecureSkipVerify: true,
	 })

func (*Client) Sow

func (client *Client) Sow(topic string, filter ...string) (*MessageStream, error)

Sow is the synchronous version of the SowAsync() method that returns the MessageStream object which can be iterated over in a for loop. Executed in the main thread context.

The sow command is used 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.

Example:

messages, err := client.Sow("orders", "/id > 20")
if err != nil { fmt.Println(err); return }

for message := messages.Next(); message != nil; message = messages.Next() {
    fmt.Println("Message Data:", string(message.Data()))
}

Arguments:

topic [string] - The topic argument in SOW.

filter [string] (optional) - An optional content filter value.

func (*Client) SowAndDeltaSubscribe

func (client *Client) SowAndDeltaSubscribe(topic string, filter ...string) (*MessageStream, error)

SowAndDeltaSubscribe is the synchronous version of the SowAndDeltaSubscribeAsync() method that returns the MessageStream object which can be iterated over in a for loop. Executed in the main thread context.

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:

- to query the contents of a SOW topic (this is the sow command); and

- to place a subscription such that any messages matching the subscribed SOW topic and query filter will be published to the AMPS client (this is the delta_subscribe command).

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.

Example:

messages, err := client.SowAndDeltaSubscribe("orders", "/id > 20")
if err != nil { fmt.Println(err); return }

for message := messages.Next(); message != nil; message = messages.Next() {
    fmt.Println("Message Data:", string(message.Data()))
}

Arguments:

topic [string] - The topic argument in SOW.

filter [string] (optional) - An optional content filter value.

func (*Client) SowAndDeltaSubscribeAsync

func (client *Client) SowAndDeltaSubscribeAsync(messageHandler func(*Message) error, topic string, filter ...string) (string, error)

SowAndDeltaSubscribeAsync 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:

- to query the contents of a SOW topic (this is the sow command); and

- to place a subscription such that any messages matching the subscribed SOW topic and query filter will be published to the AMPS client (this is the delta_subscribe command).

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.

Example:

subID, err := client.SowAndDeltaSubscribeAsync(func(message *amps.Message) error {
	fmt.Println("Message Data:", string(message.Data()))
	return nil
}, "orders")

Arguments:

messageHandler [func(*Message) error] - The message handler that will be called each time a message is received. Message handler is called from the background thread context.

topic [string] - The topic argument in SOW.

filter [string] (optional) - An optional content filter value.

func (*Client) SowAndSubscribe

func (client *Client) SowAndSubscribe(topic string, filter ...string) (*MessageStream, error)

SowAndSubscribe is the synchronous version of the SowAndSubscribeAsync() method that returns the MessageStream object which can be iterated over in a for loop. Executed in the main thread context.

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:

- to query the contents of a SOW topic (this is the sow command); and

- to place a subscription such that any messages matching the subscribed SOW topic and query filter will be published to the AMPS client (this is the subscribe command).

As with the subscribe command, publish messages representing updates to SOW records will contain only information that has changed.

Example:

messages, err := client.SowAndSubscribe("orders", "/id > 20")
if err != nil { fmt.Println(err); return }

for message := messages.Next(); message != nil; message = messages.Next() {
    fmt.Println("Message Data:", string(message.Data()))
}

Arguments:

topic [string] - The topic argument in SOW.

filter [string] (optional) - An optional content filter value.

func (*Client) SowAndSubscribeAsync

func (client *Client) SowAndSubscribeAsync(messageHandler func(*Message) error, topic string, filter ...string) (string, error)

SowAndSubscribeAsync 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:

- to query the contents of a SOW topic (this is the sow command); and

- to place a subscription such that any messages matching the subscribed SOW topic and query filter will be published to the AMPS client (this is the subscribe command).

As with the subscribe command, publish messages representing updates to SOW records will contain only information that has changed.

Example:

subID, err := client.SowAndSubscribeAsync(func(message *amps.Message) error {
	fmt.Println("Message Data:", string(message.Data()))
	return nil
}, "orders")

Arguments:

messageHandler [func(*Message) error] - The message handler that will be called each time a message is received. Message handler is called from the background thread context.

topic [string] - The topic argument in SOW.

filter [string] (optional) - An optional content filter value.

func (*Client) SowAsync

func (client *Client) SowAsync(messageHandler func(*Message) error, topic string, filter ...string) (string, error)

SowAsync performs the sow command. The sow command is used 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.

Example:

subID, err := client.SowAsync(func(message *amps.Message) error {
	fmt.Println("Message Data:", string(message.Data()))
	return nil
}, "orders")

Arguments:

messageHandler [func(*Message) error] - The message handler that will be called each time a message is received. Message handler is called from the background thread context.

topic [string] - The topic argument in SOW.

filter [string] (optional) - An optional content filter value.

func (*Client) SowDelete

func (client *Client) SowDelete(topic string, filter string) (*Message, error)

SowDelete executes a SOW delete with a filter.

Example:

stats, err := client.SowDelete("orders", "1=1")
if err != nil { ... }

fmt.Println(stats.AckType())
fmt.Println(stats.Status())

Arguments:

topic [string] - The topic to execute the SOW delete against.

filter [string] - The filter. To delete all records, set a filter that is always true: "1 = 1"

Returns the stats message in case of success, error as the second argument otherwise.

func (*Client) SowDeleteByData

func (client *Client) SowDeleteByData(topic string, data []byte) (*Message, error)

SowDeleteByData deletes a message from a SOW, using data supplied to locate a SOW entry with matching keys.

Example:

topic, _ := message.Topic()

stats, err := client.SowDeleteByData(topic, message.Data())
if err != nil { ... }

fmt.Println(stats.AckType())
fmt.Println(stats.Status())

Arguments:

topic [string] - The topic to execute the SOW delete against.

data [[]byte] - The message data whose keys match the message to be deleted in the server’s SOW.

Returns the stats message in case of success, error as the second argument otherwise.

func (*Client) SowDeleteByKeys

func (client *Client) SowDeleteByKeys(topic string, keys string) (*Message, error)

SowDeleteByKeys 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.

Example:

topic, _ := sowMessage1.Topic()
firstMessageKey, _ := sowMessage1.SowKey()
secondMessageKey, _ := sowMessage2.SowKey()

stats, err := client.SowDeleteByKeys(topic, firstMessageKey + "," + secondMessageKey)
if err != nil { ... }

fmt.Println(stats.AckType())
fmt.Println(stats.Status())

Arguments:

topic [string] - The topic to execute the SOW delete against.

keys [string] - 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.

Returns the stats message in case of success, error as the second argument otherwise.

func (*Client) Subscribe

func (client *Client) Subscribe(topic string, filter ...string) (*MessageStream, error)

Subscribe is the synchronous version of the SubscribeAsync() method that returns the MessageStream object which can be iterated over in a for loop. Executed in the main thread context.

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.

Example:

messages, err := client.Subscribe("invoices", "/price > 10000")
if err != nil { fmt.Println(err); return }

for message := messages.Next(); message != nil; message = messages.Next() {
    fmt.Println("Message Data:", string(message.Data()))
}

Arguments:

topic [string] - The topic argument.

filter [string] (optional) - An optional content filter value.

func (*Client) SubscribeAsync

func (client *Client) SubscribeAsync(messageHandler func(*Message) error, topic string, filter ...string) (string, error)

SubscribeAsync 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.

Example:

subID, err := client.SubscribeAsync(func(message *amps.Message) error {
	fmt.Println("Message Data:", string(message.Data()))
	return nil
}, "invoices", "/price < 10000")

Arguments:

messageHandler [func(*Message) error] - The message handler that will be called each time a message is received. Message handler is called from the background thread context.

topic [string] - The topic argument.

filter [string] (optional) - An optional content filter value.

func (*Client) Unsubscribe

func (client *Client) Unsubscribe(subID ...string) error

Unsubscribe performs the unsubscribe command. The unsubscribe command unsubscribes the client from the topic which messages the client is is no more interested in receiving. If the subID is not provided, the client will unsubscribe from all subscriptions.

Arguments:

subID [string] (optional) - The id of the subscription to unsubscribe from. If not provided, the client will unsubscribe from all subscriptions.

type Command

Command class encapsulates the AMPS Command entity. The Go client sends Command objects to the server and receives Message objects from the server.

type Command struct {
    // contains filtered or unexported fields
}

func NewCommand

func NewCommand(commandName string) *Command

NewCommand creates a new Command object and returns it.

Arguments:

commandName [string] - a type of the command to be created. It can be on of the following:

- publish

- delta_publish

- subscribe

- delta_subscribe

- sow

- sow_and_subscribe

- sow_and_delta_subscribe

- sow_delete

- unsubscribe

func (*Command) AckType

func (com *Command) AckType() (int, bool)

AckType is the getter for the acknowledgement message type(s) requested by the command. Acknowledgement types can be detected using the bitwise AND and OR operators:

if ackType, _ := command.AckType(); (ackType & amps.AckTypeCompleted) > 0 { ... }

// or, to check if there are multiple acks set, the bitwise OR can be used as well:
if ackType, _ := command.AckType(); (ackType & (amps.AckTypeProcessed | amps.AckTypeCompleted)) > 0 { ... }

The second returned parameter is set to true if the value exists, false otherwise.

func (*Command) AddAckType

func (com *Command) AddAckType(ackType int) *Command

AddAckType adds the ack(s) to the list of the acknowledgements requested for the command. Multiple ack types can be combined using bitwise OR:

command.AddAckType(AckTypeProcessed | AckTypeCompleted)

The acknowledgement messages will be delivered to the message handler / message stream.

Returns the Command object, allowing combining several setters into a chain.

func (*Command) BatchSize

func (com *Command) BatchSize() (uint, bool)

BatchSize returns the batch size value -- the number of messages that are batched together when returning a query result.

The second returned parameter is set to true if the value exists, false otherwise.

func (*Command) Bookmark

func (com *Command) Bookmark() (string, bool)

Bookmark returns the bookmark value -- the client-originated identifier used to mark a location in journaled messages.

The second returned parameter is set to true if the value exists, false otherwise.

func (*Command) Command

func (com *Command) Command() (string, bool)

Command returns the command type e.g. 'publish', 'sow_and_subscribe', to be executed.

The second returned parameter is set to true if the value exists, false otherwise.

func (*Command) CommandID

func (com *Command) CommandID() (string, bool)

CommandID returns the Client-specified command id. The command id is returned by the engine in responses to commands to allow the client to correlate the response to the command.

The second returned parameter is set to true if the value exists, false otherwise.

func (*Command) CorrelationID

func (com *Command) CorrelationID() (string, bool)

CorrelationID returns the correlation id value, if any.

The second returned parameter is set to true if the value exists, false otherwise.

func (*Command) Data

func (com *Command) Data() []byte

Data returns the Command data (message payload). Only publish, delta_publish, and sow_delete commands can have a payload.

func (*Command) Expiration

func (com *Command) Expiration() (uint, bool)

Expiration returns the SOW expiration time (in seconds) if used in publish.

The second returned parameter is set to true if the value exists, false otherwise.

func (*Command) Filter

func (com *Command) Filter() (string, bool)

Filter returns the content filter expression.

The second returned parameter is set to true if the value exists, false otherwise.

func (*Command) Options

func (com *Command) Options() (string, bool)

Options returns the (comma-delimited) string of options on a specific Command.

The second returned parameter is set to true if the value exists, false otherwise.

func (*Command) OrderBy

func (com *Command) OrderBy() (string, bool)

OrderBy returns the SOW topic key(s) by which to order SOW query.

The second returned parameter is set to true if the value exists, false otherwise.

func (*Command) QueryID

func (com *Command) QueryID() (string, bool)

QueryID returns the SOW Query identifier set by client to identify a query.

The second returned parameter is set to true if the value exists, false otherwise.

func (*Command) SequenceID

func (com *Command) SequenceID() (uint64, bool)

SequenceID returns the sequence id value. Sequence id is an integer that corresponds to the publish message sequence number. For more information see the Replication section in the User Guide.

The second returned parameter is set to true if the value exists, false otherwise.

func (*Command) SetAckType

func (com *Command) SetAckType(ackType int) *Command

SetAckType sets the acknowledgements requested for the command. Multiple ack types can be combined using bitwise OR:

command.SetAckType(AckTypeProcessed | AckTypeCompleted)

The acknowledgement messages will be delivered to the message handler / message stream.

Returns the Command object, allowing combining several setters into a chain.

func (*Command) SetBatchSize

func (com *Command) SetBatchSize(batchSize uint) *Command

SetBatchSize sets the number of messages that are batched together when returning a SOW query result. If it's not set, it is 10 by default.

Returns the Command object, allowing combining several setters into a chain.

func (*Command) SetBookmark

func (com *Command) SetBookmark(bookmark string) *Command

SetBookmark sets the client-originated identifier used to mark a location in journaled messages.

Returns the Command object, allowing combining several setters into a chain.

func (*Command) SetCommand

func (com *Command) SetCommand(command string) *Command

SetCommand sets the command type e.g. 'publish', 'sow_and_subscribe', to be executed. The following commands are available:

- publish

- delta_publish

- subscribe

- delta_subscribe

- sow

- sow_and_subscribe

- sow_and_delta_subscribe

- sow_delete

- unsubscribe

Returns the Command object, allowing combining several setters into a chain.

func (*Command) SetCommandID

func (com *Command) SetCommandID(commandID string) *Command

SetCommandID sets the Client-specified command id. The command id is returned by the engine in responses to commands to allow the client to correlate the response to the command.

Returns the Command object, allowing combining several setters into a chain.

func (*Command) SetCorrelationID

func (com *Command) SetCorrelationID(correlationID string) *Command

SetCorrelationID sets the opaque token set by an application and returned with the message.

Returns the Command object, allowing combining several setters into a chain.

func (*Command) SetData

func (com *Command) SetData(data []byte) *Command

SetData sets the command data (message payload). Makes sense only for publish, delta_publish, and sow_delete commands.

Returns the Command object, allowing combining several setters into a chain.

func (*Command) SetExpiration

func (com *Command) SetExpiration(expiration uint) *Command

SetExpiration sets the SOW expiration time (in seconds) if used in publish.

Returns the Command object, allowing combining several setters into a chain.

func (*Command) SetFilter

func (com *Command) SetFilter(filter string) *Command

SetFilter sets the content filter expression.

Returns the Command object, allowing combining several setters into a chain.

func (*Command) SetOptions

func (com *Command) SetOptions(options string) *Command

SetOptions sets the (comma-delimited) string of options on a specific Command.

Returns the Command object, allowing combining several setters into a chain.

func (*Command) SetOrderBy

func (com *Command) SetOrderBy(orderBy string) *Command

SetOrderBy sets the SOW topic key(s) by which to order SOW query.

Returns the Command object, allowing combining several setters into a chain.

func (*Command) SetQueryID

func (com *Command) SetQueryID(queryID string) *Command

SetQueryID sets the SOW Query identifier set by client to identify a query.

Returns the Command object, allowing combining several setters into a chain.

func (*Command) SetSequenceID

func (com *Command) SetSequenceID(sequenceID uint64) *Command

SetSequenceID sets the sequence id value. Sequence id is an integer that corresponds to the publish message sequence number. For more information see the Replication section in the User Guide.

Returns the Command object, allowing combining several setters into a chain.

func (*Command) SetSowKey

func (com *Command) SetSowKey(sowKey string) *Command

SetSowKey sets the sow key value. A SOW key will accompany each message returned in an SOW batch. A SOW key may also be added to messages coming in on a subscription when the published message matches a record in the SOW.

Format:

- string containing the digits of an unsigned long for AMPS-generated SOW keys

OR:

- arbitrary string in the base64 character set for user-provided SOW keys.

Returns the Command object, allowing combining several setters into a chain.

func (*Command) SetSowKeys

func (com *Command) SetSowKeys(sowKeys string) *Command

SetSowKeys sets the SOW keys as a comma-delimited value.

Returns the Command object, allowing combining several setters into a chain.

func (*Command) SetSubID

func (com *Command) SetSubID(subID string) *Command

SetSubID sets the subscription identifier set by server when processing a subscription.

Returns the Command object, allowing combining several setters into a chain.

func (*Command) SetSubIDs

func (com *Command) SetSubIDs(subIDs string) *Command

SetSubIDs sets the list of subscription IDs - a comma-separated list of subscription ids sent from AMPS engine to identify which client subscriptions match a given publish message.

Returns the Command object, allowing combining several setters into a chain.

func (*Command) SetTopN

func (com *Command) SetTopN(topN uint) *Command

SetTopN sets the number of records to return.

Note: If TopN is not equally divisible by the BatchSize value, then more records will be returned so that the total number of records is equally divisible by the BatchSize setting.

Returns the Command object, allowing combining several setters into a chain. Deprecated: Provide the "top_n=<value>" value as a part of the `options` field instead.

func (*Command) SetTopic

func (com *Command) SetTopic(topic string) *Command

SetTopic sets the topic value.

Returns the Command object, allowing combining several setters into a chain.

func (*Command) SowKey

func (com *Command) SowKey() (string, bool)

SowKey returns the sow key value. A SOW key will accompany each message returned in an SOW batch. A SOW key may also be added to messages coming in on a subscription when the published message matches a record in the SOW.

Format:

- string containing the digits of an unsigned long for AMPS-generated SOW keys

OR:

- arbitrary string in the base64 character set for user-provided SOW keys.

The second returned parameter is set to true if the value exists, false otherwise.

func (*Command) SowKeys

func (com *Command) SowKeys() (string, bool)

SowKeys returns the SOW keys as a comma-delimited value.

The second returned parameter is set to true if the value exists, false otherwise.

func (*Command) SubID

func (com *Command) SubID() (string, bool)

SubID returns the subscription identifier set by server when processing a subscription.

The second returned parameter is set to true if the value exists, false otherwise.

func (*Command) SubIDs

func (com *Command) SubIDs() (string, bool)

SubIDs returns the list of subscription IDs - a comma-separated list of subscription ids sent from AMPS engine to identify which client subscriptions match a given publish message.

The second returned parameter is set to true if the value exists, false otherwise.

func (*Command) TopN

func (com *Command) TopN() (uint, bool)

TopN returns the number of records to return.

Note: If TopN is not equally divisible by the BatchSize value, then more records will be returned so that the total number of records is equally divisible by the BatchSize setting.

The second returned parameter is set to true if the value exists, false otherwise.

func (*Command) Topic

func (com *Command) Topic() (string, bool)

Topic returns the topic value.

The second returned parameter is set to true if the value exists, false otherwise.

type CompositeMessageBuilder

CompositeMessageBuilder struct

type CompositeMessageBuilder struct {
    // contains filtered or unexported fields
}

func NewCompositeMessageBuilder

func NewCompositeMessageBuilder() *CompositeMessageBuilder

NewCompositeMessageBuilder ...

func (*CompositeMessageBuilder) Append

func (cmb *CompositeMessageBuilder) Append(data string) error

Append appends the given string to the composite message.

Example: json := `{"item":"car","price":20000}` builder := amps.NewCompositeMessageBuilder() builder.Append(json)

client.Publish("test", builder.GetData())

Arguments: data [string] - The string to append to the composite message

func (*CompositeMessageBuilder) AppendBytes

func (cmb *CompositeMessageBuilder) AppendBytes(data []byte, offset int, length int) error

AppendBytes appends the given byte buffer to the composite message.

Example: bin := []byte{0, 1, 2} builder := amps.NewCompositeMessageBuilder() builder.AppendBytes(bin, 0, 3)

client.Publish("test", builder.GetData())

Arguments: data [byte buffer] - The bytes to append to the composite message offset [int] - Location in the buffer where the bytes to append begin length [int] - Length of the buffer

func (*CompositeMessageBuilder) Clear

func (cmb *CompositeMessageBuilder) Clear()

Clear clears the message object.

func (*CompositeMessageBuilder) GetBytes

func (cmb *CompositeMessageBuilder) GetBytes() []byte

GetBytes returns the composite message's data, as a byte array.

Example:

bin := []byte{0, 1, 2} builder := amps.NewCompositeMessageBuilder() builder.AppendBytes(bin, 0, 3)

client.Publish("test", builder.GetBytes())

func (*CompositeMessageBuilder) GetData

func (cmb *CompositeMessageBuilder) GetData() string

GetData returns the composte message's data, as a string. Use this when you want to publish a composite message.

Example: json := `{"item":"car","price":20000}` builder := amps.NewCompositeMessageBuilder() builder.Append(json)

client.Publish("test", builder.GetData())

type CompositeMessageParser

CompositeMessageParser struct

type CompositeMessageParser struct {
    // contains filtered or unexported fields
}

func NewCompositeMessageParser

func NewCompositeMessageParser() *CompositeMessageParser

NewCompositeMessageParser ...

func (*CompositeMessageParser) Parse

func (cmp *CompositeMessageParser) Parse(data []byte) (int, error)

Parse parses a composite AMPS.Message, returns the number of valid parts parsed.

Example: _, err = client.SubscribeAsync(func(message *amps.Message) (msgError error) {

parser := amps.NewCompositeMessageParser()
parts, _ := parser.ParseMessage(message)
for i := 0; i < int(parts); i++ {
    part, _ := parser.Part(i)
    fmt.Println("part", i, string(part))
}

}

Arguments: data [byte buffer] - Byte buffer containing the data to be parsed

func (*CompositeMessageParser) ParseMessage

func (cmp *CompositeMessageParser) ParseMessage(message *Message) (int, error)

ParseMessage parses a composite AMPS.Message, returns the data from the composite message.

Example: _, err = client.SubscribeAsync(func(message *amps.Message) (msgError error) {

parser := amps.NewCompositeMessageParser()
parts, _ := parser.ParseMessage(message)
for i := 0; i < int(parts); i++ {
    part, _ := parser.Part(i)
    fmt.Println("part", i, string(part))
}

}

Arguments: message [*Message] - Message object to parse

func (*CompositeMessageParser) Part

func (cmp *CompositeMessageParser) Part(index int) ([]byte, error)

Part returns the index'th part of the composite message. If the index provided is greater than the size of the part, or if the index is negative, return an "Invalid parts index" error.

Example: _, err = client.SubscribeAsync(func(message *amps.Message) (msgError error) {

parser := amps.NewCompositeMessageParser()
parts, _ := parser.ParseMessage(message)
for i := 0; i < int(parts); i++ {
    part, _ := parser.Part(i)
    fmt.Println("part", i, string(part))
}

}

Arguments: index [int] - The index used to locate a part of the composite message

func (*CompositeMessageParser) Size

func (cmp *CompositeMessageParser) Size() int

Size returns the size of the part parsed from the composite message.

type FixMessageBuilder

FixMessageBuilder struct

type FixMessageBuilder struct {
    // contains filtered or unexported fields
}

func NewFIXBuilder

func NewFIXBuilder(fieldSep ...byte) *FixMessageBuilder

NewFIXBuilder use this method to create a new FIX message.

Example: builder := amps.NewFIXBuilder()

Arguments: fieldSep [byte] (optional) - The default is \x01, a different one can be provided

func (*FixMessageBuilder) Append

func (fmb *FixMessageBuilder) Append(tag int, value string) error

Append appends teh given tag (int) and the value (string) to the FIX message.

Example: value := "This is a value" builder := amps.NewFIXBuilder() builder.Append(1, value)

client.Publish("fix-topic", builder.Data())

Arguments: tag [int] - The int to be the key in the FIX message value [string] - The string to be the value in the FIX message

Returns: Illegal argument error - If the provided tag is negative

func (*FixMessageBuilder) AppendBytes

func (fmb *FixMessageBuilder) AppendBytes(tag int, value []byte, offset int, length int) error

AppendBytes appends the given tag (integer) and value (byte array) to the FIX message.

Example: value := "This is the value" builder := amps.NewFIXMessageBuilder() builder.AppendBytes(1, []byte(value), 0, len(value))

client.Publish("test-topic", builder.Data())

Arguments: tag [int] - The integer to be the key in the FIX message value [byte buffer] - The bytes to be the value in the FIX message offset [int] - Location in the buffer where the bytes to append begin length [int] - Length of the value in the buffer

Returns: Illegal argument error - If the provided tag is negative

func (*FixMessageBuilder) Bytes

func (fmb *FixMessageBuilder) Bytes() []byte

Bytes returns the FIX message, in the form of a byte buffer

func (*FixMessageBuilder) Clear

func (fmb *FixMessageBuilder) Clear()

Clear clears the FIX message

func (*FixMessageBuilder) Data

func (fmb *FixMessageBuilder) Data() string

Data returns the FIX message, in the form of a string

func (*FixMessageBuilder) Size

func (fmb *FixMessageBuilder) Size() int

Size returns the size of the FIX message

type FixMessageShredder

FixMessageShredder struct

type FixMessageShredder struct {
    // contains filtered or unexported fields
}

func NewFIXShredder

func NewFIXShredder(fieldSep ...byte) *FixMessageShredder

NewFIXShredder use this method to parse a FIX message.

Example: shredder := amps.NewFIXShredder()

Arguments: fieldSep [byte] (optional) - The default is \x01, a different one can be provided

func (*FixMessageShredder) ToMap

func (fms *FixMessageShredder) ToMap(fix []byte) map[int]string

ToMap use this method to parse a FIX message.

Example: shredder := amps.NewFIXShredder()

sow, _ := client.Sow("fix-topic") for sow.HasNext() {

message := sow.Next()
fields := shredder.ToMap(message.Data())
for key, value := range fields {
    fmt.Println("key:", key, "value:", value)
}

}

Arguments: fix [byte buffer] - The byte buffer containing the FIX message to be parsed

Returns: map - A map with integer keys and string values

type LogonParams

LogonParams is the struct that can be supplied to the Logon() method of the Client in order to supply an Authenticator object and/or a timeout value and Correlation id. If Timeout is not set or set to 0, there will be no timeout for Logon().

Parameters:

Authenticator [Authenticator] (optional) - The custom Authenticator object to authenticate against.

Timeout [uint] (optional) - The number of milliseconds to wait for AMPS to acknowledge the command, where 0 indicates no timeout.

CorrelationID [string] (optional) - the uninterpreted logon correlation information a client sends at logon to aid in searching server log files for specific clients.

type LogonParams struct {
    Timeout       uint
    Authenticator Authenticator
    CorrelationID string
}

type Message

Message is the AMPS message representation class. Any message received from AMPS is a Message object. Messages have two main components: header and data. Most header properties can be accessed via getters, such as command type, message length, sow key, etc. Message payload can be accessed using the Data() getter method.

Note: Not all messages populate all headers. The Command Reference provides detailed description of the headers returned on specific messages and what they contain

type Message struct {
    // contains filtered or unexported fields
}

func (*Message) AckType

func (msg *Message) AckType() (int, bool)

AckType is the getter for the acknowledgement type of the message. Acknowledgement type can be one of the following:

- amps.AckTypeNone (for all non-ACK messages)

- amps.AckTypeReceived

- amps.AckTypeParsed

- amps.AckTypeProcessed

- amps.AckTypePersisted

- amps.AckTypeCompleted

- amps.AckTypeStats

Example:

if ackType, _ := message.AckType(); ackType == amps.AckTypeCompleted { ... }

The second returned parameter is set to true if the value exists, false otherwise.

func (*Message) BatchSize

func (msg *Message) BatchSize() (uint, bool)

BatchSize returns the batch size value -- the number of messages that are batched together when returning a query result.

The second returned parameter is set to true if the value exists, false otherwise.

func (*Message) Bookmark

func (msg *Message) Bookmark() (string, bool)

Bookmark returns the bookmark value -- the client-originated identifier used to mark a location in journaled messages.

The second returned parameter is set to true if the value exists, false otherwise.

func (*Message) Command

func (msg *Message) Command() (int, bool)

Command returns the type e.g. amps.CommandPublish, amps.CommandSOW, of the message. Can be one of the following:

- amps.CommandAck

- amps.CommandGroupBegin

- amps.CommandGroupEnd

- amps.CommandOOF

- amps.CommandPublish

- amps.CommandSOW

The second returned parameter is set to true if the value exists, false otherwise.

func (*Message) CommandID

func (msg *Message) CommandID() (string, bool)

CommandID returns the Client-specified id. The command id is returned by the engine in responses to commands to allow the client to correlate the response to the command.

The second returned parameter is set to true if the value exists, false otherwise.

func (*Message) Copy

func (msg *Message) Copy() *Message

Copy creates a deep copy of the Message object. Most common use case is to keep a copy of the message delivered to a message handler by one of the async client methods, such as ExecuteAsync(), since these methods reuse the same Message object in order to be GC-friendly.

func (*Message) CorrelationID

func (msg *Message) CorrelationID() (string, bool)

CorrelationID returns the correlation id value, if any.

The second returned parameter is set to true if the value exists, false otherwise.

func (*Message) Data

func (msg *Message) Data() []byte

Data returns the Message data (payload). Only amps.CommandPublish, amps.CommandSOW, and amps.CommandOOF messages can have a payload.

func (*Message) Expiration

func (msg *Message) Expiration() (uint, bool)

Expiration returns the SOW expiration time (in seconds) if used in publish.

The second returned parameter is set to true if the value exists, false otherwise.

func (*Message) Filter

func (msg *Message) Filter() (string, bool)

Filter returns the content filter expression.

The second returned parameter is set to true if the value exists, false otherwise.

func (*Message) GroupSequenceNumber

func (msg *Message) GroupSequenceNumber() (uint, bool)

GroupSequenceNumber returns the Group Sequence Number for each batch message of a SOW response.

The second returned parameter is set to true if the value exists, false otherwise.

func (*Message) LeasePeriod

func (msg *Message) LeasePeriod() (string, bool)

LeasePeriod -- for messages from a queue, returns the time at which the lease expires.

The second returned parameter is set to true if the value exists, false otherwise.

func (*Message) Matches

func (msg *Message) Matches() (uint, bool)

Matches returns the number of matches as a part of the acknowledgement to a SOW query.

The second returned parameter is set to true if the value exists, false otherwise.

func (*Message) MessageLength

func (msg *Message) MessageLength() (uint, bool)

MessageLength is sent to indicate the number of bytes used by the message body.

The second returned parameter is set to true if the value exists, false otherwise.

func (*Message) Options

func (msg *Message) Options() (string, bool)

Options returns a comma-delimited list of options on a specific command.

The second returned parameter is set to true if the value exists, false otherwise.

func (*Message) OrderBy

func (msg *Message) OrderBy() (string, bool)

OrderBy returns the SOW topic key(s) by which to order SOW query.

The second returned parameter is set to true if the value exists, false otherwise.

func (*Message) QueryID

func (msg *Message) QueryID() (string, bool)

QueryID returns the SOW Query identifier set by client to identify a query.

The second returned parameter is set to true if the value exists, false otherwise.

func (*Message) Reason

func (msg *Message) Reason() (string, bool)

Reason returns the failure message that appears when an acknowledgement returns a status of failure.

The second returned parameter is set to true if the value exists, false otherwise.

func (*Message) RecordsDeleted

func (msg *Message) RecordsDeleted() (uint, bool)

RecordsDeleted returns the number of records deleted from the SOW with a sow_delete command. Used in conjunction with the stats acknowledgement message.

The second returned parameter is set to true if the value exists, false otherwise.

func (*Message) RecordsInserted

func (msg *Message) RecordsInserted() (uint, bool)

RecordsInserted returns the number of records inserted into the SOW. Used in conjunction with the stats acknowledgement message.

The second returned parameter is set to true if the value exists, false otherwise.

func (*Message) RecordsReturned

func (msg *Message) RecordsReturned() (uint, bool)

RecordsReturned returns number of records in the store. The value is returned in the acknowledgement to an SOW query.

The second returned parameter is set to true if the value exists, false otherwise.

func (*Message) RecordsUpdated

func (msg *Message) RecordsUpdated() (uint, bool)

RecordsUpdated returns the number of records updated in the SOW. Used in conjunction with the stats acknowledgement message.

The second returned parameter is set to true if the value exists, false otherwise.

func (*Message) SequenceID

func (msg *Message) SequenceID() (uint64, bool)

SequenceID returns an integer that corresponds to the publish message sequence number. For more information see the Replication section in the User Guide.

The second returned parameter is set to true if the value exists, false otherwise.

func (*Message) SowKey

func (msg *Message) SowKey() (string, bool)

SowKey returns the sow key value. A SOW key will accompany each message returned in an SOW batch. A SOW key may also be added to messages coming in on a subscription when the published message matches a record in the SOW.

Format:

- string containing the digits of an unsigned long for AMPS-generated SOW keys

OR:

- arbitrary string in the base64 character set for user-provided SOW keys.

The second returned parameter is set to true if the value exists, false otherwise.

func (*Message) SowKeys

func (msg *Message) SowKeys() (string, bool)

SowKeys returns the SOW keys as a comma-delimited value.

The second returned parameter is set to true if the value exists, false otherwise.

func (*Message) Status

func (msg *Message) Status() (string, bool)

Status returns the client status when client is monitored for heartbeats.

The second returned parameter is set to true if the value exists, false otherwise.

func (*Message) SubID

func (msg *Message) SubID() (string, bool)

SubID returns the subscription identifier set by server when processing a subscription.

The second returned parameter is set to true if the value exists, false otherwise.

func (*Message) SubIDs

func (msg *Message) SubIDs() (string, bool)

SubIDs returns the list of subscription IDs - a comma-separated list of subscription ids sent from AMPS engine to identify which client subscriptions match a given publish message.

The second returned parameter is set to true if the value exists, false otherwise.

func (*Message) Timestamp

func (msg *Message) Timestamp() (string, bool)

Timestamp returns the message timestamp set by the server in a ISO-8601 date-time format.

The second returned parameter is set to true if the value exists, false otherwise.

func (*Message) TopN

func (msg *Message) TopN() (uint, bool)

TopN returns the number of records to return.

Note: If TopN is not equally divisible by the BatchSize value, then more records will be returned so that the total number of records is equally divisible by the BatchSize setting.

The second returned parameter is set to true if the value exists, false otherwise.

func (*Message) Topic

func (msg *Message) Topic() (string, bool)

Topic returns the topic value.

The second returned parameter is set to true if the value exists, false otherwise.

func (*Message) TopicMatches

func (msg *Message) TopicMatches() (uint, bool)

TopicMatches returns the number of topic matches for the SOW query. Sent in stats acknowledgement message.

The second returned parameter is set to true if the value exists, false otherwise.

func (*Message) UserID

func (msg *Message) UserID() (string, bool)

UserID returns the user id used to identify the user of a command.

The second returned parameter is set to true if the value exists, false otherwise.

type MessageRoute

MessageRoute struct

type MessageRoute struct {
    // contains filtered or unexported fields
}

type MessageRouter

MessageRouter struct

type MessageRouter struct {
    MessageRoute
    // contains filtered or unexported fields
}

func (*MessageRouter) AddRoute

func (msgRouter *MessageRouter) AddRoute(
    commandID string,
    messageHandler func(*Message) error,
    requestedAcks int,
    systemAcks int,
    isSubscribe bool,
    isReplace bool,
)

AddRoute ...

func (*MessageRouter) Clear

func (msgRouter *MessageRouter) Clear()

Clear ...

func (*MessageRouter) DeliverAck

func (msgRouter *MessageRouter) DeliverAck(ackMessage *Message, ackType int) int

DeliverAck ...

func (*MessageRouter) DeliverData

func (msgRouter *MessageRouter) DeliverData(dataMessage *Message) int

DeliverData ...

func (*MessageRouter) DeliverDataWithID

func (msgRouter *MessageRouter) DeliverDataWithID(dataMessage *Message, cmdID string) int

DeliverDataWithID ...

func (*MessageRouter) FindRoute

func (msgRouter *MessageRouter) FindRoute(commandID string) func(*Message) error

FindRoute ...

func (*MessageRouter) RemoveRoute

func (msgRouter *MessageRouter) RemoveRoute(commandID string)

RemoveRoute ...

func (*MessageRouter) UnsubscribeAll

func (msgRouter *MessageRouter) UnsubscribeAll()

UnsubscribeAll ...

type MessageStream

MessageStream provides an iteration abstraction over the results of an AMPS command such as a subscribe, a SOW query, or SOW delete. MessageStream is produced when calling Client.Execute() and continues iterating over the results until the connection is closed, or the iterator is explicitly closed, or when the SOW query is ended. You can use a MessageStream as you would other iterators, for example, using a for loop:

messages, err := client.Sow("orders", "/id > 20")
if err != nil { fmt.Println(err); return }

for message := messages.Next(); message != nil; message = messages.Next() {
    fmt.Println("Message Data:", string(message.Data()))
}

All sync methods of the Client (such as Sow(), Subscribe(), SowAndSubscribe(), etc) return a MessageStream object.

type MessageStream struct {
    // contains filtered or unexported fields
}

func (*MessageStream) Close

func (ms *MessageStream) Close() (err error)

Close -- closes this MessageStream, unsubscribing from AMPS if applicable.

Returns an error object if an error occurred while closing the stream.

func (*MessageStream) Conflate

func (ms *MessageStream) Conflate()

Conflate ...

func (*MessageStream) Depth

func (ms *MessageStream) Depth() uint64

Depth returns the current amount of messages in the queue to iterate over.

func (*MessageStream) HasNext

func (ms *MessageStream) HasNext() bool

HasNext is called to verify that there are more messages in the MessageStream. Returns true if there are more messages in the MessageStream and false if the MessageStream is empty.

Example: messages, err := client.Execute(amps.NewCommand("subscribe").SetTopic("test-topic")) if err != nil { fmt.Println(err); return }

for messages.HasNext() {

message := messages.Next()
fmt.Println("Message Data:", string(message.Data()))

}

func (*MessageStream) MaxDepth

func (ms *MessageStream) MaxDepth() uint64

MaxDepth returns the maximum size of the message stream queue. Once the maximum depth is reached, the message stream blocks and stops accepting new messages, until the queue is drained below the MaxDepth value (if any).

Returns 0 by default, which means no maximum depth is set. In this case the stream will keep adding messages to the queue until all the available RAM is consumed.

func (*MessageStream) Next

func (ms *MessageStream) Next() (message *Message)

Next is called to get the next message in the stream. It only returns nil if there are no more messages in the stream (for example, for SOW queries after delivering the group_end message).

func (*MessageStream) SetMaxDepth

func (ms *MessageStream) SetMaxDepth(depth uint64) *MessageStream

SetMaxDepth sets the maximum depth of the message stream. Once the maximum depth is reached, the message stream blocks and stops accepting new messages, until the queue is drained below the MaxDepth value (if any).

If set to 0 it means no maximum depth is set. In this case the stream will keep adding messages to the queue until all the available RAM is consumed.

func (*MessageStream) SetTimeout

func (ms *MessageStream) SetTimeout(timeout uint64) *MessageStream

SetTimeout sets a timeout on self. If no message is received in this timeout, Next() returns nil, but leaves the stream open.

Arguments:

timeout [uint64] - The timeout in milliseconds, or 0 for infinite timeout.

Returns the MessageStream object, allowing combining several setters into a chain.

func (*MessageStream) Timeout

func (ms *MessageStream) Timeout() uint64

Timeout returns the timeout value in milliseconds, if any. If returns 0 then no timeout is set (by default).

type NvfixMessageBuilder

NvfixMessageBuilder struct

type NvfixMessageBuilder struct {
    // contains filtered or unexported fields
}

func NewNVFIXBuilder

func NewNVFIXBuilder(fieldSep ...byte) *NvfixMessageBuilder

NewNVFIXBuilder use this method to create a new NVFIX message.

Example: builder := amps.NewNVFIXBuilder()

Arguments: fieldSep [byte] (optional) - The default is \x01, a different one can be provided

func (*NvfixMessageBuilder) AppendBytes

func (nmb *NvfixMessageBuilder) AppendBytes(tag []byte, value []byte, valOffset int, valLength int) error

AppendBytes appends the given tag (byte array) and the value (byte array) to the NVFIX message.

Example: value := "Here is the value" builder := amps.NewNVFIXBuilder() builder.AppendBytes([]byte("key"), []byte(value), 0, len(value))

client.Publish("nvfix-topic", builder.Data())

Arguments: tag [byte buffer] - The byte buffer to be the key in the NVFIX message value [byte buffer] - The bytes to be the value in the NVFIX message valOffset [int] - The location in the buffer where the bytes to append begin (for the value) valLength [int] - The length of the value in the buffer

Returns: Illegal Argument error - If the provided tag is empty

func (*NvfixMessageBuilder) AppendStrings

func (nmb *NvfixMessageBuilder) AppendStrings(tag string, value string) error

AppendStrings appends the given tag (string) and the value (string) to the NVFIX message.

Example: value := "This is a value" key := "This is the key" builder := amps.NewNVFIXBuilder() builder.AppendStrings(key, value)

client.Publish("nvfix-topic", builder.Data())

Arguments: tag [string] - The string to be the key in the NVFIX message value [string] - The string to be the key in the NVFIX message

Returns: Illegal Argument error - If the provided tag is empty

func (*NvfixMessageBuilder) Bytes

func (nmb *NvfixMessageBuilder) Bytes() []byte

Bytes returns the NVFIX message, in the form of a byte buffer

func (*NvfixMessageBuilder) Clear

func (nmb *NvfixMessageBuilder) Clear()

Clear clears the NVFIX message

func (*NvfixMessageBuilder) Data

func (nmb *NvfixMessageBuilder) Data() string

Data returns the NVFIX message, in the form of a string

func (*NvfixMessageBuilder) Size

func (nmb *NvfixMessageBuilder) Size() int

Size returns the size of the NVFIX message

type NvfixMessageShredder

NvfixMessageShredder struct

type NvfixMessageShredder struct {
    // contains filtered or unexported fields
}

func NewNVFIXShredder

func NewNVFIXShredder(fieldSep ...byte) *NvfixMessageShredder

NewNVFIXShredder use this method to parse a FIX message.

Example: shredder := amps.NewNVFIXShredder()

Arguments: fieldSep [byte] (optional) - The default is \x01, a different one can be provided

func (*NvfixMessageShredder) ToMap

func (nfs *NvfixMessageShredder) ToMap(nvfix []byte) map[string]string

ToMap use this method to parse a NVFIX message.

Example: shredder := amps.NewNVFIXShredder()

sow, _ := client.Sow("nvfix-topic") for sow.HasNext() {

message := sow.Next()
fields := shredder.ToMap(message.Data())
for key, value := range fields {
    fmt.Println("key:", key, "value:", value)
}

}

Arguments: nvfix [byte buffer] - The byte buffer containing the NVFIX message to be parsed

Returns: map - A map with string keys and string values