AMPS C/C++ Client Class Reference
AMPS C/C++ Client Version 5.3.4.4
SOWRecoveryPointAdapter.hpp
1 //
3 // Copyright (c) 2010-2024 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  , _cmd("publish")
152  , _closeClient(closeClient_)
153  , _executed(false)
154  , _throwNotListen(updateFailureThrows_)
155  , _useTimestamp(useTimestamp_)
156  , _closed(false)
157  {
158  if (_client.getName() == _trackedName)
159  {
160  throw UsageException("The SOWRecoveryPointAdapter cannot use the tracked client to update AMPS");
161  }
162  _initSerialization();
163  _cmd.setTopic(_topic);
164  }
165 
166  virtual ~SOWRecoveryPointAdapter()
167  {
168  _close();
169  delete[] _serializeBuffer;
170  delete[] _deserializeBuffer;
171  }
172 
177  virtual bool next(RecoveryPoint& current_)
178  {
179  static Field emptyField;
180  try
181  {
182  if (!_executed)
183  {
184  Command cmd("sow");
185  cmd.setTopic(_topic)
186  .setFilter("/" + _nameField + "='" + _trackedName + "'")
187  .setTimeout(_timeoutMillis);
188  if (_useTimestamp)
189  {
190  cmd.setOptions("select=[-/,+/" + _subIdField + ",+/"
191  + _bookmarkField + "],timestamp");
192  }
193  else
194  {
195  cmd.setOptions("select=[-/,+/" + _subIdField + ",+/"
196  + _bookmarkField + "]");
197  }
198  _stream = _client.execute(cmd).timeout(_timeoutMillis);
199  _msIter = _stream.begin();
200  _executed = true;
201  }
202  else
203  {
204  ++_msIter;
205  }
206  if (_msIter == MessageStream::iterator())
207  {
208  return false;
209  }
210  Message m = *_msIter;
211  if (!m.isValid())
212  {
213  current_ = RecoveryPoint(NULL);
214  return false;
215  }
216  if (m.getCommand() == "group_begin")
217  {
218  return next(current_);
219  }
220  else if (m.getCommand() == "sow")
221  {
222  if (_useTimestamp)
223  {
224  current_ = RecoveryPoint(deserialize(m.getData(),
225  m.getTimestamp()));
226  }
227  else
228  {
229  current_ = RecoveryPoint(deserialize(m.getData(),
230  emptyField));
231  }
232  return true;
233  }
234  else if (m.getCommand() == "group_end" || m.getCommand() == "ack")
235  {
236  current_ = RecoveryPoint(NULL);
237  _msIter = MessageStream::iterator();
238  _stream = MessageStream();
239  return false;
240  }
241  }
242  SOW_RECOVERY_HANDLE_EXCEPTION("SOWRecoveryPoint::next")
243  return false;
244  }
245 
248  virtual void update(RecoveryPoint& recoveryPoint_)
249  {
250  try
251  {
252  Field data = serialize(recoveryPoint_);
253  _cmd.setData(data.data(), data.len());
254  _client.execute(_cmd);
255  }
256  SOW_RECOVERY_HANDLE_EXCEPTION("SOWRecoveryPoint::update")
257  }
258 
260  virtual void purge()
261  {
262  try
263  {
264  Message m = _client.sowDelete(_topic, "/" + _nameField
265  + "='" + _trackedName + "'");
266  }
267  SOW_RECOVERY_HANDLE_EXCEPTION("SOWRecoveryPoint::purge")
268  }
269 
272  virtual void purge(const Field& subId_)
273  {
274  try
275  {
276  Message m = _client.sowDelete(_topic, "/" + _nameField + "='"
277  + _trackedName + "' and /"
278  + _subIdField + "='"
279  + subId_ + "'");
280  }
281  SOW_RECOVERY_HANDLE_EXCEPTION("SOWRecoveryPoint::purge(subId)")
282  }
283 
285  virtual void close()
286  {
287  _close();
288  }
289 
297  void setExceptionListener(const std::shared_ptr<const ExceptionListener>& pListener_)
298  {
299  _pExceptionListener = pListener_;
300  }
301  protected:
302  void _close()
303  {
304  if (_closed || !_client.isValid())
305  {
306  return;
307  }
308  try
309  {
310  _client.publishFlush();
311  }
312  SOW_RECOVERY_HANDLE_EXCEPTION("SOWRecoveryPoint::close publishFlush")
313  try
314  {
315  if (_closeClient)
316  {
317  _closed = true;
318  _client.disconnect();
319  _client = Client();
320  }
321  }
322  SOW_RECOVERY_HANDLE_EXCEPTION("SOWRecoveryPoint::close disconnect")
323  }
324 
325  void _initSerialization()
326  {
327  try
328  {
329  // Set up json serialization
330  if (_serializeLen == 0)
331  {
332  _serializeLen = (size_t) (_nameField.length()
333  + _trackedName.length()
334  + _subIdField.length()
335  + _bookmarkField.length()
336  + (AMPS_MAX_BOOKMARK_LEN * 4UL)
337  + SUBID_LEN + JSON_EXTRA);
338  _serializeLen += (128 - (_serializeLen % 128));
339  }
340  _serializeBuffer = new char[_serializeLen];
341  AMPS_snprintf(_serializeBuffer, _serializeLen,
342  "{\"%s\":\"%s\",\"%s\":\"", _nameField.c_str()
343  , _trackedName.c_str()
344  , _subIdField.c_str());
345  _serializeStart = JSON_START + _nameField.length()
346  + _trackedName.length() + _subIdField.length();
347  }
348  SOW_RECOVERY_HANDLE_EXCEPTION("SOWRecoveryPoint::initSerialization")
349  }
350 
351  // Subclasses can override this to set up for something other than json
352  // serialization if not using json.
353  virtual void initSerialization()
354  {
355  _initSerialization();
356  }
357 
358  // Subclasses can override this function if not using json data type.
359  // It needs to return an allocated RecoveryPointImpl based on the data
360  // field from a sow message that contains only 2 fields: _subIdField and
361  // _bookmarkField. If you'd like more, override begin()
362  virtual RecoveryPointImpl* deserialize(const Field& data_,
363  const Field& timestamp_)
364  {
365  Field subId;
366  Field bookmark;
367  try
368  {
369  // We have 2 fields subId and bookmark and we only need the
370  // values. Find : then start ", then end ".
371  const char* start = (const char*)memchr((const void*)data_.data(),
372  (int)':', data_.len());
373  if (!start)
374  {
375  throw StoreException("Failure parsing json RecoveryPoint subId, no :");
376  }
377  size_t remain = data_.len() - (size_t)(start - data_.data());
378  start = (const char*)memchr((const void*)start, (int)'"', remain);
379  if (!start)
380  {
381  throw StoreException("Failure parsing json RecoveryPoint subId, no start \"");
382  }
383  ++start;
384  remain = data_.len() - (size_t)(start - data_.data());
385  const char* end = (const char*)memchr((const void*)start,
386  (int)'"', remain);
387  if (!end)
388  {
389  throw StoreException("Failure parsing json RecoveryPoint subId, no end \"");
390  }
391  size_t len = (size_t)(end - start);
392  subId = Field(start, len);
393  start = (const char*)memchr((const void*)start, (int)':', data_.len());
394  if (!start)
395  {
396  throw StoreException("Failure parsing json RecoveryPoint bookmark, no :");
397  }
398  remain = data_.len() - (size_t)(start - data_.data());
399  start = (const char*)memchr((const void*)start, (int)'"', remain);
400  if (!start)
401  {
402  throw StoreException("Failure parsing json RecoveryPoint bookmark, no start \"");
403  }
404  ++start;
405  remain = data_.len() - (size_t)(start - data_.data());
406  end = (const char*)memchr((const void*)start, (int)'"', remain);
407  if (!end)
408  {
409  throw StoreException("Failure parsing json RecoveryPoint bookmark, no end \"");
410  }
411  len = (size_t)(end - start);
412  if (_useTimestamp && !timestamp_.empty())
413  {
414  if (_deserializeLen < len + timestamp_.len())
415  {
416  delete[] _deserializeBuffer;
417  _deserializeBuffer = 0;
418  }
419  if (!_deserializeBuffer)
420  {
421  _deserializeLen = len + timestamp_.len() + 1;
422  _deserializeBuffer = new char[_deserializeLen];
423  }
424  memcpy((void*)_deserializeBuffer, (const void*)start, len);
425  _deserializeBuffer[len] = ',';
426  memcpy((void*)(_deserializeBuffer + len + 1),
427  (const void*)timestamp_.data(), timestamp_.len());
428  bookmark = Field(_deserializeBuffer, _deserializeLen);
429  }
430  else
431  {
432  bookmark = Field(start, len);
433  }
434  }
435  SOW_RECOVERY_HANDLE_EXCEPTION("SOWRecoveryPoint::deserialize")
436  // Return a recovery point that will copy current field values and
437  // clear them when destructed.
438  return new FixedRecoveryPoint(subId, bookmark, true);
439  }
440 
441  virtual Field& serialize(const RecoveryPoint& recoveryPoint_)
442  {
443  try
444  {
445  Field subId = recoveryPoint_.getSubId();
446  Field bookmark = recoveryPoint_.getBookmark();
447  size_t fullLen = _serializeStart + subId.len()
448  + _bookmarkField.length() + bookmark.len() + JSON_END;
449  if (fullLen >= _serializeLen)
450  {
451  _serializeLen = fullLen + (128 - (fullLen % 128));
452  delete[] _serializeBuffer;
453  // This will reallocate the buffer and fill with predicate
454  initSerialization();
455  }
456  AMPS_snprintf(_serializeBuffer + _serializeStart,
457  _serializeLen - _serializeStart,
458  "%.*s\",\"%s\":\"%.*s\"}", (int)subId.len()
459  , subId.data()
460  , _bookmarkField.c_str()
461  , (int)bookmark.len()
462  , bookmark.data());
463  _serializeField.assign(_serializeBuffer, fullLen);
464  }
465  SOW_RECOVERY_HANDLE_EXCEPTION("SOWRecoveryPoint::serialize")
466  return _serializeField;
467  }
468 
469  enum Constants : size_t
470  {
471  JSON_START = 11, // '{', 7 '"', 2 ':', 1 ','
472  JSON_END = 8, // '}', 5 '"', 1 ':', 1 ','
473  JSON_EXTRA = 19, // '{', '}', 3 ':', 12 '"', 2 ','
474  SUBID_LEN = 64 // rough guess on typical max len
475  };
476 
477  private:
478  size_t _serializeLen;
479  size_t _serializeStart;
480  Field _serializeField;
481  char* _serializeBuffer;
482  size_t _deserializeLen;
483  char* _deserializeBuffer;
484  Client _client;
485  std::string _trackedName;
486  std::string _topic;
487  std::string _nameField;
488  std::string _subIdField;
489  std::string _bookmarkField;
490  unsigned _timeoutMillis;
491  Command _cmd;
492  MessageStream _stream;
493  MessageStream::iterator _msIter;
494  std::shared_ptr<const ExceptionListener> _pExceptionListener;
495  bool _closeClient;
496  bool _executed;
497  bool _throwNotListen;
498  bool _useTimestamp;
499  bool _closed;
500  };
501 } // namespace AMPS
502 #endif //_SOWRECOVERYPOINTADAPTER_H_
503 
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:788
virtual void update(RecoveryPoint &recoveryPoint_)
Update the storage information with the given recovery point.
Definition: SOWRecoveryPointAdapter.hpp:248
Message encapsulates a single message sent to or received from an AMPS server, and provides methods f...
Definition: Message.hpp:531
iterator begin(void)
Returns an iterator representing the beginning of the topic or subscription.
Definition: ampsplusplus.hpp:4990
const char * data() const
Returns the (non-null-terminated) data underlying this field.
Definition: Field.hpp:260
Field getCommand() const
Retrieves the value of the Command header of the Message as a new Field.
Definition: Message.hpp:1195
MessageStream execute(Command &command_)
Execute the provided command and return messages received in response in a MessageStream.
Definition: ampsplusplus.hpp:8774
RecoveryPointAdapter virtual base class for implementing external storage of subscription recovery po...
Definition: SOWRecoveryPointAdapter.hpp:93
Command & setData(const std::string &data_)
Sets the data for this command from an existing string.
Definition: ampsplusplus.hpp:828
Command & setFilter(const std::string &filter_)
Definition: ampsplusplus.hpp:691
Client represents a connection to an AMPS server, but does not provide failover or reconnection behav...
Definition: ampsplusplus.hpp:5069
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:850
virtual void purge()
Remove all data from the storage.
Definition: SOWRecoveryPointAdapter.hpp:260
virtual bool next(RecoveryPoint &current_)
Recovery is done by iteration over elements in storage.
Definition: SOWRecoveryPointAdapter.hpp:177
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:267
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:272
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:297
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:4945
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:5637
virtual void close()
Take any necessary actions to close the associated storage.
Definition: SOWRecoveryPointAdapter.hpp:285
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:4937
Field getTimestamp() const
Retrieves the value of the Timestamp header of the Message as a new Field.
Definition: Message.hpp:1430
Field getData() const
Returns the data from this message.
Definition: Message.hpp:1460
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:678
void disconnect()
Disconnect from an AMPS server.
Definition: ampsplusplus.hpp:5256
RecoveryPointAdapterImpl virtual base class for implementing external storage of subscription recover...
Definition: RecoveryPointAdapter.hpp:52
Definition: ampsplusplus.hpp:102
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:8745
const std::string & getName() const
Returns the name of this client passed in the constructor.
Definition: ampsplusplus.hpp:5131
Command is an encapsulation of a single AMPS command sent by the client.
Definition: ampsplusplus.hpp:471
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:6679
const Field & getBookmark() const
Get the bookmark for this recovery point.
Definition: RecoveryPoint.hpp:91