3#ifndef _FRAY_LOG_STORE_HPP_
4#define _FRAY_LOG_STORE_HPP_
142 sqlite3*
db =
nullptr;
153 std::lock_guard<std::mutex> lock(
mutex);
156 const int result = sqlite3_close(
db);
157 if (result != SQLITE_OK)
159 std::fprintf(stderr,
"Cannot close log database: %s\n", sqlite3_errmsg(
db));
203 std::map<std::string, std::vector<Entry>>
_opening;
211 std::shared_ptr<Database>
_app;
215 std::atomic<std::uint64_t>
_last{0};
223 using namespace std::chrono;
224 return static_cast<std::uint64_t
>(
225 duration_cast<microseconds>(system_clock::now().time_since_epoch()).count());
234 std::uint64_t observedUs = 0)
236 auto previous =
_last.load(std::memory_order_relaxed);
237 const auto observed = observedUs ? observedUs :
nowUs();
240 const auto next = std::max(previous + 1, observed);
241 if (
_last.compare_exchange_weak(previous, next, std::memory_order_relaxed))
253 const std::filesystem::path& file)
255 auto database = std::make_shared<Database>();
256 database->path = file;
257 if (sqlite3_open(file.string().c_str(), &database->db) != SQLITE_OK)
261 sqlite3_file_control(database->db,
"main", SQLITE_FCNTL_PERSIST_WAL, &
persist);
262 sqlite3_exec(database->db,
"PRAGMA journal_mode=WAL;PRAGMA synchronous=NORMAL;",
nullptr,
nullptr,
nullptr);
264 "CREATE TABLE IF NOT EXISTS log("
265 "arrived_us INTEGER PRIMARY KEY, uid TEXT NOT NULL UNIQUE, process INTEGER NOT NULL, level TEXT NOT NULL,"
266 "thread INTEGER NOT NULL, project TEXT NOT NULL, text TEXT NOT NULL,"
267 "kind INTEGER NOT NULL DEFAULT 0, destination INTEGER NOT NULL DEFAULT 0,"
268 "operation INTEGER NOT NULL DEFAULT 0, ref_uid TEXT NOT NULL DEFAULT '',"
269 "console_visible INTEGER NOT NULL DEFAULT 1);";
270 if (sqlite3_exec(database->db, schema,
nullptr,
nullptr,
nullptr) != SQLITE_OK)
272 bool hasVisibility =
false;
275 if (!hasVisibility && sqlite3_exec(database->db,
276 "ALTER TABLE log ADD COLUMN console_visible INTEGER NOT NULL DEFAULT 1;",
277 nullptr,
nullptr,
nullptr) != SQLITE_OK)
292 sqlite3_stmt* statement =
nullptr;
293 if (sqlite3_prepare_v2(db,
294 "SELECT 1 FROM pragma_table_info('log') WHERE name='console_visible';",
295 -1, &statement,
nullptr) != SQLITE_OK)
297 std::fprintf(stderr,
"Cannot inspect log schema: %s\n", sqlite3_errmsg(db));
300 const int result = sqlite3_step(statement);
301 present = result == SQLITE_ROW;
302 if (result != SQLITE_ROW && result != SQLITE_DONE)
303 std::fprintf(stderr,
"Cannot inspect log schema: %s\n", sqlite3_errmsg(db));
304 sqlite3_finalize(statement);
305 return result == SQLITE_ROW || result == SQLITE_DONE;
315 const std::filesystem::path& folder,
318 std::error_code error;
319 std::filesystem::create_directories(folder, error);
322 return openFile(folder / (
"session-" + std::to_string(stamp) +
".sqlite"));
335 std::lock_guard<std::mutex> lock(database.
mutex);
338 std::fprintf(stderr,
"Cannot write log entry: session is closed.\n");
341 sqlite3_stmt* statement =
nullptr;
342 if (sqlite3_prepare_v2(database.
db,
343 "INSERT INTO log(arrived_us,uid,process,level,thread,project,text,kind,destination,operation,ref_uid,console_visible) "
344 "VALUES(?,?,?,?,?,?,?,?,?,?,?,?);",
345 -1, &statement,
nullptr) != SQLITE_OK)
347 std::fprintf(stderr,
"Cannot prepare log entry: %s\n", sqlite3_errmsg(database.
db));
350 sqlite3_bind_int64(statement, 1,
static_cast<sqlite3_int64
>(entry.
arrivedUs));
351 sqlite3_bind_text(statement, 2, entry.
uid.c_str(), -1, SQLITE_TRANSIENT);
352 sqlite3_bind_int(statement, 3, entry.
process);
353 sqlite3_bind_text(statement, 4, entry.
level.c_str(), -1, SQLITE_TRANSIENT);
354 sqlite3_bind_int64(statement, 5, entry.
thread);
355 sqlite3_bind_text(statement, 6, entry.
project.c_str(), -1, SQLITE_TRANSIENT);
356 sqlite3_bind_text(statement, 7, entry.
text.c_str(), -1, SQLITE_TRANSIENT);
357 sqlite3_bind_int(statement, 8, entry.
kind);
359 sqlite3_bind_int64(statement, 10,
static_cast<sqlite3_int64
>(entry.
operation));
360 sqlite3_bind_text(statement, 11, entry.
refUid.c_str(), -1, SQLITE_TRANSIENT);
362 if (sqlite3_step(statement) != SQLITE_DONE)
363 std::fprintf(stderr,
"Cannot write log entry: %s\n", sqlite3_errmsg(database.
db));
364 sqlite3_finalize(statement);
373 const std::string& text)
376 for (
const char c : text)
378 if (c ==
'\\' || c ==
'%' || c ==
'_')
397 std::vector<Entry>& out)
399 bool hasVisibility =
false;
402 std::string sql =
"SELECT arrived_us,uid,process,level,thread,project,text,kind,destination,operation,ref_uid,";
403 sql += hasVisibility ?
"console_visible" :
"1";
404 sql +=
" FROM log WHERE 1=1";
406 sql +=
" AND console_visible = 1";
408 sql +=
" AND arrived_us < ?";
411 sql +=
" AND process IN (";
412 for (std::size_t i = 0; i < query.
processes.size(); ++i)
413 sql += i ?
",?" :
"?";
416 if (!query.
levels.empty())
418 sql +=
" AND level IN (";
419 for (std::size_t i = 0; i < query.
levels.size(); ++i)
420 sql += i ?
",?" :
"?";
424 sql +=
" AND project = ?";
426 sql +=
" AND text LIKE ? ESCAPE '\\'";
427 sql +=
" ORDER BY arrived_us DESC LIMIT ?;";
429 sqlite3_stmt* statement =
nullptr;
430 if (sqlite3_prepare_v2(db, sql.c_str(), -1, &statement,
nullptr) != SQLITE_OK)
432 std::fprintf(stderr,
"Cannot read log entries: %s\n", sqlite3_errmsg(db));
437 sqlite3_bind_int64(statement, index++,
static_cast<sqlite3_int64
>(query.
beforeUs));
439 sqlite3_bind_int(statement, index++,
process);
440 for (
const auto& level : query.
levels)
441 sqlite3_bind_text(statement, index++, level.c_str(), -1, SQLITE_TRANSIENT);
443 sqlite3_bind_text(statement, index++, query.
project.c_str(), -1, SQLITE_TRANSIENT);
447 sqlite3_bind_text(statement, index++, pattern.c_str(), -1, SQLITE_TRANSIENT);
449 sqlite3_bind_int64(statement, index,
static_cast<sqlite3_int64
>(count));
451 while ((result = sqlite3_step(statement)) == SQLITE_ROW)
454 entry.
arrivedUs =
static_cast<std::uint64_t
>(sqlite3_column_int64(statement, 0));
455 entry.
uid =
reinterpret_cast<const char*
>(sqlite3_column_text(statement, 1));
456 entry.
process = sqlite3_column_int(statement, 2);
457 entry.
level =
reinterpret_cast<const char*
>(sqlite3_column_text(statement, 3));
458 entry.
thread =
static_cast<std::uint32_t
>(sqlite3_column_int64(statement, 4));
459 entry.
project =
reinterpret_cast<const char*
>(sqlite3_column_text(statement, 5));
460 entry.
text =
reinterpret_cast<const char*
>(sqlite3_column_text(statement, 6));
461 entry.
kind = sqlite3_column_int(statement, 7);
462 entry.
destination = sqlite3_column_int(statement, 8);
463 entry.
operation =
static_cast<std::uint64_t
>(sqlite3_column_int64(statement, 9));
464 entry.
refUid =
reinterpret_cast<const char*
>(sqlite3_column_text(statement, 10));
466 out.push_back(std::move(entry));
468 if (result != SQLITE_DONE)
469 std::fprintf(stderr,
"Cannot read log entries: %s\n", sqlite3_errmsg(db));
470 sqlite3_finalize(statement);
485 std::vector<Entry>& out)
487 std::error_code error;
488 for (std::filesystem::directory_iterator it(folder.
path, error), end; !error && it != end; it.increment(error))
490 const auto& path = it->path();
491 const auto name = path.filename().string();
492 if (name.rfind(
"session-", 0) != 0 || path.extension() !=
".sqlite")
494 std::shared_ptr<Database> live = folder.
session;
497 std::lock_guard<std::mutex> lock(live->mutex);
498 if (live->db && sqlite3_db_filename(live->db,
"main") &&
499 std::filesystem::path(sqlite3_db_filename(live->db,
"main")).filename() == path.filename())
501 select(live->db, query, count, out);
507 std::error_code walError;
508 const auto walSize = std::filesystem::file_size(path.string() +
"-wal", walError);
509 if (!walError && walSize > 0)
512 if (sqlite3_open_v2(path.string().c_str(), &recovered.
db, SQLITE_OPEN_READWRITE,
nullptr) == SQLITE_OK)
513 select(recovered.
db, query, count, out);
517 std::string uri =
"file:";
518 for (
const unsigned char c : path.string())
520 static const char* hex =
"0123456789ABCDEF";
521 if (std::isalnum(c) || c ==
'/' || c ==
'-' || c ==
'_' || c ==
'.')
522 uri.push_back(
static_cast<char>(c));
526 uri.push_back(hex[c >> 4]);
527 uri.push_back(hex[c & 15]);
530 uri +=
"?immutable=1";
532 if (sqlite3_open_v2(uri.c_str(), &closed.
db, SQLITE_OPEN_READONLY | SQLITE_OPEN_URI,
nullptr) == SQLITE_OK)
533 select(closed.
db, query, count, out);
544 const std::filesystem::path& folder)
546 std::lock_guard<std::mutex> lock(
_mutex);
557 const std::string& project)
559 return project.rfind(
"opening:", 0) == 0;
567 const std::string& openingTag)
569 std::lock_guard<std::mutex> lock(
_mutex);
581 const std::string&
id,
582 const std::filesystem::path& workingFolder,
583 const std::string& openingTag = std::string())
586 folder.
path = workingFolder /
"logs";
589 std::fprintf(stderr,
"Cannot open project log session in %s; using application log.\n",
590 folder.
path.string().c_str());
591 std::vector<Entry> buffered;
593 std::lock_guard<std::mutex> lock(
_mutex);
594 const auto held =
_opening.find(openingTag);
597 buffered = std::move(held->second);
601 if (!openingTag.empty())
604 for (
auto& entry : buffered)
620 const std::string& openingTag)
623 std::vector<Entry> buffered;
625 std::lock_guard<std::mutex> lock(
_mutex);
627 const auto held =
_opening.find(openingTag);
630 buffered = std::move(held->second);
633 for (
auto& entry : buffered)
635 entry.project.clear();
647 const std::string&
id)
649 std::shared_ptr<Database> session;
651 std::lock_guard<std::mutex> lock(
_mutex);
654 session = found->second.session;
656 return !session || session->close();
667 const std::string&
id,
668 const std::filesystem::path& workingFolder)
670 std::shared_ptr<Database> session;
672 std::lock_guard<std::mutex> lock(
_mutex);
674 if (found ==
_projects.end() || !found->second.session)
676 session = found->second.session;
678 if (!session->close())
680 const auto folder = workingFolder /
"logs";
681 const auto file = folder / session->path.filename();
686 std::fprintf(stderr,
"Cannot reopen project log session in %s.\n", folder.string().c_str());
687 const bool success =
static_cast<bool>(reopened);
688 std::lock_guard<std::mutex> lock(
_mutex);
690 if (found !=
_projects.end() && found->second.session == session)
692 found->second.path = folder;
693 found->second.session = std::move(reopened);
705 const std::string&
id)
709 std::lock_guard<std::mutex> lock(
_mutex);
713 folder = std::move(found->second);
718 std::lock_guard<std::mutex> lock(
_mutex);
719 _projects.emplace(
id, std::move(folder));
734 if (entry.
uid.empty())
740 catch (
const std::runtime_error& error)
742 std::fprintf(stderr,
"Cannot identify log entry: %s\n", error.what());
745 catch (
const std::bad_alloc& error)
747 std::fprintf(stderr,
"Cannot identify log entry: %s\n", error.what());
753 std::fprintf(stderr,
"Cannot identify log entry: invalid UID.\n");
766 const Entry& original)
768 Entry entry = original;
769 std::shared_ptr<Database> database;
771 std::lock_guard<std::mutex> lock(
_mutex);
776 entry.
project = resolved->second;
784 if (!entry.
project.empty() && project !=
_projects.end() && project->second.session)
785 database = project->second.session;
792 std::fprintf(stderr,
"Cannot open application log session in %s.\n",
_appFolder.string().c_str());
804 const Entry& original)
806 Entry entry = original;
807 std::shared_ptr<Database> database;
809 std::lock_guard<std::mutex> lock(
_mutex);
814 entry.
project = resolved->second;
820 std::fprintf(stderr,
"Cannot open application log session in %s.\n",
_appFolder.string().c_str());
834 auto prepared =
prepare(std::move(entry));
849 const std::size_t limit = std::max<std::uint32_t>(query.
limit, 1);
850 std::vector<Entry> found;
851 std::vector<Folder> folders;
853 std::lock_guard<std::mutex> lock(
_mutex);
857 folders.push_back(project.second);
859 for (
const auto& folder : folders)
861 std::sort(found.begin(), found.end(),
862 [](
const Entry& a,
const Entry& b) { return a.arrivedUs > b.arrivedUs; });
864 result.
exhausted = found.size() <= limit;
865 if (found.size() > limit)
867 std::reverse(found.begin(), found.end());
868 result.
entries = std::move(found);
Persist and query application and project logs across session SQLite files. Project logs use their wo...
std::map< std::string, Folder > _projects
Currently open project folders indexed by project id.
void setApplicationFolder(const std::filesystem::path &folder)
Set the destination folder for application and fallback entries. Locks _mutex and closes the current ...
static std::shared_ptr< Database > create(const std::filesystem::path &folder, std::uint64_t stamp)
Create a session database in a log folder.
std::optional< Entry > write(Entry entry)
Identify, stamp, and persist an entry synchronously.
std::map< std::string, std::vector< Entry > > _opening
Lines buffered before a project opens, keyed by opening tag.
void beginOpening(const std::string &openingTag)
Starts a new opening tag, clearing any previous resolution of the same tag.
void persist(const Entry &original)
Persist an already stamped entry in its project, opening buffer, or application session....
std::atomic< std::uint64_t > _last
Last allocated arrival timestamp or session stamp.
void discardOpening(const std::string &openingTag)
Move a failed project opening's buffered lines into the application log. Clears the project tag and d...
bool suspendProject(const std::string &id)
Close a project's live session before its folder is renamed.
Page page(const Query &query)
Query the newest matching entries across the application and open projects. Takes a snapshot of regis...
std::uint64_t nextStamp(std::uint64_t observedUs=0)
Allocates a timestamp without waiting for SQLite or project operations.
static std::string escape(const std::string &text)
Escape SQLite LIKE wildcard and escape characters.
std::map< std::string, std::string > _resolvedOpening
Resolved opening tags; an empty ID sends late entries to the application log.
void persistApplication(const Entry &original)
Persist an entry only in the application session while retaining its project identity.
static std::shared_ptr< Database > openFile(const std::filesystem::path &file)
Open or create an SQLite log database and ensure its schema exists. Configures WAL and normal synchro...
void openProject(const std::string &id, const std::filesystem::path &workingFolder, const std::string &openingTag=std::string())
Open a new project log session and flush buffered opening lines. Creates <workingFolder>/logs and a s...
void selectFolder(const Folder &folder, const Query &query, std::size_t count, std::vector< Entry > &out)
Append matching entries from session files in a folder. Uses the live connection for its current file...
std::shared_ptr< Database > _app
Shared owner of the current application session connection.
bool moveProject(const std::string &id, const std::filesystem::path &workingFolder)
Reopen a project session after its working folder moves. Closes the old-path connection and reopens t...
std::mutex _mutex
Protects folder registrations, opening buffers, and session references.
static bool isOpeningTag(const std::string &project)
Check whether a project identifier is an opening tag.
static void insert(Database &database, const Entry &entry)
Insert an entry into an open session database. SQLite prepare or write failures are reported directly...
static std::uint64_t nowUs()
Read the system clock in Unix-epoch microseconds.
static void select(sqlite3 *db, const Query &query, std::size_t count, std::vector< Entry > &out)
Append the newest matching rows from one database, newest first. SQL preparation or stepping failures...
std::filesystem::path _appFolder
Application log session directory.
static bool hasConsoleVisibility(sqlite3 *db, bool &present)
Detects whether a session has the Console visibility column.
std::optional< Entry > prepare(Entry entry)
Identify and stamp an entry without accessing SQLite. UID generation failures and invalid supplied UI...
bool closeProject(const std::string &id)
Forget a project folder and release its session connection. Waits for in-flight operations on this co...
std::string hex(const Uid &uid)
Formats a routing UID as lowercase hexadecimal.
Uid generate()
Generates a random, globally unique identifier.
bool valid(const std::string &uid)
Validates the canonical text form of an assigned UID.
One log line from a process. This store instance assigns arrivedUs as an increasing microsecond times...
std::string project
Project identifier; empty denotes the application.
std::uint64_t operation
Command id of a command or receipt; zero for lines.
std::string text
Log message text.
std::uint64_t arrivedUs
Store-assigned arrival timestamp in microseconds since the Unix epoch.
int destination
Destination process of a command or receipt; zero for lines.
bool consoleVisible
Whether this entry may be delivered to the Console or loading window.
std::string level
Log severity label.
int process
Source process identifier.
int kind
What the row records: 0 line, 1 command, 2 receipt, 3 notification, 4 session start (LogEntryKind).
std::string refUid
For a receipt, the UID of the command it confirms; empty otherwise.
std::string uid
Globally unique lowercase hexadecimal entry identity.
std::uint32_t thread
Source thread identifier.
Own an SQLite connection and close it on destruction.
std::mutex mutex
Serializes use and explicit closure of this connection.
sqlite3 * db
Owned SQLite handle, or null before opening.
std::filesystem::path path
Path used when this connection was opened.
bool close()
Closes the connection after any in-flight use completes.
~Database()
Close the owned SQLite connection if present.
Associate a log folder with its live session database.
std::filesystem::path path
Directory containing session database files.
std::shared_ptr< Database > session
Shared owner of the current session connection, if available.
A page of matching log entries and its exhaustion status.
std::vector< Entry > entries
Matching entries ordered oldest first.
bool exhausted
True when no additional matching entries were found beyond this page.
Filters and cursor for a page of log entries.
std::string project
Project identifier to match when filterProject is true; empty selects application entries.
std::uint32_t limit
Maximum results requested; page enforces a minimum of one.
std::uint64_t beforeUs
Exclusive arrival cursor; zero selects the newest entries.
std::vector< std::string > levels
Allowed severity labels; empty disables this filter.
bool filterProject
Whether to filter by the exact project identifier.
std::string contains
Literal SQLite LIKE substring filter for message text; empty disables it.
bool consoleOnly
Exclude entries intended only for the persisted log.
std::vector< int > processes
Allowed process identifiers; empty disables this filter.