diff --git a/src/chat/chat_core.c b/src/chat/chat_core.c index b20ca1b44..78f63ac2f 100644 --- a/src/chat/chat_core.c +++ b/src/chat/chat_core.c @@ -84,11 +84,19 @@ void si_register(struct UTUN_INSTANCE* inst, struct DB_SYNC_INSTANCE* si, const int chat_core_init(struct UTUN_INSTANCE* inst, const char* db_path) { if (!inst || !db_path) { DEBUG_ERROR(DEBUG_CATEGORY_CHAT_SYNC, "%s: invalid args inst=%p db_path=%p", CC_ID, (void*)inst, (void*)db_path); return -1; } - if (inst->chat_core) return 0; + if (inst->chat_core) { + if (inst->chat_core->initialized) return 0; + DEBUG_ERROR(DEBUG_CATEGORY_CHAT_SYNC, "chat init: incomplete context already exists"); return -1; + } struct chat_core_ctx* cc = u_calloc(1, sizeof(*cc)); if (!cc) { DEBUG_ERROR(DEBUG_CATEGORY_CHAT_SYNC, "%s: OOM for chat_core_ctx", CC_ID); return -1; } + if (strlen(db_path) >= sizeof(cc->db_path)) { + DEBUG_ERROR(DEBUG_CATEGORY_CHAT_SYNC, "chat init: database path exceeds capacity=%zu", sizeof(cc->db_path)); u_free(cc); return -1; + } inst->chat_core = cc; - snprintf(cc->db_path, sizeof(cc->db_path), "%s", db_path); + memcpy(cc->db_path, db_path, strlen(db_path) + 1); cc->inst = inst; cc->my_node_id = inst->node_id; + const char* stage = "open DB"; int transaction = 0, subscribed = 0, rows = 0, columns = 0; + char** channels = NULL; if (inst->topo_sqlite_db) { cc->db = inst->topo_sqlite_db; cc->shared_db = 1; @@ -99,30 +107,27 @@ int chat_core_init(struct UTUN_INSTANCE* inst, const char* db_path) { if (rc != SQLITE_OK) { DEBUG_ERROR(DEBUG_CATEGORY_CHAT_SYNC, "%s: cannot open DB %s: %s", CC_ID, db_path, sqlite3_errmsg(cc->db)); - sqlite3_close(cc->db); inst->chat_core = NULL; u_free(cc); return -1; + goto fail; } - sqlite3_exec(cc->db, "PRAGMA journal_mode=WAL", NULL, NULL, NULL); - sqlite3_exec(cc->db, "PRAGMA foreign_keys=ON", NULL, NULL, NULL); + stage = "owned DB pragmas"; + if (db_exec(cc, "PRAGMA journal_mode=WAL") != SQLITE_OK || db_exec(cc, "PRAGMA foreign_keys=ON") != SQLITE_OK) goto fail; } - if (group_avatar_schema_init(cc->db) < 0) { - if (!cc->shared_db) sqlite3_close(cc->db); - inst->chat_core = NULL; u_free(cc); return -1; + stage = "transaction admission"; + if (!sqlite3_get_autocommit(cc->db)) { + DEBUG_ERROR(DEBUG_CATEGORY_CHAT_SYNC, "chat init: external transaction rejected"); goto fail; } - if (strlen(db_path) >= sizeof(cc->db_path) || media_index_init(cc->db)) { - DEBUG_ERROR(DEBUG_CATEGORY_MEDIA, "chat media schema/path initialization failed"); - if (!cc->shared_db) sqlite3_close(cc->db); - inst->chat_core = NULL; u_free(cc); return -1; - } - cc->inst = inst; - cc->my_node_id = inst->node_id; - - /* перенести chat-настройки из конфига (заполнены парсером) в per-instance состояние */ - if (inst->config) memcpy(&inst->chat_settings, &inst->config->global.chat_settings, sizeof(inst->chat_settings)); + stage = "begin"; + if (db_exec(cc, "BEGIN IMMEDIATE /* chat init */") != SQLITE_OK) goto fail; + transaction = 1; stage = "avatar schema"; + if (group_avatar_schema_init(cc->db) < 0) goto fail; + stage = "media schema"; if (media_index_init(cc->db)) goto fail; sqlite3_int64 now_sec = (sqlite3_int64)ntp_time_get_seconds(inst); + if (now_sec <= 0) { DEBUG_ERROR(DEBUG_CATEGORY_CHAT_SYNC, "chat init: invalid identity time=%lld", (long long)now_sec); goto fail; } /* Схема нужна до первой записи идентичности, в том числе для новой пустой БД. */ + stage = "chat schema"; if (db_exec(cc, "CREATE TABLE IF NOT EXISTS local_identity (" " id INTEGER PRIMARY KEY CHECK (id = 1)," @@ -151,6 +156,7 @@ int chat_core_init(struct UTUN_INSTANCE* inst, const char* db_path) { ) != SQLITE_OK) goto fail; /* Идентичность публикуется в GUI только после успешной записи узла и локального профиля. */ + stage = "local identity"; { const char* my_name = inst->name[0] ? inst->name : "Me"; if (topo_node_sqlite_node_update_verified(cc->db, cc->my_node_id, @@ -168,18 +174,15 @@ int chat_core_init(struct UTUN_INSTANCE* inst, const char* db_path) { if (rc == SQLITE_OK) rc = sqlite3_bind_int64(st, 5, now_sec); if (rc == SQLITE_OK) rc = sqlite3_bind_int64(st, 6, now_sec); if (rc == SQLITE_OK) rc = sqlite3_step(st); + if (rc == SQLITE_DONE && sqlite3_changes(cc->db) != 1) rc = SQLITE_CONSTRAINT; if (rc != SQLITE_DONE) DEBUG_ERROR(DEBUG_CATEGORY_CHAT_SYNC, "%s: local identity write rc=%d: %s", CC_ID, rc, sqlite3_errmsg(cc->db)); int final = sqlite3_finalize(st); if (final != SQLITE_OK) DEBUG_ERROR(DEBUG_CATEGORY_CHAT_SYNC, "%s: local identity finalize rc=%d: %s", CC_ID, final, sqlite3_errmsg(cc->db)); if (rc != SQLITE_DONE || final != SQLITE_OK) goto fail; - DEBUG_INFO(DEBUG_CATEGORY_CHAT_SYNC, "%s: local identity stored node=%016llx", CC_ID, (unsigned long long)cc->my_node_id); } - cc->initialized = 1; - /* register adm_tags change callback → CHAT_EVT_MEMBER_UPDATED */ - chat_member_init(inst); - /* store media_base for block_req handler */ + stage = "media base"; { char mbase[MEDIA_BASE_MAX]; const char* ls = strrchr(db_path, '/'); @@ -188,64 +191,41 @@ int chat_core_init(struct UTUN_INSTANCE* inst, const char* db_path) { sqlite3_stmt* stored = NULL; int rc = sqlite3_prepare_v2(cc->db, "SELECT value FROM ui_state WHERE key='media_base'", -1, &stored, NULL); if (rc == SQLITE_OK) rc = sqlite3_step(stored); - int base_error = rc == SQLITE_ROW ? media_index_get_base(cc->db, mbase) - : rc == SQLITE_DONE ? media_index_set_base(cc->db, mbase) : -1; int finish = stored ? sqlite3_finalize(stored) : SQLITE_OK; - if (base_error || finish != SQLITE_OK) { + if ((rc != SQLITE_ROW && rc != SQLITE_DONE) || finish != SQLITE_OK || + (rc == SQLITE_ROW ? media_index_get_base(cc->db, mbase) : media_index_set_base(cc->db, mbase))) { DEBUG_ERROR(DEBUG_CATEGORY_MEDIA, "chat media_base initialization failed rc=%d: %s", rc, sqlite3_errmsg(cc->db)); - chat_core_destroy(inst); return -1; + goto fail; } - DEBUG_INFO(DEBUG_CATEGORY_CHAT_SYNC, "%s: media_base=%s", CC_ID, mbase); + DEBUG_DEBUG(DEBUG_CATEGORY_CHAT_SYNC, "chat init: prepared media_base=%s", mbase); } - /* seed stub accounts if empty */ + /* Список отделён от SQLite до подготовки runtime и проверен до commit метаданных. */ + stage = "channel catalog"; { - sqlite3_stmt* cnt_st = NULL; - if (sqlite3_prepare_v2(cc->db, "SELECT COUNT(*) FROM accounts", - -1, &cnt_st, NULL) == SQLITE_OK) { - if (sqlite3_step(cnt_st) == SQLITE_ROW && sqlite3_column_int(cnt_st, 0) == 0) { - DEBUG_INFO(DEBUG_CATEGORY_CHAT_SYNC, "%s: seeding 5 stub accounts", CC_ID); - struct { int64_t id; const char* name; const char* letter; const char* color; } accs[] = { - {1, "Alice", "A", "#4A90E2"}, {2, "Bob", "B", "#7ED321"}, - {3, "Carol", "C", "#F5A623"}, {4, "Dave", "D", "#9013FE"}, - {5, "Eve", "E", "#00B894"}, - }; - for (int i = 0; i < 5; i++) { - sqlite3_stmt* ins = NULL; - sqlite3_prepare_v2(cc->db, - "INSERT OR IGNORE INTO accounts(node_id,display_name,avatar_color,avatar_letter,created_at)" - " VALUES(?,?,?,?,?)", -1, &ins, NULL); - if (ins) { - sqlite3_bind_int64(ins, 1, accs[i].id); - sqlite3_bind_text(ins, 2, accs[i].name, -1, SQLITE_STATIC); - sqlite3_bind_text(ins, 3, accs[i].color, -1, SQLITE_STATIC); - sqlite3_bind_text(ins, 4, accs[i].letter, -1, SQLITE_STATIC); - sqlite3_bind_int64(ins, 5, now_sec); - sqlite3_step(ins); sqlite3_finalize(ins); - } - } - } - sqlite3_finalize(cnt_st); - } - } - - /* Сначала закрываем чтение каналов: активный statement блокирует перестройку таблиц истории. */ - { - char** channels = NULL; - int rows = 0, columns = 0, loaded = 0; - int rc = sqlite3_get_table(cc->db, "SELECT channel_id FROM channels ORDER BY created_at ASC", + int rc = sqlite3_get_table(cc->db, "SELECT channel_id,length(CAST(channel_id AS BLOB)) FROM channels ORDER BY created_at ASC", &channels, &rows, &columns, NULL); - if (rc != SQLITE_OK) { - DEBUG_ERROR(DEBUG_CATEGORY_CHAT_SYNC, "%s: load channels: %s", CC_ID, sqlite3_errmsg(cc->db)); - sqlite3_free_table(channels); chat_core_destroy(inst); return -1; - } + if (rc != SQLITE_OK || (rows && columns != 2)) goto fail; for (int i = 0; i < rows; i++) { - const char* ch = channels[(i + 1) * columns]; - if (ch && ch[0]) { chat_core_ensure_channel_ready(inst, ch); loaded++; } + const char *ch = channels[(size_t)(i + 1) * columns], *bytes = channels[(size_t)(i + 1) * columns + 1]; + if (!chat_channel_id(ch) || !bytes || strlen(ch) != strtoul(bytes, NULL, 10)) { + DEBUG_ERROR(DEBUG_CATEGORY_CHAT_SYNC, "chat init: invalid stored channel row=%d", i); goto fail; + } } - sqlite3_free_table(channels); - DEBUG_INFO(DEBUG_CATEGORY_CHAT_SYNC, "%s: loaded %d channels from DB", CC_ID, loaded); } + stage = "member subscriptions"; if (chat_member_init(inst)) goto fail; + subscribed = 1; stage = "commit"; if (db_exec(cc, "COMMIT /* chat init */") != SQLITE_OK) goto fail; + transaction = 0; cc->initialized = 1; + if (inst->config) memcpy(&inst->chat_settings, &inst->config->global.chat_settings, sizeof(inst->chat_settings)); + DEBUG_INFO(DEBUG_CATEGORY_CHAT_SYNC, "chat init: metadata committed node=%016llx channels=%d", (unsigned long long)cc->my_node_id, rows); + stage = "channel activation"; + for (int i = 0; i < rows; i++) { + const char* ch = channels[(size_t)(i + 1) * columns]; + if (chat_core_ensure_channel_ready(inst, ch)) { + DEBUG_ERROR(DEBUG_CATEGORY_CHAT_SYNC, "chat init: committed channel activation failed ch=%s;service restart required", ch); goto fail; + } + } + sqlite3_free_table(channels); channels = NULL; DEBUG_INFO(DEBUG_CATEGORY_CHAT_SYNC, "%s: initialized, db=%s node_id=0x%016llx", CC_ID, db_path, (unsigned long long)cc->my_node_id); @@ -256,12 +236,23 @@ int chat_core_init(struct UTUN_INSTANCE* inst, const char* db_path) { return 0; fail: - if (!cc->shared_db) sqlite3_close(cc->db); + DEBUG_ERROR(DEBUG_CATEGORY_CHAT_SYNC, "chat init: failed stage=%s ready=%d owned_db=%d: %s", stage, + cc->initialized, !cc->shared_db, cc->db ? sqlite3_errmsg(cc->db) : "no DB"); + sqlite3_free_table(channels); + if (transaction && !sqlite3_get_autocommit(cc->db)) { + if (db_exec(cc, "ROLLBACK") != SQLITE_OK) DEBUG_ERROR(DEBUG_CATEGORY_CHAT_SYNC, "chat init: rollback failed"); + if (!sqlite3_get_autocommit(cc->db)) { + DEBUG_ERROR(DEBUG_CATEGORY_CHAT_SYNC, "chat init: transaction remains open;requesting owner stop/DB close"); utun_instance_stop(inst); + } + } + if (cc->initialized) { chat_core_destroy(inst); return -1; } + if (subscribed) chat_member_destroy(inst); + if (cc->db && !cc->shared_db && sqlite3_close(cc->db) != SQLITE_OK) DEBUG_ERROR(DEBUG_CATEGORY_CHAT_SYNC, "chat init: owned DB close failed"); inst->chat_core = NULL; u_free(cc); return -1; } void chat_core_destroy(struct UTUN_INSTANCE* inst) { - struct chat_core_ctx* cc = CC(inst); + struct chat_core_ctx* cc = inst ? CC(inst) : NULL; if (!cc || !cc->initialized) return; cc->initialized = 0; chat_member_destroy(inst);