Returns inserted / duplicate / failure. Frontend records are already bounded, * sanitized JSON; retain their full shape so both APIs share source evidence. */
| 182 | /* Returns inserted / duplicate / failure. Frontend records are already bounded, |
| 183 | * sanitized JSON; retain their full shape so both APIs share source evidence. */ |
| 184 | static int activity_log(sqlite3 *db, const char *line, bool frontend, bool historical) { |
| 185 | if (!db || !line) |
| 186 | return -1; |
| 187 | int level = 1; |
| 188 | char source[256] = "daemon"; |
| 189 | yyjson_doc *doc = yyjson_read(line, strlen(line), 0); |
| 190 | yyjson_val *root = doc ? yyjson_doc_get_root(doc) : NULL; |
| 191 | if (frontend && (!yyjson_is_obj(root) || strlen(line) > 131072)) { |
| 192 | yyjson_doc_free(doc); |
| 193 | return -1; |
| 194 | } |
| 195 | const char *name = string_field(root, "level"); |
| 196 | if (*name) { |
| 197 | if (!strcmp(name, "error")) |
| 198 | level = 3; |
| 199 | else if (!strcmp(name, "warn")) |
| 200 | level = 2; |
| 201 | else if (!strcmp(name, "debug")) |
| 202 | level = 0; |
| 203 | } else if (!strncmp(line, "level=error ", 12) || !strncmp(line, "ui.error ", 9)) |
| 204 | level = 3; |
| 205 | else if (!strncmp(line, "level=warn ", 11) || !strncmp(line, "ui.warn ", 8)) |
| 206 | level = 2; |
| 207 | else if (!strncmp(line, "level=debug ", 12)) |
| 208 | level = 0; |
| 209 | const char *tag = string_field(root, "msg"); |
| 210 | if (!*tag) |
| 211 | tag = string_field(root, "source"); |
| 212 | if (*tag) |
| 213 | snprintf(source, sizeof(source), "%s", tag); |
| 214 | else { |
| 215 | tag = strstr(line, "msg="); |
| 216 | if (tag) { |
| 217 | tag += 4; |
| 218 | size_t len = strcspn(tag, " \r\n"); |
| 219 | snprintf(source, sizeof(source), "%.*s", (int)(len < 255 ? len : 255), tag); |
| 220 | } else if (strstr(line, "[ui/")) |
| 221 | snprintf(source, sizeof(source), "frontend"); |
| 222 | } |
| 223 | sqlite3_stmt *st = NULL; |
| 224 | bool ok = sqlite3_prepare_v2( |
| 225 | db, |
| 226 | "INSERT INTO daemon_logs(ts,level,source,message,event_key,project,origin) " |
| 227 | "SELECT coalesce(?6,strftime('%Y-%m-%dT%H:%M:%fZ','now')),?1,?2,?3,?4,?5,?7 " |
| 228 | "WHERE ?8 IS NULL OR NOT EXISTS(SELECT 1 FROM ui_log_retired WHERE session=?8 " |
| 229 | "AND max_seq>=?9) " |
| 230 | "ON CONFLICT(event_key) DO UPDATE SET message=excluded.message,origin='frontend' " |
| 231 | "WHERE daemon_logs.origin='daemon' AND excluded.origin='frontend'", |
| 232 | -1, &st, NULL) == SQLITE_OK; |
| 233 | if (ok) { |
| 234 | sqlite3_bind_int(st, 1, level); |
| 235 | sqlite3_bind_text(st, 2, source, -1, SQLITE_TRANSIENT); |
| 236 | sqlite3_bind_text(st, 3, line, |
| 237 | (int)(!frontend && strlen(line) > 8192 ? 8192 : strlen(line)), |
| 238 | SQLITE_TRANSIENT); |
| 239 | const char *session = string_field(root, "session"); |
| 240 | yyjson_val *seq = yyjson_obj_get(root, "seq"); |
| 241 | if (*session && yyjson_is_int(seq)) { |
no test coverage detected