Fray Engine
Loading...
Searching...
No Matches
state_manager.hpp
Go to the documentation of this file.
1#ifndef FRAY_STATE_MANAGER_HPP
2#define FRAY_STATE_MANAGER_HPP
3
4#include <cmath>
5#include <cstdio>
6#include <cstdint>
7#include <cstring>
8#include <initializer_list>
9#include <limits>
10#include <memory>
11#include <mutex>
12#include <string>
13#include <type_traits>
14#include <variant>
15#include <vector>
16
17#include <sqlite3.h>
18
19#include "types.hpp"
20#include "errors.hpp"
21#include "log_manager.hpp"
22#include "file_manager.hpp"
23
24namespace fray
25{
26 namespace state
27 {
33 {
34 public:
38 using Binary = std::vector<std::uint8_t>;
39
40 private:
44 using Value = std::variant<std::string, std::int64_t, double, bool, Binary>;
48 using Statement = std::unique_ptr<sqlite3_stmt, decltype(&sqlite3_finalize)>;
52 mutable std::recursive_mutex _mutex;
56 sqlite3* _db = nullptr;
60 std::string _table;
68 std::weak_ptr<int> _filesLifetime;
72 std::string _projectName;
76 std::string _applicationId;
77
84 {
85 if (_files == nullptr || _filesLifetime.expired())
86 {
87 fray::log::engineError("Cannot access state: its file manager has been destroyed.");
88 return false;
89 }
90 return true;
91 }
92
98 {
99 if (_files != nullptr && !_filesLifetime.expired())
100 _files->detach();
101 _files = nullptr;
102 _filesLifetime.reset();
103 _projectName.clear();
104 _applicationId.clear();
105 }
106
112 static std::string tableName(
113 const std::string& name)
114 {
115 static constexpr F_char hex[] = "0123456789abcdef";
116 std::string result = "fray_state_";
117 for (unsigned char byte : name)
118 {
119 result += hex[byte >> 4];
120 result += hex[byte & 15];
121 }
122 return result;
123 }
124
132 const std::string& name)
133 {
134 F_bool exists;
135 if (!tableExists(name.c_str(), exists))
136 return false;
137 if (exists && !hasExpectedColumns(name.c_str(), {"key", "type", "value"}))
138 return false;
139 const std::string sql =
140 "CREATE TABLE IF NOT EXISTS " + name +
141 " (key TEXT PRIMARY KEY NOT NULL, type INTEGER NOT NULL, value NOT NULL, "
142 "CHECK((type = 1 AND typeof(value) = 'text') OR "
143 "(type = 2 AND typeof(value) = 'integer') OR "
144 "(type = 3 AND typeof(value) = 'real') OR "
145 "(type = 4 AND typeof(value) = 'integer' AND value IN (0, 1)) OR "
146 "(type = 5 AND typeof(value) = 'blob')))";
147 if (sqlite3_exec(_db, sql.c_str(), nullptr, nullptr, nullptr) != SQLITE_OK)
148 {
149 fray::log::engineError("Failed to create state table: %s", sqlite3_errmsg(_db));
150 return false;
151 }
152 return true;
153 }
154
160 {
161 if (_db == nullptr)
162 return;
163 const int result = sqlite3_close_v2(_db);
164 if (result == SQLITE_OK)
165 _db = nullptr;
166 else
167 fray::log::engineError("Failed to close store: %s", sqlite3_errstr(result));
168 }
169
175 {
176 if (sqlite3_exec(_db, "ROLLBACK", nullptr, nullptr, nullptr) != SQLITE_OK)
177 fray::log::engineError("Failed to roll back store transaction: %s", sqlite3_errmsg(_db));
178 }
179
186 const std::string& key) const
187 {
188 if (key.empty() || key.find('\0') != std::string::npos)
189 {
190 fray::log::engineError("State key must be nonempty and contain no null characters.");
191 return false;
192 }
193 return true;
194 }
195
204 const F_char* name,
205 F_bool& exists)
206 {
207 sqlite3_stmt* raw = nullptr;
208 const int prepared = sqlite3_prepare_v2(_db,
209 "SELECT type FROM sqlite_master WHERE type IN ('table', 'view') AND name = ? COLLATE NOCASE",
210 -1, &raw, nullptr);
211 Statement statement(raw, sqlite3_finalize);
212 if (prepared != SQLITE_OK ||
213 sqlite3_bind_text(statement.get(), 1, name, -1, SQLITE_STATIC) != SQLITE_OK)
214 {
215 fray::log::engineError("Failed to inspect state tables: %s", sqlite3_errmsg(_db));
216 return false;
217 }
218 const int result = sqlite3_step(statement.get());
219 if (result != SQLITE_ROW && result != SQLITE_DONE)
220 {
221 fray::log::engineError("Failed to inspect state tables: %s", sqlite3_errmsg(_db));
222 return false;
223 }
224 if (result == SQLITE_ROW)
225 {
226 const auto* type = reinterpret_cast<const F_char*>(sqlite3_column_text(statement.get(), 0));
227 if (type == nullptr || std::strcmp(type, "table") != 0)
228 {
229 fray::log::engineError("Cannot open store: %s is not a table.", name);
230 return false;
231 }
232 }
233 exists = result == SQLITE_ROW;
234 return true;
235 }
236
245 const F_char* table,
246 std::initializer_list<const F_char*> expected)
247 {
248 sqlite3_stmt* raw = nullptr;
249 const int prepared = sqlite3_prepare_v2(_db, "SELECT name FROM pragma_table_xinfo(?)",
250 -1, &raw, nullptr);
251 Statement statement(raw, sqlite3_finalize);
252 if (prepared != SQLITE_OK ||
253 sqlite3_bind_text(statement.get(), 1, table, -1, SQLITE_STATIC) != SQLITE_OK)
254 {
255 fray::log::engineError("Failed to inspect state schema: %s", sqlite3_errmsg(_db));
256 return false;
257 }
258 std::size_t count = 0;
259 int result;
260 while ((result = sqlite3_step(statement.get())) == SQLITE_ROW)
261 {
262 const auto* name = reinterpret_cast<const F_char*>(sqlite3_column_text(statement.get(), 0));
263 F_bool found = false;
264 if (name != nullptr)
265 for (const F_char* candidate : expected)
266 if (std::strcmp(name, candidate) == 0)
267 found = true;
268 if (!found)
269 {
270 fray::log::engineError("Invalid state table: unexpected column in %s.", table);
271 return false;
272 }
273 ++count;
274 }
275 if (result != SQLITE_DONE || count != expected.size())
276 {
277 fray::log::engineError("Invalid state schema for %s.", table);
278 return false;
279 }
280 return true;
281 }
282
292 Statement& statement,
293 const F_char* operation,
294 F_err failure)
295 {
296 const std::string error = sqlite3_errmsg(_db);
297 statement.reset();
298 F_bool exists;
299 if (!tableExists(_table.c_str(), exists))
300 return failure;
301 if (!exists)
302 {
303 fray::log::engineError("State table not found.");
304 return fray::errors::STATE_NOT_FOUND;
305 }
306 fray::log::engineError("Failed to %s state: %s", operation, error.c_str());
307 return failure;
308 }
309
315 static std::string escaped(
316 const std::string& text)
317 {
318 static constexpr F_char hex[] = "0123456789abcdef";
319 std::string result;
320 for (unsigned char byte : text)
321 {
322 if (byte == '\\' || byte == '"')
323 {
324 result += '\\';
325 result += static_cast<F_char>(byte);
326 }
327 else if (byte < 0x20 || byte >= 0x7f)
328 {
329 result += "\\x";
330 result += hex[byte >> 4];
331 result += hex[byte & 15];
332 }
333 else
334 result += static_cast<F_char>(byte);
335 }
336 return result;
337 }
338
345 const std::string& key,
346 const Value& value)
347 {
348 std::string formatted;
349 if (const auto* text = std::get_if<std::string>(&value))
350 formatted = "\"" + escaped(*text) + "\"";
351 else if (const auto* integer = std::get_if<std::int64_t>(&value))
352 formatted = std::to_string(*integer);
353 else if (const auto* real = std::get_if<double>(&value))
354 {
355 F_char buffer[128];
356 std::snprintf(buffer, sizeof(buffer), "%.*g", std::numeric_limits<double>::max_digits10, *real);
357 formatted = buffer;
358 }
359 else if (const auto* boolean = std::get_if<bool>(&value))
360 formatted = *boolean ? "true" : "false";
361 else
362 {
363 static constexpr F_char hex[] = "0123456789abcdef";
364 formatted = "0x";
365 for (std::uint8_t byte : std::get<Binary>(value))
366 {
367 formatted += hex[byte >> 4];
368 formatted += hex[byte & 15];
369 }
370 }
371 fray::log::engineInfo("Set state \"" + escaped(key) + "\" = " + formatted);
372 }
373
383 const std::string& key,
384 const Value& value,
385 F_bool retry = true)
386 {
387 std::lock_guard<std::recursive_mutex> lock(_mutex);
388 if (_db == nullptr)
389 {
390 fray::log::engineError("Cannot save state: store is not open.");
391 return fray::errors::FAILED_SAVE_STATE;
392 }
393 if (!projectAvailable())
394 return fray::errors::FAILED_SAVE_STATE;
395 if (!validKey(key))
396 return fray::errors::INVALID_STATE_KEY;
397 if (const auto* real = std::get_if<double>(&value); real != nullptr && !std::isfinite(*real))
398 {
399 fray::log::engineError("Cannot save a non-finite floating-point value.");
400 return fray::errors::FAILED_SAVE_STATE;
401 }
402 sqlite3_stmt* raw = nullptr;
403 const std::string sql = "INSERT INTO " + _table +
404 " (key, type, value) VALUES (?, ?, ?) "
405 "ON CONFLICT(key) DO UPDATE SET type = excluded.type, value = excluded.value";
406 int prepared = sqlite3_prepare_v2(_db, sql.c_str(), -1, &raw, nullptr);
407 if (prepared != SQLITE_OK)
408 {
409 const std::string error = sqlite3_errmsg(_db);
410 sqlite3_finalize(raw);
411 raw = nullptr;
412 F_bool exists;
413 if (!tableExists(_table.c_str(), exists))
414 return fray::errors::FAILED_SAVE_STATE;
415 if (exists)
416 {
417 fray::log::engineError("Failed to save state: %s", error.c_str());
418 return fray::errors::FAILED_SAVE_STATE;
419 }
420 if (!retry || !createTable(_table))
421 {
422 fray::log::engineError("Failed to save state: %s", error.c_str());
423 return fray::errors::FAILED_SAVE_STATE;
424 }
425 retry = false;
426 prepared = sqlite3_prepare_v2(_db, sql.c_str(), -1, &raw, nullptr);
427 }
428 Statement statement(raw, sqlite3_finalize);
429 if (prepared != SQLITE_OK)
430 {
431 fray::log::engineError("Failed to save state: %s", sqlite3_errmsg(_db));
432 return fray::errors::FAILED_SAVE_STATE;
433 }
434 int bound = sqlite3_bind_text64(statement.get(), 1, key.data(), key.size(), SQLITE_TRANSIENT, SQLITE_UTF8);
435 if (bound == SQLITE_OK)
436 bound = sqlite3_bind_int(statement.get(), 2, static_cast<int>(value.index()) + 1);
437 if (bound == SQLITE_OK)
438 {
439 if (const auto* text = std::get_if<std::string>(&value))
440 bound = sqlite3_bind_text64(statement.get(), 3, text->data(), text->size(), SQLITE_TRANSIENT, SQLITE_UTF8);
441 else if (const auto* integer = std::get_if<std::int64_t>(&value))
442 bound = sqlite3_bind_int64(statement.get(), 3, *integer);
443 else if (const auto* real = std::get_if<double>(&value))
444 bound = sqlite3_bind_double(statement.get(), 3, *real);
445 else if (const auto* boolean = std::get_if<bool>(&value))
446 bound = sqlite3_bind_int(statement.get(), 3, *boolean ? 1 : 0);
447 else
448 {
449 const auto& binary = std::get<Binary>(value);
450 bound = binary.empty()
451 ? sqlite3_bind_zeroblob(statement.get(), 3, 0)
452 : sqlite3_bind_blob64(statement.get(), 3, binary.data(), binary.size(), SQLITE_TRANSIENT);
453 }
454 }
455 if (bound != SQLITE_OK)
456 {
457 fray::log::engineError("Failed to save state: %s", sqlite3_errmsg(_db));
458 return fray::errors::FAILED_SAVE_STATE;
459 }
460 if (sqlite3_step(statement.get()) != SQLITE_DONE)
461 {
462 const std::string error = sqlite3_errmsg(_db);
463 statement.reset();
464 F_bool exists;
465 if (!tableExists(_table.c_str(), exists))
466 return fray::errors::FAILED_SAVE_STATE;
467 if (!exists && retry && createTable(_table))
468 return write(key, value, false);
469 fray::log::engineError("Failed to save state: %s", error.c_str());
470 return fray::errors::FAILED_SAVE_STATE;
471 }
472 statement.reset();
473 logSet(key, value);
474 return fray::errors::NONE;
475 }
476
485 template<typename T>
487 const std::string& key,
488 T& output,
489 int expectedType)
490 {
491 std::lock_guard<std::recursive_mutex> lock(_mutex);
492 if (_db == nullptr)
493 {
494 fray::log::engineError("Cannot load state: store is not open.");
495 return fray::errors::FAILED_LOAD_STATE;
496 }
497 if (!projectAvailable())
498 return fray::errors::FAILED_LOAD_STATE;
499 if (!validKey(key))
500 return fray::errors::INVALID_STATE_KEY;
501 sqlite3_stmt* raw = nullptr;
502 const std::string sql = "SELECT type, value FROM " + _table + " WHERE key = ?";
503 const int prepared = sqlite3_prepare_v2(_db, sql.c_str(), -1, &raw, nullptr);
504 Statement statement(raw, sqlite3_finalize);
505 if (prepared != SQLITE_OK)
506 {
507 return statementFailure(statement, "load", fray::errors::FAILED_LOAD_STATE);
508 }
509 if (sqlite3_bind_text64(statement.get(), 1, key.data(), key.size(), SQLITE_TRANSIENT, SQLITE_UTF8) != SQLITE_OK)
510 {
511 fray::log::engineError("Failed to load state: %s", sqlite3_errmsg(_db));
512 return fray::errors::FAILED_LOAD_STATE;
513 }
514 const int result = sqlite3_step(statement.get());
515 if (result == SQLITE_DONE)
516 {
517 fray::log::engineError("State key not found: %s", key.c_str());
518 return fray::errors::STATE_NOT_FOUND;
519 }
520 if (result != SQLITE_ROW)
521 {
522 return statementFailure(statement, "load", fray::errors::FAILED_LOAD_STATE);
523 }
524 if (sqlite3_column_type(statement.get(), 0) != SQLITE_INTEGER)
525 {
526 fray::log::engineError("Failed to load state: invalid value type.");
527 return fray::errors::FAILED_LOAD_STATE;
528 }
529 const sqlite3_int64 storedType = sqlite3_column_int64(statement.get(), 0);
530 if (storedType < 1 || storedType > 5)
531 return invalidStoredValue();
532 if (storedType != expectedType)
533 {
534 fray::log::engineError("Cannot load state: value type does not match.");
535 return fray::errors::STATE_TYPE_MISMATCH;
536 }
537 if constexpr (std::is_same_v<T, std::string>)
538 {
539 if (sqlite3_column_type(statement.get(), 1) != SQLITE_TEXT)
540 return invalidStoredValue();
541 const auto* text = reinterpret_cast<const char*>(sqlite3_column_text(statement.get(), 1));
542 if (text == nullptr)
543 return invalidStoredValue();
544 output.assign(text, sqlite3_column_bytes(statement.get(), 1));
545 }
546 else if constexpr (std::is_same_v<T, std::int64_t>)
547 {
548 if (sqlite3_column_type(statement.get(), 1) != SQLITE_INTEGER)
549 return invalidStoredValue();
550 output = sqlite3_column_int64(statement.get(), 1);
551 }
552 else if constexpr (std::is_same_v<T, double>)
553 {
554 if (sqlite3_column_type(statement.get(), 1) != SQLITE_FLOAT ||
555 !std::isfinite(sqlite3_column_double(statement.get(), 1)))
556 return invalidStoredValue();
557 output = sqlite3_column_double(statement.get(), 1);
558 }
559 else if constexpr (std::is_same_v<T, bool>)
560 {
561 if (sqlite3_column_type(statement.get(), 1) != SQLITE_INTEGER)
562 return invalidStoredValue();
563 const auto number = sqlite3_column_int64(statement.get(), 1);
564 if (number != 0 && number != 1)
565 return invalidStoredValue();
566 output = number != 0;
567 }
568 else
569 {
570 if (sqlite3_column_type(statement.get(), 1) != SQLITE_BLOB)
571 return invalidStoredValue();
572 const int size = sqlite3_column_bytes(statement.get(), 1);
573 const auto* bytes = static_cast<const std::uint8_t*>(sqlite3_column_blob(statement.get(), 1));
574 if (size > 0 && bytes == nullptr)
575 return invalidStoredValue();
576 if (size == 0)
577 output.clear();
578 else
579 output.assign(bytes, bytes + size);
580 }
581 return fray::errors::NONE;
582 }
583
589 {
590 fray::log::engineError("Failed to load state: invalid stored value.");
591 return fray::errors::FAILED_LOAD_STATE;
592 }
593
594 public:
598 StateManager() = default;
603 const StateManager&) = delete;
608 const StateManager&) = delete;
609
615 {
616 if (_db != nullptr)
617 {
618 const int result = sqlite3_close_v2(_db);
619 if (result != SQLITE_OK)
620 fray::log::engineError("Failed to close store: %s", sqlite3_errstr(result));
621 }
623 }
624
636 const std::string& table = "Fray",
637 const std::string& applicationId = "",
638 bool requireExistingTable = false)
639 {
640 std::lock_guard<std::recursive_mutex> lock(_mutex);
641 if (!files.isOpen())
642 {
643 fray::log::engineError("Cannot open state: file manager is not open.");
644 return fray::errors::FAILED_OPEN_STORE;
645 }
646 if (_db != nullptr || table.empty() || table.find('\0') != std::string::npos)
647 {
648 fray::log::engineError("Cannot open store: invalid table or a database is already open.");
649 return fray::errors::FAILED_OPEN_STORE;
650 }
651 std::filesystem::path path;
652 if (files.filePath(files.databaseFileName(), path) != fray::errors::NONE)
653 return fray::errors::FAILED_OPEN_STORE;
654 std::error_code pathError;
655 const auto status = std::filesystem::symlink_status(path, pathError);
656 if ((pathError && pathError != std::errc::no_such_file_or_directory) ||
657 std::filesystem::is_symlink(status))
658 {
659 fray::log::engineError("Cannot open project database: invalid file path.");
660 return fray::errors::FAILED_OPEN_STORE;
661 }
662 const std::string filename = path.string();
663 const int flags = SQLITE_OPEN_READWRITE | (files.requiresExistingDatabase() ? 0 : SQLITE_OPEN_CREATE);
664 const int result = sqlite3_open_v2(filename.c_str(), &_db, flags, nullptr);
665 if (result != SQLITE_OK)
666 {
667 fray::log::engineError("Failed to open store: %s",
668 _db != nullptr ? sqlite3_errmsg(_db) : sqlite3_errstr(result));
670 return fray::errors::FAILED_OPEN_STORE;
671 }
672 if (sqlite3_exec(_db, "BEGIN IMMEDIATE", nullptr, nullptr, nullptr) != SQLITE_OK)
673 {
674 fray::log::engineError("Failed to begin store initialization: %s", sqlite3_errmsg(_db));
676 return fray::errors::FAILED_OPEN_STORE;
677 }
678 const std::string requestedTable = tableName(table);
679 bool exists = false;
680 if ((requireExistingTable &&
681 (!tableExists(requestedTable.c_str(), exists) || !exists ||
682 !hasExpectedColumns(requestedTable.c_str(), {"key", "type", "value"}))) ||
683 (!requireExistingTable && !createTable(requestedTable)))
684 {
685 if (requireExistingTable && !exists)
686 fray::log::engineError("Cannot open store: required state table does not exist.");
687 rollback();
689 return fray::errors::FAILED_OPEN_STORE;
690 }
691 if (sqlite3_exec(_db, "COMMIT", nullptr, nullptr, nullptr) != SQLITE_OK)
692 {
693 fray::log::engineError("Failed to commit store initialization: %s", sqlite3_errmsg(_db));
694 rollback();
696 return fray::errors::FAILED_OPEN_STORE;
697 }
698 _table = requestedTable;
699 _files = &files;
700 _filesLifetime = files.lifetime();
701 _projectName = files.projectName();
703 files.attach();
704 return fray::errors::NONE;
705 }
706
711 const std::string& projectName() const { return _projectName; }
716 const std::string& applicationId() const { return _applicationId; }
722 bool isOpen() const
723 {
724 std::lock_guard<std::recursive_mutex> lock(_mutex);
725 return _db != nullptr;
726 }
727
734 template<typename Function>
736 Function&& function)
737 {
738 std::lock_guard<std::recursive_mutex> lock(_mutex);
739 if (_db == nullptr)
740 {
741 fray::log::engineError("Cannot use the database: store is not open.");
742 return fray::errors::FAILED_HISTORY;
743 }
744 return function(_db);
745 }
746
750 std::recursive_mutex& mutex() { return _mutex; }
751
758 {
759 std::lock_guard<std::recursive_mutex> lock(_mutex);
760 if (_db == nullptr)
761 {
762 fray::log::engineError("Cannot close store: no database is open.");
763 return fray::errors::FAILED_CLOSE_STORE;
764 }
765 const int result = sqlite3_close_v2(_db);
766 if (result != SQLITE_OK)
767 {
768 fray::log::engineError("Failed to close store: %s", sqlite3_errstr(result));
769 return fray::errors::FAILED_CLOSE_STORE;
770 }
771 _db = nullptr;
772 _table.clear();
774 return fray::errors::NONE;
775 }
776
785 const std::string& key,
786 const std::string& value) { return write(key, Value(value)); }
787
795 const std::string& key,
796 const F_char* value)
797 {
798 if (value == nullptr)
799 {
800 fray::log::engineError("Cannot save state: string value is null.");
801 return fray::errors::FAILED_SAVE_STATE;
802 }
803 return set(key, std::string(value));
804 }
805
813 const std::string& key,
814 double value) { return write(key, Value(value)); }
815
823 const std::string& key,
824 bool value) { return write(key, Value(value)); }
825
833 const std::string& key,
834 const Binary& value) { return write(key, Value(value)); }
835
843 template<typename T, std::enable_if_t<std::is_integral_v<T> && !std::is_same_v<T, bool>, int> = 0>
845 const std::string& key,
846 T value)
847 {
848 if constexpr (std::is_unsigned_v<T>)
849 {
850 if (static_cast<std::uintmax_t>(value) >
851 static_cast<std::uintmax_t>(std::numeric_limits<std::int64_t>::max()))
852 {
853 fray::log::engineError("Cannot save state: integer is out of range.");
854 return fray::errors::STATE_VALUE_OUT_OF_RANGE;
855 }
856 }
857 return write(key, Value(static_cast<std::int64_t>(value)));
858 }
859
868 const std::string& key,
869 std::string& value) { return read(key, value, 1); }
870
878 const std::string& key,
879 double& value) { return read(key, value, 3); }
880
888 const std::string& key,
889 bool& value) { return read(key, value, 4); }
890
898 const std::string& key,
899 Binary& value) { return read(key, value, 5); }
900
909 const std::string& key,
910 F_bool& exists)
911 {
912 std::lock_guard<std::recursive_mutex> lock(_mutex);
913 if (_db == nullptr)
914 {
915 fray::log::engineError("Cannot inspect state: store is not open.");
916 return fray::errors::FAILED_LOAD_STATE;
917 }
918 if (!projectAvailable())
919 return fray::errors::FAILED_LOAD_STATE;
920 if (!validKey(key))
921 return fray::errors::INVALID_STATE_KEY;
922 sqlite3_stmt* raw = nullptr;
923 const std::string sql = "SELECT 1 FROM " + _table + " WHERE key = ?";
924 const int prepared = sqlite3_prepare_v2(_db, sql.c_str(), -1, &raw, nullptr);
925 Statement statement(raw, sqlite3_finalize);
926 if (prepared != SQLITE_OK)
927 return statementFailure(statement, "inspect", fray::errors::FAILED_LOAD_STATE);
928 if (sqlite3_bind_text64(statement.get(), 1, key.data(), key.size(), SQLITE_TRANSIENT, SQLITE_UTF8) != SQLITE_OK)
929 {
930 fray::log::engineError("Failed to inspect state: %s", sqlite3_errmsg(_db));
931 return fray::errors::FAILED_LOAD_STATE;
932 }
933 const int result = sqlite3_step(statement.get());
934 if (result != SQLITE_ROW && result != SQLITE_DONE)
935 return statementFailure(statement, "inspect", fray::errors::FAILED_LOAD_STATE);
936 exists = result == SQLITE_ROW;
937 return fray::errors::NONE;
938 }
939
948 const std::string& key,
949 float& value)
950 {
951 double stored;
952 const F_err result = read(key, stored, 3);
953 if (result != fray::errors::NONE)
954 return result;
955 if (std::abs(stored) > std::numeric_limits<float>::max() ||
956 (stored != 0 && std::abs(stored) < std::numeric_limits<float>::denorm_min()))
957 {
958 fray::log::engineError("Cannot load state: floating-point value is out of range.");
959 return fray::errors::STATE_VALUE_OUT_OF_RANGE;
960 }
961 value = static_cast<float>(stored);
962 return fray::errors::NONE;
963 }
964
972 template<typename T, std::enable_if_t<std::is_integral_v<T> && !std::is_same_v<T, bool>, int> = 0>
974 const std::string& key,
975 T& value)
976 {
977 std::int64_t stored;
978 const F_err result = read(key, stored, 2);
979 if (result != fray::errors::NONE)
980 return result;
981 F_bool inRange = true;
982 if constexpr (std::is_signed_v<T>)
983 {
984 if constexpr (std::numeric_limits<T>::digits < std::numeric_limits<std::int64_t>::digits)
985 inRange = stored >= static_cast<std::int64_t>(std::numeric_limits<T>::min()) &&
986 stored <= static_cast<std::int64_t>(std::numeric_limits<T>::max());
987 }
988 else
989 inRange = stored >= 0 &&
990 static_cast<std::uint64_t>(stored) <= std::numeric_limits<T>::max();
991 if (!inRange)
992 {
993 fray::log::engineError("Cannot load state: integer is out of range.");
994 return fray::errors::STATE_VALUE_OUT_OF_RANGE;
995 }
996 value = static_cast<T>(stored);
997 return fray::errors::NONE;
998 }
999
1007 const std::string& key)
1008 {
1009 std::lock_guard<std::recursive_mutex> lock(_mutex);
1010 if (_db == nullptr)
1011 {
1012 fray::log::engineError("Cannot remove state: store is not open.");
1013 return fray::errors::FAILED_REMOVE_STATE;
1014 }
1015 if (!projectAvailable())
1016 return fray::errors::FAILED_REMOVE_STATE;
1017 if (!validKey(key))
1018 return fray::errors::INVALID_STATE_KEY;
1019 sqlite3_stmt* raw = nullptr;
1020 const std::string sql = "DELETE FROM " + _table + " WHERE key = ?";
1021 const int prepared = sqlite3_prepare_v2(_db, sql.c_str(), -1, &raw, nullptr);
1022 Statement statement(raw, sqlite3_finalize);
1023 if (prepared != SQLITE_OK)
1024 {
1025 return statementFailure(statement, "remove", fray::errors::FAILED_REMOVE_STATE);
1026 }
1027 if (sqlite3_bind_text64(statement.get(), 1, key.data(), key.size(), SQLITE_TRANSIENT, SQLITE_UTF8) != SQLITE_OK)
1028 {
1029 fray::log::engineError("Failed to remove state: %s", sqlite3_errmsg(_db));
1030 return fray::errors::FAILED_REMOVE_STATE;
1031 }
1032 if (sqlite3_step(statement.get()) != SQLITE_DONE)
1033 {
1034 return statementFailure(statement, "remove", fray::errors::FAILED_REMOVE_STATE);
1035 }
1036 if (sqlite3_changes(_db) == 0)
1037 {
1038 fray::log::engineError("State key not found: %s", key.c_str());
1039 return fray::errors::STATE_NOT_FOUND;
1040 }
1041 statement.reset();
1042 return fray::errors::NONE;
1043 }
1044
1051 {
1052 std::lock_guard<std::recursive_mutex> lock(_mutex);
1053 if (_db == nullptr)
1054 {
1055 fray::log::engineError("Cannot remove state table: store is not open.");
1056 return fray::errors::FAILED_REMOVE_STATE;
1057 }
1058 if (!projectAvailable())
1059 return fray::errors::FAILED_REMOVE_STATE;
1060 F_bool exists;
1061 if (!tableExists(_table.c_str(), exists))
1062 return fray::errors::FAILED_REMOVE_STATE;
1063 if (!exists)
1064 {
1065 fray::log::engineError("State table not found.");
1066 return fray::errors::STATE_NOT_FOUND;
1067 }
1068 const std::string sql = "DROP TABLE " + _table;
1069 if (sqlite3_exec(_db, sql.c_str(), nullptr, nullptr, nullptr) != SQLITE_OK)
1070 {
1071 fray::log::engineError("Failed to remove state table: %s", sqlite3_errmsg(_db));
1072 return fray::errors::FAILED_REMOVE_STATE;
1073 }
1074 return fray::errors::NONE;
1075 }
1076
1084 const std::string& name)
1085 {
1086 std::lock_guard<std::recursive_mutex> lock(_mutex);
1087 if (_db == nullptr || name.empty() || name.find('\0') != std::string::npos)
1088 {
1089 fray::log::engineError("Cannot rename state table: store is not open or name is invalid.");
1090 return fray::errors::FAILED_RENAME_STATE_TABLE;
1091 }
1092 if (!projectAvailable())
1093 return fray::errors::FAILED_RENAME_STATE_TABLE;
1094 F_bool exists;
1095 if (!tableExists(_table.c_str(), exists))
1096 return fray::errors::FAILED_RENAME_STATE_TABLE;
1097 if (!exists)
1098 {
1099 fray::log::engineError("State table not found.");
1100 return fray::errors::STATE_NOT_FOUND;
1101 }
1102 const std::string renamed = tableName(name);
1103 if (renamed == _table)
1104 return fray::errors::NONE;
1105 if (!tableExists(renamed.c_str(), exists))
1106 return fray::errors::FAILED_RENAME_STATE_TABLE;
1107 if (exists)
1108 {
1109 fray::log::engineError("Cannot rename state table: destination already exists.");
1110 return fray::errors::FAILED_RENAME_STATE_TABLE;
1111 }
1112 const std::string sql = "ALTER TABLE " + _table + " RENAME TO " + renamed;
1113 if (sqlite3_exec(_db, sql.c_str(), nullptr, nullptr, nullptr) != SQLITE_OK)
1114 {
1115 fray::log::engineError("Failed to rename state table: %s", sqlite3_errmsg(_db));
1116 return fray::errors::FAILED_RENAME_STATE_TABLE;
1117 }
1118 _table = renamed;
1119 return fray::errors::NONE;
1120 }
1121 };
1122 }
1123}
1124
1125#endif
Owns one working directory, its database name and a nonblocking file lock. Project workspaces additio...
F_err write(const std::string &key, const Value &value, F_bool retry=true)
Insert or replace a typed value in the state table. Locks _mutex, may recreate a missing table once,...
bool isOpen() const
Check whether a database connection is open. Locks _mutex.
std::unique_ptr< sqlite3_stmt, decltype(&sqlite3_finalize)> Statement
SQLite statement owner that finalizes its statement on destruction.
StateManager(const StateManager &)=delete
Disallow copying the owned connection.
F_err set(const std::string &key, const std::string &value)
Save a string state value. The underlying write locks _mutex and logs successful writes.
F_err open(fray::files::FileManager &files, const std::string &table="Fray", const std::string &applicationId="", bool requireExistingTable=false)
Open and initialize a SQLite state table in the file manager's directory. Locks _mutex,...
F_bool tableExists(const F_char *name, F_bool &exists)
Inspect whether an SQLite table exists, rejecting a matching view. Requires an open database and _mut...
static std::string escaped(const std::string &text)
Escape bytes for diagnostic log output.
F_err removeTable()
Drop the current state table without closing the store. Locks _mutex; a later write can recreate the ...
F_err remove(const std::string &key)
Remove a state key. Locks _mutex.
F_err renameTable(const std::string &name)
Rename the current state table to an encoded logical name. Locks _mutex and updates the active table ...
std::recursive_mutex & mutex()
Return the store mutex, held by the owner across close and reopen during file rename.
F_bool projectAvailable()
Check that the borrowed file manager still exists. Logs on failure; callers accessing store state mus...
std::weak_ptr< int > _filesLifetime
Weak lifetime token guarding access to the borrowed file manager.
F_err get(const std::string &key, T &value)
Read an integer state value into a checked destination type. The underlying read locks _mutex; value ...
std::string _table
Encoded name of the active state table.
F_void rollback()
Roll back the current SQLite transaction and log any failure. Requires an open database and _mutex he...
F_err close()
Close the database and detach the project. Locks _mutex; logs errors.
F_err invalidStoredValue()
Log an invalid stored value.
~StateManager()
Close the connection and detach from the file manager if still alive. The owner must stop concurrent ...
static std::string tableName(const std::string &name)
Encode a logical table name as a safe SQLite identifier.
F_err set(const std::string &key, bool value)
Save a boolean state value. The underlying write locks _mutex and logs successful writes.
F_err set(const std::string &key, const F_char *value)
Save a NUL-terminated string; null is rejected state value. The underlying write locks _mutex and log...
F_err get(const std::string &key, double &value)
Read a double state value. The underlying read locks _mutex; value is unchanged on failure.
static F_void logSet(const std::string &key, const Value &value)
Log a successfully saved key and its formatted value.
F_err get(const std::string &key, std::string &value)
Read a string state value. The underlying read locks _mutex; value is unchanged on failure.
F_err set(const std::string &key, const Binary &value)
Save a binary blob state value. The underlying write locks _mutex and logs successful writes.
F_void releaseProject()
Detach the live file manager and clear the associated project metadata. Call while holding _mutex,...
const std::string & projectName() const
Return the project name captured at open; its contents change on open or close. Does not acquire _mut...
std::recursive_mutex _mutex
Serializes database and mutable store operations; recursive for nested calls.
sqlite3 * _db
Owned SQLite connection, or null when closed.
std::vector< std::uint8_t > Binary
Byte sequence stored as a SQLite blob.
fray::files::FileManager * _files
Borrowed attached project file manager, valid only while its lifetime token is alive.
std::variant< std::string, std::int64_t, double, bool, Binary > Value
Supported state value; variant order defines persistent type tags and must remain stable.
std::string _applicationId
Application identifier captured when the store opened.
std::string _projectName
Project name captured when the store opened.
F_err read(const std::string &key, T &output, int expectedType)
Read and validate a typed state value. Locks _mutex; output is changed only on a successful read.
F_err get(const std::string &key, Binary &value)
Read a binary blob state value. The underlying read locks _mutex; value is unchanged on failure.
StateManager()=default
Construct a closed state manager.
F_err get(const std::string &key, float &value)
Read a float state value. The underlying read locks _mutex; value is unchanged on failure.
F_bool validKey(const std::string &key) const
Validate a state key and log invalid input.
F_err set(const std::string &key, double value)
Save a finite double state value. The underlying write locks _mutex and logs successful writes.
F_err contains(const std::string &key, F_bool &exists)
Check whether a state key exists. Locks _mutex.
F_err withDatabase(Function &&function)
Run a callback against the open database for supporting tables. Holds _mutex throughout the callback ...
F_err set(const std::string &key, T value)
Save an integral value as signed 64-bit state. The underlying write locks _mutex and logs successful ...
F_void closeAfterOpenFailure()
Close the SQLite connection after initialization fails. Requires _mutex held; logs a close failure.
F_bool createTable(const std::string &name)
Create a typed state table or validate an existing table's columns. Requires an open database and _mu...
F_err get(const std::string &key, bool &value)
Read a boolean state value. The underlying read locks _mutex; value is unchanged on failure.
const std::string & applicationId() const
Return the application identifier captured at open; its contents change on open or close....
StateManager & operator=(const StateManager &)=delete
Disallow copy assignment of the owned connection.
F_bool hasExpectedColumns(const F_char *table, std::initializer_list< const F_char * > expected)
Check that a table has exactly the named columns. Requires an open database and _mutex held; column t...
F_err statementFailure(Statement &statement, const F_char *operation, F_err failure)
Classify and log a failed state statement after finalizing it. Requires an open database and _mutex h...
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 engineInfo(const F_char *fmt,...)
Log info for Engine.
F_void engineError(const F_char *fmt,...)
Log error for Engine.
void F_void
Alias for void.
Definition types.hpp:20
bool F_bool
Alias for bool.
Definition types.hpp:22
char F_char
Alias for char.
Definition types.hpp:24