Fray Engine
Loading...
Searching...
No Matches
history_manager.hpp
Go to the documentation of this file.
1#ifndef FRAY_HISTORY_MANAGER_HPP
2#define FRAY_HISTORY_MANAGER_HPP
3
4#include <cstdint>
5#include <memory>
6#include <optional>
7#include <string>
8#include <vector>
9
10#include <sqlite3.h>
11
12#include "errors.hpp"
13#include "log_manager.hpp"
14#include "state_manager.hpp"
15#include "types.hpp"
16
17namespace fray
18{
19 namespace history
20 {
24 struct Node
25 {
29 std::int64_t id = 0;
33 std::int64_t parentId = 0;
37 std::int64_t sequence = 0;
41 std::uint64_t revision = 0;
45 std::string domain;
49 std::string payload;
50 };
51
57 {
58 private:
62 using Statement = std::unique_ptr<sqlite3_stmt, decltype(&sqlite3_finalize)>;
67
75 sqlite3* db,
76 const char* sql)
77 {
78 sqlite3_stmt* raw = nullptr;
79 if (sqlite3_prepare_v2(db, sql, -1, &raw, nullptr) != SQLITE_OK)
80 {
81 log::engineError("Failed to prepare history statement: %s", sqlite3_errmsg(db));
82 sqlite3_finalize(raw);
83 return Statement(nullptr, sqlite3_finalize);
84 }
85 return Statement(raw, sqlite3_finalize);
86 }
87
95 static bool bindText(
96 sqlite3_stmt* statement,
97 int index,
98 const std::string& value)
99 {
100 return sqlite3_bind_text64(statement, index, value.data(), value.size(), SQLITE_TRANSIENT,
101 SQLITE_UTF8) == SQLITE_OK;
102 }
103
110 static bool run(
111 sqlite3* db,
112 const char* sql)
113 {
114 if (sqlite3_exec(db, sql, nullptr, nullptr, nullptr) == SQLITE_OK)
115 return true;
116 log::engineError("History statement failed: %s", sqlite3_errmsg(db));
117 return false;
118 }
119
125 static bool ensureTables(
126 sqlite3* db)
127 {
128 return run(db,
129 "CREATE TABLE IF NOT EXISTS fray_history_nodes ("
130 "node_id INTEGER PRIMARY KEY AUTOINCREMENT, "
131 "domain TEXT NOT NULL, "
132 "revision INTEGER NOT NULL, "
133 "parent_id INTEGER, "
134 "sequence INTEGER NOT NULL, "
135 "payload TEXT NOT NULL, "
136 "created_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now')), "
137 "UNIQUE (domain, revision))") &&
138 run(db,
139 "CREATE TABLE IF NOT EXISTS fray_history_heads ("
140 "domain TEXT PRIMARY KEY NOT NULL, "
141 "node_id INTEGER NOT NULL)");
142 }
143
150 sqlite3_stmt* statement)
151 {
152 Node node;
153 node.id = sqlite3_column_int64(statement, 0);
154 node.domain.assign(reinterpret_cast<const char*>(sqlite3_column_text(statement, 1)),
155 static_cast<std::size_t>(sqlite3_column_bytes(statement, 1)));
156 node.revision = static_cast<std::uint64_t>(sqlite3_column_int64(statement, 2));
157 node.parentId = sqlite3_column_int64(statement, 3);
158 node.sequence = sqlite3_column_int64(statement, 4);
159 node.payload.assign(reinterpret_cast<const char*>(sqlite3_column_text(statement, 5)),
160 static_cast<std::size_t>(sqlite3_column_bytes(statement, 5)));
161 return node;
162 }
163
167 static constexpr const char* nodeColumns =
168 "node_id, domain, revision, COALESCE(parent_id, 0), sequence, payload";
169
180 sqlite3* db,
181 const char* sql,
182 const std::string& domain,
183 std::optional<std::int64_t> number,
184 std::optional<Node>& found)
185 {
186 found.reset();
187 if (!ensureTables(db))
188 return errors::FAILED_HISTORY;
189 auto statement = prepare(db, sql);
190 if (!statement || (!domain.empty() && !bindText(statement.get(), 1, domain)) ||
191 (number && sqlite3_bind_int64(statement.get(), 2, *number) != SQLITE_OK))
192 return errors::FAILED_HISTORY;
193 const int step = sqlite3_step(statement.get());
194 if (step == SQLITE_ROW)
195 found = readNode(statement.get());
196 else if (step != SQLITE_DONE)
197 {
198 log::engineError("Failed to read history: %s", sqlite3_errmsg(db));
199 return errors::FAILED_HISTORY;
200 }
201 return errors::NONE;
202 }
203
204 public:
211 : _state(state)
212 {
213 }
214
225 const std::string& domain,
226 std::uint64_t revision,
227 const std::string& payload,
228 bool& created)
229 {
230 created = false;
231 if (domain.empty() || revision > static_cast<std::uint64_t>(INT64_MAX))
232 {
233 log::engineError("Cannot record history: invalid domain or revision.");
234 return errors::FAILED_HISTORY;
235 }
236 return _state.withDatabase([&](sqlite3* db) -> F_err
237 {
238 if (!ensureTables(db) || !run(db, "BEGIN IMMEDIATE"))
239 return errors::FAILED_HISTORY;
240 const auto fail = [db]
241 {
242 run(db, "ROLLBACK");
243 return errors::FAILED_HISTORY;
244 };
245 std::optional<Node> existing;
246 if (selectNode(db, (std::string("SELECT ") + nodeColumns +
247 " FROM fray_history_nodes WHERE domain = ?1 AND revision = ?2").c_str(),
248 domain, static_cast<std::int64_t>(revision), existing) != errors::NONE)
249 return fail();
250 if (existing)
251 return run(db, "COMMIT") ? errors::NONE : fail();
252 std::optional<Node> head;
253 if (selectNode(db, (std::string("SELECT ") + nodeColumns +
254 " FROM fray_history_nodes WHERE node_id = "
255 "(SELECT node_id FROM fray_history_heads WHERE domain = ?1)").c_str(),
256 domain, std::nullopt, head) != errors::NONE)
257 return fail();
258 auto insert = prepare(db,
259 "INSERT INTO fray_history_nodes (domain, revision, parent_id, sequence, payload) "
260 "VALUES (?1, ?2, ?3, (SELECT COALESCE(MAX(sequence), 0) + 1 FROM fray_history_nodes), ?4)");
261 if (!insert || !bindText(insert.get(), 1, domain) ||
262 sqlite3_bind_int64(insert.get(), 2, static_cast<std::int64_t>(revision)) != SQLITE_OK ||
263 (head ? sqlite3_bind_int64(insert.get(), 3, head->id) : sqlite3_bind_null(insert.get(), 3)) !=
264 SQLITE_OK ||
265 !bindText(insert.get(), 4, payload) || sqlite3_step(insert.get()) != SQLITE_DONE)
266 {
267 log::engineError("Failed to record history: %s", sqlite3_errmsg(db));
268 return fail();
269 }
270 const std::int64_t id = sqlite3_last_insert_rowid(db);
271 auto point = prepare(db,
272 "INSERT INTO fray_history_heads (domain, node_id) VALUES (?1, ?2) "
273 "ON CONFLICT(domain) DO UPDATE SET node_id = excluded.node_id");
274 if (!point || !bindText(point.get(), 1, domain) ||
275 sqlite3_bind_int64(point.get(), 2, id) != SQLITE_OK ||
276 sqlite3_step(point.get()) != SQLITE_DONE)
277 {
278 log::engineError("Failed to move the history head: %s", sqlite3_errmsg(db));
279 return fail();
280 }
281 if (!run(db, "COMMIT"))
282 return fail();
283 created = true;
284 return errors::NONE;
285 });
286 }
287
295 const std::string& domain,
296 std::optional<Node>& node)
297 {
298 return _state.withDatabase([&](sqlite3* db)
299 {
300 return selectNode(db, (std::string("SELECT ") + nodeColumns +
301 " FROM fray_history_nodes WHERE node_id = "
302 "(SELECT node_id FROM fray_history_heads WHERE domain = ?1)").c_str(),
303 domain, std::nullopt, node);
304 });
305 }
306
315 const std::string& domain,
316 std::uint64_t revision,
317 std::optional<Node>& node)
318 {
319 return _state.withDatabase([&](sqlite3* db)
320 {
321 return selectNode(db, (std::string("SELECT ") + nodeColumns +
322 " FROM fray_history_nodes WHERE domain = ?1 AND revision = ?2").c_str(),
323 domain, static_cast<std::int64_t>(revision), node);
324 });
325 }
326
334 const std::string& domain,
335 std::optional<Node>& node)
336 {
337 return _state.withDatabase([&](sqlite3* db)
338 {
339 return selectNode(db, (std::string("SELECT ") + nodeColumns +
340 " FROM fray_history_nodes WHERE domain = ?1 "
341 "ORDER BY revision DESC LIMIT 1").c_str(),
342 domain, std::nullopt, node);
343 });
344 }
345
353 const Node& node,
354 std::optional<Node>& found)
355 {
356 return _state.withDatabase([&](sqlite3* db)
357 {
358 return selectNode(db, (std::string("SELECT ") + nodeColumns +
359 " FROM fray_history_nodes WHERE node_id = ?2").c_str(),
360 "", node.parentId, found);
361 });
362 }
363
371 const Node& node,
372 std::optional<Node>& found)
373 {
374 return _state.withDatabase([&](sqlite3* db)
375 {
376 return selectNode(db, (std::string("SELECT ") + nodeColumns +
377 " FROM fray_history_nodes WHERE parent_id = ?2 "
378 "ORDER BY sequence DESC LIMIT 1").c_str(),
379 "", node.id, found);
380 });
381 }
382
389 std::vector<Node>& nodes)
390 {
391 nodes.clear();
392 return _state.withDatabase([&](sqlite3* db) -> F_err
393 {
394 if (!ensureTables(db))
395 return errors::FAILED_HISTORY;
396 auto statement = prepare(db, (std::string("SELECT ") + nodeColumns +
397 " FROM fray_history_nodes WHERE node_id IN (SELECT node_id FROM fray_history_heads)").c_str());
398 if (!statement)
399 return errors::FAILED_HISTORY;
400 int step;
401 while ((step = sqlite3_step(statement.get())) == SQLITE_ROW)
402 nodes.push_back(readNode(statement.get()));
403 return step == SQLITE_DONE ? errors::NONE : errors::FAILED_HISTORY;
404 });
405 }
406
415 const std::string& domain,
416 std::int64_t nodeId)
417 {
418 return _state.withDatabase([&](sqlite3* db) -> F_err
419 {
420 if (!ensureTables(db))
421 return errors::FAILED_HISTORY;
422 auto update = prepare(db,
423 "INSERT INTO fray_history_heads (domain, node_id) "
424 "SELECT domain, node_id FROM fray_history_nodes WHERE domain = ?1 AND node_id = ?2 "
425 "ON CONFLICT(domain) DO UPDATE SET node_id = excluded.node_id");
426 if (!update || !bindText(update.get(), 1, domain) ||
427 sqlite3_bind_int64(update.get(), 2, nodeId) != SQLITE_OK ||
428 sqlite3_step(update.get()) != SQLITE_DONE || sqlite3_changes(db) == 0)
429 {
430 log::engineError("Cannot move the history head: no such node in the domain.");
431 return errors::FAILED_HISTORY;
432 }
433 return errors::NONE;
434 });
435 }
436 };
437 }
438}
439
440#endif
F_err moveHead(const std::string &domain, std::int64_t nodeId)
Moves a domain head to an existing node without deleting branches. Runs on the calling thread under t...
F_err heads(std::vector< Node > &nodes)
Reads all domain heads under the state mutex.
static Node readNode(sqlite3_stmt *statement)
Reads a node from the current row in nodeColumns order.
F_err head(const std::string &domain, std::optional< Node > &node)
Finds the current node for a domain under the state mutex.
F_err find(const std::string &domain, std::uint64_t revision, std::optional< Node > &node)
Finds a domain node by revision under the state mutex.
static bool bindText(sqlite3_stmt *statement, int index, const std::string &value)
Binds a copied UTF-8 string to a statement parameter.
std::unique_ptr< sqlite3_stmt, decltype(&sqlite3_finalize)> Statement
Owns an SQLite statement and finalizes it on destruction.
F_err record(const std::string &domain, std::uint64_t revision, const std::string &payload, bool &created)
Records a new node under the domain head and advances the head transactionally. An existing domain/re...
HistoryManager(state::StateManager &state)
Borrows the state store that owns the project database.
F_err parent(const Node &node, std::optional< Node > &found)
Finds a node’s parent under the state mutex.
static bool ensureTables(sqlite3 *db)
Creates the history node and head tables if absent.
static Statement prepare(sqlite3 *db, const char *sql)
Prepares an SQLite statement and logs failures.
state::StateManager & _state
Non-owning reference to the state store and its database mutex.
F_err latest(const std::string &domain, std::optional< Node > &node)
Finds the highest revision in a domain across all branches under the state mutex.
static constexpr const char * nodeColumns
Column order expected by readNode, with null parents mapped to zero.
F_err child(const Node &node, std::optional< Node > &found)
Finds the most recently recorded child for redo under the state mutex.
static F_err selectNode(sqlite3 *db, const char *sql, const std::string &domain, std::optional< std::int64_t > number, std::optional< Node > &found)
Ensures history tables and reads at most one node.
static bool run(sqlite3 *db, const char *sql)
Executes SQL and logs an SQLite failure.
Owns a SQLite connection and a typed key/value state table. Database operations serialize on a recurs...
F_long F_err
Error return type used across the Engine; the value is a fray::errors::code (0 / NONE means success).
Definition errors.hpp:13
F_void engineError(const F_char *fmt,...)
Log error for Engine.
One recorded history action with domain-defined opaque payload.
std::int64_t parentId
Parent node identifier, or 0 for the first node in a domain.
std::string domain
Domain that owns and interprets this action.
std::uint64_t revision
Recorder-assigned, never-reused revision within the domain.
std::int64_t sequence
Global recording order across domains.
std::string payload
Opaque action data interpreted by its domain.
std::int64_t id
Database identifier of this node.