AMPS C/C++ Client Class Reference
AMPS C/C++ Client Version 5.3.4.3
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 && _pExceptionListener) \
51  { \
52  _pExceptionListener->exceptionThrown(ex); \
53  } \
54  else throw ex; \
55  } \
56  catch (const std::exception& ex_) \
57  { \
58  std::ostringstream os; \
59  os << x << ": std::exception " << ex_.what(); \
60  StoreException ex(os.str()); \
61  if (!_throwNotListen && _pExceptionListener) \
62  { \
63  _pExceptionListener->exceptionThrown(ex); \
64  } \
65  else throw ex; \
66  } \
67  catch (...) \
68  { \
69  std::ostringstream os; \
70  os << x << ": Unknown exception"; \
71  StoreException ex(os.str()); \
72  if (!_throwNotListen && _pExceptionListener) \
73  { \
74  _pExceptionListener->exceptionThrown(ex); \
75  } \
76  else throw ex; \
77  }
78 
79 namespace AMPS
80 {
81 
85  {
86  public:
87 
119  SOWRecoveryPointAdapter(const Client& storeClient_,
120  const string& trackedClientName_,
121  unsigned timeoutMillis_ = 5000,
122  bool useTimestamp_ = false,
123  bool closeClient_ = true,
124  bool updateFailureThrows_ = false,
125  const string& topic_ = AMPS_SOW_STORE_DEFAULT_TOPIC,
126  const string& clientNameField_ = AMPS_SOW_STORE_DEFAULT_CLIENT_FIELD,
127  const string& subIdField_ = AMPS_SOW_STORE_DEFAULT_SUB_FIELD,
128  const string& bookmarkField_ = AMPS_SOW_STORE_DEFAULT_BOOKMARK_FIELD
129  )
131  , _serializeLen(0)
132  , _serializeBuffer(0)
133  , _deserializeLen(0)
134  , _deserializeBuffer(0)
135  , _client(storeClient_)
136  , _trackedName(trackedClientName_)
137  , _topic(topic_)
138  , _nameField(clientNameField_)
139  , _subIdField(subIdField_)
140  , _bookmarkField(bookmarkField_)
141  , _timeoutMillis(timeoutMillis_)
142  , _cmd("publish")
143  , _closeClient(closeClient_)
144  , _executed(false)
145  , _throwNotListen(updateFailureThrows_)
146  , _useTimestamp(useTimestamp_)
147  , _closed(false)
148  {
149  if (_client.getName() == _trackedName)
150  {
151  throw UsageException("The SOWRecoveryPointAdapter cannot use the tracked client to update AMPS");
152  }
153  _initSerialization();
154  _cmd.setTopic(_topic);
155  }
156 
157  virtual ~SOWRecoveryPointAdapter()
158  {
159  _close();
160  delete[] _serializeBuffer;
161  delete[] _deserializeBuffer;
162  }
163 
168  virtual bool next(RecoveryPoint& current_)
169  {
170  static Field emptyField;
171  try
172  {
173  if (!_executed)
174  {
175  Command cmd("sow");
176  cmd.setTopic(_topic)
177  .setFilter("/" + _nameField + "='" + _trackedName + "'")
178  .setTimeout(_timeoutMillis);
179  if (_useTimestamp)
180  {
181  cmd.setOptions("select=[-/,+/" + _subIdField + ",+/"
182  + _bookmarkField + "],timestamp");
183  }
184  else
185  {
186  cmd.setOptions("select=[-/,+/" + _subIdField + ",+/"
187  + _bookmarkField + "]");
188  }
189  _stream = _client.execute(cmd).timeout(_timeoutMillis);
190  _msIter = _stream.begin();
191  _executed = true;
192  }
193  else
194  {
195  ++_msIter;
196  }
197  if (_msIter == MessageStream::iterator())
198  {
199  return false;
200  }
201  Message m = *_msIter;
202  if (!m.isValid())
203  {
204  current_ = RecoveryPoint(NULL);
205  return false;
206  }
207  if (m.getCommand() == "group_begin")
208  {
209  return next(current_);
210  }
211  else if (m.getCommand() == "sow")
212  {
213  if (_useTimestamp)
214  {
215  current_ = RecoveryPoint(deserialize(m.getData(),
216  m.getTimestamp()));
217  }
218  else
219  {
220  current_ = RecoveryPoint(deserialize(m.getData(),
221  emptyField));
222  }
223  return true;
224  }
225  else if (m.getCommand() == "group_end" || m.getCommand() == "ack")
226  {
227  current_ = RecoveryPoint(NULL);
228  _msIter = MessageStream::iterator();
229  _stream = MessageStream();
230  return false;
231  }
232  }
233  SOW_RECOVERY_HANDLE_EXCEPTION("SOWRecoveryPoint::next")
234  return false;
235  }
236 
239  virtual void update(RecoveryPoint& recoveryPoint_)
240  {
241  try
242  {
243  Field data = serialize(recoveryPoint_);
244  _cmd.setData(data.data(), data.len());
245  _client.execute(_cmd);
246  }
247  SOW_RECOVERY_HANDLE_EXCEPTION("SOWRecoveryPoint::update")
248  }
249 
251  virtual void purge()
252  {
253  try
254  {
255  Message m = _client.sowDelete(_topic, "/" + _nameField
256  + "='" + _trackedName + "'");
257  }
258  SOW_RECOVERY_HANDLE_EXCEPTION("SOWRecoveryPoint::purge")
259  }
260 
263  virtual void purge(const Field& subId_)
264  {
265  try
266  {
267  Message m = _client.sowDelete(_topic, "/" + _nameField + "='"
268  + _trackedName + "' and /"
269  + _subIdField + "='"
270  + subId_ + "'");
271  }
272  SOW_RECOVERY_HANDLE_EXCEPTION("SOWRecoveryPoint::purge(subId)")
273  }
274 
276  virtual void close()
277  {
278  _close();
279  }
280 
288  void setExceptionListener(const std::shared_ptr<const ExceptionListener>& pListener_)
289  {
290  _pExceptionListener = pListener_;
291  }
292  protected:
293  void _close()
294  {
295  if (_closed || !_client.isValid())
296  {
297  return;
298  }
299  try
300  {
301  _client.publishFlush();
302  }
303  SOW_RECOVERY_HANDLE_EXCEPTION("SOWRecoveryPoint::close publishFlush")
304  try
305  {
306  if (_closeClient)
307  {
308  _closed = true;
309  _client.disconnect();
310  _client = Client();
311  }
312  }
313  SOW_RECOVERY_HANDLE_EXCEPTION("SOWRecoveryPoint::close disconnect")
314  }
315 
316  void _initSerialization()
317  {
318  try
319  {
320  // Set up json serialization
321  if (_serializeLen == 0)
322  {
323  _serializeLen = (size_t) (_nameField.length()
324  + _trackedName.length()
325  + _subIdField.length()
326  + _bookmarkField.length()
327  + (AMPS_MAX_BOOKMARK_LEN * 4UL)
328  + SUBID_LEN + JSON_EXTRA);
329  _serializeLen += (128 - (_serializeLen % 128));
330  }
331  _serializeBuffer = new char[_serializeLen];
332  AMPS_snprintf(_serializeBuffer, _serializeLen,
333  "{\"%s\":\"%s\",\"%s\":\"", _nameField.c_str()
334  , _trackedName.c_str()
335  , _subIdField.c_str());
336  _serializeStart = JSON_START + _nameField.length()
337  + _trackedName.length() + _subIdField.length();
338  }
339  SOW_RECOVERY_HANDLE_EXCEPTION("SOWRecoveryPoint::initSerialization")
340  }
341 
342  // Subclasses can override this to set up for something other than json
343  // serialization if not using json.
344  virtual void initSerialization()
345  {
346  _initSerialization();
347  }
348 
349  // Subclasses can override this function if not using json data type.
350  // It needs to return an allocated RecoveryPointImpl based on the data
351  // field from a sow message that contains only 2 fields: _subIdField and
352  // _bookmarkField. If you'd like more, override begin()
353  virtual RecoveryPointImpl* deserialize(const Field& data_,
354  const Field& timestamp_)
355  {
356  Field subId;
357  Field bookmark;
358  try
359  {
360  // We have 2 fields subId and bookmark and we only need the
361  // values. Find : then start ", then end ".
362  const char* start = (const char*)memchr((const void*)data_.data(),
363  (int)':', data_.len());
364  if (!start)
365  {
366  throw StoreException("Failure parsing json RecoveryPoint subId, no :");
367  }
368  size_t remain = data_.len() - (size_t)(start - data_.data());
369  start = (const char*)memchr((const void*)start, (int)'"', remain);
370  if (!start)
371  {
372  throw StoreException("Failure parsing json RecoveryPoint subId, no start \"");
373  }
374  ++start;
375  remain = data_.len() - (size_t)(start - data_.data());
376  const char* end = (const char*)memchr((const void*)start,
377  (int)'"', remain);
378  if (!end)
379  {
380  throw StoreException("Failure parsing json RecoveryPoint subId, no end \"");
381  }
382  size_t len = (size_t)(end - start);
383  subId = Field(start, len);
384  start = (const char*)memchr((const void*)start, (int)':', data_.len());
385  if (!start)
386  {
387  throw StoreException("Failure parsing json RecoveryPoint bookmark, no :");
388  }
389  remain = data_.len() - (size_t)(start - data_.data());
390  start = (const char*)memchr((const void*)start, (int)'"', remain);
391  if (!start)
392  {
393  throw StoreException("Failure parsing json RecoveryPoint bookmark, no start \"");
394  }
395  ++start;
396  remain = data_.len() - (size_t)(start - data_.data());
397  end = (const char*)memchr((const void*)start, (int)'"', remain);
398  if (!end)
399  {
400  throw StoreException("Failure parsing json RecoveryPoint bookmark, no end \"");
401  }
402  len = (size_t)(end - start);
403  if (_useTimestamp && !timestamp_.empty())
404  {
405  if (_deserializeLen < len + timestamp_.len())
406  {
407  delete[] _deserializeBuffer;
408  _deserializeBuffer = 0;
409  }
410  if (!_deserializeBuffer)
411  {
412  _deserializeLen = len + timestamp_.len() + 1;
413  _deserializeBuffer = new char[_deserializeLen];
414  }
415  memcpy((void*)_deserializeBuffer, (const void*)start, len);
416  _deserializeBuffer[len] = ',';
417  memcpy((void*)(_deserializeBuffer + len + 1),
418  (const void*)timestamp_.data(), timestamp_.len());
419  bookmark = Field(_deserializeBuffer, _deserializeLen);
420  }
421  else
422  {
423  bookmark = Field(start, len);
424  }
425  }
426  SOW_RECOVERY_HANDLE_EXCEPTION("SOWRecoveryPoint::deserialize")
427  // Return a recovery point that will copy current field values and
428  // clear them when destructed.
429  return new FixedRecoveryPoint(subId, bookmark, true);
430  }
431 
432  virtual Field& serialize(const RecoveryPoint& recoveryPoint_)
433  {
434  try
435  {
436  Field subId = recoveryPoint_.getSubId();
437  Field bookmark = recoveryPoint_.getBookmark();
438  size_t fullLen = _serializeStart + subId.len()
439  + _bookmarkField.length() + bookmark.len() + JSON_END;
440  if (fullLen >= _serializeLen)
441  {
442  _serializeLen = fullLen + (128 - (fullLen % 128));
443  delete[] _serializeBuffer;
444  // This will reallocate the buffer and fill with predicate
445  initSerialization();
446  }
447  AMPS_snprintf(_serializeBuffer + _serializeStart,
448  _serializeLen - _serializeStart,
449  "%.*s\",\"%s\":\"%.*s\"}", (int)subId.len()
450  , subId.data()
451  , _bookmarkField.c_str()
452  , (int)bookmark.len()
453  , bookmark.data());
454  _serializeField.assign(_serializeBuffer, fullLen);
455  }
456  SOW_RECOVERY_HANDLE_EXCEPTION("SOWRecoveryPoint::serialize")
457  return _serializeField;
458  }
459 
460  enum Constants : size_t
461  {
462  JSON_START = 11, // '{', 7 '"', 2 ':', 1 ','
463  JSON_END = 8, // '}', 5 '"', 1 ':', 1 ','
464  JSON_EXTRA = 19, // '{', '}', 3 ':', 12 '"', 2 ','
465  SUBID_LEN = 64 // rough guess on typical max len
466  };
467 
468  private:
469  size_t _serializeLen;
470  size_t _serializeStart;
471  Field _serializeField;
472  char* _serializeBuffer;
473  size_t _deserializeLen;
474  char* _deserializeBuffer;
475  Client _client;
476  std::string _trackedName;
477  std::string _topic;
478  std::string _nameField;
479  std::string _subIdField;
480  std::string _bookmarkField;
481  unsigned _timeoutMillis;
482  Command _cmd;
483  MessageStream _stream;
484  MessageStream::iterator _msIter;
485  std::shared_ptr<const ExceptionListener> _pExceptionListener;
486  bool _closeClient;
487  bool _executed;
488  bool _throwNotListen;
489  bool _useTimestamp;
490  bool _closed;
491  };
492 } // namespace AMPS
493 #endif //_SOWRECOVERYPOINTADAPTER_H_
494 
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:785
virtual void update(RecoveryPoint &recoveryPoint_)
Update the storage information with the given recovery point.
Definition: SOWRecoveryPointAdapter.hpp:239
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:4984
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:8745
RecoveryPointAdapter virtual base class for implementing external storage of subscription recovery po...
Definition: SOWRecoveryPointAdapter.hpp:84
Command & setData(const std::string &data_)
Sets the data for this command from an existing string.
Definition: ampsplusplus.hpp:825
Command & setFilter(const std::string &filter_)
Definition: ampsplusplus.hpp:688
Client represents a connection to an AMPS server, but does not provide failover or reconnection behav...
Definition: ampsplusplus.hpp:5063
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:847
virtual void purge()
Remove all data from the storage.
Definition: SOWRecoveryPointAdapter.hpp:251
virtual bool next(RecoveryPoint &current_)
Recovery is done by iteration over elements in storage.
Definition: SOWRecoveryPointAdapter.hpp:168
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:263
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:288
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:119
Provides AMPS::RecoveryPoint, AMPS::RecoveryPointFactory, AMPS::FixedRecoveryPoint, and AMPS::DynamicRecoveryPoint.
Represents an iterator over messages in an AMPS topic.
Definition: ampsplusplus.hpp:4939
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:5631
virtual void close()
Take any necessary actions to close the associated storage.
Definition: SOWRecoveryPointAdapter.hpp:276
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:4931
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:675
void disconnect()
Disconnect from an AMPS server.
Definition: ampsplusplus.hpp:5250
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:8716
const std::string & getName() const
Returns the name of this client passed in the constructor.
Definition: ampsplusplus.hpp:5125
Command is an encapsulation of a single AMPS command sent by the client.
Definition: ampsplusplus.hpp:468
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:6673
const Field & getBookmark() const
Get the bookmark for this recovery point.
Definition: RecoveryPoint.hpp:91