Mads
Multi-Agent Distributed System
Loading...
Searching...
No Matches
play_restamp.hpp
Go to the documentation of this file.
1/*
2 mads-play's --restamp helper.
3
4 Rewrites the "timestamp"/"timecode" fields of a legacy, header-less
5 [topic][snappy(json)] record part (a single Snappy-compressed JSON
6 object -- the shape Agent::publish() emits whenever the payload ends up
7 Snappy-compressed, see agent.cpp's WireHeader comment) to fresh values,
8 leaving every other field, and every other frame shape (an uncompressed
9 JSON payload carrying a self-describing header, MsgPack, or a blob's
10 meta+bytes parts), byte-for-byte unchanged.
11
12 Header-only so it is directly unit-testable (tests/test_bag_roundtrip.cpp)
13 without linking src/main/play.cpp's main(); mirrors the precedent of
14 src/main/plugin_migrate.hpp.
15
16 See src/main/play.cpp's file header for the full --restamp rationale/scope.
17
18 Author(s): Paolo Bosetti
19*/
20#ifndef MADS_MAIN_PLAY_RESTAMP_HPP
21#define MADS_MAIN_PLAY_RESTAMP_HPP
22
23#include <chrono>
24#include <nlohmann/json.hpp>
25#include <snappy.h>
26#include <string>
27#include <vector>
28
29#include "../mads.hpp"
30
31namespace Mads {
32namespace Play {
33
43inline bool try_restamp(std::vector<std::string> &parts) {
44 if (parts.size() != 1)
45 return false; // extended header or blob (meta+bytes): out of scope
46
47 std::string decompressed;
48 const std::string *json_text = &parts[0];
49 bool was_compressed = false;
50 if (snappy::Uncompress(parts[0].data(), parts[0].size(), &decompressed)) {
51 json_text = &decompressed;
52 was_compressed = true;
53 }
54
55 nlohmann::json payload;
56 try {
57 payload = nlohmann::json::parse(*json_text);
58 } catch (...) {
59 return false; // not JSON: leave untouched
60 }
61 if (!payload.is_object())
62 return false;
63
64 auto now = std::chrono::system_clock::now();
65 bool touched = false;
66 if (payload.contains("timestamp")) {
67 payload["timestamp"]["$date"] = Mads::get_ISODate_time(now);
68 touched = true;
69 }
70 if (payload.contains("timecode")) {
71 payload["timecode"] = Mads::timecode(now, MADS_FPS);
72 touched = true;
73 }
74 if (!touched)
75 return false;
76
77 std::string dumped = payload.dump();
78 if (was_compressed) {
79 std::string recompressed;
80 snappy::Compress(dumped.data(), dumped.size(), &recompressed);
81 parts[0] = std::move(recompressed);
82 } else {
83 parts[0] = std::move(dumped);
84 }
85 return true;
86}
87
88} // namespace Play
89} // namespace Mads
90
91#endif // MADS_MAIN_PLAY_RESTAMP_HPP
bool try_restamp(std::vector< std::string > &parts)
Best-effort –restamp rewrite of a raw record's parts, in place.
Definition agent.hpp:67