25 #ifndef _AMPSPLUSPLUS_H_ 26 #define _AMPSPLUSPLUS_H_ 28 #include "amps/ampsver.h" 47 #include <sys/atomic.h> 49 #include "amps/BookmarkStore.hpp" 50 #include "amps/MessageRouter.hpp" 51 #include "amps/util.hpp" 52 #include "amps/ampscrc.hpp" 53 #if __cplusplus >= 201100L || _MSC_VER >= 1900 57 #ifndef AMPS_TESTING_SLOW_MESSAGE_STREAM 58 #define AMPS_TESTING_SLOW_MESSAGE_STREAM 86 #define AMPS_MEMORYBUFFER_DEFAULT_BUFFERS 10 87 #define AMPS_MEMORYBUFFER_DEFAULT_LENGTH 40960 88 #define AMPS_SUBSCRIPTION_MANAGER_DEFAULT_TIMEOUT 0 89 #define AMPS_HACLIENT_TIMEOUT_DEFAULT 10000 90 #define AMPS_HACLIENT_RECONNECT_DEFAULT 200 91 #define AMPS_DEFAULT_COMMAND_TIMEOUT 5000 92 #define AMPS_DEFAULT_TOP_N -1 93 #define AMPS_DEFAULT_BATCH_SIZE 10 94 #define AMPS_NUMBER_BUFFER_LEN 20 95 #define AMPS_DEFAULT_QUEUE_ACK_TIMEOUT 1000 97 #if defined(_M_X64) || defined(__x86_64) || defined(_WIN64) 106 typedef std::map<std::string, std::string> ConnectionInfo;
109 inline std::string asString(Type x_)
111 std::ostringstream os;
117 size_t convertToCharArray(
char* buf_, amps_uint64_t seqNo_)
119 size_t pos = AMPS_NUMBER_BUFFER_LEN;
120 for (
int i = 0; i < AMPS_NUMBER_BUFFER_LEN; ++i)
124 buf_[--pos] = (char)(seqNo_ % 10 +
'0');
133 size_t convertToCharArray(
char* buf_,
unsigned long seqNo_)
135 size_t pos = AMPS_NUMBER_BUFFER_LEN;
136 for (
int i = 0; i < AMPS_NUMBER_BUFFER_LEN; ++i)
140 buf_[--pos] = (char)(seqNo_ % 10 +
'0');
154 static const char* duplicate()
158 static const char* badFilter()
162 static const char* badRegexTopic()
164 return "bad regex topic";
166 static const char* subscriptionAlreadyExists()
168 return "subscription already exists";
170 static const char* nameInUse()
172 return "name in use";
174 static const char* authFailure()
176 return "auth failure";
178 static const char* notEntitled()
180 return "not entitled";
182 static const char* authDisabled()
184 return "authentication disabled";
186 static const char* subidInUse()
188 return "subid in use";
190 static const char* noTopic()
208 virtual void exceptionThrown(
const std::exception&)
const {;}
214 #define AMPS_CALL_EXCEPTION_WRAPPER(x) \ 219 catch (std::exception& stdEx_)\ 223 _exceptionListener->exceptionThrown(stdEx_);\ 247 #define AMPS_CALL_EXCEPTION_WRAPPER_2(me,x) \ 250 while(me->_connected)\ 257 catch(MessageStreamFullException&)\ 261 me->checkAndSendHeartbeat(false);\ 263 catch (std::exception& stdEx_)\ 267 me->_exceptionListener->exceptionThrown(stdEx_);\ 278 catch (std::exception& stdEx_)\ 282 me->_exceptionListener->exceptionThrown(stdEx_);\ 306 #define AMPS_CALL_EXCEPTION_WRAPPER_STREAM_FULL_2(me, x)\ 307 while(me->_connected)\ 314 catch(MessageStreamFullException&)\ 318 me->checkAndSendHeartbeat(false);\ 320 catch (std::exception& stdEx_)\ 324 me->_exceptionListener->exceptionThrown(stdEx_);\ 335 #define AMPS_CALL_EXCEPTION_WRAPPER_2(me,x) \ 338 while(me->_connected)\ 345 catch(MessageStreamFullException& msfEx_)\ 349 me->checkAndSendHeartbeat(false);\ 351 catch (std::exception& stdEx_)\ 355 me->_exceptionListener->exceptionThrown(stdEx_);\ 366 catch (std::exception& stdEx_)\ 370 me->_exceptionListener->exceptionThrown(stdEx_);\ 394 #define AMPS_CALL_EXCEPTION_WRAPPER_STREAM_FULL_2(me, x)\ 395 while(me->_connected)\ 402 catch(MessageStreamFullException& msfEx_)\ 406 me->checkAndSendHeartbeat(false);\ 408 catch (std::exception& stdEx_)\ 412 me->_exceptionListener->exceptionThrown(stdEx_);\ 424 #define AMPS_UNHANDLED_EXCEPTION(ex) \ 427 _exceptionListener->exceptionThrown(ex);\ 434 #define AMPS_UNHANDLED_EXCEPTION_2(me,ex) \ 437 me->_exceptionListener->exceptionThrown(ex);\ 478 static const unsigned Subscribe = 1;
479 static const unsigned SOW = 2;
480 static const unsigned NeedsSequenceNumber = 4;
481 static const unsigned ProcessedAck = 8;
482 static const unsigned StatsAck = 16;
483 void init(Message::Command::Type command_)
492 void init(
const std::string& command_)
501 void init(
const char* command_,
size_t commandLen_)
513 if (!(command & Message::Command::NoDataCommands))
516 if (command == Message::Command::Subscribe ||
517 command == Message::Command::SOWAndSubscribe ||
518 command == Message::Command::DeltaSubscribe ||
519 command == Message::Command::SOWAndDeltaSubscribe)
524 if (command == Message::Command::SOW
525 || command == Message::Command::SOWAndSubscribe
526 || command == Message::Command::SOWAndDeltaSubscribe)
531 setBatchSize(AMPS_DEFAULT_BATCH_SIZE);
533 if (command == Message::Command::SOW)
538 _flags |= ProcessedAck;
540 else if (command == Message::Command::SOWDelete)
543 _flags |= ProcessedAck;
544 _flags |= NeedsSequenceNumber;
546 else if (command == Message::Command::Publish
547 || command == Message::Command::DeltaPublish)
549 _flags |= NeedsSequenceNumber;
551 else if (command == Message::Command::StopTimer)
568 Command(
const char* command_,
size_t commandLen_)
570 init(command_, commandLen_);
594 init(command_, commandLen_);
688 _message.
setTopic(topic_, topicLen_);
818 std::ostringstream os;
823 amps_uint64_t getSequence()
const 839 _message.
setData(data_, dataLen_);
859 if (topN_ != (
unsigned)AMPS_DEFAULT_TOP_N)
876 _batchSize = batchSize_;
898 if (ackType_ ==
"processed")
900 _flags |= ProcessedAck;
902 else if (ackType_ ==
"stats")
912 if (ackType_.find(
"processed") != std::string::npos)
914 _flags |= ProcessedAck;
918 _flags &= ~ProcessedAck;
920 if (ackType_.find(
"stats") != std::string::npos)
934 if (ackType_ & Message::AckType::Processed)
936 _flags |= ProcessedAck;
940 _flags &= ~ProcessedAck;
942 if (ackType_ & Message::AckType::Stats)
967 unsigned getTimeout(
void)
const 971 unsigned getBatchSize(
void)
const 975 bool isSubscribe(
void)
const 977 return _flags & Subscribe;
979 bool isSow(
void)
const 981 return (_flags & SOW) != 0;
983 bool hasProcessedAck(
void)
const 985 return (_flags & ProcessedAck) != 0;
987 bool hasStatsAck(
void)
const 989 return (_flags & StatsAck) != 0;
991 bool needsSequenceNumber(
void)
const 993 return (_flags & NeedsSequenceNumber) != 0;
999 typedef void(*DisconnectHandlerFunc)(
Client&,
void* userData);
1016 virtual std::string authenticate(
const std::string& userName_,
const std::string& password_) = 0;
1024 virtual std::string retry(
const std::string& userName_,
const std::string& password_) = 0;
1031 virtual void completed(
const std::string& userName_,
const std::string& password_,
const std::string& reason_) = 0;
1043 std::string
authenticate(
const std::string& ,
const std::string& password_)
1050 std::string
retry(
const std::string& ,
const std::string& )
1052 throw AuthenticationException(
"retry not implemented by DefaultAuthenticator.");
1055 void completed(
const std::string& ,
const std::string& ,
const std::string& ) {;}
1076 virtual void execute(
Message& message_) = 0;
1091 typedef bool (*PublishStoreResizeHandler)(
Store store_,
1106 : _resizeHandler(NULL)
1107 , _resizeHandlerData(NULL)
1108 , _errorOnPublishGap(errorOnPublishGap_)
1115 virtual amps_uint64_t store(
const Message& message_) = 0;
1123 virtual void discardUpTo(amps_uint64_t index_) = 0;
1138 virtual bool replaySingle(
StoreReplayer& replayer_, amps_uint64_t index_) = 0;
1144 virtual size_t unpersistedCount()
const = 0;
1156 virtual void flush(
long timeout_) = 0;
1162 return AMPS_UNSET_INDEX;
1169 return AMPS_UNSET_SEQUENCE;
1175 virtual amps_uint64_t getLowestUnpersisted()
const = 0;
1180 virtual amps_uint64_t getLastPersisted() = 0;
1194 _resizeHandler = handler_;
1195 _resizeHandlerData = userData_;
1200 return _resizeHandler;
1203 bool callResizeHandler(
size_t newSize_);
1205 inline virtual void setErrorOnPublishGap(
bool errorOnPublishGap_)
1207 _errorOnPublishGap = errorOnPublishGap_;
1210 inline virtual bool getErrorOnPublishGap()
const 1212 return _errorOnPublishGap;
1217 void* _resizeHandlerData;
1218 bool _errorOnPublishGap;
1225 RefHandle<StoreImpl> _body;
1229 Store(
const Store& rhs) : _body(rhs._body) {;}
1241 return _body.get().store(message_);
1252 _body.get().discardUpTo(index_);
1261 _body.get().replay(replayer_);
1273 return _body.get().replaySingle(replayer_, index_);
1282 return _body.get().unpersistedCount();
1290 return _body.isValid();
1303 return _body.get().flush(timeout_);
1311 return _body.get().getLowestUnpersisted();
1319 return _body.get().getLastPersisted();
1334 _body.get().setResizeHandler(handler_, userData_);
1339 return _body.get().getResizeHandler();
1348 _body.get().setErrorOnPublishGap(errorOnPublishGap_);
1357 return _body.get().getErrorOnPublishGap();
1365 if (_body.isValid())
1367 return &_body.get();
1391 virtual void failedWrite(
const Message& message_,
1392 const char* reason_,
size_t reasonLength_) = 0;
1396 inline bool StoreImpl::callResizeHandler(
size_t newSize_)
1400 return _resizeHandler(
Store(
this), newSize_, _resizeHandlerData);
1414 long* timeoutp = (
long*)data_;
1422 store_.
flush(*timeoutp);
1425 catch (
const TimedOutException&)
1427 catch (
const TimedOutException& e)
1454 unsigned requestedAckTypes_,
1475 unsigned requestedAckTypes_) = 0;
1489 virtual void clear() = 0;
1493 virtual void resubscribe(Client& client_) = 0;
1500 _failedResubscribeHandler = handler_;
1503 std::shared_ptr<FailedResubscribeHandler> _failedResubscribeHandler;
1514 typedef enum { Disconnected = 0,
1518 PublishReplayed = 8,
1519 HeartbeatInitiated = 16,
1533 virtual void connectionStateChanged(
State newState_) = 0;
1538 class MessageStreamImpl;
1541 typedef void(*DeferredExecutionFunc)(
void*);
1543 class ClientImpl :
public RefBody
1549 AMPS_SOCKET _socket;
1555 socklen_t _valueLen;
1559 : _socket(AMPS_INVALID_SOCKET), _noDelay(0), _valueLen(
sizeof(
int))
1561 _valuePtr = (
char*)&_noDelay;
1563 if (_socket != AMPS_INVALID_SOCKET)
1565 getsockopt(_socket, IPPROTO_TCP, TCP_NODELAY, _valuePtr, &_valueLen);
1569 setsockopt(_socket, IPPROTO_TCP, TCP_NODELAY, _valuePtr, _valueLen);
1573 _socket = AMPS_INVALID_SOCKET;
1580 if (_socket != AMPS_INVALID_SOCKET)
1583 setsockopt(_socket, IPPROTO_TCP, TCP_NODELAY, _valuePtr, _valueLen);
1588 friend class Client;
1591 DisconnectHandler _disconnectHandler;
1592 enum GlobalCommandTypeHandlers :
size_t 1602 DuplicateMessage = 8,
1605 std::vector<MessageHandler> _globalCommandTypeHandlers;
1606 Message _beatMessage, _readMessage;
1608 MessageRouter::RouteCache _routeCache;
1609 mutable Mutex _lock;
1610 std::string _name, _nameHash, _connectionName, _lastUri, _logonCorrelationData, _preflightMessage;
1611 std::vector<std::string> _httpPreflightHeaders;
1612 amps_uint64_t _nameHashValue;
1614 Store _publishStore;
1615 bool _isRetryOnDisconnect;
1616 amps_unique_ptr<FailedWriteHandler> _failedWriteHandler;
1617 #if __cplusplus >= 201100L || _MSC_VER >= 1900 1618 std::atomic<amps_uint64_t> _lastSentHaSequenceNumber;
1620 volatile amps_uint64_t _lastSentHaSequenceNumber;
1622 AMPS_ATOMIC_TYPE_8 _logonInProgress;
1623 AMPS_ATOMIC_TYPE _subscriptionManagerGenerationCount;
1624 VersionInfo _serverVersion;
1625 Timer _heartbeatTimer;
1626 amps_unique_ptr<MessageStream> _pEmptyMessageStream;
1629 int _queueAckTimeout;
1630 bool _isAutoAckEnabled;
1631 unsigned _ackBatchSize;
1632 unsigned _queuedAckCount;
1633 unsigned _defaultMaxDepth;
1634 struct QueueBookmarks
1636 QueueBookmarks(
const std::string& topic_)
1643 amps_uint64_t _oldestTime;
1644 unsigned _bookmarkCount;
1646 typedef amps_uint64_t topic_hash;
1647 typedef std::map<topic_hash, QueueBookmarks> TopicHashMap;
1648 TopicHashMap _topicHashMap;
1652 ClientImpl* _client;
1657 ClientStoreReplayer()
1658 : _client(NULL), _version(0), _res(
AMPS_E_OK)
1661 ClientStoreReplayer(ClientImpl* client_)
1662 : _client(client_), _version(0), _res(
AMPS_E_OK)
1665 void setClient(ClientImpl* client_)
1670 void execute(
Message& message_)
1674 throw CommandException(
"Can't replay without a client.");
1678 if (index > _client->_lastSentHaSequenceNumber)
1680 _client->_lastSentHaSequenceNumber = index;
1688 (!_client->_logonInProgress ||
1692 message_.getMessage(),
1697 throw DisconnectedException(
"AMPS Server disconnected during replay");
1703 ClientStoreReplayer _replayer;
1707 ClientImpl* _parent;
1708 const char* _reason;
1709 size_t _reasonLength;
1710 size_t _replayCount;
1712 FailedWriteStoreReplayer(ClientImpl* parent,
const char* reason_,
size_t reasonLength_)
1715 _reasonLength(reasonLength_),
1718 void execute(
Message& message_)
1720 if (_parent->_failedWriteHandler)
1723 _parent->_failedWriteHandler->failedWrite(message_,
1724 _reason, _reasonLength);
1727 size_t replayCount(
void)
const 1729 return _replayCount;
1733 struct AckResponseImpl :
public RefBody
1735 std::string username, password, reason, status, bookmark, options;
1736 amps_uint64_t sequenceNo;
1737 amps_uint64_t nameHashValue;
1738 VersionInfo serverVersion;
1739 #if __cplusplus >= 201100L || _MSC_VER >= 1900 1740 std::atomic<bool> responded;
1741 std::atomic<bool> abandoned;
1743 volatile bool responded;
1744 volatile bool abandoned;
1746 unsigned connectionVersion;
1749 username(), password(), reason(), status(), bookmark(), options(),
1750 sequenceNo((amps_uint64_t)0),
1751 nameHashValue((amps_uint64_t)0),
1755 connectionVersion(UINT_MAX)
1762 RefHandle<AckResponseImpl> _body;
1764 AckResponse() : _body(NULL) {;}
1765 AckResponse(
const AckResponse& rhs) : _body(rhs._body) {;}
1766 static AckResponse create()
1769 r._body =
new AckResponseImpl();
1773 const std::string& username()
1775 return _body.get().username;
1777 void setUsername(
const char* data_,
size_t len_)
1781 _body.get().username.assign(data_, len_);
1785 _body.get().username.clear();
1788 const std::string& password()
1790 return _body.get().password;
1792 void setPassword(
const char* data_,
size_t len_)
1796 _body.get().password.assign(data_, len_);
1800 _body.get().password.clear();
1803 const std::string& reason()
1805 return _body.get().reason;
1807 void setReason(
const char* data_,
size_t len_)
1811 _body.get().reason.assign(data_, len_);
1815 _body.get().reason.clear();
1818 const std::string& status()
1820 return _body.get().status;
1822 void setStatus(
const char* data_,
size_t len_)
1826 _body.get().status.assign(data_, len_);
1830 _body.get().status.clear();
1833 const std::string& bookmark()
1835 return _body.get().bookmark;
1837 void setBookmark(
const Field& bookmark_)
1839 AckResponseImpl& body = _body.get();
1840 if (!bookmark_.
empty())
1842 body.bookmark.assign(bookmark_.
data(), bookmark_.
len());
1843 Field::parseBookmark(bookmark_, body.nameHashValue,
1848 body.bookmark.clear();
1849 body.sequenceNo = (amps_uint64_t)0;
1850 body.nameHashValue = (amps_uint64_t)0;
1853 amps_uint64_t sequenceNo()
const 1855 return _body.get().sequenceNo;
1857 amps_uint64_t nameHashValue()
const 1859 return _body.get().nameHashValue;
1861 void setSequenceNo(
const char* data_,
size_t len_)
1863 amps_uint64_t result = (amps_uint64_t)0;
1866 for (
size_t i = 0; i < len_; ++i)
1868 result *= (amps_uint64_t)10;
1869 result += (amps_uint64_t)(data_[i] -
'0');
1872 _body.get().sequenceNo = result;
1874 VersionInfo serverVersion()
const 1876 return _body.get().serverVersion;
1878 void setServerVersion(
const char* data_,
size_t len_)
1882 _body.get().serverVersion.setVersion(std::string(data_, len_));
1887 return _body.get().responded;
1891 _body.get().responded =
true;
1895 return _body.get().abandoned;
1899 if (_body.isValid())
1901 _body.get().abandoned =
true;
1905 void setConnectionVersion(
unsigned connectionVersion)
1907 _body.get().connectionVersion = connectionVersion;
1910 unsigned getConnectionVersion()
1912 return _body.get().connectionVersion;
1915 void setOptions(
const char* data_,
size_t len_)
1919 _body.get().options.assign(data_, len_);
1923 _body.get().options.clear();
1927 const std::string& options()
1929 return _body.get().options;
1932 AckResponse& operator=(
const AckResponse& rhs)
1940 typedef std::map<std::string, AckResponse> AckMap;
1943 DefaultExceptionListener _defaultExceptionListener;
1946 struct DeferredExecutionRequest
1948 DeferredExecutionRequest(DeferredExecutionFunc func_,
1951 _userData(userData_)
1954 DeferredExecutionFunc _func;
1958 std::shared_ptr<const ExceptionListener> _pExceptionListener;
1959 amps_unique_ptr<SubscriptionManager> _subscriptionManager;
1960 volatile bool _connected;
1961 std::string _username;
1962 typedef std::set<ConnectionStateListener*> ConnectionStateListeners;
1963 ConnectionStateListeners _connectionStateListeners;
1964 typedef std::vector<DeferredExecutionRequest> DeferredExecutionList;
1965 Mutex _deferredExecutionLock;
1966 DeferredExecutionList _deferredExecutionList;
1967 unsigned _heartbeatInterval;
1968 unsigned _readTimeout;
1976 if (!_connected && newState_ > ConnectionStateListener::Connected)
1980 for (ConnectionStateListeners::iterator it = _connectionStateListeners.begin(); it != _connectionStateListeners.end(); ++it)
1982 AMPS_CALL_EXCEPTION_WRAPPER(
1983 (*it)->connectionStateChanged(newState_));
1986 void captureSubscriptionManagerGenerationCount()
1988 if (_subscriptionManager)
1990 _subscriptionManagerGenerationCount = _subscriptionManager->getGenerationCount();
1994 unsigned processedAck(
Message& message);
1995 unsigned persistedAck(
Message& meesage);
1996 void lastChance(
Message& message);
1997 void checkAndSendHeartbeat(
bool force =
false);
1998 virtual ConnectionInfo getConnectionInfo()
const;
2000 ClientImplMessageHandler(
amps_handle message,
void* userData);
2002 ClientImplPreDisconnectHandler(
amps_handle client,
unsigned failedConnectionVersion,
void* userData);
2004 ClientImplDisconnectHandler(
amps_handle client,
void* userData);
2006 ClientImplGetHttpPreflightMessage(
void* userData);
2008 void unsubscribeInternal(
const std::string&
id)
2016 subId.assign(
id.data(),
id.length());
2017 _routes.removeRoute(subId);
2019 if (_subscriptionManager)
2022 Unlock<Mutex> unlock(_lock);
2023 _subscriptionManager->unsubscribe(subId);
2025 threadLocalMessage.reset();
2026 threadLocalMessage.
setCommandEnum(Message::Command::Unsubscribe);
2029 _sendWithoutRetry(threadLocalMessage);
2030 deferredExecution(&s_noOpFn, NULL);
2033 AckResponse syncAckProcessing(
long timeout_,
Message& message_,
2034 amps_uint64_t haSeq = (amps_uint64_t)0,
2035 AMPS_ATOMIC_BASE_TYPE subscribeGeneration_ = 0)
2037 bool isLogon = message_.
getCommand() ==
"logon";
2038 if (_logonInProgress && !isLogon)
2040 while (_logonInProgress)
2042 if (!_lock.wait(200))
2044 amps_invoke_waiting_function();
2045 if (!_isRetryOnDisconnect)
2054 AckResponse ack = AckResponse::create();
2057 Lock<Mutex> guard(_ackMapLock);
2060 if (subscribeGeneration_ == 0)
2062 ack.setConnectionVersion((
unsigned)_sendSequenced(message_, haSeq, 0));
2066 ack.setConnectionVersion((
unsigned)_send(message_, subscribeGeneration_));
2068 if (ack.getConnectionVersion() == 0)
2071 throw DisconnectedException(
"Connection closed while waiting for response.");
2073 else if (ack.getConnectionVersion() == UINT_MAX)
2076 Lock<Mutex> guard(_ackMapLock);
2077 AckMap::iterator i = _ackMap.find(message_.
getCommandId());
2078 if (i != _ackMap.end())
2084 bool timedOut =
false;
2085 AMPS_START_TIMER(timeout_)
2086 while (!timedOut && !ack.responded() && !ack.abandoned())
2090 timedOut = !_lock.wait(timeout_);
2094 AMPS_RESET_TIMER(timedOut, timeout_);
2101 Unlock<Mutex> unlck(_lock);
2102 amps_invoke_waiting_function();
2105 if (ack.responded())
2107 if (ack.status() !=
"failure")
2111 amps_uint64_t ackSequence = ack.sequenceNo();
2112 if (_lastSentHaSequenceNumber < ackSequence)
2114 _lastSentHaSequenceNumber = ackSequence;
2127 _nameHash = ack.bookmark().substr(0, ack.bookmark().find(
'|'));
2128 _nameHashValue = ack.nameHashValue();
2129 const std::string& ackOptions = ack.options();
2130 size_t start = ackOptions.find(
"connection_name=");
2131 if (start != std::string::npos)
2134 size_t end = ackOptions.find(
',', start);
2135 if (end != std::string::npos)
2139 _connectionName = ackOptions.substr(start, end);
2141 _serverVersion = ack.serverVersion();
2142 if (_bookmarkStore.isValid())
2149 const std::string& options = ack.options();
2150 size_t index = options.find_first_of(
"max_backlog=");
2151 if (index != std::string::npos)
2154 const char* c = options.c_str() + index + 12;
2155 while (*c && *c !=
',')
2157 data = (data * 10) + (
unsigned)(*c++ -48);
2159 if (_ackBatchSize > data)
2161 _ackBatchSize = data;
2167 const size_t NotEntitled = 12;
2168 std::string ackReason = ack.reason();
2169 if (ackReason.length() == 0)
2173 if (ackReason.length() == NotEntitled &&
2174 ackReason[0] ==
'n' &&
2179 message_.throwFor(_client, ackReason);
2183 if (!ack.abandoned())
2185 throw TimedOutException(
"timed out waiting for operation.");
2189 throw DisconnectedException(
"Connection closed while waiting for response.");
2203 AMPS_CALL_EXCEPTION_WRAPPER(ClientImpl::disconnect());
2204 _pEmptyMessageStream.reset(NULL);
2211 ClientImpl(
const std::string& clientName)
2212 : _client(NULL), _name(clientName)
2213 , _isRetryOnDisconnect(
true)
2214 , _lastSentHaSequenceNumber((amps_uint64_t)0), _logonInProgress(0)
2215 , _subscriptionManagerGenerationCount(0), _serverVersion()
2216 , _queueAckTimeout(AMPS_DEFAULT_QUEUE_ACK_TIMEOUT)
2217 , _isAutoAckEnabled(
false)
2219 , _queuedAckCount(0)
2220 , _defaultMaxDepth(0)
2222 , _heartbeatInterval(0)
2225 _replayer.setClient(
this);
2228 (amps_handler)ClientImpl::ClientImplMessageHandler,
2231 (amps_predisconnect_handler)ClientImpl::ClientImplPreDisconnectHandler,
2234 (amps_handler)ClientImpl::ClientImplDisconnectHandler,
2237 ClientImpl::ClientImplGetHttpPreflightMessage,
2239 _exceptionListener = &_defaultExceptionListener;
2240 for (
size_t i = 0; i < GlobalCommandTypeHandlers::COUNT; ++i)
2246 virtual ~ClientImpl()
2251 const std::string& getName()
const 2256 const std::string& getNameHash()
const 2261 const amps_uint64_t getNameHashValue()
const 2263 return _nameHashValue;
2266 const std::string& getConnectionName()
const 2268 return _connectionName;
2271 void setName(
const std::string& name)
2283 const std::string& getLogonCorrelationData()
const 2285 return _logonCorrelationData;
2288 void setLogonCorrelationData(
const std::string& logonCorrelationData_)
2290 _logonCorrelationData = logonCorrelationData_;
2293 size_t getServerVersion()
const 2295 return _serverVersion.getOldStyleVersion();
2298 VersionInfo getServerVersionInfo()
const 2300 return _serverVersion;
2303 const std::string& getURI()
const 2308 virtual void connect(
const std::string& uri)
2310 Lock<Mutex> l(_lock);
2314 virtual void _connect(
const std::string& uri)
2322 threadLocalMessage.reset();
2325 _readMessage.setClientImpl(
this);
2326 if (_queueAckTimeout)
2335 broadcastConnectionStateChanged(ConnectionStateListener::Connected);
2338 void addHttpPreflightHeader(
const std::string& header_)
2340 _httpPreflightHeaders.emplace_back(header_);
2343 void addHttpPreflightHeader(
const std::string& key_,
const std::string& value_)
2345 _httpPreflightHeaders.emplace_back(key_ + std::string(
": ") + value_);
2348 void clearHttpPreflightHeaders()
2350 _httpPreflightHeaders.clear();
2354 void setHttpPreflightHeaders(
const T& headers_)
2356 _httpPreflightHeaders.clear();
2357 for (
typename T::const_iterator i = headers_.begin(); i != headers_.end(); ++i)
2359 _httpPreflightHeaders.push_back(*i);
2363 void setDisconnected()
2366 Lock<Mutex> l(_lock);
2369 AMPS_CALL_EXCEPTION_WRAPPER(broadcastConnectionStateChanged(ConnectionStateListener::Disconnected));
2372 _heartbeatTimer.setTimeout(0.0);
2375 clearAcks(UINT_MAX-1);
2381 virtual void disconnect()
2383 AMPS_CALL_EXCEPTION_WRAPPER(flushAcks());
2386 clearAcks(UINT_MAX);
2387 AMPS_CALL_EXCEPTION_WRAPPER(processDeferredExecutions());
2388 Lock<Mutex> l(_lock);
2389 broadcastConnectionStateChanged(ConnectionStateListener::Shutdown);
2392 void clearAcks(
unsigned failedVersion)
2395 Lock<Mutex> guard(_ackMapLock);
2398 std::vector<std::string> worklist;
2399 for (AckMap::iterator i = _ackMap.begin(), e = _ackMap.end(); i != e; ++i)
2401 if (i->second.getConnectionVersion() <= failedVersion)
2403 i->second.setAbandoned();
2404 worklist.push_back(i->first);
2408 for (std::vector<std::string>::iterator j = worklist.begin(), e = worklist.end(); j != e; ++j)
2417 unsigned send(
const Message& message)
2419 Lock<Mutex> l(_lock);
2420 return _send(message);
2423 void sendWithoutRetry(
const Message& message_)
2425 Lock<Mutex> l(_lock);
2428 if (_logonInProgress)
2430 throw DisconnectedException(
"The client has been disconnected.");
2432 _sendWithoutRetry(message_);
2435 void _sendWithoutRetry(
const Message& message_)
2446 unsigned _sendSequenced(
const Message& message, amps_uint64_t haSeq,
int isBatch_)
2453 Message localMessage = message;
2454 unsigned version = 0;
2455 bool isNotLogon = (haSeq) || (localMessage.
getCommand().
data()[0] !=
'l');
2459 if (_logonInProgress && isNotLogon)
2461 if (!_isRetryOnDisconnect)
2474 if (localMessage.getMessage() == message.getMessage())
2478 while (_logonInProgress)
2480 if (!_lock.wait(1000))
2482 amps_invoke_waiting_function();
2489 if (haSeq <= _lastSentHaSequenceNumber)
2496 while (haSeq > _lastSentHaSequenceNumber + 1)
2502 _lastSentHaSequenceNumber + 1))
2507 version = _replayer._version;
2510 catch (
const DisconnectedException&)
2512 catch (
const DisconnectedException& e)
2515 if (!_isRetryOnDisconnect)
2520 result = _replayer._res;
2524 ++_lastSentHaSequenceNumber;
2527 localMessage.getMessage(),
2533 && localMessage.getMessage() == message.getMessage())
2537 if (_isRetryOnDisconnect)
2539 Unlock<Mutex> u(_lock);
2566 amps_invoke_waiting_function();
2579 unsigned _send(
const Message& message, AMPS_ATOMIC_BASE_TYPE subscribeGeneration_ = 0)
2586 Message localMessage = message;
2587 unsigned version = 0;
2588 bool isHASubscribe = subscribeGeneration_ > 0;
2592 if (_logonInProgress && localMessage.
getCommand().
data()[0] !=
'l')
2595 && localMessage.getMessage() == message.getMessage())
2599 while (_logonInProgress)
2601 if (!_lock.wait(1000))
2603 amps_invoke_waiting_function();
2604 if (!_isRetryOnDisconnect)
2613 && subscribeGeneration_ <= (AMPS_ATOMIC_BASE_TYPE)_subscriptionManagerGenerationCount)
2621 localMessage.getMessage(),
2627 && localMessage.getMessage() == message.getMessage())
2631 if (_isRetryOnDisconnect)
2633 Unlock<Mutex> u(_lock);
2638 if (isHASubscribe &&
2656 amps_invoke_waiting_function();
2667 void addMessageHandler(
const Field& commandId_,
2669 unsigned requestedAcks_, Message::Command::Type commandType_)
2671 Lock<Mutex> lock(_lock);
2672 _routes.addRoute(commandId_, messageHandler_, requestedAcks_,
2676 bool removeMessageHandler(
const Field& commandId_)
2678 Lock<Mutex> lock(_lock);
2679 return _routes.removeRoute(commandId_);
2685 AMPS_ATOMIC_BASE_TYPE subscribeGeneration_ = 0)
2690 bool isSubscribeOnly =
false;
2691 bool replace =
false;
2693 unsigned systemAddedAcks = Message::AckType::None;
2696 switch (commandType)
2698 case Message::Command::Subscribe:
2699 case Message::Command::DeltaSubscribe:
2700 replace = message_.
getOptions().operator std::string().find(AMPS_OPTIONS_REPLACE, 0, strlen(AMPS_OPTIONS_REPLACE) - 1) != std::string::npos;
2701 isSubscribeOnly =
true;
2703 case Message::Command::SOWAndSubscribe:
2704 case Message::Command::SOWAndDeltaSubscribe:
2711 while (!replace &&
id != subId && _routes.hasRoute(
id))
2723 systemAddedAcks |= Message::AckType::Persisted;
2726 case Message::Command::SOW:
2733 while (!replace &&
id != subId && _routes.hasRoute(
id))
2744 if (!isSubscribeOnly)
2753 while (!replace && qid != subId && qid !=
id 2754 && _routes.hasRoute(qid))
2760 systemAddedAcks |= Message::AckType::Processed;
2763 int routesAdded = 0;
2764 Lock<Mutex> l(_lock);
2766 if (subscribeGeneration_ > 0
2767 && subscribeGeneration_ <= _subscriptionManagerGenerationCount)
2770 return std::string();
2772 if (!subId.
empty() && messageHandler_.isValid())
2774 if (!_routes.hasRoute(subId))
2780 _routes.addRoute(subId, messageHandler_, requestedAcks,
2781 systemAddedAcks, commandType);
2783 if (!isSubscribeOnly && !qid.
empty()
2784 && messageHandler_.isValid() && qid != subId)
2786 if (routesAdded == 0)
2788 _routes.addRoute(qid, messageHandler_,
2789 requestedAcks, systemAddedAcks, commandType);
2795 Unlock<Mutex> u(_lock);
2796 data = amps_invoke_copy_route_function(
2797 messageHandler_.userData());
2801 _routes.addRoute(qid, messageHandler_, requestedAcks,
2802 systemAddedAcks, commandType);
2806 _routes.addRoute(qid,
2809 requestedAcks, systemAddedAcks, commandType);
2814 if (!
id.empty() && messageHandler_.isValid()
2815 && requestedAcks & ~
Message::AckType::Persisted
2816 &&
id != subId &&
id != qid)
2818 if (routesAdded == 0)
2820 _routes.addRoute(
id, messageHandler_, requestedAcks,
2821 systemAddedAcks, commandType);
2827 Unlock<Mutex> u(_lock);
2828 data = amps_invoke_copy_route_function(
2829 messageHandler_.userData());
2833 _routes.addRoute(
id, messageHandler_, requestedAcks,
2834 systemAddedAcks, commandType);
2838 _routes.addRoute(
id,
2842 systemAddedAcks, commandType);
2849 AckResponse resp = syncAckProcessing(timeout_, message_, 0, subscribeGeneration_);
2851 if (resp.getConnectionVersion() == UINT_MAX)
2860 _routes.removeRoute(
id);
2868 _routes.removeRoute(
id);
2875 case Message::Command::Unsubscribe:
2876 case Message::Command::Heartbeat:
2877 case Message::Command::Logon:
2878 case Message::Command::StartTimer:
2879 case Message::Command::StopTimer:
2880 case Message::Command::SOWDelete:
2882 Lock<Mutex> l(_lock);
2891 if (messageHandler_.isValid())
2893 _routes.addRoute(
id, messageHandler_, requestedAcks,
2894 Message::AckType::None, commandType);
2900 case Message::Command::DeltaPublish:
2901 case Message::Command::Publish:
2904 Lock<Mutex> l(_lock);
2907 if (ackType != Message::AckType::None
2915 if (messageHandler_.isValid())
2917 _routes.addRoute(
id, messageHandler_, requestedAcks,
2918 Message::AckType::None, commandType);
2924 syncAckProcessing(timeout_, message_, 0, 0);
2928 _sendSequenced(message_, 0, 1);
2933 case Message::Command::GroupBegin:
2934 case Message::Command::GroupEnd:
2935 case Message::Command::OOF:
2936 case Message::Command::Ack:
2937 case Message::Command::Unknown:
2939 throw CommandException(
"Command type " + message_.
getCommand() +
" can not be sent directly to AMPS");
2945 void setDisconnectHandler(
const DisconnectHandler& disconnectHandler)
2947 Lock<Mutex> l(_lock);
2948 _disconnectHandler = disconnectHandler;
2951 void setGlobalCommandTypeMessageHandler(
const std::string& command_,
const MessageHandler& handler_)
2953 switch (command_[0])
2955 #if 0 // Not currently implemented to avoid an extra branch in delivery 2957 _globalCommandTypeHandlers[GlobalCommandTypeHandlers::Publish] = handler_;
2960 _globalCommandTypeHandlers[GlobalCommandTypeHandlers::SOW] = handler_;
2964 _globalCommandTypeHandlers[GlobalCommandTypeHandlers::Heartbeat] = handler_;
2966 #if 0 // Not currently implemented to avoid an extra branch in delivery 2968 if (command_[6] ==
'b')
2970 _globalCommandTypeHandlers[GlobalCommandTypeHandlers::GroupBegin] = handler_;
2972 else if (command_[6] ==
'e')
2974 _globalCommandTypeHandlers[GlobalCommandTypeHandlers::GroupEnd] = handler_;
2978 std::ostringstream os;
2979 os <<
"Invalid command '" << command_ <<
"' passed to setGlobalCommandTypeHandler";
2980 throw CommandException(os.str());
2984 _globalCommandTypeHandlers[GlobalCommandTypeHandlers::OOF] = handler_;
2988 _globalCommandTypeHandlers[GlobalCommandTypeHandlers::Ack] = handler_;
2992 _globalCommandTypeHandlers[GlobalCommandTypeHandlers::LastChance] = handler_;
2996 _globalCommandTypeHandlers[GlobalCommandTypeHandlers::DuplicateMessage] = handler_;
2999 std::ostringstream os;
3000 os <<
"Invalid command '" << command_ <<
"' passed to setGlobalCommandTypeHandler";
3001 throw CommandException(os.str());
3006 void setGlobalCommandTypeMessageHandler(
const Message::Command::Type command_,
const MessageHandler& handler_)
3010 #if 0 // Not currently implemented to avoid an extra branch in delivery 3011 case Message::Command::Publish:
3012 _globalCommandTypeHandlers[GlobalCommandTypeHandlers::Publish] = handler_;
3014 case Message::Command::SOW:
3015 _globalCommandTypeHandlers[GlobalCommandTypeHandlers::SOW] = handler_;
3018 case Message::Command::Heartbeat:
3019 _globalCommandTypeHandlers[GlobalCommandTypeHandlers::Heartbeat] = handler_;
3021 #if 0 // Not currently implemented to avoid an extra branch in delivery 3022 case Message::Command::GroupBegin:
3023 _globalCommandTypeHandlers[GlobalCommandTypeHandlers::GroupBegin] = handler_;
3025 case Message::Command::GroupEnd:
3026 _globalCommandTypeHandlers[GlobalCommandTypeHandlers::GroupEnd] = handler_;
3028 case Message::Command::OOF:
3029 _globalCommandTypeHandlers[GlobalCommandTypeHandlers::OOF] = handler_;
3032 case Message::Command::Ack:
3033 _globalCommandTypeHandlers[GlobalCommandTypeHandlers::Ack] = handler_;
3037 unsigned command = command_;
3044 AMPS_snprintf(errBuf,
sizeof(errBuf),
3045 "Invalid command '%.*s' passed to setGlobalCommandTypeHandler",
3046 CommandConstants<0>::Lengths[bits],
3047 CommandConstants<0>::Values[bits]);
3048 throw CommandException(errBuf);
3053 void setGlobalCommandTypeMessageHandler(
const GlobalCommandTypeHandlers handlerType_,
const MessageHandler& handler_)
3055 _globalCommandTypeHandlers[handlerType_] = handler_;
3060 Lock<Mutex> l(_lock);
3061 _failedWriteHandler.reset(handler_);
3064 void setPublishStore(
const Store& publishStore_)
3066 Lock<Mutex> l(_lock);
3069 throw AlreadyConnectedException(
"Setting a publish store on a connected client is undefined behavior");
3071 _publishStore = publishStore_;
3076 Lock<Mutex> l(_lock);
3079 throw AlreadyConnectedException(
"Setting a bookmark store on a connected client is undefined behavior");
3081 _bookmarkStore = bookmarkStore_;
3086 Lock<Mutex> l(_lock);
3089 throw AlreadyConnectedException(
"Setting a subscription manager on a connected client is undefined behavior");
3091 _subscriptionManager.reset(subscriptionManager_);
3092 captureSubscriptionManagerGenerationCount();
3100 DisconnectHandler getDisconnectHandler()
const 3102 return _disconnectHandler;
3107 return _globalCommandTypeHandlers[GlobalCommandTypeHandlers::DuplicateMessage];
3115 Store getPublishStore()
const 3117 return _publishStore;
3122 return _bookmarkStore;
3125 amps_uint64_t publish(
const char* topic_,
size_t topicLen_,
const char* data_,
size_t dataLen_)
3127 threadLocalMessage.reset();
3131 threadLocalMessage.
assignTopic(topic_, topicLen_);
3132 threadLocalMessage.assignData(data_, dataLen_);
3133 Lock<Mutex> l(_lock);
3134 _sendSequenced(threadLocalMessage, 0, 1);
3139 return _publish(topic_, topicLen_, data_, dataLen_);
3143 amps_uint64_t publish(
const char* topic_,
size_t topicLen_,
const char* data_,
3144 size_t dataLen_,
unsigned long expiration_)
3146 threadLocalMessage.reset();
3147 char exprBuf[AMPS_NUMBER_BUFFER_LEN];
3148 size_t exprPos = convertToCharArray(exprBuf, expiration_);
3151 AMPS_NUMBER_BUFFER_LEN - exprPos);
3154 threadLocalMessage.
assignTopic(topic_, topicLen_);
3155 threadLocalMessage.assignData(data_, dataLen_);
3156 Lock<Mutex> l(_lock);
3157 _sendSequenced(threadLocalMessage, 0, 1);
3162 return _publish(topic_, topicLen_, data_, dataLen_);
3169 ClientImpl* _pClient;
3171 #if __cplusplus >= 201100L || _MSC_VER >= 1900 3172 std::atomic<bool> _acked;
3173 std::atomic<bool> _disconnected;
3175 volatile bool _acked;
3176 volatile bool _disconnected;
3179 FlushAckHandler(ClientImpl* pClient_)
3180 : _pClient(pClient_), _cmdId(), _acked(
false), _disconnected(
false)
3182 pClient_->addConnectionStateListener(
this);
3186 _pClient->removeConnectionStateListener(
this);
3187 _pClient->removeMessageHandler(_cmdId);
3190 void setCommandId(
const Field& cmdId_)
3198 void connectionStateChanged(
State state_)
3200 if (state_ <= Shutdown)
3202 _disconnected =
true;
3211 return _acked || _disconnected;
3215 void publishFlush(
long timeout_,
unsigned ackType_)
3217 static const char* processed =
"processed";
3218 static const size_t processedLen = strlen(processed);
3219 static const char* persisted =
"persisted";
3220 static const size_t persistedLen = strlen(persisted);
3221 static const char* flush =
"flush";
3222 static const size_t flushLen = strlen(flush);
3223 static const VersionInfo minPersisted(
"5.3.3.0");
3224 static const VersionInfo minFlush(
"4");
3225 if (ackType_ != Message::AckType::Processed
3226 && ackType_ != Message::AckType::Persisted)
3228 throw CommandException(
"Flush can only be used with processed or persisted acks.");
3230 FlushAckHandler flushHandler(
this);
3231 if (_serverVersion >= minFlush)
3233 Lock<Mutex> l(_lock);
3236 throw DisconnectedException(
"Not connected trying to flush");
3238 threadLocalMessage.reset();
3241 if (_serverVersion < minPersisted
3242 || ackType_ == Message::AckType::Processed)
3250 flushHandler.setCommandId(threadLocalMessage.
getCommandId());
3252 std::bind(&FlushAckHandler::invoke,
3253 std::ref(flushHandler),
3254 std::placeholders::_1),
3256 NoDelay noDelay(_client);
3257 _send(threadLocalMessage);
3263 _publishStore.
flush(timeout_);
3267 AMPS_UNHANDLED_EXCEPTION(ex);
3271 else if (_serverVersion < minFlush)
3275 AMPS_USLEEP(timeout_ * 1000);
3279 AMPS_USLEEP(1000 * 1000);
3285 Timer timer((
double)timeout_);
3287 while (!timer.check() && !flushHandler.done())
3290 amps_invoke_waiting_function();
3295 while (!flushHandler.done())
3298 amps_invoke_waiting_function();
3302 if (!flushHandler.done())
3304 throw TimedOutException(
"Timed out waiting for flush");
3307 if (!flushHandler.acked() && !_publishStore.
isValid())
3309 throw DisconnectedException(
"Disconnected waiting for flush");
3313 amps_uint64_t deltaPublish(
const char* topic_,
size_t topicLength_,
3314 const char* data_,
size_t dataLength_)
3316 threadLocalMessage.reset();
3317 threadLocalMessage.
setCommandEnum(Message::Command::DeltaPublish);
3320 threadLocalMessage.
assignTopic(topic_, topicLength_);
3321 threadLocalMessage.assignData(data_, dataLength_);
3322 Lock<Mutex> l(_lock);
3323 _sendSequenced(threadLocalMessage, 0, 1);
3328 return _publish(topic_, topicLength_, data_, dataLength_);
3332 amps_uint64_t deltaPublish(
const char* topic_,
size_t topicLength_,
3333 const char* data_,
size_t dataLength_,
3334 unsigned long expiration_)
3336 threadLocalMessage.reset();
3337 char exprBuf[AMPS_NUMBER_BUFFER_LEN];
3338 size_t exprPos = convertToCharArray(exprBuf, expiration_);
3339 threadLocalMessage.
setCommandEnum(Message::Command::DeltaPublish)
3341 AMPS_NUMBER_BUFFER_LEN - exprPos);
3344 threadLocalMessage.
assignTopic(topic_, topicLength_);
3345 threadLocalMessage.assignData(data_, dataLength_);
3346 Lock<Mutex> l(_lock);
3347 _sendSequenced(threadLocalMessage, 0, 1);
3352 return _publish(topic_, topicLength_, data_, dataLength_);
3356 amps_uint64_t _publish(
const char* topic_,
size_t topicLength_,
3357 const char* data_,
size_t dataLength_)
3359 threadLocalMessage.
assignTopic(topic_, topicLength_)
3361 .assignData(data_, dataLength_);
3362 amps_uint64_t haSequenceNumber = _publishStore.
store(threadLocalMessage);
3363 char buf[AMPS_NUMBER_BUFFER_LEN];
3364 size_t pos = convertToCharArray(buf, haSequenceNumber);
3365 threadLocalMessage.
assignSequence(buf + pos, AMPS_NUMBER_BUFFER_LEN - pos);
3367 Lock<Mutex> l(_lock);
3368 _sendSequenced(threadLocalMessage, haSequenceNumber, 1);
3370 return haSequenceNumber;
3373 virtual std::string logon(
long timeout_,
Authenticator& authenticator_,
3374 const char* options_ = NULL);
3376 virtual std::string _logon(
long timeout_,
Authenticator& authenticator_,
3377 const char* options_ = NULL)
3380 threadLocalMessage.reset();
3382 std::string newCommandId = threadLocalMessage.
getCommandId();
3385 #ifdef AMPS_CLIENT_VERSION_WITH_LANGUAGE 3386 threadLocalMessage.
assignVersion(AMPS_CLIENT_VERSION_WITH_LANGUAGE,
3387 strlen(AMPS_CLIENT_VERSION_WITH_LANGUAGE));
3390 if (uri.user().size())
3392 threadLocalMessage.
setUserId(uri.user());
3394 if (uri.password().size())
3398 if (uri.protocol() ==
"amps" && uri.messageType().size())
3402 if (uri.isTrue(
"pretty"))
3408 if (!_logonCorrelationData.empty())
3416 _username = threadLocalMessage.
getUserId();
3419 AtomicFlagFlip pubFlip(&_logonInProgress);
3420 NoDelay noDelay(_client);
3424 AckResponse ack = syncAckProcessing(timeout_, threadLocalMessage);
3425 if (ack.status() ==
"retry")
3427 threadLocalMessage.
setPassword(authenticator_.
retry(ack.username(), ack.password()));
3428 _username = ack.username();
3429 threadLocalMessage.
setUserId(_username);
3433 authenticator_.
completed(ack.username(), ack.password(), ack.reason());
3437 broadcastConnectionStateChanged(ConnectionStateListener::LoggedOn);
3447 Unlock<Mutex> u(_lock);
3451 AMPS_UNHANDLED_EXCEPTION(ex);
3457 Unlock<Mutex> u(_lock);
3468 _publishStore.
replay(_replayer);
3469 broadcastConnectionStateChanged(ConnectionStateListener::PublishReplayed);
3471 catch (
const PublishStoreGapException& ex)
3474 Unlock<Mutex> u(_lock);
3478 AMPS_UNHANDLED_EXCEPTION(ex);
3481 catch (
const StoreException& ex)
3484 Unlock<Mutex> u(_lock);
3488 std::ostringstream os;
3489 os <<
"A local store exception occurred while logging on." 3491 throw ConnectionException(os.str());
3496 Unlock<Mutex> u(_lock);
3500 AMPS_UNHANDLED_EXCEPTION(ex);
3503 catch (
const std::exception& ex)
3506 Unlock<Mutex> u(_lock);
3510 AMPS_UNHANDLED_EXCEPTION(ex);
3516 Unlock<Mutex> u(_lock);
3524 return newCommandId;
3528 const std::string& topic_,
3530 const std::string& filter_,
3531 const std::string& bookmark_,
3532 const std::string& options_,
3533 const std::string& subId_,
3534 bool isHASubscribe_ =
true)
3536 isHASubscribe_ &= (bool)_subscriptionManager;
3537 Lock<Mutex> l(_lock);
3538 threadLocalMessage.reset();
3541 std::string subId(subId_);
3544 if (options_.find(AMPS_OPTIONS_REPLACE, 0, strlen(AMPS_OPTIONS_REPLACE) - 1) != std::string::npos)
3546 throw ConnectionException(
"Cannot issue a replacement subscription; a valid subscription id is required.");
3553 unsigned ackTypes = Message::AckType::Processed;
3555 if (!bookmark_.empty() && _bookmarkStore.isValid())
3557 ackTypes |= Message::AckType::Persisted;
3559 threadLocalMessage.
setTopic(topic_);
3561 if (filter_.length())
3565 if (bookmark_.length())
3576 if (_bookmarkStore.isValid())
3581 _bookmarkStore.
log(threadLocalMessage);
3582 _bookmarkStore.
discard(threadLocalMessage);
3588 if (options_.length())
3593 Message message = threadLocalMessage;
3594 AMPS_ATOMIC_BASE_TYPE generation = (AMPS_ATOMIC_BASE_TYPE)0;
3597 message = threadLocalMessage.
deepCopy();
3599 Unlock<Mutex> u(_lock);
3601 _subscriptionManager->subscribe(messageHandler_, message,
3602 Message::AckType::None);
3604 if (generation <= (AMPS_ATOMIC_BASE_TYPE)_subscriptionManagerGenerationCount)
3615 if (!options_.empty())
3621 syncAckProcessing(timeout_, message, 0, generation);
3623 catch (
const DisconnectedException&)
3625 if (!isHASubscribe_)
3627 _routes.removeRoute(subIdField);
3632 AMPS_CALL_EXCEPTION_WRAPPER(unsubscribeInternal(subIdField));
3636 catch (
const TimedOutException&)
3638 AMPS_CALL_EXCEPTION_WRAPPER(unsubscribeInternal(subIdField));
3646 Unlock<Mutex> unlock(_lock);
3647 _subscriptionManager->unsubscribe(subIdField);
3649 _routes.removeRoute(subIdField);
3655 std::string deltaSubscribe(
const MessageHandler& messageHandler_,
3656 const std::string& topic_,
3658 const std::string& filter_,
3659 const std::string& bookmark_,
3660 const std::string& options_,
3661 const std::string& subId_ =
"",
3662 bool isHASubscribe_ =
true)
3664 isHASubscribe_ &= (bool)_subscriptionManager;
3665 Lock<Mutex> l(_lock);
3666 threadLocalMessage.reset();
3667 threadLocalMessage.
setCommandEnum(Message::Command::DeltaSubscribe);
3669 std::string subId(subId_);
3676 unsigned ackTypes = Message::AckType::Processed;
3678 if (!bookmark_.empty() && _bookmarkStore.isValid())
3680 ackTypes |= Message::AckType::Persisted;
3682 threadLocalMessage.
setTopic(topic_);
3683 if (filter_.length())
3687 if (bookmark_.length())
3698 if (_bookmarkStore.isValid())
3703 _bookmarkStore.
log(threadLocalMessage);
3704 _bookmarkStore.
discard(threadLocalMessage);
3710 if (options_.length())
3714 AMPS_ATOMIC_BASE_TYPE generation = (AMPS_ATOMIC_BASE_TYPE)0;
3718 Unlock<Mutex> u(_lock);
3720 _subscriptionManager->subscribe(messageHandler_, threadLocalMessage.
deepCopy(),
3721 Message::AckType::None);
3723 if (generation <= (AMPS_ATOMIC_BASE_TYPE)_subscriptionManagerGenerationCount)
3731 Message::AckType::None, ackTypes, threadLocalMessage.
getCommandEnum());
3734 if (!options_.empty())
3740 syncAckProcessing(timeout_, threadLocalMessage, 0, generation);
3742 catch (
const DisconnectedException&)
3744 if (!isHASubscribe_)
3746 _routes.removeRoute(subIdField);
3750 catch (
const TimedOutException&)
3752 AMPS_CALL_EXCEPTION_WRAPPER(unsubscribeInternal(subIdField));
3760 Unlock<Mutex> unlock(_lock);
3761 _subscriptionManager->unsubscribe(subIdField);
3763 _routes.removeRoute(subIdField);
3769 void unsubscribe(
const std::string&
id)
3771 Lock<Mutex> l(_lock);
3772 unsubscribeInternal(
id);
3775 void unsubscribe(
void)
3777 if (_subscriptionManager)
3779 _subscriptionManager->clear();
3782 _routes.unsubscribeAll();
3783 Lock<Mutex> l(_lock);
3784 threadLocalMessage.reset();
3785 threadLocalMessage.
setCommandEnum(Message::Command::Unsubscribe);
3788 _sendWithoutRetry(threadLocalMessage);
3790 deferredExecution(&s_noOpFn, NULL);
3794 const std::string& topic_,
3795 const std::string& filter_ =
"",
3796 const std::string& orderBy_ =
"",
3797 const std::string& bookmark_ =
"",
3798 int batchSize_ = AMPS_DEFAULT_BATCH_SIZE,
3799 int topN_ = AMPS_DEFAULT_TOP_N,
3800 const std::string& options_ =
"",
3801 long timeout_ = AMPS_DEFAULT_COMMAND_TIMEOUT)
3803 Lock<Mutex> l(_lock);
3804 threadLocalMessage.reset();
3808 std::string commandId = threadLocalMessage.
getCommandId();
3810 unsigned ackTypes = Message::AckType::Processed | Message::AckType::Completed;
3812 threadLocalMessage.
setTopic(topic_);
3813 if (filter_.length())
3817 if (orderBy_.length())
3821 if (bookmark_.length())
3825 threadLocalMessage.
setBatchSize(AMPS::asString(batchSize_));
3826 if (topN_ != AMPS_DEFAULT_TOP_N)
3830 if (options_.length())
3835 _routes.addRoute(threadLocalMessage.
getQueryID(), messageHandler_,
3836 Message::AckType::None, ackTypes, threadLocalMessage.
getCommandEnum());
3840 syncAckProcessing(timeout_, threadLocalMessage);
3844 AMPS_CALL_EXCEPTION_WRAPPER(_routes.removeRoute(commandId));
3852 const std::string& topic_,
3854 const std::string& filter_ =
"",
3855 int batchSize_ = AMPS_DEFAULT_BATCH_SIZE,
3856 int topN_ = AMPS_DEFAULT_TOP_N)
3859 return sow(messageHandler_,
3870 std::string sowAndSubscribe(
const MessageHandler& messageHandler_,
3871 const std::string& topic_,
3872 const std::string& filter_ =
"",
3873 const std::string& orderBy_ =
"",
3874 const std::string& bookmark_ =
"",
3875 int batchSize_ = AMPS_DEFAULT_BATCH_SIZE,
3876 int topN_ = AMPS_DEFAULT_TOP_N,
3877 const std::string& options_ =
"",
3878 long timeout_ = AMPS_DEFAULT_COMMAND_TIMEOUT,
3879 bool isHASubscribe_ =
true)
3881 isHASubscribe_ &= (bool)_subscriptionManager;
3882 unsigned ackTypes = Message::AckType::Processed;
3883 Lock<Mutex> l(_lock);
3884 threadLocalMessage.reset();
3885 threadLocalMessage.
setCommandEnum(Message::Command::SOWAndSubscribe);
3888 std::string subId = cid;
3890 if (filter_.length())
3894 if (orderBy_.length())
3898 if (bookmark_.length())
3902 if (_bookmarkStore.isValid())
3904 ackTypes |= Message::AckType::Persisted;
3912 _bookmarkStore.
log(threadLocalMessage);
3913 if (!BookmarkRange::isRange(bookmark))
3915 _bookmarkStore.
discard(threadLocalMessage);
3926 threadLocalMessage.
setBatchSize(AMPS::asString(batchSize_));
3927 if (topN_ != AMPS_DEFAULT_TOP_N)
3931 if (options_.length())
3936 AMPS_ATOMIC_BASE_TYPE generation = (AMPS_ATOMIC_BASE_TYPE)0;
3940 Unlock<Mutex> u(_lock);
3942 _subscriptionManager->subscribe(messageHandler_, threadLocalMessage.
deepCopy(),
3943 Message::AckType::None);
3945 if (generation <= (AMPS_ATOMIC_BASE_TYPE)_subscriptionManagerGenerationCount)
3950 _routes.addRoute(cid, messageHandler_,
3951 Message::AckType::None, ackTypes, threadLocalMessage.
getCommandEnum());
3953 if (!options_.empty())
3959 syncAckProcessing(timeout_, threadLocalMessage, 0, generation);
3961 catch (
const DisconnectedException&)
3963 if (!isHASubscribe_)
3965 _routes.removeRoute(subId);
3969 catch (
const TimedOutException&)
3971 AMPS_CALL_EXCEPTION_WRAPPER(unsubscribeInternal(subId));
3979 Unlock<Mutex> unlock(_lock);
3980 _subscriptionManager->unsubscribe(cid);
3982 _routes.removeRoute(subId);
3988 std::string sowAndSubscribe(
const MessageHandler& messageHandler_,
3989 const std::string& topic_,
3991 const std::string& filter_ =
"",
3992 int batchSize_ = AMPS_DEFAULT_BATCH_SIZE,
3993 bool oofEnabled_ =
false,
3994 int topN_ = AMPS_DEFAULT_TOP_N,
3995 bool isHASubscribe_ =
true)
3998 return sowAndSubscribe(messageHandler_,
4005 (oofEnabled_ ?
"oof" :
""),
4010 std::string sowAndDeltaSubscribe(
const MessageHandler& messageHandler_,
4011 const std::string& topic_,
4012 const std::string& filter_ =
"",
4013 const std::string& orderBy_ =
"",
4014 int batchSize_ = AMPS_DEFAULT_BATCH_SIZE,
4015 int topN_ = AMPS_DEFAULT_TOP_N,
4016 const std::string& options_ =
"",
4017 long timeout_ = AMPS_DEFAULT_COMMAND_TIMEOUT,
4018 bool isHASubscribe_ =
true)
4020 isHASubscribe_ &= (bool)_subscriptionManager;
4021 Lock<Mutex> l(_lock);
4022 threadLocalMessage.reset();
4023 threadLocalMessage.
setCommandEnum(Message::Command::SOWAndDeltaSubscribe);
4028 threadLocalMessage.
setTopic(topic_);
4029 if (filter_.length())
4033 if (orderBy_.length())
4037 threadLocalMessage.
setBatchSize(AMPS::asString(batchSize_));
4038 if (topN_ != AMPS_DEFAULT_TOP_N)
4042 if (options_.length())
4046 AMPS_ATOMIC_BASE_TYPE generation = (AMPS_ATOMIC_BASE_TYPE)0;
4050 Unlock<Mutex> u(_lock);
4052 _subscriptionManager->subscribe(messageHandler_, threadLocalMessage.
deepCopy(),
4053 Message::AckType::None);
4055 if (generation <= (AMPS_ATOMIC_BASE_TYPE)_subscriptionManagerGenerationCount)
4060 _routes.addRoute(threadLocalMessage.
getQueryID(), messageHandler_,
4061 Message::AckType::None, Message::AckType::Processed, threadLocalMessage.
getCommandEnum());
4063 if (!options_.empty())
4069 syncAckProcessing(timeout_, threadLocalMessage, 0, generation);
4071 catch (
const DisconnectedException&)
4073 if (!isHASubscribe_)
4075 _routes.removeRoute(subId);
4079 catch (
const TimedOutException&)
4081 AMPS_CALL_EXCEPTION_WRAPPER(unsubscribeInternal(subId));
4089 Unlock<Mutex> unlock(_lock);
4090 _subscriptionManager->unsubscribe(
Field(subId));
4092 _routes.removeRoute(subId);
4098 std::string sowAndDeltaSubscribe(
const MessageHandler& messageHandler_,
4099 const std::string& topic_,
4101 const std::string& filter_ =
"",
4102 int batchSize_ = AMPS_DEFAULT_BATCH_SIZE,
4103 bool oofEnabled_ =
false,
4104 bool sendEmpties_ =
false,
4105 int topN_ = AMPS_DEFAULT_TOP_N,
4106 bool isHASubscribe_ =
true)
4114 if (sendEmpties_ ==
false)
4118 return sowAndDeltaSubscribe(messageHandler_,
4130 const std::string& topic_,
4131 const std::string& filter_,
4137 unsigned ackType = Message::AckType::Processed |
4138 Message::AckType::Stats |
4139 Message::AckType::Persisted;
4140 threadLocalMessage.reset();
4141 if (commandId_.
empty())
4152 .assignQueryID(commandId_.
data(), commandId_.
len())
4153 .setAckTypeEnum(ackType)
4155 .assignFilter(filter_.c_str(), filter_.length());
4156 amps_uint64_t haSequenceNumber = _publishStore.
store(threadLocalMessage);
4157 char buf[AMPS_NUMBER_BUFFER_LEN];
4158 size_t pos = convertToCharArray(buf, haSequenceNumber);
4159 threadLocalMessage.
assignSequence(buf + pos, AMPS_NUMBER_BUFFER_LEN - pos);
4163 Lock<Mutex> l(_lock);
4164 _routes.addRoute(commandId_, messageHandler_,
4165 Message::AckType::Stats,
4166 Message::AckType::Processed | Message::AckType::Persisted,
4168 syncAckProcessing(timeout_, threadLocalMessage,
4171 catch (
const DisconnectedException&)
4177 AMPS_CALL_EXCEPTION_WRAPPER(_routes.removeRoute(commandId_));
4181 return (std::string)commandId_;
4185 Lock<Mutex> l(_lock);
4186 threadLocalMessage.reset();
4187 if (commandId_.
empty())
4198 .assignQueryID(commandId_.
data(), commandId_.
len())
4199 .setAckTypeEnum(Message::AckType::Processed |
4200 Message::AckType::Stats)
4202 .assignFilter(filter_.c_str(), filter_.length());
4203 _routes.addRoute(commandId_, messageHandler_,
4204 Message::AckType::Stats,
4205 Message::AckType::Processed,
4209 syncAckProcessing(timeout_, threadLocalMessage);
4213 AMPS_CALL_EXCEPTION_WRAPPER(_routes.removeRoute(commandId_));
4216 return (std::string)commandId_;
4220 std::string sowDeleteByData(
const MessageHandler& messageHandler_,
4221 const std::string& topic_,
4222 const std::string& data_,
4228 unsigned ackType = Message::AckType::Processed |
4229 Message::AckType::Stats |
4230 Message::AckType::Persisted;
4231 threadLocalMessage.reset();
4232 if (commandId_.
empty())
4243 .assignQueryID(commandId_.
data(), commandId_.
len())
4244 .setAckTypeEnum(ackType)
4246 .assignData(data_.c_str(), data_.length());
4247 amps_uint64_t haSequenceNumber = _publishStore.
store(threadLocalMessage);
4248 char buf[AMPS_NUMBER_BUFFER_LEN];
4249 size_t pos = convertToCharArray(buf, haSequenceNumber);
4250 threadLocalMessage.
assignSequence(buf + pos, AMPS_NUMBER_BUFFER_LEN - pos);
4254 Lock<Mutex> l(_lock);
4255 _routes.addRoute(commandId_, messageHandler_,
4256 Message::AckType::Stats,
4257 Message::AckType::Processed | Message::AckType::Persisted,
4259 syncAckProcessing(timeout_, threadLocalMessage,
4262 catch (
const DisconnectedException&)
4268 AMPS_CALL_EXCEPTION_WRAPPER(_routes.removeRoute(commandId_));
4272 return (std::string)commandId_;
4276 Lock<Mutex> l(_lock);
4277 threadLocalMessage.reset();
4278 if (commandId_.
empty())
4289 .assignQueryID(commandId_.
data(), commandId_.
len())
4290 .setAckTypeEnum(Message::AckType::Processed |
4291 Message::AckType::Stats)
4293 .assignData(data_.c_str(), data_.length());
4294 _routes.addRoute(commandId_, messageHandler_,
4295 Message::AckType::Stats,
4296 Message::AckType::Processed,
4300 syncAckProcessing(timeout_, threadLocalMessage);
4304 AMPS_CALL_EXCEPTION_WRAPPER(_routes.removeRoute(commandId_));
4307 return (std::string)commandId_;
4311 std::string sowDeleteByKeys(
const MessageHandler& messageHandler_,
4312 const std::string& topic_,
4313 const std::string& keys_,
4319 unsigned ackType = Message::AckType::Processed |
4320 Message::AckType::Stats |
4321 Message::AckType::Persisted;
4322 threadLocalMessage.reset();
4323 if (commandId_.
empty())
4334 .assignQueryID(commandId_.
data(), commandId_.
len())
4335 .setAckTypeEnum(ackType)
4337 .assignSowKeys(keys_.c_str(), keys_.length());
4338 amps_uint64_t haSequenceNumber = _publishStore.
store(threadLocalMessage);
4339 char buf[AMPS_NUMBER_BUFFER_LEN];
4340 size_t pos = convertToCharArray(buf, haSequenceNumber);
4341 threadLocalMessage.
assignSequence(buf + pos, AMPS_NUMBER_BUFFER_LEN - pos);
4345 Lock<Mutex> l(_lock);
4346 _routes.addRoute(commandId_, messageHandler_,
4347 Message::AckType::Stats,
4348 Message::AckType::Processed | Message::AckType::Persisted,
4350 syncAckProcessing(timeout_, threadLocalMessage,
4353 catch (
const DisconnectedException&)
4359 AMPS_CALL_EXCEPTION_WRAPPER(_routes.removeRoute(commandId_));
4363 return (std::string)commandId_;
4367 Lock<Mutex> l(_lock);
4368 threadLocalMessage.reset();
4369 if (commandId_.
empty())
4380 .assignQueryID(commandId_.
data(), commandId_.
len())
4381 .setAckTypeEnum(Message::AckType::Processed |
4382 Message::AckType::Stats)
4384 .assignSowKeys(keys_.c_str(), keys_.length());
4385 _routes.addRoute(commandId_, messageHandler_,
4386 Message::AckType::Stats,
4387 Message::AckType::Processed,
4391 syncAckProcessing(timeout_, threadLocalMessage);
4395 AMPS_CALL_EXCEPTION_WRAPPER(_routes.removeRoute(commandId_));
4398 return (std::string)commandId_;
4402 void startTimer(
void)
4404 if (_serverVersion >=
"5.3.2.0")
4406 throw CommandException(
"The start_timer command is deprecated.");
4408 Lock<Mutex> l(_lock);
4409 threadLocalMessage.reset();
4412 _send(threadLocalMessage);
4417 if (_serverVersion >=
"5.3.2.0")
4419 throw CommandException(
"The stop_timer command is deprecated.");
4421 return executeAsync(
Command(
"stop_timer").addAckType(
"completed"), messageHandler_);
4436 void setExceptionListener(
const std::shared_ptr<const ExceptionListener>& pListener_)
4438 _pExceptionListener = pListener_;
4439 _exceptionListener = _pExceptionListener.get();
4444 _exceptionListener = &listener_;
4449 return *_exceptionListener;
4452 void setHeartbeat(
unsigned heartbeatInterval_,
unsigned readTimeout_)
4454 if (readTimeout_ < heartbeatInterval_)
4456 throw UsageException(
"The socket read timeout must be >= the heartbeat interval.");
4458 Lock<Mutex> l(_lock);
4459 if (_heartbeatInterval != heartbeatInterval_ ||
4460 _readTimeout != readTimeout_)
4462 _heartbeatInterval = heartbeatInterval_;
4463 _readTimeout = readTimeout_;
4468 void _sendHeartbeat(
void)
4470 if (_connected && _heartbeatInterval != 0)
4472 std::ostringstream options;
4473 options <<
"start," << _heartbeatInterval;
4476 _heartbeatTimer.setTimeout(_heartbeatInterval * 1000.0);
4477 _heartbeatTimer.start();
4480 _sendWithoutRetry(_beatMessage);
4481 broadcastConnectionStateChanged(ConnectionStateListener::HeartbeatInitiated);
4483 catch (ConnectionException& ex_)
4487 AMPS_UNHANDLED_EXCEPTION(ex_);
4492 if (_readTimeout && _connected)
4499 if (!_queueAckTimeout)
4502 (
int)(_heartbeatInterval * 1000));
4513 Lock<Mutex> lock(_lock);
4514 _connectionStateListeners.insert(listener_);
4519 Lock<Mutex> lock(_lock);
4520 _connectionStateListeners.erase(listener_);
4523 void clearConnectionStateListeners()
4525 Lock<Mutex> lock(_lock);
4526 _connectionStateListeners.clear();
4531 unsigned systemAddedAcks_, Message::Command::Type commandType_)
4533 Message message = command_.getMessage();
4538 bool added = qid.
len() || subid.
len() || cid_.
len();
4539 bool cidIsQid = cid_ == qid;
4540 bool cidUnique = !cidIsQid && cid_.
len() > 0 && cid_ != subid;
4542 if (subid.
len() > 0)
4546 addedCount += _routes.addRoute(subid, handler_, requestedAcks_,
4547 systemAddedAcks_, commandType_);
4549 && (commandType == Message::Command::Subscribe
4550 || commandType == Message::Command::DeltaSubscribe))
4557 if (qid.
len() > 0 && qid != subid
4558 && (commandType == Message::Command::SOW
4559 || commandType == Message::Command::SOWDelete
4560 || commandType == Message::Command::SOWAndSubscribe
4561 || commandType == Message::Command::SOWAndDeltaSubscribe))
4563 while (_routes.hasRoute(qid))
4572 if (addedCount == 0)
4574 _routes.addRoute(qid, handler_, requestedAcks_,
4575 systemAddedAcks_, commandType_);
4581 Unlock<Mutex> u(_lock);
4582 data = amps_invoke_copy_route_function(handler_.userData());
4586 _routes.addRoute(qid, handler_, requestedAcks_,
4587 systemAddedAcks_, commandType_);
4591 _routes.addRoute(qid,
4595 systemAddedAcks_, commandType_);
4600 if (cidUnique && requestedAcks_ & ~Message::AckType::Persisted)
4602 while (_routes.hasRoute(cid_))
4606 if (addedCount == 0)
4608 _routes.addRoute(cid_, handler_, requestedAcks_,
4609 systemAddedAcks_, commandType_);
4615 Unlock<Mutex> u(_lock);
4616 data = amps_invoke_copy_route_function(handler_.userData());
4620 _routes.addRoute(cid_, handler_, requestedAcks_,
4621 systemAddedAcks_, commandType_);
4625 _routes.addRoute(cid_,
4629 systemAddedAcks_, commandType_);
4633 else if ((commandType == Message::Command::Publish ||
4634 commandType == Message::Command::DeltaPublish)
4635 && requestedAcks_ & ~
Message::AckType::Persisted)
4638 _routes.addRoute(cid_, handler_, requestedAcks_,
4639 systemAddedAcks_, commandType_);
4644 throw UsageException(
"To use a messagehandler, you must also supply a command or subscription ID.");
4649 bool isHASubscribe_ =
true)
4651 isHASubscribe_ &= (bool)_subscriptionManager;
4652 Message& message = command_.getMessage();
4653 unsigned systemAddedAcks = (handler_.isValid() || command_.hasProcessedAck()) ?
4654 Message::AckType::Processed : Message::AckType::None;
4656 bool isPublishStore = _publishStore.
isValid() && command_.needsSequenceNumber();
4658 if (commandType == Message::Command::StopTimer)
4660 systemAddedAcks |= Message::AckType::Completed;
4662 else if (commandType == Message::Command::Unsubscribe)
4668 _routes.unsubscribeAll();
4669 if (_subscriptionManager)
4671 Unlock<Mutex> unlock(_lock);
4672 _subscriptionManager->clear();
4677 _routes.removeRoute(subId);
4679 if (_subscriptionManager)
4682 Unlock<Mutex> unlock(_lock);
4683 _subscriptionManager->unsubscribe(subId);
4687 deferredExecution(&s_noOpFn, NULL);
4690 if (handler_.isValid() && cid.
empty())
4696 if (command_.isSubscribe())
4699 if (_bookmarkStore.isValid())
4701 systemAddedAcks |= Message::AckType::Persisted;
4709 _bookmarkStore.
log(message);
4710 if (!BookmarkRange::isRange(bookmark))
4712 _bookmarkStore.
discard(message);
4726 systemAddedAcks |= Message::AckType::Persisted;
4728 bool isSubscribe = command_.isSubscribe();
4729 if (handler_.isValid() && !isSubscribe)
4731 _registerHandler(command_, cid, handler_,
4732 requestedAcks, systemAddedAcks, commandType);
4736 bool useSyncSend = cid.
len() > 0 && command_.hasProcessedAck();
4737 amps_uint64_t haSequenceNumber = (amps_uint64_t)0;
4740 Unlock<Mutex> u(_lock);
4741 haSequenceNumber = _publishStore.
store(message);
4748 syncAckProcessing((
long)command_.getTimeout(), message,
4753 _sendSequenced(message, haSequenceNumber,
4754 commandType & (Message::Command::Publish
4755 | Message::Command::DeltaPublish));
4758 catch (
const DisconnectedException&)
4764 AMPS_CALL_EXCEPTION_WRAPPER(_routes.removeRoute(cid));
4773 AMPS_ATOMIC_BASE_TYPE generation = (AMPS_ATOMIC_BASE_TYPE)0;
4777 Unlock<Mutex> u(_lock);
4779 _subscriptionManager->subscribe(handler_,
4783 if (generation <= (AMPS_ATOMIC_BASE_TYPE)_subscriptionManagerGenerationCount)
4786 return std::string(subId.
data(), subId.
len());
4789 if (handler_.isValid())
4791 _registerHandler(command_, cid, handler_,
4792 requestedAcks, systemAddedAcks, commandType);
4797 syncAckProcessing((
long)command_.getTimeout(), message, 0, generation);
4799 catch (
const DisconnectedException&)
4801 if (!isHASubscribe_)
4803 AMPS_CALL_EXCEPTION_WRAPPER(_routes.removeRoute(cid));
4804 AMPS_CALL_EXCEPTION_WRAPPER(_routes.removeRoute(subId));
4805 AMPS_CALL_EXCEPTION_WRAPPER(_routes.removeRoute(message.
getQueryId()));
4810 catch (
const TimedOutException&)
4812 AMPS_CALL_EXCEPTION_WRAPPER(unsubscribeInternal(cid));
4813 AMPS_CALL_EXCEPTION_WRAPPER(unsubscribeInternal(subId));
4814 AMPS_CALL_EXCEPTION_WRAPPER(unsubscribeInternal(message.
getQueryId()));
4823 Unlock<Mutex> unlock(_lock);
4824 _subscriptionManager->unsubscribe(subId);
4830 _routes.removeRoute(cid);
4831 _routes.removeRoute(subId);
4835 if (subId.
len() > 0)
4838 return std::string(subId.
data(), subId.
len());
4844 bool useSyncSend = commandType & ~
Message::Command::NoDataCommands
4845 || (cid.
len() > 0 && command_.hasProcessedAck());
4851 syncAckProcessing((
long)(command_.getTimeout()), message);
4855 _sendSequenced(message, 0,
4856 commandType & (Message::Command::Publish
4857 | Message::Command::DeltaPublish));
4860 catch (
const TimedOutException&)
4862 AMPS_CALL_EXCEPTION_WRAPPER(unsubscribeInternal(cid));
4863 AMPS_CALL_EXCEPTION_WRAPPER(unsubscribeInternal(message.
getQueryId()));
4867 catch (
const DisconnectedException&)
4869 AMPS_CALL_EXCEPTION_WRAPPER(_routes.removeRoute(cid));
4870 AMPS_CALL_EXCEPTION_WRAPPER(_routes.removeRoute(message.
getQueryId()));
4876 AMPS_CALL_EXCEPTION_WRAPPER(_routes.removeRoute(cid));
4877 AMPS_CALL_EXCEPTION_WRAPPER(_routes.removeRoute(message.
getQueryId()));
4890 bool isHASubscribe_ =
true)
4892 Lock<Mutex> lock(_lock);
4893 return executeAsyncNoLock(command_, handler_, isHASubscribe_);
4897 void setAutoAck(
bool isAutoAckEnabled_)
4899 _isAutoAckEnabled = isAutoAckEnabled_;
4901 bool getAutoAck(
void)
const 4903 return _isAutoAckEnabled;
4905 void setAckBatchSize(
const unsigned batchSize_)
4907 _ackBatchSize = batchSize_;
4908 if (!_queueAckTimeout)
4910 _queueAckTimeout = AMPS_DEFAULT_QUEUE_ACK_TIMEOUT;
4914 unsigned getAckBatchSize(
void)
const 4916 return _ackBatchSize;
4918 int getAckTimeout(
void)
const 4920 return _queueAckTimeout;
4922 void setAckTimeout(
const int ackTimeout_)
4925 _queueAckTimeout = ackTimeout_;
4927 size_t _ack(QueueBookmarks& queueBookmarks_)
4929 if (queueBookmarks_._bookmarkCount)
4931 threadLocalMessage.reset();
4936 amps_uint64_t haSequenceNumber = 0;
4939 haSequenceNumber = _publishStore.
store(threadLocalMessage);
4942 queueBookmarks_._data.erase();
4943 queueBookmarks_._bookmarkCount = 0;
4945 _sendSequenced(threadLocalMessage, haSequenceNumber, 0);
4948 queueBookmarks_._data.erase();
4949 queueBookmarks_._bookmarkCount = 0;
4955 void ack(
const Field& topic_,
const Field& bookmark_,
const char* options_ = NULL)
4957 if (_isAutoAckEnabled)
4961 _ack(topic_, bookmark_, options_);
4963 void _ack(
const Field& topic_,
const Field& bookmark_,
const char* options_ = NULL)
4965 if (bookmark_.
len() == 0)
4969 Lock<Mutex> lock(_lock);
4970 if (_ackBatchSize < 2 || options_ != NULL)
4972 threadLocalMessage.reset();
4980 amps_uint64_t haSequenceNumber = 0;
4983 haSequenceNumber = _publishStore.
store(threadLocalMessage);
4987 _sendSequenced(threadLocalMessage, haSequenceNumber, 0);
4991 topic_hash hash = CRC<0>::crcNoSSE(topic_.
data(), topic_.
len());
4992 TopicHashMap::iterator it = _topicHashMap.find(hash);
4993 if (it == _topicHashMap.end())
4996 it = _topicHashMap.emplace(TopicHashMap::value_type(hash, QueueBookmarks(topic_))).first;
4998 QueueBookmarks& queueBookmarks = it->second;
4999 if (queueBookmarks._data.length())
5001 queueBookmarks._data.append(
",");
5005 queueBookmarks._oldestTime = amps_now();
5007 queueBookmarks._data.append(bookmark_);
5008 if (++queueBookmarks._bookmarkCount >= _ackBatchSize)
5010 _ack(queueBookmarks);
5013 void flushAcks(
void)
5015 size_t sendCount = 0;
5022 Lock<Mutex> lock(_lock);
5023 typedef TopicHashMap::iterator iterator;
5024 for (iterator it = _topicHashMap.begin(), end = _topicHashMap.end(); it != end; ++it)
5026 QueueBookmarks& queueBookmarks = it->second;
5027 sendCount += _ack(queueBookmarks);
5030 if (sendCount && _connected)
5032 publishFlush(0, Message::AckType::Processed);
5036 void checkQueueAcks(
void)
5038 if (!_topicHashMap.size())
5042 Lock<Mutex> lock(_lock);
5045 amps_uint64_t threshold = amps_now()
5046 - (amps_uint64_t)_queueAckTimeout;
5047 typedef TopicHashMap::iterator iterator;
5048 for (iterator it = _topicHashMap.begin(), end = _topicHashMap.end(); it != end; ++it)
5050 QueueBookmarks& queueBookmarks = it->second;
5051 if (queueBookmarks._bookmarkCount && queueBookmarks._oldestTime < threshold)
5053 _ack(queueBookmarks);
5057 catch (std::exception& ex)
5059 AMPS_UNHANDLED_EXCEPTION(ex);
5063 void deferredExecution(DeferredExecutionFunc func_,
void* userData_)
5065 Lock<Mutex> lock(_deferredExecutionLock);
5066 _deferredExecutionList.emplace_back(
5067 DeferredExecutionRequest(func_, userData_));
5070 inline void processDeferredExecutions(
void)
5072 if (_deferredExecutionList.size())
5074 Lock<Mutex> lock(_deferredExecutionLock);
5075 DeferredExecutionList::iterator it = _deferredExecutionList.begin();
5076 DeferredExecutionList::iterator end = _deferredExecutionList.end();
5077 for (; it != end; ++it)
5081 it->_func(it->_userData);
5088 _deferredExecutionList.clear();
5089 _routes.invalidateCache();
5090 _routeCache.invalidateCache();
5094 bool getRetryOnDisconnect(
void)
const 5096 return _isRetryOnDisconnect;
5099 void setRetryOnDisconnect(
bool isRetryOnDisconnect_)
5101 _isRetryOnDisconnect = isRetryOnDisconnect_;
5104 void setDefaultMaxDepth(
unsigned maxDepth_)
5106 _defaultMaxDepth = maxDepth_;
5109 unsigned getDefaultMaxDepth(
void)
const 5111 return _defaultMaxDepth;
5126 void setPublishBatching(amps_uint64_t batchSizeBytes_, amps_uint64_t batchTimeoutMillis_)
5209 RefHandle<MessageStreamImpl> _body;
5219 inline void advance(
void);
5226 : _pStream(pStream_)
5231 bool operator==(
const iterator& rhs)
const 5233 return _pStream == rhs._pStream;
5235 bool operator!=(
const iterator& rhs)
const 5237 return _pStream != rhs._pStream;
5239 void operator++(
void)
5255 return _body.isValid();
5262 if (!_body.isValid())
5264 throw UsageException(
"This MessageStream is not valid and cannot be iterated.");
5296 unsigned getMaxDepth(
void)
const;
5299 unsigned getDepth(
void)
const;
5304 inline void setSOWOnly(
const std::string& commandId_,
5305 const std::string& queryId_ =
"");
5306 inline void setSubscription(
const std::string& subId_,
5307 const std::string& commandId_ =
"",
5308 const std::string& queryId_ =
"");
5309 inline void setStatsOnly(
const std::string& commandId_,
5310 const std::string& queryId_ =
"");
5311 inline void setAcksOnly(
const std::string& commandId_,
unsigned acks_);
5317 friend class Client;
5318 friend class ClientImpl;
5344 BorrowRefHandle<ClientImpl> _body;
5346 static const int DEFAULT_COMMAND_TIMEOUT = AMPS_DEFAULT_COMMAND_TIMEOUT;
5347 static const int DEFAULT_BATCH_SIZE = AMPS_DEFAULT_BATCH_SIZE;
5348 static const int DEFAULT_TOP_N = AMPS_DEFAULT_TOP_N;
5359 : _body(new ClientImpl(clientName), true)
5362 Client(ClientImpl* existingClient)
5363 : _body(existingClient,
true)
5366 Client(ClientImpl* existingClient,
bool isRef)
5367 : _body(existingClient, isRef)
5370 Client(
const Client& rhs) : _body(rhs._body) {;}
5371 virtual ~Client(
void) {;}
5373 Client& operator=(
const Client& rhs)
5381 return _body.isValid();
5398 _body.get().setName(name);
5405 return _body.get().getName();
5413 return _body.get().getNameHash();
5421 return _body.get().getNameHashValue();
5429 return _body.get().getConnectionName();
5440 _body.get().setLogonCorrelationData(logonCorrelationData_);
5447 return _body.get().getLogonCorrelationData();
5455 _body.get().addHttpPreflightHeader(header_);
5464 _body.get().addHttpPreflightHeader(key_, value_);
5470 _body.get().clearHttpPreflightHeaders();
5479 _body.get().setHttpPreflightHeaders(headers_);
5492 return _body.get().getServerVersion();
5503 return _body.get().getServerVersionInfo();
5517 return AMPS::convertVersionToNumber(version_.c_str(), version_.length());
5532 return AMPS::convertVersionToNumber(data_, len_);
5539 return _body.get().getURI();
5563 _body.get().connect(uri);
5570 _body.get().disconnect();
5588 _body.get().send(message);
5601 unsigned requestedAcks_,
bool isSubscribe_)
5603 Message::Command::Type commandType = isSubscribe_ ? Message::Command::Subscribe : Message::Command::SOW;
5604 _body.get().addMessageHandler(commandId_, messageHandler_,
5605 requestedAcks_, commandType);
5618 unsigned requestedAcks_, Message::Command::Type commandType_)
5620 _body.get().addMessageHandler(commandId_, messageHandler_,
5621 requestedAcks_, commandType_);
5629 return _body.get().removeMessageHandler(commandId_);
5659 AMPS_ATOMIC_BASE_TYPE subscribeGeneration_ = 0)
5661 return _body.get().send(messageHandler_, message_, timeout_, subscribeGeneration_);
5677 #if defined(_WIN32) || __cplusplus >= 201402L 5678 [[deprecated(
"Use HAClient for automatic reconnection and a ConnectionStateListener to monitor connection state.")]]
5682 _body.get().setDisconnectHandler(disconnectHandler);
5691 #if defined(_WIN32) || __cplusplus >= 201402L 5692 [[deprecated(
"Use HAClient for automatic reconnection and a ConnectionStateListener to monitor connection state.")]]
5696 return _body.get().getDisconnectHandler();
5705 return _body.get().getConnectionInfo();
5718 _body.get().setBookmarkStore(bookmarkStore_);
5726 return _body.
get().getBookmarkStore();
5734 return _body.get().getSubscriptionManager();
5746 _body.get().setSubscriptionManager(subscriptionManager_);
5770 _body.get().setPublishStore(publishStore_);
5778 return _body.
get().getPublishStore();
5786 _body.get().setGlobalCommandTypeMessageHandler(ClientImpl::GlobalCommandTypeHandlers::DuplicateMessage,
5787 duplicateMessageHandler_);
5801 return _body.get().getDuplicateMessageHandler();
5815 _body.get().setFailedWriteHandler(handler_);
5823 return _body.get().getFailedWriteHandler();
5844 amps_uint64_t
publish(
const std::string& topic_,
const std::string& data_)
5846 return _body.get().publish(topic_.c_str(), topic_.length(),
5847 data_.c_str(), data_.length());
5869 amps_uint64_t
publish(
const char* topic_,
size_t topicLength_,
5870 const char* data_,
size_t dataLength_)
5872 return _body.get().publish(topic_, topicLength_, data_, dataLength_);
5893 amps_uint64_t
publish(
const std::string& topic_,
const std::string& data_,
5894 unsigned long expiration_)
5896 return _body.get().publish(topic_.c_str(), topic_.length(),
5897 data_.c_str(), data_.length(), expiration_);
5920 amps_uint64_t
publish(
const char* topic_,
size_t topicLength_,
5921 const char* data_,
size_t dataLength_,
5922 unsigned long expiration_)
5924 return _body.get().publish(topic_, topicLength_,
5925 data_, dataLength_, expiration_);
5966 void publishFlush(
long timeout_ = 0,
unsigned ackType_ = Message::AckType::Processed)
5968 _body.get().publishFlush(timeout_, ackType_);
5987 amps_uint64_t
deltaPublish(
const std::string& topic_,
const std::string& data_)
5989 return _body.get().deltaPublish(topic_.c_str(), topic_.length(),
5990 data_.c_str(), data_.length());
6011 const char* data_,
size_t dataLength_)
6013 return _body.get().deltaPublish(topic_, topicLength_,
6014 data_, dataLength_);
6033 amps_uint64_t
deltaPublish(
const std::string& topic_,
const std::string& data_,
6034 unsigned long expiration_)
6036 return _body.get().deltaPublish(topic_.c_str(), topic_.length(),
6037 data_.c_str(), data_.length(),
6060 const char* data_,
size_t dataLength_,
6061 unsigned long expiration_)
6063 return _body.get().deltaPublish(topic_, topicLength_,
6064 data_, dataLength_, expiration_);
6084 const char* options_ = NULL)
6086 return _body.get().logon(timeout_, authenticator_, options_);
6101 std::string
logon(
const char* options_,
int timeout_ = 0)
6120 std::string
logon(
const std::string& options_,
int timeout_ = 0)
6146 const std::string& topic_,
6148 const std::string& filter_ =
"",
6149 const std::string& options_ =
"",
6150 const std::string& subId_ =
"")
6152 return _body.get().subscribe(messageHandler_, topic_, timeout_,
6153 filter_,
"", options_, subId_);
6172 long timeout_ = 0,
const std::string& filter_ =
"",
6173 const std::string& options_ =
"",
6174 const std::string& subId_ =
"")
6177 if (_body.get().getDefaultMaxDepth())
6179 result.
maxDepth(_body.get().getDefaultMaxDepth());
6181 result.setSubscription(_body.get().subscribe(
6183 topic_, timeout_, filter_,
"",
6184 options_, subId_,
false));
6204 long timeout_ = 0,
const std::string& filter_ =
"",
6205 const std::string& options_ =
"",
6206 const std::string& subId_ =
"")
6209 if (_body.get().getDefaultMaxDepth())
6211 result.
maxDepth(_body.get().getDefaultMaxDepth());
6213 result.setSubscription(_body.get().subscribe(
6215 topic_, timeout_, filter_,
"",
6216 options_, subId_,
false));
6233 const std::string& topic_,
6235 const std::string& filter_ =
"",
6236 const std::string& options_ =
"",
6237 const std::string& subId_ =
"")
6239 return _body.get().deltaSubscribe(messageHandler_, topic_, timeout_,
6240 filter_,
"", options_, subId_);
6251 long timeout_,
const std::string& filter_ =
"",
6252 const std::string& options_ =
"",
6253 const std::string& subId_ =
"")
6256 if (_body.get().getDefaultMaxDepth())
6258 result.
maxDepth(_body.get().getDefaultMaxDepth());
6260 result.setSubscription(_body.get().deltaSubscribe(
6262 topic_, timeout_, filter_,
"",
6263 options_, subId_,
false));
6269 long timeout_,
const std::string& filter_ =
"",
6270 const std::string& options_ =
"",
6271 const std::string& subId_ =
"")
6274 if (_body.get().getDefaultMaxDepth())
6276 result.
maxDepth(_body.get().getDefaultMaxDepth());
6278 result.setSubscription(_body.get().deltaSubscribe(
6280 topic_, timeout_, filter_,
"",
6281 options_, subId_,
false));
6311 const std::string& topic_,
6313 const std::string& bookmark_,
6314 const std::string& filter_ =
"",
6315 const std::string& options_ =
"",
6316 const std::string& subId_ =
"")
6318 return _body.get().subscribe(messageHandler_, topic_, timeout_,
6319 filter_, bookmark_, options_, subId_);
6340 const std::string& bookmark_,
6341 const std::string& filter_ =
"",
6342 const std::string& options_ =
"",
6343 const std::string& subId_ =
"")
6346 if (_body.get().getDefaultMaxDepth())
6348 result.
maxDepth(_body.get().getDefaultMaxDepth());
6350 result.setSubscription(_body.get().subscribe(
6352 topic_, timeout_, filter_,
6353 bookmark_, options_,
6361 const std::string& bookmark_,
6362 const std::string& filter_ =
"",
6363 const std::string& options_ =
"",
6364 const std::string& subId_ =
"")
6367 if (_body.get().getDefaultMaxDepth())
6369 result.
maxDepth(_body.get().getDefaultMaxDepth());
6371 result.setSubscription(_body.get().subscribe(
6373 topic_, timeout_, filter_,
6374 bookmark_, options_,
6389 return _body.get().unsubscribe(commandId);
6401 return _body.get().unsubscribe();
6435 const std::string& topic_,
6436 const std::string& filter_ =
"",
6437 const std::string& orderBy_ =
"",
6438 const std::string& bookmark_ =
"",
6439 int batchSize_ = DEFAULT_BATCH_SIZE,
6440 int topN_ = DEFAULT_TOP_N,
6441 const std::string& options_ =
"",
6442 long timeout_ = DEFAULT_COMMAND_TIMEOUT)
6444 return _body.get().sow(messageHandler_, topic_, filter_, orderBy_,
6445 bookmark_, batchSize_, topN_, options_,
6473 const std::string& filter_ =
"",
6474 const std::string& orderBy_ =
"",
6475 const std::string& bookmark_ =
"",
6476 int batchSize_ = DEFAULT_BATCH_SIZE,
6477 int topN_ = DEFAULT_TOP_N,
6478 const std::string& options_ =
"",
6479 long timeout_ = DEFAULT_COMMAND_TIMEOUT)
6482 if (_body.get().getDefaultMaxDepth())
6484 result.
maxDepth(_body.get().getDefaultMaxDepth());
6486 result.setSOWOnly(_body.get().sow(result.operator
MessageHandler(),
6487 topic_, filter_, orderBy_, bookmark_,
6488 batchSize_, topN_, options_, timeout_));
6494 const std::string& filter_ =
"",
6495 const std::string& orderBy_ =
"",
6496 const std::string& bookmark_ =
"",
6497 int batchSize_ = DEFAULT_BATCH_SIZE,
6498 int topN_ = DEFAULT_TOP_N,
6499 const std::string& options_ =
"",
6500 long timeout_ = DEFAULT_COMMAND_TIMEOUT)
6503 if (_body.get().getDefaultMaxDepth())
6505 result.
maxDepth(_body.get().getDefaultMaxDepth());
6507 result.setSOWOnly(_body.get().sow(result.operator
MessageHandler(),
6508 topic_, filter_, orderBy_, bookmark_,
6509 batchSize_, topN_, options_, timeout_));
6535 const std::string& topic_,
6537 const std::string& filter_ =
"",
6538 int batchSize_ = DEFAULT_BATCH_SIZE,
6539 int topN_ = DEFAULT_TOP_N)
6541 return _body.get().sow(messageHandler_, topic_, timeout_, filter_,
6567 const std::string& topic_,
6569 const std::string& filter_ =
"",
6570 int batchSize_ = DEFAULT_BATCH_SIZE,
6571 bool oofEnabled_ =
false,
6572 int topN_ = DEFAULT_TOP_N)
6574 return _body.get().sowAndSubscribe(messageHandler_, topic_, timeout_,
6575 filter_, batchSize_, oofEnabled_,
6600 const std::string& filter_ =
"",
6601 int batchSize_ = DEFAULT_BATCH_SIZE,
6602 bool oofEnabled_ =
false,
6603 int topN_ = DEFAULT_TOP_N)
6606 if (_body.get().getDefaultMaxDepth())
6608 result.
maxDepth(_body.get().getDefaultMaxDepth());
6610 result.setSubscription(_body.get().sowAndSubscribe(
6612 topic_, timeout_, filter_,
6613 batchSize_, oofEnabled_,
6638 const std::string& filter_ =
"",
6639 int batchSize_ = DEFAULT_BATCH_SIZE,
6640 bool oofEnabled_ =
false,
6641 int topN_ = DEFAULT_TOP_N)
6644 if (_body.get().getDefaultMaxDepth())
6646 result.
maxDepth(_body.get().getDefaultMaxDepth());
6648 result.setSubscription(_body.get().sowAndSubscribe(
6650 topic_, timeout_, filter_,
6651 batchSize_, oofEnabled_,
6685 const std::string& topic_,
6686 const std::string& filter_ =
"",
6687 const std::string& orderBy_ =
"",
6688 const std::string& bookmark_ =
"",
6689 int batchSize_ = DEFAULT_BATCH_SIZE,
6690 int topN_ = DEFAULT_TOP_N,
6691 const std::string& options_ =
"",
6692 long timeout_ = DEFAULT_COMMAND_TIMEOUT)
6694 return _body.get().sowAndSubscribe(messageHandler_, topic_, filter_,
6695 orderBy_, bookmark_, batchSize_,
6696 topN_, options_, timeout_);
6724 const std::string& filter_ =
"",
6725 const std::string& orderBy_ =
"",
6726 const std::string& bookmark_ =
"",
6727 int batchSize_ = DEFAULT_BATCH_SIZE,
6728 int topN_ = DEFAULT_TOP_N,
6729 const std::string& options_ =
"",
6730 long timeout_ = DEFAULT_COMMAND_TIMEOUT)
6733 if (_body.get().getDefaultMaxDepth())
6735 result.
maxDepth(_body.get().getDefaultMaxDepth());
6737 result.setSubscription(_body.get().sowAndSubscribe(
6739 topic_, filter_, orderBy_,
6740 bookmark_, batchSize_, topN_,
6741 options_, timeout_,
false));
6747 const std::string& filter_ =
"",
6748 const std::string& orderBy_ =
"",
6749 const std::string& bookmark_ =
"",
6750 int batchSize_ = DEFAULT_BATCH_SIZE,
6751 int topN_ = DEFAULT_TOP_N,
6752 const std::string& options_ =
"",
6753 long timeout_ = DEFAULT_COMMAND_TIMEOUT)
6756 if (_body.get().getDefaultMaxDepth())
6758 result.
maxDepth(_body.get().getDefaultMaxDepth());
6760 result.setSubscription(_body.get().sowAndSubscribe(
6762 topic_, filter_, orderBy_,
6763 bookmark_, batchSize_, topN_,
6764 options_, timeout_,
false));
6793 const std::string& topic_,
6794 const std::string& filter_ =
"",
6795 const std::string& orderBy_ =
"",
6796 int batchSize_ = DEFAULT_BATCH_SIZE,
6797 int topN_ = DEFAULT_TOP_N,
6798 const std::string& options_ =
"",
6799 long timeout_ = DEFAULT_COMMAND_TIMEOUT)
6801 return _body.get().sowAndDeltaSubscribe(messageHandler_, topic_,
6802 filter_, orderBy_, batchSize_,
6803 topN_, options_, timeout_);
6826 const std::string& filter_ =
"",
6827 const std::string& orderBy_ =
"",
6828 int batchSize_ = DEFAULT_BATCH_SIZE,
6829 int topN_ = DEFAULT_TOP_N,
6830 const std::string& options_ =
"",
6831 long timeout_ = DEFAULT_COMMAND_TIMEOUT)
6834 if (_body.get().getDefaultMaxDepth())
6836 result.
maxDepth(_body.get().getDefaultMaxDepth());
6838 result.setSubscription(_body.get().sowAndDeltaSubscribe(
6840 topic_, filter_, orderBy_,
6841 batchSize_, topN_, options_,
6848 const std::string& filter_ =
"",
6849 const std::string& orderBy_ =
"",
6850 int batchSize_ = DEFAULT_BATCH_SIZE,
6851 int topN_ = DEFAULT_TOP_N,
6852 const std::string& options_ =
"",
6853 long timeout_ = DEFAULT_COMMAND_TIMEOUT)
6856 if (_body.get().getDefaultMaxDepth())
6858 result.
maxDepth(_body.get().getDefaultMaxDepth());
6860 result.setSubscription(_body.get().sowAndDeltaSubscribe(
6862 topic_, filter_, orderBy_,
6863 batchSize_, topN_, options_,
6893 const std::string& topic_,
6895 const std::string& filter_ =
"",
6896 int batchSize_ = DEFAULT_BATCH_SIZE,
6897 bool oofEnabled_ =
false,
6898 bool sendEmpties_ =
false,
6899 int topN_ = DEFAULT_TOP_N)
6901 return _body.get().sowAndDeltaSubscribe(messageHandler_, topic_,
6902 timeout_, filter_, batchSize_,
6903 oofEnabled_, sendEmpties_,
6930 const std::string& filter_ =
"",
6931 int batchSize_ = DEFAULT_BATCH_SIZE,
6932 bool oofEnabled_ =
false,
6933 bool sendEmpties_ =
false,
6934 int topN_ = DEFAULT_TOP_N)
6937 if (_body.get().getDefaultMaxDepth())
6939 result.
maxDepth(_body.get().getDefaultMaxDepth());
6941 result.setSubscription(_body.get().sowAndDeltaSubscribe(
6943 topic_, timeout_, filter_,
6944 batchSize_, oofEnabled_,
6945 sendEmpties_, topN_,
false));
6971 const std::string& filter_ =
"",
6972 int batchSize_ = DEFAULT_BATCH_SIZE,
6973 bool oofEnabled_ =
false,
6974 bool sendEmpties_ =
false,
6975 int topN_ = DEFAULT_TOP_N)
6978 if (_body.get().getDefaultMaxDepth())
6980 result.
maxDepth(_body.get().getDefaultMaxDepth());
6982 result.setSubscription(_body.get().sowAndDeltaSubscribe(
6984 topic_, timeout_, filter_,
6985 batchSize_, oofEnabled_,
6986 sendEmpties_, topN_,
false));
7009 const std::string& topic,
7010 const std::string& filter,
7013 return _body.get().sowDelete(messageHandler, topic, filter, timeout);
7035 stream.
timeout((
unsigned int)timeout_);
7042 stream.setStatsOnly(cid);
7043 _body.get().sowDelete(stream.operator
MessageHandler(), topic_, filter_, timeout_, cid);
7044 return *(stream.
begin());
7046 catch (
const DisconnectedException&)
7048 removeMessageHandler(cid);
7051 catch (
const TimedOutException&)
7053 removeMessageHandler(cid);
7064 _body.get().startTimer();
7075 return _body.get().stopTimer(messageHandler);
7100 const std::string& topic_,
7101 const std::string& keys_,
7104 return _body.get().sowDeleteByKeys(messageHandler_, topic_, keys_, timeout_);
7130 stream.
timeout((
unsigned int)timeout_);
7137 stream.setStatsOnly(cid);
7138 _body.get().sowDeleteByKeys(stream.operator
MessageHandler(), topic_, keys_, timeout_, cid);
7139 return *(stream.
begin());
7141 catch (
const DisconnectedException&)
7143 removeMessageHandler(cid);
7146 catch (
const TimedOutException&)
7148 removeMessageHandler(cid);
7168 const std::string& topic_,
const std::string& data_,
7171 return _body.get().sowDeleteByData(messageHandler_, topic_, data_, timeout_);
7192 stream.
timeout((
unsigned int)timeout_);
7199 stream.setStatsOnly(cid);
7200 _body.get().sowDeleteByData(stream.operator
MessageHandler(), topic_, data_, timeout_, cid);
7201 return *(stream.
begin());
7203 catch (
const DisconnectedException&)
7205 removeMessageHandler(cid);
7208 catch (
const TimedOutException&)
7210 removeMessageHandler(cid);
7220 return _body.get().getHandle();
7233 _body.get().setExceptionListener(pListener_);
7244 #if defined(_WIN32) || __cplusplus >= 201402L 7245 [[deprecated(
"Use setExceptionListener(std::shared_ptr<const ExceptionListener>&)")]]
7249 _body.get().setExceptionListener(listener_);
7256 return _body.get().getExceptionListener();
7282 _body.get().setHeartbeat(heartbeatTime_, readTimeout_);
7306 _body.get().setHeartbeat(heartbeatTime_, 2 * heartbeatTime_);
7310 #if defined(_WIN32) || __cplusplus >= 201402L 7311 [[deprecated(
"Use setLastChanceMessageHandler.")]]
7315 setLastChanceMessageHandler(messageHandler);
7322 _body.get().setGlobalCommandTypeMessageHandler(ClientImpl::GlobalCommandTypeHandlers::LastChance,
7348 _body.get().setGlobalCommandTypeMessageHandler(command_, handler_);
7373 _body.get().setGlobalCommandTypeMessageHandler(command_, handler_);
7456 _body.get().addConnectionStateListener(listener);
7464 _body.get().removeConnectionStateListener(listener);
7471 _body.get().clearConnectionStateListeners();
7501 return _body.get().executeAsync(command_, handler_);
7539 if (command_.isSubscribe())
7541 Message& message = command_.getMessage();
7544 if (useExistingHandler)
7547 if (_body.get()._routes.getRoute(subId, existingHandler))
7550 _body.get().executeAsync(command_, existingHandler,
false);
7555 id = _body.get().executeAsync(command_, handler_,
false);
7557 catch (
const DisconnectedException&)
7559 removeMessageHandler(command_.getMessage().
getCommandId());
7560 if (command_.isSubscribe())
7564 if (command_.isSow())
7566 removeMessageHandler(command_.getMessage().
getQueryID());
7597 _body.get().ack(topic_, bookmark_, options_);
7619 void ack(
const std::string& topic_,
const std::string& bookmark_,
7620 const char* options_ = NULL)
7622 _body.get().ack(
Field(topic_.data(), topic_.length()),
Field(bookmark_.data(), bookmark_.length()), options_);
7630 void ackDeferredAutoAck(
Field& topic_,
Field& bookmark_,
const char* options_ = NULL)
7632 _body.get()._ack(topic_, bookmark_, options_);
7645 _body.get().flushAcks();
7654 return _body.get().getAutoAck();
7664 _body.get().setAutoAck(isAutoAckEnabled_);
7672 return _body.get().getAckBatchSize();
7682 _body.get().setAckBatchSize(ackBatchSize_);
7693 return _body.get().getAckTimeout();
7705 if (!ackTimeout_ && _body.get().getAckBatchSize() > 1)
7707 throw UsageException(
"Ack timeout must be > 0 when ack batch size > 1");
7709 _body.get().setAckTimeout(ackTimeout_);
7723 _body.get().setRetryOnDisconnect(isRetryOnDisconnect_);
7732 return _body.get().getRetryOnDisconnect();
7741 _body.get().setDefaultMaxDepth(maxDepth_);
7750 return _body.get().getDefaultMaxDepth();
7762 return _body.get().setTransportFilterFunction(filter_, userData_);
7776 return _body.get().setThreadCreatedCallback(callback_, userData_);
7787 return _body.get().setPublishBatching(batchSize_, batchTimeoutMillis_);
7795 void deferredExecution(DeferredExecutionFunc func_,
void* userData_)
7797 _body.get().deferredExecution(func_, userData_);
7807 AMPS_CALL_EXCEPTION_WRAPPER(_globalCommandTypeHandlers[GlobalCommandTypeHandlers::LastChance].invoke(message));
7813 unsigned deliveries = 0;
7825 const char* data = NULL;
7827 const char* status = NULL;
7828 size_t statusLen = 0;
7830 const size_t NotEntitled = 12, Duplicate = 9, Failure = 7;
7833 if (len == NotEntitled || len == Duplicate ||
7834 (statusLen == Failure && status[0] ==
'f'))
7836 if (_failedWriteHandler)
7838 if (_publishStore.isValid())
7840 amps_uint64_t sequence =
7842 FailedWriteStoreReplayer replayer(
this, data, len);
7843 AMPS_CALL_EXCEPTION_WRAPPER(_publishStore.replaySingle(
7844 replayer, sequence));
7850 AMPS_CALL_EXCEPTION_WRAPPER(
7851 _failedWriteHandler->failedWrite(emptyMessage,
7857 if (_publishStore.isValid())
7866 AMPS_CALL_EXCEPTION_WRAPPER(_publishStore.discardUpTo(seq));
7870 if (!deliveries && _bookmarkStore.isValid())
7877 const char* bookmarkData = NULL;
7878 size_t bookmarkLen = 0;
7884 if (bookmarkLen > 0 && _routes.hasRoute(subId))
7887 _bookmarkStore.persisted(subId,
Message::Field(bookmarkData, bookmarkLen));
7892 catch (std::exception& ex)
7894 AMPS_UNHANDLED_EXCEPTION(ex);
7900 ClientImpl::processedAck(
Message& message)
7902 unsigned deliveries = 0;
7904 const char* data = NULL;
7908 Lock<Mutex> l(_lock);
7911 Lock<Mutex> guard(_ackMapLock);
7912 AckMap::iterator i = _ackMap.find(std::string(data, len));
7913 if (i != _ackMap.end())
7923 ack.setStatus(data, len);
7925 ack.setReason(data, len);
7927 ack.setUsername(data, len);
7929 ack.setPassword(data, len);
7931 ack.setServerVersion(data, len);
7933 ack.setOptions(data, len);
7943 ClientImpl::checkAndSendHeartbeat(
bool force)
7945 if (force || _heartbeatTimer.check())
7947 _heartbeatTimer.start();
7950 sendWithoutRetry(_beatMessage);
7959 inline ConnectionInfo ClientImpl::getConnectionInfo()
const 7961 ConnectionInfo info;
7962 std::ostringstream writer;
7964 info[
"client.uri"] = _lastUri;
7965 info[
"client.name"] = _name;
7966 info[
"client.username"] = _username;
7967 if (_publishStore.isValid())
7969 writer << _publishStore.unpersistedCount();
7970 info[
"publishStore.unpersistedCount"] = writer.str();
7978 inline std::string ClientImpl::logon(
long timeout_,
Authenticator& authenticator_,
7979 const char* options_)
7981 Lock<Mutex> l(_lock);
7982 std::string cmdId = _logon(timeout_, authenticator_, options_);
7984 if (_subscriptionManager)
7987 Client wrapper(
this,
false);
7990 Unlock<Mutex> unlock(_lock);
7991 _subscriptionManager->resubscribe(wrapper);
7993 broadcastConnectionStateChanged(ConnectionStateListener::Resubscribed);
7999 ClientImpl::ClientImplMessageHandler(
amps_handle messageHandle_,
void* userData_)
8001 const unsigned SOWMask = Message::Command::SOW | Message::Command::GroupBegin | Message::Command::GroupEnd;
8002 const unsigned PublishMask = Message::Command::OOF | Message::Command::Publish | Message::Command::DeltaPublish;
8003 ClientImpl* me = (ClientImpl*) userData_;
8004 AMPS_CALL_EXCEPTION_WRAPPER_2(me, me->processDeferredExecutions());
8005 if (!messageHandle_)
8007 if (me->_queueAckTimeout)
8009 me->checkQueueAcks();
8011 me->checkAndSendHeartbeat();
8015 me->_readMessage.replace(messageHandle_);
8016 Message& message = me->_readMessage;
8018 if (commandType & SOWMask)
8020 #if 0 // Not currently implemented, to avoid an extra branch in delivery 8024 AMPS_CALL_EXCEPTION_WRAPPER_2(me,
8025 me->_globalCommandTypeHandlers[1 + (commandType / 8192)].invoke(message));
8027 AMPS_CALL_EXCEPTION_WRAPPER_2(me, me->_routes.deliverData(message,
8030 else if (commandType & PublishMask)
8032 #if 0 // Not currently implemented, to avoid an extra branch in delivery 8033 AMPS_CALL_EXCEPTION_WRAPPER_2(me,
8034 me->_globalCommandTypeHandlers[(commandType == Message::Command::Publish ?
8035 GlobalCommandTypeHandlers::Publish :
8036 GlobalCommandTypeHandlers::OOF)].invoke(message));
8038 const char* subIds = NULL;
8039 size_t subIdsLen = 0;
8042 &subIds, &subIdsLen);
8043 size_t subIdCount = me->_routes.parseRoutes(
AMPS::Field(subIds, subIdsLen), me->_routeCache);
8044 for (
size_t i = 0; i < subIdCount; ++i)
8046 MessageRouter::RouteCache::value_type& lookupResult = me->_routeCache[i];
8048 if (handler.isValid())
8051 AMPS_SubscriptionId,
8052 subIds + lookupResult.idOffset,
8053 lookupResult.idLength);
8056 bool isAutoAck = me->_isAutoAckEnabled;
8058 if (!isMessageQueue && !bookmark.
empty() &&
8059 me->_bookmarkStore.isValid())
8061 if (me->_bookmarkStore.isDiscarded(me->_readMessage))
8064 if (me->_globalCommandTypeHandlers[GlobalCommandTypeHandlers::DuplicateMessage].isValid())
8066 AMPS_CALL_EXCEPTION_WRAPPER_2(me, me->_globalCommandTypeHandlers[GlobalCommandTypeHandlers::DuplicateMessage].invoke(message));
8071 me->_bookmarkStore.log(me->_readMessage);
8072 AMPS_CALL_EXCEPTION_WRAPPER_2(me,
8073 handler.invoke(message));
8078 if (isMessageQueue && isAutoAck)
8082 AMPS_CALL_EXCEPTION_WRAPPER_STREAM_FULL_2(me, handler.invoke(message));
8083 if (!message.getIgnoreAutoAck())
8085 AMPS_CALL_EXCEPTION_WRAPPER_2(me,
8089 catch (std::exception& ex)
8091 if (!message.getIgnoreAutoAck())
8093 AMPS_CALL_EXCEPTION_WRAPPER_2(me,
8096 AMPS_UNHANDLED_EXCEPTION_2(me, ex);
8101 AMPS_CALL_EXCEPTION_WRAPPER_2(me,
8102 handler.invoke(message));
8108 me->lastChance(message);
8112 else if (commandType == Message::Command::Ack)
8115 unsigned deliveries = 0U;
8118 case Message::AckType::Persisted:
8119 deliveries += me->persistedAck(message);
8121 case Message::AckType::Processed:
8122 deliveries += me->processedAck(message);
8125 MessageHandler ackHandler = me->_globalCommandTypeHandlers[GlobalCommandTypeHandlers::Ack];
8126 if (ackHandler.isValid())
8128 AMPS_CALL_EXCEPTION_WRAPPER_2(me, ackHandler.invoke(message));
8131 AMPS_CALL_EXCEPTION_WRAPPER_2(me, deliveries += me->_routes.deliverAck(message, ackType));
8132 if (deliveries == 0)
8134 me->lastChance(message);
8137 else if (commandType == Message::Command::Heartbeat)
8139 AMPS_CALL_EXCEPTION_WRAPPER_2(me,
8140 me->_globalCommandTypeHandlers[GlobalCommandTypeHandlers::Heartbeat].invoke(message));
8141 if (me->_heartbeatTimer.getTimeout() != 0.0)
8143 me->checkAndSendHeartbeat(
true);
8147 me->lastChance(message);
8153 unsigned deliveries = 0U;
8156 while (me->_connected)
8160 deliveries = me->_routes.deliverData(message, message.
getCommandId());
8164 catch (MessageStreamFullException&)
8166 catch (MessageStreamFullException& msfEx_)
8171 me->checkAndSendHeartbeat(
false);
8174 catch (std::exception&)
8176 catch (std::exception& stdEx_)
8184 catch (std::exception& stdEx_)
8188 me->_exceptionListener->exceptionThrown(stdEx_);
8195 if (deliveries == 0)
8197 me->lastChance(message);
8200 me->checkAndSendHeartbeat();
8205 ClientImpl::ClientImplPreDisconnectHandler(
amps_handle ,
unsigned failedConnectionVersion,
void* userData)
8207 ClientImpl* me = (ClientImpl*) userData;
8210 me->clearAcks(failedConnectionVersion);
8214 ClientImpl::ClientImplDisconnectHandler(
amps_handle ,
void* userData)
8216 ClientImpl* me = (ClientImpl*) userData;
8217 Lock<Mutex> l(me->_lock);
8218 Client wrapper(me,
false);
8221 me->broadcastConnectionStateChanged(ConnectionStateListener::Disconnected);
8223 me->captureSubscriptionManagerGenerationCount();
8224 bool retryInProgress =
false;
8227 me->_connected =
false;
8228 me->_lock.signalAll();
8231 Unlock<Mutex> unlock(me->_lock);
8232 me->_disconnectHandler.invoke(wrapper);
8235 catch (
const RetryOperationException&)
8237 catch (
const RetryOperationException& ex)
8240 retryInProgress =
true;
8242 catch (
const std::exception& ex)
8244 AMPS_UNHANDLED_EXCEPTION_2(me, ex);
8246 me->_lock.signalAll();
8248 if (!me->_connected)
8250 if (retryInProgress)
8252 AMPS_UNHANDLED_EXCEPTION_2(me, RetryOperationException(
"Reconnect in progress."));
8256 me->broadcastConnectionStateChanged(ConnectionStateListener::Shutdown);
8257 AMPS_UNHANDLED_EXCEPTION_2(me, DisconnectedException(
"Reconnect failed."));
8265 ClientImpl::ClientImplGetHttpPreflightMessage(
void* userData_)
8267 ClientImpl* me = (ClientImpl*)userData_;
8268 std::ostringstream os;
8271 size_t firstColon = me->_lastUri.find(
':');
8273 size_t pathEnd = me->_lastUri.find(
'?');
8275 size_t lastColon = me->_lastUri.rfind(
':', pathEnd);
8277 size_t at = me->_lastUri.rfind(
'@', lastColon);
8279 size_t hostStart = at == std::string::npos ? firstColon + 3 : at + 1;
8280 size_t hostLen = lastColon - hostStart;
8282 size_t pathStart = me->_lastUri.find(
'/', lastColon);
8283 size_t pathLen = pathEnd;
8284 if (pathEnd != std::string::npos)
8286 pathLen = pathEnd - pathStart;
8288 os <<
"GET " << me->_lastUri.substr(pathStart, pathLen)
8289 <<
" HTTP/1.1\r\nHost: " << me->_lastUri.substr(hostStart, hostLen)
8290 <<
"\r\nConnection: upgrade\r\nUpgrade: " 8291 << me->_lastUri.substr(0, firstColon) <<
"\r\n";
8292 for (
auto& header : me->_httpPreflightHeaders)
8294 os << header <<
"\r\n";
8297 me->_preflightMessage = os.str();
8298 return me->_preflightMessage.c_str();
8313 iterator(
const char* data_,
size_t len_,
size_t pos_,
char fieldSep_)
8314 : _data(data_), _len(len_), _pos(pos_), _fieldSep(fieldSep_)
8316 while (_pos != _len && _data[_pos] == _fieldSep)
8322 typedef void* difference_type;
8323 typedef std::forward_iterator_tag iterator_category;
8324 typedef std::pair<Message::Field, Message::Field> value_type;
8325 typedef value_type* pointer;
8326 typedef value_type& reference;
8327 bool operator==(
const iterator& rhs)
const 8329 return _pos == rhs._pos;
8331 bool operator!=(
const iterator& rhs)
const 8333 return _pos != rhs._pos;
8335 iterator& operator++()
8338 while (_pos != _len && _data[_pos] != _fieldSep)
8343 while (_pos != _len && _data[_pos] == _fieldSep)
8350 value_type operator*()
const 8353 size_t i = _pos, keyLength = 0, valueStart = 0, valueLength = 0;
8354 for (; i < _len && _data[i] !=
'='; ++i)
8359 result.first.assign(_data + _pos, keyLength);
8361 if (i < _len && _data[i] ==
'=')
8365 for (; i < _len && _data[i] != _fieldSep; ++i)
8370 result.second.assign(_data + valueStart, valueLength);
8376 class reverse_iterator
8383 typedef std::pair<Message::Field, Message::Field> value_type;
8384 reverse_iterator(
const char* data,
size_t len,
const char* pos,
char fieldsep)
8385 : _data(data), _len(len), _pos(pos), _fieldSep(fieldsep)
8390 while (_pos >= _data && *_pos == _fieldSep)
8394 while (_pos > _data && *_pos != _fieldSep)
8401 if (_pos > _data || (_pos == _data && *_pos == _fieldSep))
8411 bool operator==(
const reverse_iterator& rhs)
const 8413 return _pos == rhs._pos;
8415 bool operator!=(
const reverse_iterator& rhs)
const 8417 return _pos != rhs._pos;
8419 reverse_iterator& operator++()
8430 while (_pos >= _data && *_pos == _fieldSep)
8435 while (_pos > _data && *_pos != _fieldSep)
8439 if (_pos > _data || (_pos == _data && *_pos == _fieldSep))
8450 value_type operator*()
const 8453 size_t keyLength = 0, valueStart = 0, valueLength = 0;
8454 size_t i = (size_t)(_pos - _data);
8455 for (; i < _len && _data[i] !=
'='; ++i)
8459 result.first.assign(_pos, keyLength);
8460 if (i < _len && _data[i] ==
'=')
8464 for (; i < _len && _data[i] != _fieldSep; ++i)
8469 result.second.assign(_data + valueStart, valueLength);
8474 : _data(data.
data()), _len(data.
len()),
8475 _fieldSep(fieldSeparator)
8479 FIX(
const char* data,
size_t len,
char fieldSeparator = 1)
8480 : _data(data), _len(len), _fieldSep(fieldSeparator)
8484 iterator begin()
const 8486 return iterator(_data, _len, 0, _fieldSep);
8488 iterator end()
const 8490 return iterator(_data, _len, _len, _fieldSep);
8494 reverse_iterator rbegin()
const 8496 return reverse_iterator(_data, _len, _data + (_len - 1), _fieldSep);
8499 reverse_iterator rend()
const 8501 return reverse_iterator(_data, _len, 0, _fieldSep);
8522 std::stringstream _data;
8539 void append(
const T& tag,
const char* value,
size_t offset,
size_t length)
8541 _data << tag <<
'=';
8542 _data.write(value + offset, (std::streamsize)length);
8550 void append(
const T& tag,
const std::string& value)
8552 _data << tag <<
'=' << value << _fs;
8561 operator std::string()
const 8569 _data.str(std::string());
8606 typedef std::map<Message::Field, Message::Field>
map_type;
8617 for (FIX::iterator a = fix.begin(); a != fix.end(); ++a)
8626 #define AMPS_MESSAGE_STREAM_CACHE_MAX 128 8630 std::deque<Message> _q;
8631 std::deque<Message> _cache;
8632 std::string _commandId;
8634 std::string _queryId;
8638 unsigned _requestedAcks;
8642 typedef enum :
unsigned int { Unset = 0x0, Running = 0x10, Subscribe = 0x11, SOWOnly = 0x12, AcksOnly = 0x13, Conflate = 0x14, Closed = 0x1, Disconnected = 0x2 } State;
8643 #if __cplusplus >= 201100L || _MSC_VER >= 1900 8644 std::atomic<State> _state;
8646 volatile State _state;
8648 typedef std::map<std::string, Message*> SOWKeyMap;
8649 SOWKeyMap _sowKeyMap;
8651 MessageStreamImpl(
const Client& client_)
8654 _maxDepth((
unsigned)~0),
8656 _cacheMax(AMPS_MESSAGE_STREAM_CACHE_MAX),
8659 if (_client.isValid())
8665 MessageStreamImpl(ClientImpl* client_)
8666 : _client(client_,
false),
8668 _maxDepth((
unsigned)~0),
8672 if (_client.isValid())
8678 ~MessageStreamImpl()
8682 virtual void destroy()
8688 catch (std::exception& e)
8692 if (_client.isValid())
8699 if (_client.isValid())
8703 _client = Client((ClientImpl*)NULL);
8704 c.deferredExecution(MessageStreamImpl::destroyer,
this);
8712 static void destroyer(
void* vpMessageStreamImpl_)
8714 delete ((MessageStreamImpl*)vpMessageStreamImpl_);
8717 void setSubscription(
const std::string& subId_,
8718 const std::string& commandId_ =
"",
8719 const std::string& queryId_ =
"")
8721 Lock<Mutex> lock(_lock);
8723 if (!commandId_.empty() && commandId_ != subId_)
8725 _commandId = commandId_;
8727 if (!queryId_.empty() && queryId_ != subId_ && queryId_ != commandId_)
8729 _queryId = queryId_;
8732 if (Disconnected == _state)
8736 assert(Unset == _state);
8740 void setSOWOnly(
const std::string& commandId_,
8741 const std::string& queryId_ =
"")
8743 Lock<Mutex> lock(_lock);
8744 _commandId = commandId_;
8745 if (!queryId_.empty() && queryId_ != commandId_)
8747 _queryId = queryId_;
8750 if (Disconnected == _state)
8754 assert(Unset == _state);
8758 void setStatsOnly(
const std::string& commandId_,
8759 const std::string& queryId_ =
"")
8761 Lock<Mutex> lock(_lock);
8762 _commandId = commandId_;
8763 if (!queryId_.empty() && queryId_ != commandId_)
8765 _queryId = queryId_;
8768 if (Disconnected == _state)
8772 assert(Unset == _state);
8774 _requestedAcks = Message::AckType::Stats;
8777 void setAcksOnly(
const std::string& commandId_,
unsigned acks_)
8779 Lock<Mutex> lock(_lock);
8780 _commandId = commandId_;
8782 if (Disconnected == _state)
8786 assert(Unset == _state);
8788 _requestedAcks = acks_;
8793 Lock<Mutex> lock(_lock);
8794 if (state_ == AMPS::ConnectionStateListener::Disconnected)
8796 _state = Disconnected;
8799 else if (state_ == AMPS::ConnectionStateListener::Connected
8800 && _commandId.empty()
8802 && _queryId.empty())
8810 void timeout(
unsigned timeout_)
8812 _timeout = timeout_;
8816 if (_state == Subscribe)
8821 void maxDepth(
unsigned maxDepth_)
8825 _maxDepth = maxDepth_;
8829 _maxDepth = (unsigned)~0;
8832 unsigned getMaxDepth(
void)
const 8836 unsigned getDepth(
void)
const 8838 return (
unsigned)(_q.size());
8843 Lock<Mutex> lock(_lock);
8844 if (!_previousTopic.
empty() && !_previousBookmark.
empty())
8848 if (_client.isValid())
8850 _client.ackDeferredAutoAck(_previousTopic, _previousBookmark);
8859 current_.invalidate();
8860 _previousTopic.
clear();
8861 _previousBookmark.
clear();
8864 _previousTopic.
clear();
8865 _previousBookmark.
clear();
8868 long minWaitTime = (_timeout && _timeout < 1000) ? _timeout : 1000;
8869 Timer timer((
double)_timeout);
8871 while (_q.empty() && _state & Running)
8874 _lock.wait(minWaitTime);
8876 Unlock<Mutex> unlck(_lock);
8877 amps_invoke_waiting_function();
8882 if (timer.checkAndGetRemaining(&minWaitTime))
8888 minWaitTime = (minWaitTime < 1000) ? minWaitTime : 1000;
8891 if (current_.isValid() && _cache.size() < _cacheMax)
8894 _cache.push_back(current_);
8898 current_ = _q.front();
8899 if (_q.size() == _maxDepth)
8904 if (_state == Conflate)
8906 std::string sowKey = current_.
getSowKey();
8907 if (sowKey.length())
8909 _sowKeyMap.erase(sowKey);
8912 else if (_state == AcksOnly)
8916 if ((_state == AcksOnly && _requestedAcks == 0) ||
8917 (_state == SOWOnly && current_.
getCommand() ==
"group_end"))
8921 else if (current_.isValid()
8932 if (_state == Disconnected)
8934 throw DisconnectedException(
"Connection closed.");
8936 current_.invalidate();
8937 if (_state == Closed)
8941 return _timeout != 0;
8945 if (_client.isValid())
8947 if (_state == SOWOnly || _state == Subscribe)
8949 if (!_commandId.empty())
8953 if (!_subId.empty())
8957 if (!_queryId.empty())
8964 if (!_commandId.empty())
8968 if (!_subId.empty())
8972 if (!_queryId.empty())
8978 if (_state == SOWOnly || _state == Subscribe || _state == Unset)
8983 static void _messageHandler(
const Message& message_, MessageStreamImpl* this_)
8985 Lock<Mutex> lock(this_->_lock);
8986 if (this_->_state != Conflate)
8988 AMPS_TESTING_SLOW_MESSAGE_STREAM
8989 if (this_->_q.size() >= this_->_maxDepth)
8994 this_->_lock.signalAll();
8995 throw MessageStreamFullException(
"Stream is currently full.");
8997 if (!this_->_cache.empty())
8999 this_->_cache.front().deepCopy(message_);
9000 this_->_q.push_back(this_->_cache.front());
9001 this_->_cache.pop_front();
9005 this_->_q.emplace_back(message_.
deepCopy());
9008 this_->_client.isValid() && this_->_client.getAutoAck() &&
9012 message_.setIgnoreAutoAck();
9017 std::string sowKey = message_.
getSowKey();
9018 if (sowKey.length())
9020 SOWKeyMap::iterator it = this_->_sowKeyMap.find(sowKey);
9021 if (it != this_->_sowKeyMap.end())
9023 it->second->deepCopy(message_);
9027 if (this_->_q.size() >= this_->_maxDepth)
9033 this_->_lock.signalAll();
9034 throw MessageStreamFullException(
"Stream is currently full.");
9036 if (!this_->_cache.empty())
9038 this_->_cache.front().deepCopy(message_);
9039 this_->_q.push_back(this_->_cache.front());
9040 this_->_cache.pop_front();
9044 this_->_q.emplace_back(message_.
deepCopy());
9046 this_->_sowKeyMap[sowKey] = &(this_->_q.back());
9051 if (this_->_q.size() >= this_->_maxDepth)
9056 this_->_lock.signalAll();
9057 throw MessageStreamFullException(
"Stream is currently full.");
9059 if (!this_->_cache.empty())
9061 this_->_cache.front().deepCopy(message_);
9062 this_->_q.push_back(this_->_cache.front());
9063 this_->_cache.pop_front();
9067 this_->_q.emplace_back(message_.
deepCopy());
9070 this_->_client.isValid() && this_->_client.getAutoAck() &&
9074 message_.setIgnoreAutoAck();
9078 this_->_lock.signalAll();
9081 inline MessageStream::MessageStream(
const Client& client_)
9082 : _body(
new MessageStreamImpl(client_))
9085 inline MessageStream::MessageStream(RefHandle<MessageStreamImpl> body_)
9089 inline void MessageStream::iterator::advance(
void)
9091 _pStream = _pStream->_body->next(_current) ? _pStream : NULL;
9095 return MessageHandler((
void(*)(
const Message&,
void*))MessageStreamImpl::_messageHandler, &_body.get());
9100 if (handler_._func == (MessageHandler::FunctionType)MessageStreamImpl::_messageHandler)
9102 result._body = (MessageStreamImpl*)(handler_._userData);
9107 inline void MessageStream::setSOWOnly(
const std::string& commandId_,
9108 const std::string& queryId_)
9110 _body->setSOWOnly(commandId_, queryId_);
9112 inline void MessageStream::setSubscription(
const std::string& subId_,
9113 const std::string& commandId_,
9114 const std::string& queryId_)
9116 _body->setSubscription(subId_, commandId_, queryId_);
9118 inline void MessageStream::setStatsOnly(
const std::string& commandId_,
9119 const std::string& queryId_)
9121 _body->setStatsOnly(commandId_, queryId_);
9123 inline void MessageStream::setAcksOnly(
const std::string& commandId_,
9126 _body->setAcksOnly(commandId_, acks_);
9145 return _body->getMaxDepth();
9149 return _body->getDepth();
9152 inline MessageStream ClientImpl::getEmptyMessageStream(
void)
9162 ClientImpl& body = _body.get();
9163 Message& message = command_.getMessage();
9167 if (useExistingHandler)
9173 if (body._routes.getRoute(subId, existingHandler))
9176 body.executeAsync(command_, existingHandler,
false);
9177 return MessageStream::fromExistingHandler(existingHandler);
9186 if ((command & Message::Command::NoDataCommands)
9187 && (ackTypes == Message::AckType::Persisted
9188 || ackTypes == Message::AckType::None))
9191 if (!body._pEmptyMessageStream)
9193 body._pEmptyMessageStream.reset(
new MessageStream((ClientImpl*)0));
9194 body._pEmptyMessageStream.get()->_body->close();
9196 return body.getEmptyMessageStream();
9199 if (body.getDefaultMaxDepth())
9201 stream.
maxDepth(body.getDefaultMaxDepth());
9204 std::string commandID = body.executeAsync(command_, handler,
false);
9205 if (command_.hasStatsAck())
9207 stream.setStatsOnly(commandID, command_.getMessage().
getQueryId());
9209 else if (command_.isSow())
9213 stream.setAcksOnly(commandID,
9218 stream.setSOWOnly(commandID, command_.getMessage().
getQueryId());
9221 else if (command_.isSubscribe())
9223 stream.setSubscription(commandID,
9230 if (command == Message::Command::Publish ||
9231 command == Message::Command::DeltaPublish ||
9232 command == Message::Command::SOWDelete)
9234 stream.setAcksOnly(commandID,
9235 ackTypes & (
unsigned)~Message::AckType::Persisted);
9239 stream.setAcksOnly(commandID, ackTypes);
9246 inline void Message::ack(
const char* options_)
const 9248 ClientImpl* pClient = _body.get().clientImpl();
9250 if (pClient && bookmark.
len() &&
9251 !pClient->getAutoAck())
9254 pClient->ack(getTopic(), bookmark, options_);
Command & setBookmark(const std::string &bookmark_)
Set the bookmark to be used this command.
Definition: ampsplusplus.hpp:748
Command & setFilter(const char *filter_, size_t filterLen_)
Definition: ampsplusplus.hpp:699
Class to hold string versions of failure reasons.
Definition: ampsplusplus.hpp:151
Message & setData(const std::string &v_)
Sets the data portion of self.
Definition: Message.hpp:1518
Core type and function declarations for the AMPS C client.
Client(const std::string &clientName="")
Constructs a new client with a given client name.
Definition: ampsplusplus.hpp:5358
AMPSDLL amps_result amps_client_set_http_preflight_callback(amps_handle client, amps_http_preflight_callback callback, void *userData)
Sets a user-supplied callback function for when a connection is established and the provided uri incl...
Field getUserId() const
Retrieves the value of the UserId header of the Message as a Field which references the underlying bu...
Definition: Message.hpp:1495
std::string sowDeleteByKeys(const MessageHandler &messageHandler_, const std::string &topic_, const std::string &keys_, long timeout_=0)
Deletes messages that match SOW keys from a topic's SOW cache.
Definition: ampsplusplus.hpp:7099
std::string stopTimer(const MessageHandler &messageHandler)
Definition: ampsplusplus.hpp:7073
static const unsigned int IdentifierLength
The length of identifiers used for unique identification of commands and subscriptions.
Definition: Message.hpp:530
std::string getAckType() const
Definition: ampsplusplus.hpp:953
AMPSDLL void amps_client_set_disconnect_handler(amps_handle client, amps_handler disconnectHandler, void *userData)
Sets the disconnect handler function to be called when a disconnect occurs.
Message & assignOwnershipBookmark(const Field &f)
Assigns the value of the Bookmark header for this Message without copying and makes this Message resp...
Definition: Message.hpp:1236
bool removeMessageHandler(const Field &commandId_)
Removes a MessageHandler for a given ComandId from self.
Definition: ampsplusplus.hpp:5627
Message & assignTopic(const std::string &v)
Assigns the value of the Topic header for this Message without copying.
Definition: Message.hpp:1491
Provides a convenient way of building messages in FIX format, typically referenced using the typedefs...
Definition: ampsplusplus.hpp:8520
void startTimer()
Definition: ampsplusplus.hpp:7062
MessageStream sowAndSubscribe(const std::string &topic_, long timeout_, const std::string &filter_="", int batchSize_=DEFAULT_BATCH_SIZE, bool oofEnabled_=false, int topN_=DEFAULT_TOP_N)
Query the SOW cache of a topic and initiates a new subscription on it.
Definition: ampsplusplus.hpp:6598
Abstract base class for storing published messages for an HA publisher client.
Definition: ampsplusplus.hpp:1097
MessageStream conflate(void)
Sets self to conflation mode, where a new update for a matching sow key will replace the previous one...
Definition: ampsplusplus.hpp:9133
Field getSequence() const
Retrieves the value of the Sequence header of the Message as a Field which references the underlying ...
Definition: Message.hpp:1464
AMPSDLL amps_result amps_client_set_name(amps_handle handle, const amps_char *clientName)
Sets the name on an amps client object.
Message & setCorrelationId(const std::string &v)
Sets the value of the CorrelationId header for this Message.
Definition: Message.hpp:1346
Message & setQueryID(const std::string &v)
Sets the value of the QueryID header for this Message.
Definition: Message.hpp:1459
Command(const std::string &command_)
Creates an object to represent the given AMPS command, such as "sow" or "subscribe".
Definition: ampsplusplus.hpp:560
Command::Type getCommandEnum() const
Decode self's "command" field and return one of the values from Command.
Definition: Message.hpp:1270
Command & setBookmark(const char *bookmark_, size_t bookmarkLen_)
Set the bookmark to be used this command.
Definition: ampsplusplus.hpp:759
void setGlobalCommandTypeMessageHandler(const Message::Command::Type command_, const MessageHandler &handler_)
Sets a handler for all messages of a particular type: currently supported types are heartbeat message...
Definition: ampsplusplus.hpp:7371
Command & setAckType(unsigned ackType_)
Definition: ampsplusplus.hpp:931
void setServerVersion(size_t version_)
Internally used to set the server version so the store knows how to deal with persisted acks and call...
Definition: BookmarkStore.hpp:429
void setDefaultMaxDepth(unsigned maxDepth_)
Sets a default max depth on all subsequently created MessageStream objects.
Definition: ampsplusplus.hpp:7739
const amps_uint64_t getNameHashValue() const
Returns the numeric name hash of this client as generated by the server and returned when the client ...
Definition: ampsplusplus.hpp:5419
Field getSubscriptionId() const
Retrieves the value of the SubscriptionId header of the Message as a Field which references the under...
Definition: Message.hpp:1469
AMPSDLL amps_result amps_client_connect(amps_handle handle, const amps_char *uri)
Connects to the AMPS server specified in uri.
static size_t convertVersionToNumber(const std::string &version_)
Converts a string version, such as "3.8.1.5" into the same numeric form used internally and returned ...
Definition: ampsplusplus.hpp:5515
void unsubscribe(const std::string &commandId)
Unsubscribe from a topic.
Definition: ampsplusplus.hpp:6387
Command & setOptions(const std::string &options_)
Sets the options string for this command: see Message.Options for a helper class for constructing the...
Definition: ampsplusplus.hpp:789
Message & setOrderBy(const std::string &v)
Sets the value of the OrderBy header for this Message.
Definition: Message.hpp:1457
Abstract base class for replaying a publish message.
Definition: ampsplusplus.hpp:1069
Command & setCommandId(const char *cmdId_, size_t cmdIdLen_)
Definition: ampsplusplus.hpp:673
void persisted(const Message::Field &subId_, const Message::Field &bookmark_)
Called internally to indicate messages up to and including bookmark are replicated to all replication...
Definition: BookmarkStore.hpp:405
unsigned getDefaultMaxDepth(void) const
Returns the default max depth for returned MessageStream objects.
Definition: ampsplusplus.hpp:7748
void ack(Message &message_, const char *options_=NULL)
Acknowledge a message queue message by supplying the message directly: this adds the ack to the curre...
Definition: ampsplusplus.hpp:7607
MessageStream bookmarkSubscribe(const std::string &topic_, long timeout_, const std::string &bookmark_, const std::string &filter_="", const std::string &options_="", const std::string &subId_="")
Subscribe to a topic using a bookmark.
Definition: ampsplusplus.hpp:6338
AMPSDLL void amps_client_disconnect(amps_handle handle)
Disconnects from the AMPS server, if connected.
AMPSDLL AMPS_SOCKET amps_client_get_socket(amps_handle client)
Returns the socket from the underlying transport in client, or NULL if no transport is associated wit...
void discard(const Message::Field &subId_, size_t bookmarkSeqNo_)
Log a discard-bookmark entry to the persistent log based on a bookmark sequence number.
Definition: BookmarkStore.hpp:283
void setPublishStore(const Store &publishStore_)
Set the publish store to be used by the client.
Definition: ampsplusplus.hpp:5768
void setErrorOnPublishGap(bool errorOnPublishGap_)
Called to enable or disable throwing PublishStoreGapException.
Definition: ampsplusplus.hpp:1346
amps_uint64_t deltaPublish(const std::string &topic_, const std::string &data_, unsigned long expiration_)
Publish the changed fields of a message to an AMPS topic.
Definition: ampsplusplus.hpp:6033
static size_t convertVersionToNumber(const char *data_, size_t len_)
Converts a string version, such as "3.8.1.5" into the same numeric form used internally and returned ...
Definition: ampsplusplus.hpp:5530
Message & setFilter(const std::string &v)
Sets the value of the Filter header for this Message.
Definition: Message.hpp:1348
Command & setSubId(const char *subId_, size_t subIdLen_)
Definition: ampsplusplus.hpp:725
void setNoEmpties(void)
Set the option to not send empty messages on a delta subscription.
Definition: Message.hpp:850
void setDuplicateMessageHandler(const MessageHandler &duplicateMessageHandler_)
Sets a callback function that is invoked when a duplicate message is detected.
Definition: ampsplusplus.hpp:5784
Message deepCopy(void) const
Returns a deep copy of self.
Definition: Message.hpp:567
void removeConnectionStateListener(ConnectionStateListener *listener)
Attempts to remove listener from self's set of ConnectionStateListeners.
Definition: ampsplusplus.hpp:7462
void setOOF(void)
Set the option to receive out of focus (OOF) messages on a subscription, where applicable.
Definition: Message.hpp:833
int getAckTimeout(void) const
Returns the current value of the message queue ack timeout setting – that is, the amount of time aft...
Definition: ampsplusplus.hpp:7691
VersionInfo getServerVersionInfo() const
Returns the server version retrieved during logon.
Definition: ampsplusplus.hpp:5501
Message sowDeleteByKeys(const std::string &topic_, const std::string &keys_, long timeout_=0)
Deletes messages that match SOW keys from a topic's SOW cache.
Definition: ampsplusplus.hpp:7126
AMPSDLL amps_result amps_client_set_transport_filter_function(amps_handle client, amps_transport_filter_function filter, void *userData)
Sets a user-supplied callback function for filtering data before it is sent and after it is received...
Command(const char *command_, size_t commandLen_)
Creates an object to represent the given AMPS command, such as "sow" or "subscribe".
Definition: ampsplusplus.hpp:568
AMPSDLL amps_uint64_t amps_message_get_field_uint64(amps_handle message, FieldId field)
Gets the unsigned 64-bit int value of a header field in an AMPS message.
AMPSDLL amps_result amps_client_set_idle_time(amps_handle client, int idleTime)
Sets an idle-time (milliseconds).
Message encapsulates a single message sent to or received from an AMPS server, and provides methods f...
Definition: Message.hpp:519
Message & setAckTypeEnum(unsigned ackType_)
Encode self's "ack type" field from a bitmask of values from AckType.
Definition: Message.hpp:1225
amps_uint64_t getLastPersisted()
Get the last persisted message sequence in the store.
Definition: ampsplusplus.hpp:1317
static void throwFor(const T &context_, amps_result result_)
Constructs and throws the appropriate exception corresponding to a given result.
std::string getString() const
Returns the current contents of this builder as a string.
Definition: ampsplusplus.hpp:8557
void setTransportFilterFunction(amps_transport_filter_function filter_, void *userData_)
Sets a filter function on the transport that is called with all raw data sent or received.
Definition: ampsplusplus.hpp:7759
amps_uint64_t publish(const char *topic_, size_t topicLength_, const char *data_, size_t dataLength_, unsigned long expiration_)
Publish a message to an AMPS topic, returning the sequence number assigned by the publish store if on...
Definition: ampsplusplus.hpp:5920
iterator begin(void)
Returns an iterator representing the beginning of the topic or subscription.
Definition: ampsplusplus.hpp:5260
void addHttpPreflightHeader(const std::string &key_, const std::string &value_)
Adds a given key/value pair as an HTTP header line as "key: value" to the end of the headers that wil...
Definition: ampsplusplus.hpp:5462
Field getLeasePeriod() const
Retrieves the value of the LeasePeriod header of the Message as a Field which references the underlyi...
Definition: Message.hpp:1351
Command & setSowKeys(const char *sowKeys_, size_t sowKeysLen_)
Sets the SowKeys for the command.
Definition: ampsplusplus.hpp:660
static const char * NOW()
Convenience method for returning the special value to start a subscription at the end of the transact...
Definition: ampsplusplus.hpp:7390
Command & setAckType(const std::string &ackType_)
Definition: ampsplusplus.hpp:909
static const char * BOOKMARK_EPOCH()
Convenience method for returning the special value to start a subscription at the beginning of the tr...
Definition: ampsplusplus.hpp:7400
void send(const Message &message)
Sends a Message to the connected AMPS server, performing only minimal validation and bypassing client...
Definition: ampsplusplus.hpp:5586
Message & setSowKey(const std::string &v)
Sets the value of the SowKey header for this Message.
Definition: Message.hpp:1466
AMPSDLL void amps_message_set_field_value(amps_handle message, FieldId field, const amps_char *value, size_t length)
Sets the value of a header field in an AMPS message.
std::string bookmarkSubscribe(const MessageHandler &messageHandler_, const std::string &topic_, long timeout_, const std::string &bookmark_, const std::string &filter_="", const std::string &options_="", const std::string &subId_="")
Subscribe to a topic using a bookmark.
Definition: ampsplusplus.hpp:6310
Field getFilter() const
Retrieves the value of the Filter header of the Message as a Field which references the underlying bu...
Definition: Message.hpp:1348
static size_t getUnsetPosition()
Method to return the value used to represent not found or unset.
Definition: ampsplusplus.hpp:1160
void setRetryOnDisconnect(bool isRetryOnDisconnect_)
Enables or disables automatic retry of a command to AMPS after a reconnect.
Definition: ampsplusplus.hpp:7721
unsigned getMaxDepth(void) const
Gets the maximum number of messages that can be held in the underlying queue.
Definition: ampsplusplus.hpp:9143
Message & assignUserId(const std::string &v)
Assigns the value of the UserId header for this Message without copying.
Definition: Message.hpp:1495
void connect(const std::string &uri)
Connect to an AMPS server.
Definition: ampsplusplus.hpp:5561
void clear()
Deletes the data associated with this Field, should only be used on Fields that were created as deepC...
Definition: Field.hpp:266
void addMessageHandler(const Field &commandId_, const AMPS::MessageHandler &messageHandler_, unsigned requestedAcks_, Message::Command::Type commandType_)
Adds a MessageHandler to be invoked for Messages with the given CommandId as their command id...
Definition: ampsplusplus.hpp:5616
Abstract base class to manage all subscriptions placed on a client so that they can be re-established...
Definition: ampsplusplus.hpp:1461
std::string sowAndDeltaSubscribe(const MessageHandler &messageHandler_, const std::string &topic_, const std::string &filter_="", const std::string &orderBy_="", int batchSize_=DEFAULT_BATCH_SIZE, int topN_=DEFAULT_TOP_N, const std::string &options_="", long timeout_=DEFAULT_COMMAND_TIMEOUT)
Query the SOW cache of a topic and initiates a new delta subscription on it.
Definition: ampsplusplus.hpp:6792
Success.
Definition: amps.h:221
AMPSDLL void amps_client_set_batch_send(amps_handle client_, amps_uint64_t batchSizeBytes_, amps_uint64_t batchTimeout_)
Sets a byte size batchSizeBytes and timeout for using batch sends of publish and delta_publish messag...
Message & setCommandEnum(Command::Type command_)
Set self's "command" field from one of the values in Command.
Definition: Message.hpp:1330
Field getOptions() const
Retrieves the value of the Options header of the Message as a Field which references the underlying b...
Definition: Message.hpp:1358
std::string authenticate(const std::string &, const std::string &password_)
A simple implementation that returns an unmodified password.
Definition: ampsplusplus.hpp:1043
amps_uint64_t deltaPublish(const char *topic_, size_t topicLength_, const char *data_, size_t dataLength_)
Publish the changed fields of a message to an AMPS topic.
Definition: ampsplusplus.hpp:6010
FIXShredder(char fieldSep_=(char) 1)
Construct an instance of FIXShredder using the specified value as the delimiter between fields...
Definition: ampsplusplus.hpp:8602
std::string sow(const MessageHandler &messageHandler_, const std::string &topic_, const std::string &filter_="", const std::string &orderBy_="", const std::string &bookmark_="", int batchSize_=DEFAULT_BATCH_SIZE, int topN_=DEFAULT_TOP_N, const std::string &options_="", long timeout_=DEFAULT_COMMAND_TIMEOUT)
Query a State-of-the-World topic.
Definition: ampsplusplus.hpp:6434
void * amps_handle
Opaque handle type used to refer to objects in the AMPS api.
Definition: amps.h:211
Class for constructing the options string to pass to AMPS in a Message.
Definition: Message.hpp:589
void addMessageHandler(const Field &commandId_, const AMPS::MessageHandler &messageHandler_, unsigned requestedAcks_, bool isSubscribe_)
Adds a MessageHandler to be invoked for Messages with the given CommandId as their command id...
Definition: ampsplusplus.hpp:5599
const char * data() const
Returns the (non-null-terminated) data underlying this field.
Definition: Field.hpp:279
bool isValid() const
Returns true if self is a valid stream that may be iterated.
Definition: ampsplusplus.hpp:5253
amps_result
Return values from amps_xxx functions.
Definition: amps.h:216
FailedWriteHandler * getFailedWriteHandler()
Get the handler that is invoked to report on failed writes.
Definition: ampsplusplus.hpp:5821
Field getAckType() const
Retrieves the value of the AckType header of the Message as a Field which references the underlying b...
Definition: Message.hpp:1172
AMPSDLL amps_handle amps_client_create(const amps_char *clientName)
Functions for creation of an AMPS client.
Field getCommand() const
Retrieves the value of the Command header of the Message as a Field which references the underlying b...
Definition: Message.hpp:1237
MessageStream execute(Command &command_)
Execute the provided command and return messages received in response in a MessageStream.
Definition: ampsplusplus.hpp:9157
void(* amps_transport_filter_function)(const unsigned char *, size_t, short, void *)
Prototype for a user-supplied callback function for filtering data before it is sent and after it is ...
Definition: amps.h:670
Message & setTopic(const std::string &v)
Sets the value of the Topic header for this Message.
Definition: Message.hpp:1491
Store getPublishStore()
Get the publish store used by the client.
Definition: ampsplusplus.hpp:5776
void setThreadCreatedCallback(amps_thread_created_callback callback_, void *userData_)
Sets a callback function on the transport that is called when a new thread is created to receive data...
Definition: ampsplusplus.hpp:7773
unsigned getAckTypeEnum() const
Definition: ampsplusplus.hpp:958
size_t getServerVersion() const
Returns the server version retrieved during logon.
Definition: ampsplusplus.hpp:5490
State
Constants for the state of the connection.
Definition: ampsplusplus.hpp:1514
Command & setData(const std::string &data_)
Sets the data for this command from an existing string.
Definition: ampsplusplus.hpp:829
std::string logon(int timeout_=0, Authenticator &authenticator_=DefaultAuthenticator::instance(), const char *options_=NULL)
Logon to the server, providing the client name, credentials (if available), and client information (s...
Definition: ampsplusplus.hpp:6082
void discardUpTo(amps_uint64_t index_)
Called by Client to indicate that all messages up to and including.
Definition: ampsplusplus.hpp:1250
Command & setFilter(const std::string &filter_)
Definition: ampsplusplus.hpp:692
const std::string & getNameHash() const
Returns the name hash string of this client as generated by the server and returned when the client l...
Definition: ampsplusplus.hpp:5411
virtual AMPS_ATOMIC_BASE_TYPE getGenerationCount() const
Gets the current subscription manager generation count.
Definition: ampsplusplus.hpp:1479
StoreImpl(bool errorOnPublishGap_=false)
Default constructor.
Definition: ampsplusplus.hpp:1105
MessageStream sowAndSubscribe(const char *topic_, const std::string &filter_="", const std::string &orderBy_="", const std::string &bookmark_="", int batchSize_=DEFAULT_BATCH_SIZE, int topN_=DEFAULT_TOP_N, const std::string &options_="", long timeout_=DEFAULT_COMMAND_TIMEOUT)
Query the SOW cache of a topic and initiates a new subscription on it.
Definition: ampsplusplus.hpp:6746
Client represents a connection to an AMPS server, but does not provide failover or reconnection behav...
Definition: ampsplusplus.hpp:5341
void setGlobalCommandTypeMessageHandler(const std::string &command_, const MessageHandler &handler_)
Sets a handler for all messages of a particular type, or for messages that would be delivered to a pa...
Definition: ampsplusplus.hpp:7346
Command & setSubId(const std::string &subId_)
Definition: ampsplusplus.hpp:718
static const char * BOOKMARK_NOW()
Convenience method for returning the special value to start a subscription at the end of the transact...
Definition: ampsplusplus.hpp:7381
Message & newCommandId()
Creates and sets a new sequential value for the CommandId header for this Message.
Definition: Message.hpp:1344
void addConnectionStateListener(ConnectionStateListener *listener)
Adds a ConnectionStateListener to self's set of listeners.
Definition: ampsplusplus.hpp:7454
Command & reset(const std::string &command_)
Resets the fields of self, and sets the command to command_.
Definition: ampsplusplus.hpp:583
void clearHttpPreflightHeaders()
Clears all previously set HTTP header lines.
Definition: ampsplusplus.hpp:5468
Command & setTimeout(unsigned timeout_)
Sets the client-side timeout for this command.
Definition: ampsplusplus.hpp:851
void clearConnectionStateListeners()
Clear all listeners from self's set of ConnectionStateListeners.
Definition: ampsplusplus.hpp:7469
Message & setSequence(const std::string &v)
Sets the value of the Sequence header for this Message.
Definition: Message.hpp:1464
amps_uint64_t publish(const char *topic_, size_t topicLength_, const char *data_, size_t dataLength_)
Publish a message to an AMPS topic, returning the sequence number assigned by the publish store if on...
Definition: ampsplusplus.hpp:5869
Command & setCommandId(const std::string &cmdId_)
Definition: ampsplusplus.hpp:666
Message & setUserId(const std::string &v)
Sets the value of the UserId header for this Message.
Definition: Message.hpp:1495
Base class for all exceptions in AMPS.
Definition: AMPSException.hpp:40
Field getTopic() const
Retrieves the value of the Topic header of the Message as a Field which references the underlying buf...
Definition: Message.hpp:1491
AMPSDLL void amps_client_set_message_handler(amps_handle client, amps_handler messageHandler, void *userData)
Sets the message handler function for this client.
SubscriptionManager * getSubscriptionManager()
Get the subscription manager being used by the client.
Definition: ampsplusplus.hpp:5732
std::string subscribe(const MessageHandler &messageHandler_, const std::string &topic_, long timeout_=0, const std::string &filter_="", const std::string &options_="", const std::string &subId_="")
Subscribe to a topic.
Definition: ampsplusplus.hpp:6145
Command(Message::Command::Type command_)
Creates an object to represent the given AMPS command, such as "sow" or "subscribe".
Definition: ampsplusplus.hpp:575
Message & setMessageType(const std::string &v)
Sets the value of the MessageType header for this Message.
Definition: Message.hpp:1354
Field getCommandId() const
Retrieves the value of the CommandId header of the Message as a Field which references the underlying...
Definition: Message.hpp:1344
const ExceptionListener & getExceptionListener(void) const
Returns the exception listener set on this Client.
Definition: ampsplusplus.hpp:7254
Field getQueryId() const
Retrieves the value of the QueryID header of the Message as a Field which references the underlying b...
Definition: Message.hpp:1459
static Authenticator & instance()
Static function to return a static instance used when no Authenticator is supplied to a Client...
Definition: ampsplusplus.hpp:1060
Abstract base class for connection state listeners.
Definition: ampsplusplus.hpp:1510
Message & setSubscriptionId(const std::string &v)
Sets the value of the SubscriptionId header for this Message.
Definition: Message.hpp:1469
virtual void setDisconnectHandler(const DisconnectHandler &disconnectHandler)
Definition: ampsplusplus.hpp:5680
std::string sowDeleteByData(const MessageHandler &messageHandler_, const std::string &topic_, const std::string &data_, long timeout_=0)
Deletes the message whose keys match the message data provided.
Definition: ampsplusplus.hpp:7167
Command & setOptions(const char *options_, size_t optionsLen_)
Sets the options string for this command: see Message.Options for a helper class for constructing the...
Definition: ampsplusplus.hpp:797
Message & newQueryId()
Creates and sets a new sequential value for the QueryID header for this Message.
Definition: Message.hpp:1459
#define AMPS_BOOKMARK_RECENT
Start the subscription at the first undiscarded message in the bookmark store, or at the end of the b...
Definition: BookmarkStore.hpp:47
Message & assignExpiration(const std::string &v)
Assigns the value of the Expiration header for this Message without copying.
Definition: Message.hpp:1347
bool empty() const
Returns 'true' if empty, 'false' otherwise.
Definition: Field.hpp:129
bool replaySingle(StoreReplayer &replayer_, amps_uint64_t index_)
Called by Client to get a single message replayed by the store onto the StoreReplayer.
Definition: ampsplusplus.hpp:1271
void completed(const std::string &, const std::string &, const std::string &)
Called by Client once a logon completes successfully.
Definition: ampsplusplus.hpp:1055
MessageStream deltaSubscribe(const std::string &topic_, long timeout_, const std::string &filter_="", const std::string &options_="", const std::string &subId_="")
Delta Subscribe to a topic.
Definition: ampsplusplus.hpp:6250
static const char * EPOCH()
Convenience method for returning the special value to start a subscription at the beginning of the tr...
Definition: ampsplusplus.hpp:7410
Interface for BookmarkStoreImpl classes.
Definition: BookmarkStore.hpp:228
Command & reset(const char *command_, size_t commandLen_)
Resets the fields of self, and sets the command to command_.
Definition: ampsplusplus.hpp:592
Command & setSequence(const char *seq_, size_t seqLen_)
Definition: ampsplusplus.hpp:810
std::string logon(const char *options_, int timeout_=0)
Logon to the server, providing the client name, credentials (if available) client information (such a...
Definition: ampsplusplus.hpp:6101
size_t len() const
Returns the length of the data underlying this field.
Definition: Field.hpp:286
virtual void completed(const std::string &userName_, const std::string &password_, const std::string &reason_)=0
Called by Client once a logon completes successfully.
Message & setClientName(const std::string &v)
Sets the value of the ClientName header for this Message.
Definition: Message.hpp:1345
Field getSowKey() const
Retrieves the value of the SowKey header of the Message as a Field which references the underlying bu...
Definition: Message.hpp:1466
#define AMPS_BOOKMARK_EPOCH
Start the subscription at the beginning of the journal.
Definition: BookmarkStore.hpp:51
A default implementation of Authenticator that only uses an unchanged password and does not implement...
Definition: ampsplusplus.hpp:1037
void setLogonCorrelationData(const std::string &logonCorrelationData_)
Sets the logon correlation data for the client.
Definition: ampsplusplus.hpp:5438
Message & setCommand(const std::string &v)
Sets the value of the Command header for this Message.
Definition: Message.hpp:1237
_FIXBuilder(char fieldSep_=(char) 1)
Construct an instance of _FIXBuilder, using the specified separator between fields.
Definition: ampsplusplus.hpp:8530
void addHttpPreflightHeader(const std::string &header_)
Adds a given HTTP header line to the end of the headers that will be sent for the HTTP GET Upgrade re...
Definition: ampsplusplus.hpp:5453
void ack(const std::string &topic_, const std::string &bookmark_, const char *options_=NULL)
Acknowledge a message queue message by supplying a topic and bookmark string: this adds the ack to th...
Definition: ampsplusplus.hpp:7619
std::string retry(const std::string &, const std::string &)
Throws an AuthenticationException because retry is not implemented.
Definition: ampsplusplus.hpp:1050
Message & assignSubscriptionId(const std::string &v)
Assigns the value of the SubscriptionId header for this Message without copying.
Definition: Message.hpp:1469
bool(* PublishStoreResizeHandler)(Store store_, size_t size_, void *userData_)
Function type for PublishStore resize events The store_ param is store which is resizing.
Definition: ampsplusplus.hpp:1091
AMPSDLL void amps_message_get_field_value(amps_handle message, FieldId field, const amps_char **value_ptr, size_t *length_ptr)
Retrieves the value of a header field in an AMPS message.
MessageStream sowAndSubscribe(const char *topic_, long timeout_, const std::string &filter_="", int batchSize_=DEFAULT_BATCH_SIZE, bool oofEnabled_=false, int topN_=DEFAULT_TOP_N)
Query the SOW cache of a topic and initiates a new subscription on it.
Definition: ampsplusplus.hpp:6636
virtual void setResizeHandler(PublishStoreResizeHandler handler_, void *userData_)
Set a handler to be called if the Store needs to resize in order to keep storing messages.
Definition: ampsplusplus.hpp:1191
void append(const T &tag, const char *value, size_t offset, size_t length)
Write a field with the provided tag and value to the message being constructed.
Definition: ampsplusplus.hpp:8539
Message & assignCommand(const std::string &v)
Assigns the value of the Command header for this Message without copying.
Definition: Message.hpp:1237
#define AMPS_BOOKMARK_NOW
Start the subscription at the point in time when AMPS processes the subscription. ...
Definition: BookmarkStore.hpp:55
void setResizeHandler(PublishStoreResizeHandler handler_, void *userData_)
Set a handler to be called if the Store needs to resize in order to keep storing messages.
Definition: ampsplusplus.hpp:1331
virtual std::string retry(const std::string &userName_, const std::string &password_)=0
Called by Client when a logon ack is received with a status of retry.
BookmarkStore getBookmarkStore()
Get the bookmark store being used by the client.
Definition: ampsplusplus.hpp:5724
void setHttpPreflightHeaders(const T &headers_)
Sets the given HTTP header lines to be sent for the HTTP GET Upgrade request.
Definition: ampsplusplus.hpp:5477
bool isValid() const
Method to return if there is an underlying implementation for the Store.
Definition: ampsplusplus.hpp:1288
void setAckBatchSize(const unsigned ackBatchSize_)
Sets the queue ack batch size setting.
Definition: ampsplusplus.hpp:7680
Field getPassword() const
Retrieves the value of the Password header of the Message as a Field which references the underlying ...
Definition: Message.hpp:1458
Message & setTopNRecordsReturned(const std::string &v)
Sets the value of the TopNRecordsReturned header for this Message.
Definition: Message.hpp:1493
Class to handle when a client receives a duplicate publish message, or not entitled message...
Definition: ampsplusplus.hpp:1381
virtual void setFailedResubscribeHandler(std::shared_ptr< FailedResubscribeHandler > handler_)
Set a handler to deal with failing subscriptions after a failover event.
Definition: ampsplusplus.hpp:1498
void setPublishBatching(size_t batchSize_, amps_uint64_t batchTimeoutMillis_)
Sets the max bytes to cache and max timeout in millis for caching delta_publish and publish commands...
Definition: ampsplusplus.hpp:7785
Message & setSowKeys(const std::string &v)
Sets the value of the SowKeys header for this Message.
Definition: Message.hpp:1467
void setBookmarkStore(const BookmarkStore &bookmarkStore_)
Set the bookmark store to be used by the client.
Definition: ampsplusplus.hpp:5716
This class multiplexes messages from AMPS to multiple subscribers and uses the stream of acks from AM...
Definition: MessageRouter.hpp:135
Message & setExpiration(const std::string &v)
Sets the value of the Expiration header for this Message.
Definition: Message.hpp:1347
virtual std::string authenticate(const std::string &userName_, const std::string &password_)=0
Called by Client just before the logon command is sent.
Command & setOrderBy(const std::string &orderBy_)
Definition: ampsplusplus.hpp:705
void setExceptionListener(const ExceptionListener &listener_)
Definition: ampsplusplus.hpp:7247
Command & reset(Message::Command::Type command_)
Resets the fields of self, and sets the command to command_.
Definition: ampsplusplus.hpp:600
void setSubscriptionManager(SubscriptionManager *subscriptionManager_)
Set the subscription manager to be used by the client.
Definition: ampsplusplus.hpp:5744
void setUnhandledMessageHandler(const AMPS::MessageHandler &messageHandler)
Definition: ampsplusplus.hpp:7313
void append(const T &tag, const std::string &value)
Write a field with the provided tag and value to the message being constructed.
Definition: ampsplusplus.hpp:8550
unsigned getAckBatchSize(void) const
Returns the value of the queue ack batch size setting.
Definition: ampsplusplus.hpp:7670
amps_uint64_t deltaPublish(const std::string &topic_, const std::string &data_)
Publish the changed fields of a message to an AMPS topic.
Definition: ampsplusplus.hpp:5987
MessageStream sowAndSubscribe(const std::string &topic_, const std::string &filter_="", const std::string &orderBy_="", const std::string &bookmark_="", int batchSize_=DEFAULT_BATCH_SIZE, int topN_=DEFAULT_TOP_N, const std::string &options_="", long timeout_=DEFAULT_COMMAND_TIMEOUT)
Query the SOW cache of a topic and initiates a new subscription on it.
Definition: ampsplusplus.hpp:6723
Command & setExpiration(unsigned expiration_)
Set the expiration time for a publish command.
Definition: ampsplusplus.hpp:889
AMPSDLL void amps_client_set_predisconnect_handler(amps_handle client, amps_predisconnect_handler predisconnectHandler, void *userData)
Sets the predisconnect handler function to be called when a disconnect occurs.
Represents an iterator over messages in an AMPS topic.
Definition: ampsplusplus.hpp:5215
size_t log(Message &message_)
Log a bookmark to the persistent log.
Definition: BookmarkStore.hpp:268
MessageStream sowAndDeltaSubscribe(const char *topic_, long timeout_, const std::string &filter_="", int batchSize_=DEFAULT_BATCH_SIZE, bool oofEnabled_=false, bool sendEmpties_=false, int topN_=DEFAULT_TOP_N)
Query the SOW cache of a topic and initiates a new delta subscription on it.
Definition: ampsplusplus.hpp:6969
size_t unpersistedCount() const
Method to return how many messages are in the store that have not been discarded, indicating that the...
Definition: ampsplusplus.hpp:1280
AMPSDLL amps_result amps_client_send_batch(amps_handle client, amps_handle message, unsigned *version_out, int addToBatch)
Adds a message to the send cache, possibly sending the cache.
Command & setData(const char *data_, size_t dataLen_)
Sets the data for this command.
Definition: ampsplusplus.hpp:837
Message & assignAckType(const std::string &v)
Assigns the value of the AckType header for this Message without copying.
Definition: Message.hpp:1172
void publishFlush(long timeout_=0, unsigned ackType_=Message::AckType::Processed)
Ensure that AMPS messages are sent and have been processed by the AMPS server.
Definition: ampsplusplus.hpp:5966
std::string executeAsync(Command &command_, MessageHandler handler_)
Execute the provided command and, once AMPS acknowledges the command, process messages in response to...
Definition: ampsplusplus.hpp:7499
Command & setSowKey(const char *sowKey_, size_t sowKeyLen_)
Sets the SowKey field of the command, typically used for a publish command to a topic in the state of...
Definition: ampsplusplus.hpp:625
MessageStream sowAndDeltaSubscribe(const std::string &topic_, long timeout_, const std::string &filter_="", int batchSize_=DEFAULT_BATCH_SIZE, bool oofEnabled_=false, bool sendEmpties_=false, int topN_=DEFAULT_TOP_N)
Query the SOW cache of a topic and initiates a new delta subscription on it.
Definition: ampsplusplus.hpp:6928
std::string logon(const std::string &options_, int timeout_=0)
Logon to the server, providing the client name, credentials (if available) client information (such a...
Definition: ampsplusplus.hpp:6120
void unsubscribe()
Unsubscribe from all topics.
Definition: ampsplusplus.hpp:6399
void setAutoAck(bool isAutoAckEnabled_)
Sets the queue auto-ack setting on this client.
Definition: ampsplusplus.hpp:7662
MessageStream deltaSubscribe(const char *topic_, long timeout_, const std::string &filter_="", const std::string &options_="", const std::string &subId_="")
Delta Subscribe to a topic.
Definition: ampsplusplus.hpp:6268
Message & assignCorrelationId(const std::string &v)
Assigns the value of the CorrelationId header for this Message without copying.
Definition: Message.hpp:1346
amps_uint64_t store(const Message &message_)
Called by Client to store a message being published.
Definition: ampsplusplus.hpp:1239
std::string sowAndDeltaSubscribe(const MessageHandler &messageHandler_, const std::string &topic_, long timeout_, const std::string &filter_="", int batchSize_=DEFAULT_BATCH_SIZE, bool oofEnabled_=false, bool sendEmpties_=false, int topN_=DEFAULT_TOP_N)
Query the SOW cache of a topic and initiates a new delta subscription on it.
Definition: ampsplusplus.hpp:6892
Command & setBatchSize(unsigned batchSize_)
Sets the batch size for this command, which controls how many records are sent together in the result...
Definition: ampsplusplus.hpp:873
void setExceptionListener(const std::shared_ptr< const ExceptionListener > &pListener_)
Sets the exception listener for exceptions that are not thrown back to the user (for example...
Definition: ampsplusplus.hpp:7231
StoreImpl * get()
Used to get a pointer to the implementation.
Definition: ampsplusplus.hpp:1363
MessageHandler getDuplicateMessageHandler(void)
Returns the callback function that is invoked when a duplicate message is detected.
Definition: ampsplusplus.hpp:5799
Command & setQueryId(const char *queryId_, size_t queryIdLen_)
Definition: ampsplusplus.hpp:738
DisconnectHandler getDisconnectHandler(void) const
Definition: ampsplusplus.hpp:5694
Class for parsing a FIX format message into a std::map of keys and values, where the keys and values ...
Definition: ampsplusplus.hpp:8594
Field represents the value of a single field in a Message.
Definition: Field.hpp:87
Message & setAckType(const std::string &v)
Sets the value of the AckType header for this Message.
Definition: Message.hpp:1172
virtual ConnectionInfo getConnectionInfo() const
Get the connection information for the current connection.
Definition: ampsplusplus.hpp:5703
Message & setOptions(const std::string &v)
Sets the value of the Options header for this Message.
Definition: Message.hpp:1386
void ack(Field &topic_, Field &bookmark_, const char *options_=NULL)
Acknowledge a message queue message by supplying a topic and bookmark: this adds the ack to the curre...
Definition: ampsplusplus.hpp:7595
Abstract base class where you can implement handling of exceptions that occur when a SubscriptionMana...
Definition: ampsplusplus.hpp:1439
AMPSDLL amps_result amps_client_send(amps_handle client, amps_handle message)
Sends a message to the AMPS server.
std::map< Message::Field, Message::Field > map_type
Convenience defintion for the std::map specialization used for this class.
Definition: ampsplusplus.hpp:8606
Command & setTopic(const char *topic_, size_t topicLen_)
Definition: ampsplusplus.hpp:686
Handle class for StoreImpl classes that track publish messages.
Definition: ampsplusplus.hpp:1223
map_type toMap(const Message::Field &data)
Returns the key/value pairs within the message, represented as AMPS::Field objects that contain point...
Definition: ampsplusplus.hpp:8613
Exception listener for unhandled exceptions.
Definition: ampsplusplus.hpp:204
MessageStream sowAndDeltaSubscribe(const std::string &topic_, const std::string &filter_="", const std::string &orderBy_="", int batchSize_=DEFAULT_BATCH_SIZE, int topN_=DEFAULT_TOP_N, const std::string &options_="", long timeout_=DEFAULT_COMMAND_TIMEOUT)
Query the SOW cache of a topic and initiates a new delta subscription on it.
Definition: ampsplusplus.hpp:6825
void setHeartbeat(unsigned heartbeatTime_)
Requests heartbeating with the AMPS server.
Definition: ampsplusplus.hpp:7304
MessageStream subscribe(const char *topic_, long timeout_=0, const std::string &filter_="", const std::string &options_="", const std::string &subId_="")
Subscribe to a topic.
Definition: ampsplusplus.hpp:6203
An iterable object representing the results of an AMPS subscription and/or query. ...
Definition: ampsplusplus.hpp:5207
bool getErrorOnPublishGap() const
Called to check if the Store will throw PublishStoreGapException.
Definition: ampsplusplus.hpp:1355
Command & setSequence(const std::string &seq_)
Definition: ampsplusplus.hpp:803
static const char * MOST_RECENT()
Convenience method for returning the special value to start a subscription at a recovery point based ...
Definition: ampsplusplus.hpp:7432
Command & setQueryId(const std::string &queryId_)
Definition: ampsplusplus.hpp:731
AMPSDLL amps_result amps_client_set_thread_created_callback(amps_handle client, amps_thread_created_callback callback, void *userData)
Sets a user-supplied callback function to allow thread attributes to set when a new thread is created...
Message sowDelete(const std::string &topic_, const std::string &filter_, long timeout_=0)
Deletes one or more messages from a topic's SOW cache.
Definition: ampsplusplus.hpp:7031
Message & setCommandId(const std::string &v)
Sets the value of the CommandId header for this Message.
Definition: Message.hpp:1344
Command & setSequence(const amps_uint64_t seq_)
Definition: ampsplusplus.hpp:816
static const char * BOOKMARK_RECENT()
Convenience method for returning the special value to start a subscription at a recovery point based ...
Definition: ampsplusplus.hpp:7443
Message & setQueryId(const std::string &v)
Sets the value of the QueryID header for this Message.
Definition: Message.hpp:1459
amps_result(* amps_thread_created_callback)(AMPS_THREAD_T, void *)
Prototype for a user-supplied callback function to allow thread attributes to be set when a new threa...
Definition: amps.h:696
amps_uint64_t getLowestUnpersisted()
Get the oldest unpersisted message sequence in the store.
Definition: ampsplusplus.hpp:1309
Command & setTopic(const std::string &topic_)
Definition: ampsplusplus.hpp:679
MessageStream maxDepth(unsigned maxDepth_)
Sets the maximum number of messages that can be held in the underlying queue.
Definition: ampsplusplus.hpp:9138
Message & assignVersion(const std::string &v)
Assigns the value of the Version header for this Message without copying.
Definition: Message.hpp:1494
void disconnect()
Disconnect from an AMPS server.
Definition: ampsplusplus.hpp:5568
MessageStream sow(const std::string &topic_, const std::string &filter_="", const std::string &orderBy_="", const std::string &bookmark_="", int batchSize_=DEFAULT_BATCH_SIZE, int topN_=DEFAULT_TOP_N, const std::string &options_="", long timeout_=DEFAULT_COMMAND_TIMEOUT)
Query the SOW cache of a topic.
Definition: ampsplusplus.hpp:6472
unsigned getDepth(void) const
Gets the current number of messages held in the underlying queue.
Definition: ampsplusplus.hpp:9147
Field getQueryID() const
Retrieves the value of the QueryID header of the Message as a Field which references the underlying b...
Definition: Message.hpp:1459
The operation has not succeeded, but ought to be retried.
Definition: amps.h:245
const std::string & getLogonCorrelationData() const
Returns the currently set logon correlation data for the client.
Definition: ampsplusplus.hpp:5445
void setHeartbeat(unsigned heartbeatTime_, unsigned readTimeout_)
Requests heartbeating with the AMPS server.
Definition: ampsplusplus.hpp:7280
Command & setTopN(unsigned topN_)
Definition: ampsplusplus.hpp:857
AMPSDLL amps_result amps_client_set_read_timeout(amps_handle client, int readTimeout)
Sets a read timeout (seconds), in which if no message is received, the connection is presumed dead...
const std::string & getURI() const
Returns the last URI this client is connected to.
Definition: ampsplusplus.hpp:5537
Command & addAckType(const std::string &ackType_)
Definition: ampsplusplus.hpp:895
void replay(StoreReplayer &replayer_)
Called by Client to get all stored and non-discarded messages replayed by the store onto the StoreRep...
Definition: ampsplusplus.hpp:1259
static const char * BOOKMARK_MOST_RECENT()
Convenience method for returning the special value to start a subscription at a recovery point based ...
Definition: ampsplusplus.hpp:7421
Message & setBookmark(const std::string &v)
Sets the value of the Bookmark header for this Message.
Definition: Message.hpp:1236
std::string send(const MessageHandler &messageHandler_, Message &message_, int timeout_=0, AMPS_ATOMIC_BASE_TYPE subscribeGeneration_=0)
Sends a Message to the connected AMPS server, performing only minimal validation and bypassing client...
Definition: ampsplusplus.hpp:5656
void deepCopy(const Field &orig_)
Makes self a deep copy of the original field.
Definition: Field.hpp:219
Command & setOrderBy(const char *orderBy_, size_t orderByLen_)
Definition: ampsplusplus.hpp:712
unsigned getAckTypeEnum() const
Decode self's "ack type" field and return the corresponding bitmask of values from AckType...
Definition: Message.hpp:1202
BookmarkStoreImpl * get()
Used to get a pointer to the implementation.
Definition: BookmarkStore.hpp:465
amps_handle getHandle()
Returns the underlying amps_handle for this client, to be used with amps_client_* functions from the ...
Definition: ampsplusplus.hpp:7218
AMPSDLL amps_result amps_client_attempt_reconnect(amps_handle client, unsigned version)
Manually invokes the user-supplied disconnect handler for this client.
AMPSDLL void amps_client_destroy(amps_handle handle)
Disconnects and destroys an AMPS client object.
void reset()
Clear all data from the builder.
Definition: ampsplusplus.hpp:8567
void setFailedWriteHandler(FailedWriteHandler *handler_)
Set the handler that is invoked to report when a publish fails, for example if the publisher is not e...
Definition: ampsplusplus.hpp:5813
MessageStream sowAndDeltaSubscribe(const char *topic_, const std::string &filter_="", const std::string &orderBy_="", int batchSize_=DEFAULT_BATCH_SIZE, int topN_=DEFAULT_TOP_N, const std::string &options_="", long timeout_=DEFAULT_COMMAND_TIMEOUT)
Query the SOW cache of a topic and initiates a new delta subscription on it.
Definition: ampsplusplus.hpp:6847
void setAckTimeout(const int ackTimeout_)
Sets the message queue ack timeout value.
Definition: ampsplusplus.hpp:7703
Command & setSowKeys(const std::string &sowKeys_)
Sets the SowKeys for the command.
Definition: ampsplusplus.hpp:642
Message & setPassword(const std::string &v)
Sets the value of the Password header for this Message.
Definition: Message.hpp:1458
bool getAutoAck(void) const
Returns the value of the queue auto-ack setting.
Definition: ampsplusplus.hpp:7652
amps_uint64_t publish(const std::string &topic_, const std::string &data_)
Publish a message to an AMPS topic, returning the sequence number assigned by the publish store if on...
Definition: ampsplusplus.hpp:5844
Definition: AMPSException.hpp:32
void setName(const std::string &name)
Sets the name of this client, assuming no name was provided previously.
Definition: ampsplusplus.hpp:5396
The interface for handling authentication with the AMPS server.
Definition: ampsplusplus.hpp:1006
void flush(long timeout_=0)
Method to wait for the Store to discard everything that has been stored up to the point in time when ...
Definition: ampsplusplus.hpp:1301
Field getBookmark() const
Retrieves the value of the Bookmark header of the Message as a Field which references the underlying ...
Definition: Message.hpp:1236
bool DangerousFlushPublishStoreResizeHandler(Store store_, size_t, void *data_)
PublishStoreResizeHandler that will block up to the timeout specified in user data milliseconds tryin...
Definition: ampsplusplus.hpp:1411
static amps_uint64_t getUnsetSequence()
Method to return the value used to represent no such sequence.
Definition: ampsplusplus.hpp:1167
Command & setCorrelationId(const char *correlationId_, size_t correlationIdLen_)
Set the correlation ID for this command.
Definition: ampsplusplus.hpp:782
MessageStream sow(const char *topic_, const std::string &filter_="", const std::string &orderBy_="", const std::string &bookmark_="", int batchSize_=DEFAULT_BATCH_SIZE, int topN_=DEFAULT_TOP_N, const std::string &options_="", long timeout_=DEFAULT_COMMAND_TIMEOUT)
Query the SOW cache of a topic.
Definition: ampsplusplus.hpp:6493
amps_uint64_t publish(const std::string &topic_, const std::string &data_, unsigned long expiration_)
Publish a message to an AMPS topic, returning the sequence number assigned by the publish store (if a...
Definition: ampsplusplus.hpp:5893
void setLastChanceMessageHandler(const AMPS::MessageHandler &messageHandler)
Sets the message handler called when no other handler matches.
Definition: ampsplusplus.hpp:7320
Message::Field getMostRecent(const Message::Field &subId_)
Returns the most recent bookmark from the log that ought to be used for (re-)subscriptions.
Definition: BookmarkStore.hpp:310
amps_uint64_t deltaPublish(const char *topic_, size_t topicLength_, const char *data_, size_t dataLength_, unsigned long expiration_)
Publish the changed fields of a message to an AMPS topic.
Definition: ampsplusplus.hpp:6059
The client and server are disconnected.
Definition: amps.h:249
Message sowDeleteByData(const std::string &topic_, const std::string &data_, long timeout_=0)
Deletes the message whose keys match the message data provided.
Definition: ampsplusplus.hpp:7188
std::string deltaSubscribe(const MessageHandler &messageHandler_, const std::string &topic_, long timeout_, const std::string &filter_="", const std::string &options_="", const std::string &subId_="")
Delta Subscribe to a topic.
Definition: ampsplusplus.hpp:6232
MessageStream timeout(unsigned timeout_)
Sets the maximum time to wait for the next message in milliseconds; if no message is available within...
Definition: ampsplusplus.hpp:9128
std::string sow(const MessageHandler &messageHandler_, const std::string &topic_, long timeout_, const std::string &filter_="", int batchSize_=DEFAULT_BATCH_SIZE, int topN_=DEFAULT_TOP_N)
Query the SOW cache of a topic.
Definition: ampsplusplus.hpp:6534
const std::string & getName() const
Returns the name of this client passed in the constructor.
Definition: ampsplusplus.hpp:5403
Command is an encapsulation of a single AMPS command sent by the client.
Definition: ampsplusplus.hpp:472
std::string sowAndSubscribe(const MessageHandler &messageHandler_, const std::string &topic_, const std::string &filter_="", const std::string &orderBy_="", const std::string &bookmark_="", int batchSize_=DEFAULT_BATCH_SIZE, int topN_=DEFAULT_TOP_N, const std::string &options_="", long timeout_=DEFAULT_COMMAND_TIMEOUT)
Query the SOW cache of a topic and initiates a new subscription on it.
Definition: ampsplusplus.hpp:6684
Message & setBatchSize(const std::string &v)
Sets the value of the BatchSize header for this Message.
Definition: Message.hpp:1235
MessageStream subscribe(const std::string &topic_, long timeout_=0, const std::string &filter_="", const std::string &options_="", const std::string &subId_="")
Subscribe to a topic.
Definition: ampsplusplus.hpp:6171
MessageStream bookmarkSubscribe(const char *topic_, long timeout_, const std::string &bookmark_, const std::string &filter_="", const std::string &options_="", const std::string &subId_="")
Subscribe to a topic using a bookmark.
Definition: ampsplusplus.hpp:6359
Command & setSowKey(const std::string &sowKey_)
Sets the SowKey field of the command, typically used for a publish command to a topic in the state of...
Definition: ampsplusplus.hpp:612
const std::string & getConnectionName() const
Returns the connection name string of this client as generated by the server and returned when the cl...
Definition: ampsplusplus.hpp:5427
Message & assignSequence(const std::string &v)
Assigns the value of the Sequence header for this Message without copying.
Definition: Message.hpp:1464
std::string executeAsyncNoResubscribe(Command &command_, MessageHandler handler_)
Execute the provided command and, once AMPS acknowledges the command, process messages in response to...
Definition: ampsplusplus.hpp:7533
Command & setCorrelationId(const std::string &correlationId_)
Set the correlation ID for this command.
Definition: ampsplusplus.hpp:770
std::string sowDelete(const MessageHandler &messageHandler, const std::string &topic, const std::string &filter, long timeout)
Deletes one or more messages from a topic's SOW cache.
Definition: ampsplusplus.hpp:7008
iterator end(void)
Returns an iterator representing the end of the topic or subscription.
Definition: ampsplusplus.hpp:5271
bool getRetryOnDisconnect(void) const
Returns true if automatic retry of a command to AMPS after a reconnect is enabled.
Definition: ampsplusplus.hpp:7730
void flushAcks(void)
Sends any queued message queue ack messages to the server immediately.
Definition: ampsplusplus.hpp:7643
std::string sowAndSubscribe(const MessageHandler &messageHandler_, const std::string &topic_, long timeout_, const std::string &filter_="", int batchSize_=DEFAULT_BATCH_SIZE, bool oofEnabled_=false, int topN_=DEFAULT_TOP_N)
Query the SOW cache of a topic and initiates a new subscription on it.
Definition: ampsplusplus.hpp:6566