AMPS C/C++ Client Class Reference
AMPS C/C++ Client Version 5.3.5.0
SOWRecoveryPointAdapter.hpp
1 //
3 // Copyright (c) 2010-2025 60East Technologies Inc., All Rights Reserved.
4 //
5 // This computer software is owned by 60East Technologies Inc. and is
6 // protected by U.S. copyright laws and other laws and by international
7 // treaties. This computer software is furnished by 60East Technologies
8 // Inc. pursuant to a written license agreement and may be used, copied,
9 // transmitted, and stored only in accordance with the terms of such
10 // license agreement and with the inclusion of the above copyright notice.
11 // This computer software or any other copies thereof may not be provided
12 // or otherwise made available to any other person.
13 //
14 // U.S. Government Restricted Rights. This computer software: (a) was
15 // developed at private expense and is in all respects the proprietary
16 // information of 60East Technologies Inc.; (b) was not developed with
17 // government funds; (c) is a trade secret of 60East Technologies Inc.
18 // for all purposes of the Freedom of Information Act; and (d) is a
19 // commercial item and thus, pursuant to Section 12.212 of the Federal
20 // Acquisition Regulations (FAR) and DFAR Supplement Section 227.7202,
21 // Government's use, duplication or disclosure of the computer software
22 // is subject to the restrictions set forth by 60East Technologies Inc..
23 //
25 
26 #ifndef _SOWRECOVERYPOINTADAPTER_H_
27 #define _SOWRECOVERYPOINTADAPTER_H_
28 
29 #include <amps/ampsplusplus.hpp>
30 #include <amps/Field.hpp>
31 #include <amps/RecoveryPoint.hpp>
33 #include <assert.h>
34 #include <memory>
35 #include <string>
36 
37 using std::string;
38 
39 #define AMPS_SOW_STORE_DEFAULT_TOPIC "/ADMIN/bookmark_store"
40 #define AMPS_SOW_STORE_DEFAULT_CLIENT_FIELD "clientName"
41 #define AMPS_SOW_STORE_DEFAULT_SUB_FIELD "subId"
42 #define AMPS_SOW_STORE_DEFAULT_BOOKMARK_FIELD "bookmark"
43 
44 #define SOW_RECOVERY_HANDLE_EXCEPTION(x) \
45  catch (const AMPSException& ex_) \
46  { \
47  std::ostringstream os; \
48  os << x << ": AMPSException " << ex_.what(); \
49  StoreException ex(os.str()); \
50  if (_throwNotListen) \
51  { \
52  throw ex;\
53  } \
54  else if (_pExceptionListener) \
55  { \
56  _pExceptionListener->exceptionThrown(ex); \
57  } \
58  } \
59  catch (const std::exception& ex_) \
60  { \
61  std::ostringstream os; \
62  os << x << ": std::exception " << ex_.what(); \
63  StoreException ex(os.str()); \
64  if (_throwNotListen) \
65  { \
66  throw ex;\
67  } \
68  else if (_pExceptionListener) \
69  { \
70  _pExceptionListener->exceptionThrown(ex); \
71  } \
72  } \
73  catch (...) \
74  { \
75  std::ostringstream os; \
76  os << x << ": Unknown exception"; \
77  StoreException ex(os.str()); \
78  if (_throwNotListen) \
79  { \
80  throw ex;\
81  } \
82  else if (_pExceptionListener) \
83  { \
84  _pExceptionListener->exceptionThrown(ex); \
85  } \
86  }
87 
88 namespace AMPS
89 {
90 
94  {
95  public:
96 
128  SOWRecoveryPointAdapter(const Client& storeClient_,
129  const string& trackedClientName_,
130  unsigned timeoutMillis_ = 5000,
131  bool useTimestamp_ = false,
132  bool closeClient_ = true,
133  bool updateFailureThrows_ = false,
134  const string& topic_ = AMPS_SOW_STORE_DEFAULT_TOPIC,
135  const string& clientNameField_ = AMPS_SOW_STORE_DEFAULT_CLIENT_FIELD,
136  const string& subIdField_ = AMPS_SOW_STORE_DEFAULT_SUB_FIELD,
137  const string& bookmarkField_ = AMPS_SOW_STORE_DEFAULT_BOOKMARK_FIELD
138  )
140  , _serializeLen(0)
141  , _serializeBuffer(0)
142  , _deserializeLen(0)
143  , _deserializeBuffer(0)
144  , _client(storeClient_)
145  , _trackedName(trackedClientName_)
146  , _topic(topic_)
147  , _nameField(clientNameField_)
148  , _subIdField(subIdField_)
149  , _bookmarkField(bookmarkField_)
150  , _timeoutMillis(timeoutMillis_)
151  , _closeClient(closeClient_)
152  , _executed(false)
153  , _throwNotListen(updateFailureThrows_)
154  , _useTimestamp(useTimestamp_)
155  , _closed(false)
156  {
157  if (_client.getName() == _trackedName)
158  {
159  throw UsageException("The SOWRecoveryPointAdapter cannot use the tracked client to update AMPS");
160  }
161  _initSerialization();
162  }
163 
164  virtual ~SOWRecoveryPointAdapter()
165  {
166  _close();
167  delete[] _serializeBuffer;
168  delete[] _deserializeBuffer;
169  }
170 
175  virtual bool next(RecoveryPoint& current_)
176  {
177  static Field emptyField;
178  try
179  {
180  if (!_executed)
181  {
182  Command cmd("sow");
183  cmd.setTopic(_topic)
184  .setFilter("/" + _nameField + "='" + _trackedName + "'")
185  .setTimeout(_timeoutMillis);
186  if (_useTimestamp)
187  {
188  cmd.setOptions("select=[-/,+/" + _subIdField + ",+/"
189  + _bookmarkField + "],timestamp");
190  }
191  else
192  {
193  cmd.setOptions("select=[-/,+/" + _subIdField + ",+/"
194  + _bookmarkField + "]");
195  }
196  _stream = _client.execute(cmd).timeout(_timeoutMillis);
197  _msIter = _stream.begin();
198  _executed = true;
199  }
200  else
201  {
202  ++_msIter;
203  }
204  if (_msIter == MessageStream::iterator())
205  {
206  return false;
207  }
208  Message m = *_msIter;
209  if (!m.isValid())
210  {
211  current_ = RecoveryPoint(NULL);
212  return false;
213  }
214  if (m.getCommand() == "group_begin")
215  {
216  return next(current_);
217  }
218  else if (m.getCommand() == "sow")
219  {
220  if (_useTimestamp)
221  {
222  current_ = RecoveryPoint(deserialize(m.getData(),
223  m.getTimestamp()));
224  }
225  else
226  {
227  current_ = RecoveryPoint(deserialize(m.getData(),
228  emptyField));
229  }
230  return true;
231  }
232  else if (m.getCommand() == "group_end" || m.getCommand() == "ack")
233  {
234  current_ = RecoveryPoint(NULL);
235  _msIter = MessageStream::iterator();
236  _stream = MessageStream();
237  return false;
238  }
239  }
240  SOW_RECOVERY_HANDLE_EXCEPTION("SOWRecoveryPoint::next")
241  return false;
242  }
243 
246  virtual void update(RecoveryPoint& recoveryPoint_)
247  {
248  try
249  {
250  Field data = serialize(recoveryPoint_);
251  _client.publish(_topic.data(), _topic.length(), data.data(), data.len());
252  }
253  SOW_RECOVERY_HANDLE_EXCEPTION("SOWRecoveryPoint::update")
254  }
255 
257  virtual void purge()
258  {
259  try
260  {
261  Message m = _client.sowDelete(_topic, "/" + _nameField
262  + "='" + _trackedName + "'");
263  }
264  SOW_RECOVERY_HANDLE_EXCEPTION("SOWRecoveryPoint::purge")
265  }
266 
269  virtual void purge(const Field& subId_)
270  {
271  try
272  {
273  Message m = _client.sowDelete(_topic, "/" + _nameField + "='"
274  + _trackedName + "' and /"
275  + _subIdField + "='"
276  + subId_ + "'");
277  }
278  SOW_RECOVERY_HANDLE_EXCEPTION("SOWRecoveryPoint::purge(subId)")
279  }
280 
282  virtual void close()
283  {
284  _close();
285  }
286 
294  void setExceptionListener(const std::shared_ptr<const ExceptionListener>& pListener_)
295  {
296  _pExceptionListener = pListener_;
297  }
298  protected:
299  void _close()
300  {
301  if (_closed)
302  {
303  return;
304  }
305  // If client is invalid or unused
306  if (!_client.isValid() || !_executed)
307  {
308  _closed = true;
309  if (_closeClient && _client.isValid())
310  {
311  _client.disconnect();
312  _client = Client();
313  }
314  return;
315  }
316  try
317  {
318  _client.publishFlush();
319  }
320  SOW_RECOVERY_HANDLE_EXCEPTION("SOWRecoveryPoint::close publishFlush")
321  try
322  {
323  if (_closeClient)
324  {
325  _closed = true;
326  _client.disconnect();
327  _client = Client();
328  }
329  }
330  SOW_RECOVERY_HANDLE_EXCEPTION("SOWRecoveryPoint::close disconnect")
331  }
332 
333  void _initSerialization()
334  {
335  try
336  {
337  // Set up json serialization
338  if (_serializeLen == 0)
339  {
340  _serializeLen = (size_t) (_nameField.length()
341  + _trackedName.length()
342  + _subIdField.length()
343  + _bookmarkField.length()
344  + (AMPS_MAX_BOOKMARK_LEN * 4UL)
345  + SUBID_LEN + JSON_EXTRA);
346  _serializeLen += (128 - (_serializeLen % 128));
347  }
348  _serializeBuffer = new char[_serializeLen];
349  AMPS_snprintf(_serializeBuffer, _serializeLen,
350  "{\"%s\":\"%s\",\"%s\":\"", _nameField.c_str()
351  , _trackedName.c_str()
352  , _subIdField.c_str());
353  _serializeStart = JSON_START + _nameField.length()
354  + _trackedName.length() + _subIdField.length();
355  }
356  SOW_RECOVERY_HANDLE_EXCEPTION("SOWRecoveryPoint::initSerialization")
357  }
358 
359  // Subclasses can override this to set up for something other than json
360  // serialization if not using json.
361  virtual void initSerialization()
362  {
363  _initSerialization();
364  }
365 
366  // Subclasses can override this function if not using json data type.
367  // It needs to return an allocated RecoveryPointImpl based on the data
368  // field from a sow message that contains only 2 fields: _subIdField and
369  // _bookmarkField. If you'd like more, override begin()
370  virtual RecoveryPointImpl* deserialize(const Field& data_,
371  const Field& timestamp_)
372  {
373  Field subId;
374  Field bookmark;
375  try
376  {
377  // We have 2 fields subId and bookmark and we only need the
378  // values. Find : then start ", then end ".
379  const char* start = (const char*)memchr((const void*)data_.data(),
380  (int)':', data_.len());
381  if (!start)
382  {
383  throw StoreException("Failure parsing json RecoveryPoint subId, no :");
384  }
385  size_t remain = data_.len() - (size_t)(start - data_.data());
386  start = (const char*)memchr((const void*)start, (int)'"', remain);
387  if (!start)
388  {
389  throw StoreException("Failure parsing json RecoveryPoint subId, no start \"");
390  }
391  ++start;
392  remain = data_.len() - (size_t)(start - data_.data());
393  const char* end = (const char*)memchr((const void*)start,
394  (int)'"', remain);
395  if (!end)
396  {
397  throw StoreException("Failure parsing json RecoveryPoint subId, no end \"");
398  }
399  size_t len = (size_t)(end - start);
400  subId = Field(start, len);
401  start = (const char*)memchr((const void*)start, (int)':', data_.len());
402  if (!start)
403  {
404  throw StoreException("Failure parsing json RecoveryPoint bookmark, no :");
405  }
406  remain = data_.len() - (size_t)(start - data_.data());
407  start = (const char*)memchr((const void*)start, (int)'"', remain);
408  if (!start)
409  {
410  throw StoreException("Failure parsing json RecoveryPoint bookmark, no start \"");
411  }
412  ++start;
413  remain = data_.len() - (size_t)(start - data_.data());
414  end = (const char*)memchr((const void*)start, (int)'"', remain);
415  if (!end)
416  {
417  throw StoreException("Failure parsing json RecoveryPoint bookmark, no end \"");
418  }
419  len = (size_t)(end - start);
420  if (_useTimestamp && !timestamp_.empty())
421  {
422  if (_deserializeLen < len + timestamp_.len())
423  {
424  delete[] _deserializeBuffer;
425  _deserializeBuffer = 0;
426  }
427  if (!_deserializeBuffer)
428  {
429  _deserializeLen = len + timestamp_.len() + 1;
430  _deserializeBuffer = new char[_deserializeLen];
431  }
432  memcpy((void*)_deserializeBuffer, (const void*)start, len);
433  _deserializeBuffer[len] = ',';
434  memcpy((void*)(_deserializeBuffer + len + 1),
435  (const void*)timestamp_.data(), timestamp_.len());
436  bookmark = Field(_deserializeBuffer, _deserializeLen);
437  }
438  else
439  {
440  bookmark = Field(start, len);
441  }
442  }
443  SOW_RECOVERY_HANDLE_EXCEPTION("SOWRecoveryPoint::deserialize")
444  // Return a recovery point that will copy current field values and
445  // clear them when destructed.
446  return new FixedRecoveryPoint(subId, bookmark, true);
447  }
448 
449  virtual Field& serialize(const RecoveryPoint& recoveryPoint_)
450  {
451  try
452  {
453  Field subId = recoveryPoint_.getSubId();
454  Field bookmark = recoveryPoint_.getBookmark();
455  size_t fullLen = _serializeStart + subId.len()
456  + _bookmarkField.length() + bookmark.len() + JSON_END;
457  if (fullLen >= _serializeLen)
458  {
459  _serializeLen = fullLen + (128 - (fullLen % 128));
460  delete[] _serializeBuffer;
461  // This will reallocate the buffer and fill with predicate
462  initSerialization();
463  }
464  AMPS_snprintf(_serializeBuffer + _serializeStart,
465  _serializeLen - _serializeStart,
466  "%.*s\",\"%s\":\"%.*s\"}", (int)subId.len()
467  , subId.data()
468  , _bookmarkField.c_str()
469  , (int)bookmark.len()
470  , bookmark.data());
471  _serializeField.assign(_serializeBuffer, fullLen);
472  }
473  SOW_RECOVERY_HANDLE_EXCEPTION("SOWRecoveryPoint::serialize")
474  return _serializeField;
475  }
476 
477  enum Constants : size_t
478  {
479  JSON_START = 11, // '{', 7 '"', 2 ':', 1 ','
480  JSON_END = 8, // '}', 5 '"', 1 ':', 1 ','
481  JSON_EXTRA = 19, // '{', '}', 3 ':', 12 '"', 2 ','
482  SUBID_LEN = 64 // rough guess on typical max len
483  };
484 
485  private:
486  size_t _serializeLen;
487  size_t _serializeStart;
488  Field _serializeField;
489  char* _serializeBuffer;
490  size_t _deserializeLen;
491  char* _deserializeBuffer;
492  Client _client;
493  std::string _trackedName;
494  std::string _topic;
495  std::string _nameField;
496  std::string _subIdField;
497  std::string _bookmarkField;
498  unsigned _timeoutMillis;
499  MessageStream _stream;
500  MessageStream::iterator _msIter;
501  std::shared_ptr<const ExceptionListener> _pExceptionListener;
502  bool _closeClient;
503  bool _executed;
504  bool _throwNotListen;
505  bool _useTimestamp;
506  bool _closed;
507  };
508 } // namespace AMPS
509 #endif //_SOWRECOVERYPOINTADAPTER_H_
510 
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
virtual void update(RecoveryPoint &recoveryPoint_)
Update the storage information with the given recovery point.
Definition: SOWRecoveryPointAdapter.hpp:246
Message encapsulates a single message sent to or received from an AMPS server, and provides methods f...
Definition: Message.hpp:539
iterator begin(void)
Returns an iterator representing the beginning of the topic or subscription.
Definition: ampsplusplus.hpp:5086
const char * data() const
Returns the (non-null-terminated) data underlying this field.
Definition: Field.hpp:273
Field getCommand() const
Retrieves the value of the Command header of the Message as a Field which references the underlying b...
Definition: Message.hpp:1257
MessageStream execute(Command &command_)
Execute the provided command and return messages received in response in a MessageStream.
Definition: ampsplusplus.hpp:8982
RecoveryPointAdapter virtual base class for implementing external storage of subscription recovery po...
Definition: SOWRecoveryPointAdapter.hpp:93
Command & setFilter(const std::string &filter_)
Definition: ampsplusplus.hpp:692
Client represents a connection to an AMPS server, but does not provide failover or reconnection behav...
Definition: ampsplusplus.hpp:5167
Provides access to the subId and bookmark needed to restart a subscription.
Definition: RecoveryPoint.hpp:67
RecoveryPointImpl virtual base class provides access to the subId and bookmark needed to restart a su...
Definition: RecoveryPoint.hpp:49
Command & setTimeout(unsigned timeout_)
Sets the client-side timeout for this command.
Definition: ampsplusplus.hpp:851
virtual void purge()
Remove all data from the storage.
Definition: SOWRecoveryPointAdapter.hpp:257
virtual bool next(RecoveryPoint &current_)
Recovery is done by iteration over elements in storage.
Definition: SOWRecoveryPointAdapter.hpp:175
bool empty() const
Returns &#39;true&#39; if empty, &#39;false&#39; otherwise.
Definition: Field.hpp:128
Defines the AMPS::Field class, which represents the value of a field in a message.
Core type, function, and class declarations for the AMPS C++ client.
size_t len() const
Returns the length of the data underlying this field.
Definition: Field.hpp:280
Provides AMPS::RecoveryPointAdapter, an iterface for implementing external storage of bookmark subscr...
virtual void purge(const Field &subId_)
Remove the specified subId_ from the storage.
Definition: SOWRecoveryPointAdapter.hpp:269
void setExceptionListener(const std::shared_ptr< const ExceptionListener > &pListener_)
Set an exception listener on this adapter that will be notified of all exceptions that occur rather t...
Definition: SOWRecoveryPointAdapter.hpp:294
SOWRecoveryPointAdapter(const Client &storeClient_, const string &trackedClientName_, unsigned timeoutMillis_=5000, bool useTimestamp_=false, bool closeClient_=true, bool updateFailureThrows_=false, const string &topic_=AMPS_SOW_STORE_DEFAULT_TOPIC, const string &clientNameField_=AMPS_SOW_STORE_DEFAULT_CLIENT_FIELD, const string &subIdField_=AMPS_SOW_STORE_DEFAULT_SUB_FIELD, const string &bookmarkField_=AMPS_SOW_STORE_DEFAULT_BOOKMARK_FIELD)
Create a SOWRecoveryPointAdapter for a BookmarkStore that writes updated RecoveryPoints to the server...
Definition: SOWRecoveryPointAdapter.hpp:128
Provides AMPS::RecoveryPoint, AMPS::RecoveryPointFactory, AMPS::FixedRecoveryPoint, and AMPS::DynamicRecoveryPoint.
Represents an iterator over messages in an AMPS topic.
Definition: ampsplusplus.hpp:5041
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:5780
virtual void close()
Take any necessary actions to close the associated storage.
Definition: SOWRecoveryPointAdapter.hpp:282
Field represents the value of a single field in a Message.
Definition: Field.hpp:86
An iterable object representing the results of an AMPS subscription and/or query. ...
Definition: ampsplusplus.hpp:5033
Field getTimestamp() const
Retrieves the value of the Timestamp header of the Message as a Field which references the underlying...
Definition: Message.hpp:1492
Field getData() const
Returns the data from this message.
Definition: Message.hpp:1522
FixedRecoveryPoint is a RecoveryPoint implementation where subId and bookmark are set explicitly...
Definition: RecoveryPoint.hpp:133
Command & setTopic(const std::string &topic_)
Definition: ampsplusplus.hpp:679
void disconnect()
Disconnect from an AMPS server.
Definition: ampsplusplus.hpp:5386
RecoveryPointAdapterImpl virtual base class for implementing external storage of subscription recover...
Definition: RecoveryPointAdapter.hpp:52
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:5658
Definition: ampsplusplus.hpp:103
const Field & getSubId() const
Get the sub id for this recovery point.
Definition: RecoveryPoint.hpp:84
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:8953
const std::string & getName() const
Returns the name of this client passed in the constructor.
Definition: ampsplusplus.hpp:5229
Command is an encapsulation of a single AMPS command sent by the client.
Definition: ampsplusplus.hpp:472
std::string sowDelete(const MessageHandler &messageHandler, const std::string &topic, const std::string &filter, long timeout)
Deletes one or more messages from a topic&#39;s SOW cache.
Definition: ampsplusplus.hpp:6822
const Field & getBookmark() const
Get the bookmark for this recovery point.
Definition: RecoveryPoint.hpp:91