scorpiox-bot-plugin-memory
←graph.cc
943 lines · 27 KBHEADBlameDownload
1/*
2 * graph.c - storage engine for plugin_memory.
3 *
4 * The graph is one JSONL file: one JSON object per line, tagged
5 * {"type":"entity",...} or {"type":"relation",...}. This file owns the
6 * location of that file, the loader, the atomic writer, the in-memory store
7 * and the little utilities the other units share.
8 *
9 * Two properties are load-bearing:
10 *
11 * 1. A save stages a temp file in the SAME directory (so the rename stays
12 * on one filesystem), fsyncs it, restores the target's permission bits
13 * and renames it over the graph. A kill -9 halfway through leaves the
14 * previous graph intact and a stray .tmp behind - never a truncated
15 * graph. The temp file is removed on every failure path.
16 *
17 * 2. A line the loader cannot parse is not dropped. It is kept verbatim in
18 * G.bad and written back unchanged, so a hand-edited or half-imported
19 * graph survives a round trip. Silently losing someone's data would be
20 * worse than reporting it, so the count is also reported in stats.
21 *
22 * MIT License. Copyright (c) 2026 SCORPIOX INC.
23 */
24
25#if defined(_WIN32) && !defined(_WIN32_WINNT)
26# define _WIN32_WINNT 0x0601
27#endif
28
29#if !defined(_WIN32)
30# define _POSIX_C_SOURCE 200809L
31# define _DEFAULT_SOURCE 1
32# if defined(__APPLE__)
33# define _DARWIN_C_SOURCE 1
34# endif
35#endif
36
37#include <stdio.h>
38#include <stdlib.h>
39#include <string.h>
40#include <ctype.h>
41#include <errno.h>
42#include <time.h>
43#include <stdarg.h>
44
45#if defined(_WIN32)
46# define WIN32_LEAN_AND_MEAN
47# include <windows.h>
48# include <direct.h>
49# include <io.h>
50# include <fcntl.h> /* _O_CREAT/_O_EXCL/_O_WRONLY/_O_BINARY on MinGW */
51# include <sys/stat.h>
52# include <sys/types.h>
53#else
54# include <unistd.h>
55# include <fcntl.h>
56# include <sys/stat.h>
57# include <sys/types.h>
58#endif
59
60#include "memory.h"
61
62/* ------------------------------------------------------------------ */
63/* Growable byte buffer */
64/* ------------------------------------------------------------------ */
65
66void buf_init(buf_t *b)
67{
68 b->p = NULL;
69 b->n = 0;
70 b->cap = 0;
71}
72
73int buf_need(buf_t *b, size_t extra)
74{
75 size_t want = b->n + extra + 1;
76 char *np;
77 if (want <= b->cap) return 1;
78 if (b->cap == 0) b->cap = 1024;
79 while (b->cap < want) {
80 if (b->cap > (size_t)128 * 1024 * 1024) return 0; /* hard ceiling */
81 b->cap *= 2;
82 }
83 np = (char *)realloc(b->p, b->cap);
84 if (!np) return 0;
85 b->p = np;
86 return 1;
87}
88
89void buf_add(buf_t *b, const char *s, size_t n)
90{
91 if (!s || n == 0) return;
92 if (!buf_need(b, n)) return;
93 memcpy(b->p + b->n, s, n);
94 b->n += n;
95 b->p[b->n] = '\0';
96}
97
98void buf_puts(buf_t *b, const char *s)
99{
100 if (s) buf_add(b, s, strlen(s));
101}
102
103void buf_putc(buf_t *b, int c)
104{
105 char ch = (char)c;
106 buf_add(b, &ch, 1);
107}
108
109const char *buf_str(const buf_t *b)
110{
111 return b->p ? b->p : "";
112}
113
114void buf_free(buf_t *b)
115{
116 free(b->p);
117 b->p = NULL;
118 b->n = b->cap = 0;
119}
120
121/* ------------------------------------------------------------------ */
122/* Small helpers */
123/* ------------------------------------------------------------------ */
124
125void str_copy(char *dst, size_t dsz, const char *src)
126{
127 size_t i;
128 if (!dst || dsz == 0) return;
129 dst[0] = '\0';
130 if (!src) return;
131 for (i = 0; i + 1 < dsz && src[i]; i++) dst[i] = src[i];
132 dst[i] = '\0';
133}
134
135/* Case-insensitive substring: the reference search is a plain includes()
136 * over lower-cased fields, so this is the whole matching rule. */
137int str_icontains(const char *hay, const char *needle)
138{
139 if (!needle || !*needle) return 1;
140 if (!hay) return 0;
141 for (; *hay; hay++) {
142 const char *h = hay, *n = needle;
143 while (*h && *n &&
144 tolower((unsigned char)*h) == tolower((unsigned char)*n)) {
145 h++; n++;
146 }
147 if (!*n) return 1;
148 }
149 return 0;
150}
151
152void json_str(buf_t *b, const char *s)
153{
154 buf_putc(b, '"');
155 if (s) {
156 for (; *s; s++) {
157 unsigned char c = (unsigned char)*s;
158 if (c == '"') buf_puts(b, "\\\"");
159 else if (c == '\\') buf_puts(b, "\\\\");
160 else if (c == '\n') buf_puts(b, "\\n");
161 else if (c == '\r') buf_puts(b, "\\r");
162 else if (c == '\t') buf_puts(b, "\\t");
163 else if (c == '\b') buf_puts(b, "\\b");
164 else if (c == '\f') buf_puts(b, "\\f");
165 else if (c < 0x20) {
166 char tmp[8];
167 snprintf(tmp, sizeof tmp, "\\u%04x", (unsigned)c);
168 buf_puts(b, tmp);
169 } else buf_putc(b, (char)c);
170 }
171 }
172 buf_putc(b, '"');
173}
174
175char *dup_or_null(const char *s)
176{
177 char *p;
178 size_t n;
179 if (!s) return NULL;
180 n = strlen(s);
181 p = (char *)malloc(n + 1);
182 if (!p) return NULL;
183 memcpy(p, s, n + 1);
184 return p;
185}
186
187int env_int(const char *name, int dflt, int lo, int hi)
188{
189 const char *v = getenv(name);
190 long n;
191 char *end;
192 if (!v || !*v) return dflt;
193 errno = 0;
194 n = strtol(v, &end, 10);
195 if (end == v || errno != 0) return dflt;
196 if (n < lo) n = lo;
197 if (n > hi) n = hi;
198 return (int)n;
199}
200
201/* ------------------------------------------------------------------ */
202/* Filesystem helpers */
203/* ------------------------------------------------------------------ */
204
205static int file_exists_p(const char *p)
206{
207 struct stat st;
208 return p && *p && stat(p, &st) == 0;
209}
210
211static int is_dir_p(const char *p)
212{
213 struct stat st;
214 return p && *p && stat(p, &st) == 0 && S_ISDIR(st.st_mode);
215}
216
217static void path_join(char *out, size_t osz, const char *a, const char *b)
218{
219 size_t la;
220 if (!a || !*a) { str_copy(out, osz, b ? b : ""); return; }
221 la = strlen(a);
222 if (a[la - 1] == '/' || a[la - 1] == '\\')
223 snprintf(out, osz, "%s%s", a, b ? b : "");
224 else
225 snprintf(out, osz, "%s/%s", a, b ? b : "");
226}
227
228/* mkdir -p with 0700 - the graph holds the operator's notes about their own
229 * projects, so it is never world-readable. Returns 1 when it exists after. */
230static int mkdirs(const char *path)
231{
232 char tmp[PATH_SZ];
233 size_t i, n;
234
235 if (!path || !*path) return 0;
236 if (is_dir_p(path)) return 1;
237 str_copy(tmp, sizeof tmp, path);
238 n = strlen(tmp);
239 while (n > 1 && (tmp[n - 1] == '/' || tmp[n - 1] == '\\')) tmp[--n] = '\0';
240
241 for (i = 1; i < n; i++) {
242 if (tmp[i] == '/' || tmp[i] == '\\') {
243 char save = tmp[i];
244 tmp[i] = '\0';
245 if (!is_dir_p(tmp)) {
246#if defined(_WIN32)
247 (void)_mkdir(tmp);
248#else
249 (void)mkdir(tmp, 0700);
250#endif
251 }
252 tmp[i] = save;
253 }
254 }
255 if (!is_dir_p(tmp)) {
256#if defined(_WIN32)
257 (void)_mkdir(tmp);
258#else
259 (void)mkdir(tmp, 0700);
260#endif
261 }
262 return is_dir_p(tmp);
263}
264
265static char *read_file_all(const char *path, size_t *len_out)
266{
267 FILE *f;
268 long sz;
269 char *mem;
270 size_t got;
271
272 if (len_out) *len_out = 0;
273 if (!path || !*path) return NULL;
274 f = fopen(path, "rb");
275 if (!f) return NULL;
276 if (fseek(f, 0, SEEK_END) != 0) { fclose(f); return NULL; }
277 sz = ftell(f);
278 if (sz < 0) { fclose(f); return NULL; }
279 if ((size_t)sz > (size_t)FILE_MAX) { fclose(f); return NULL; }
280 if (fseek(f, 0, SEEK_SET) != 0) { fclose(f); return NULL; }
281 mem = (char *)malloc((size_t)sz + 1);
282 if (!mem) { fclose(f); return NULL; }
283 got = fread(mem, 1, (size_t)sz, f);
284 fclose(f);
285 mem[got] = '\0';
286 if (len_out) *len_out = got;
287 return mem;
288}
289
290/* ------------------------------------------------------------------ */
291/* Where the graph lives */
292/* ------------------------------------------------------------------ */
293
294static void connector_dir(char *out, size_t osz)
295{
296 const char *env;
297 struct stat st;
298
299 env = getenv("MEMORY_CONNECTOR_DIR");
300 if (env && *env) { str_copy(out, osz, env); return; }
301
302 /* BotCloud containers lose their rootfs on stop -> start, so /workspace
303 * is the durable place and wins whenever it exists. */
304 if (stat("/workspace", &st) == 0 && S_ISDIR(st.st_mode)) {
305 str_copy(out, osz, "/workspace/.scorpiox/connectors/" PLUGIN_ID);
306 return;
307 }
308#if defined(_WIN32)
309 {
310 const char *la = getenv("LOCALAPPDATA");
311 if (la && *la) {
312 snprintf(out, osz, "%s\\scorpiox\\connectors\\%s", la, PLUGIN_ID);
313 return;
314 }
315 }
316#endif
317 env = getenv("HOME");
318 if (!env || !*env) env = ".";
319 snprintf(out, osz, "%s/.scorpiox/connectors/%s", env, PLUGIN_ID);
320}
321
322static void expand_home(char *out, size_t osz, const char *in)
323{
324 const char *h;
325 if (!in) { out[0] = '\0'; return; }
326 h = getenv("HOME");
327 if (strcmp(in, "~") == 0) { str_copy(out, osz, (h && *h) ? h : "."); return; }
328 if (in[0] == '~' && (in[1] == '/' || in[1] == '\\')) {
329 snprintf(out, osz, "%s%s", (h && *h) ? h : ".", in + 1);
330 return;
331 }
332 str_copy(out, osz, in);
333}
334
335static int path_is_abs(const char *p)
336{
337 if (!p || !*p) return 0;
338 if (p[0] == '/') return 1;
339#if defined(_WIN32)
340 if (p[0] == '\\' || (isalpha((unsigned char)p[0]) && p[1] == ':')) return 1;
341#endif
342 return 0;
343}
344
345static char g_path[PATH_SZ];
346static int g_path_resolved;
347
348/* Resolve the graph path and create its parent. 1 on success. */
349static int ensure_path(void)
350{
351 const char *env;
352 char dir[PATH_SZ];
353 char cand[PATH_SZ];
354
355 if (g_path_resolved) return 1;
356
357 connector_dir(dir, sizeof dir);
358 env = getenv("MEMORY_FILE_PATH");
359
360 if (env && *env) {
361 const char *slash;
362 expand_home(cand, sizeof cand, env);
363 if (path_is_abs(cand)) {
364 char d[PATH_SZ];
365 size_t dn;
366 slash = strrchr(cand, '/');
367#if defined(_WIN32)
368 { const char *bs = strrchr(cand, '\\');
369 if (!slash || (bs && bs > slash)) slash = bs; }
370#endif
371 if (!slash) {
372 str_copy(g_data_err, sizeof g_data_err,
373 "MEMORY_FILE_PATH must name a file, not a bare name");
374 return 0;
375 }
376 dn = (size_t)(slash - cand);
377 if (dn == 0) dn = 1; /* keep the root slash */
378 if (dn >= sizeof d) dn = sizeof d - 1;
379 memcpy(d, cand, dn);
380 d[dn] = '\0';
381 if (!mkdirs(d)) {
382 str_copy(g_data_err, sizeof g_data_err,
383 "cannot create the directory for MEMORY_FILE_PATH");
384 return 0;
385 }
386 str_copy(g_path, sizeof g_path, cand);
387 g_path_resolved = 1;
388 return 1;
389 }
390 /* A relative MEMORY_FILE_PATH lands inside the connector dir, exactly
391 * like the reference server resolving against its package dir. */
392 if (strstr(cand, "..")) {
393 str_copy(g_data_err, sizeof g_data_err,
394 "MEMORY_FILE_PATH may not contain '..'");
395 return 0;
396 }
397 if (!mkdirs(dir)) {
398 str_copy(g_data_err, sizeof g_data_err,
399 "cannot create the connector data directory");
400 return 0;
401 }
402 path_join(g_path, sizeof g_path, dir, cand);
403 g_path_resolved = 1;
404 return 1;
405 }
406
407 if (!mkdirs(dir)) {
408 str_copy(g_data_err, sizeof g_data_err,
409 "cannot create the connector data directory");
410 return 0;
411 }
412 path_join(g_path, sizeof g_path, dir, "memory.jsonl");
413 g_path_resolved = 1;
414 return 1;
415}
416
417const char *graph_path(void)
418{
419 if (!g_path_resolved && !ensure_path()) return "";
420 return g_path;
421}
422
423int graph_path_info(long long *size, int *exists)
424{
425 struct stat st;
426 const char *p = graph_path();
427 if (size) *size = 0;
428 if (exists) *exists = 0;
429 if (!p || !*p) return -1;
430 if (stat(p, &st) != 0) return 0;
431 if (exists) *exists = 1;
432 if (size) *size = (long long)st.st_size;
433 return 0;
434}
435
436/* ------------------------------------------------------------------ */
437/* A best-effort cross-process lock */
438/* */
439/* Every mutation is a read-modify-write of the whole file, so two */
440/* concurrent agents could otherwise lose one of their writes. The */
441/* reference server uses an O_EXCL lock file with a stale-break; this */
442/* is the same idea in twenty lines. It is deliberately best-effort: */
443/* if the lock cannot be taken we still serve the request, because */
444/* losing a node's memory over a stuck lock file is the worse failure. */
445/* ------------------------------------------------------------------ */
446
447static int g_lock_fd = -1;
448static char g_lock_path[PATH_SZ + SUFFIX_SZ];
449
450static void lock_remove(void)
451{
452 if (g_lock_path[0]) {
453#if defined(_WIN32)
454 _unlink(g_lock_path);
455#else
456 unlink(g_lock_path);
457#endif
458 g_lock_path[0] = '\0';
459 }
460}
461
462static int lock_try_once(void)
463{
464 int fd;
465 long stale_ms;
466 struct stat st;
467 time_t now;
468
469 snprintf(g_lock_path, sizeof g_lock_path, "%s.lock", graph_path());
470
471 /* Break a lock left behind by a killed process. */
472 if (stat(g_lock_path, &st) == 0) {
473 stale_ms = (long)env_int("MEMORY_LOCK_STALE_MS", 10000, 100, 600000);
474 time(&now);
475 if ((long)(now - st.st_mtime) * 1000 > stale_ms) lock_remove();
476 }
477
478#if defined(_WIN32)
479 fd = _open(g_lock_path, _O_CREAT | _O_EXCL | _O_WRONLY | _O_BINARY, _S_IREAD | _S_IWRITE);
480#else
481 fd = open(g_lock_path, O_CREAT | O_EXCL | O_WRONLY, 0600);
482#endif
483 if (fd < 0) return -1;
484 {
485 char pid[32];
486 int n = snprintf(pid, sizeof pid, "%ld\n", (long)
487#if defined(_WIN32)
488 GetCurrentProcessId()
489#else
490 (long)getpid()
491#endif
492 );
493 if (n > 0) {
494#if defined(_WIN32)
495 ssize_t w = _write(fd, pid, (unsigned)n);
496#else
497 ssize_t w = write(fd, pid, (size_t)n);
498#endif
499 (void)w;
500 }
501 }
502#if defined(_WIN32)
503 _close(fd);
504#else
505 close(fd);
506#endif
507 g_lock_fd = 0;
508 return 0;
509}
510
511void graph_lock(void)
512{
513 int tries, timeout_ms;
514 if (!ensure_path()) return;
515 timeout_ms = env_int("MEMORY_LOCK_TIMEOUT_MS", 2000, 0, 30000);
516 tries = timeout_ms / 10 + 1;
517 while (tries-- > 0) {
518 if (lock_try_once() == 0) return;
519#if defined(_WIN32)
520 Sleep(10);
521#else
522 { struct timespec ts; ts.tv_sec = 0; ts.tv_nsec = 10 * 1000 * 1000L;
523 nanosleep(&ts, NULL); }
524#endif
525 }
526 /* Best effort: proceed unlocked rather than failing the user's write. */
527 g_lock_path[0] = '\0';
528}
529
530void graph_unlock(void)
531{
532 if (g_lock_fd == 0) lock_remove();
533 g_lock_fd = -1;
534}
535
536/* ------------------------------------------------------------------ */
537/* The store */
538/* ------------------------------------------------------------------ */
539
540graph_t G;
541char g_data_err[256];
542
543static char *dup_or_empty(const char *s)
544{
545 return dup_or_null(s ? s : "");
546}
547
548void graph_clear(graph_t *g)
549{
550 size_t i, j;
551 for (i = 0; i < g->n_ent; i++) {
552 free(g->ent[i].name);
553 free(g->ent[i].etype);
554 for (j = 0; j < g->ent[i].n_obs; j++) free(g->ent[i].obs[j]);
555 free(g->ent[i].obs);
556 }
557 free(g->ent);
558 for (i = 0; i < g->n_rel; i++) {
559 free(g->rel[i].from);
560 free(g->rel[i].to);
561 free(g->rel[i].rtype);
562 }
563 free(g->rel);
564 for (i = 0; i < g->n_bad; i++) free(g->bad[i]);
565 free(g->bad);
566 memset(g, 0, sizeof *g);
567}
568
569entity_t *ent_find(graph_t *g, const char *name)
570{
571 size_t i;
572 if (!name) return NULL;
573 for (i = 0; i < g->n_ent; i++)
574 if (strcmp(g->ent[i].name, name) == 0) return &g->ent[i];
575 return NULL;
576}
577
578int ent_add(graph_t *g, const char *name, const char *etype,
579 char **obs, size_t n_obs, char *err, size_t errsz)
580{
581 entity_t *e;
582 size_t i, cap_obs;
583
584 if (g->n_ent >= (size_t)env_int("MEMORY_MAX_ENTITIES",
585 MAX_ENTITIES_DEFAULT, 1, 2000000)) {
586 if (err) snprintf(err, errsz,
587 "The graph is at its entity limit; delete entities "
588 "before adding more.");
589 return -1;
590 }
591 if (!name || !*name || strlen(name) > (size_t)SX_NAME_MAX ||
592 !etype || !*etype || strlen(etype) > (size_t)SX_TYPE_MAX) {
593 if (err) snprintf(err, errsz,
594 "An entity needs a non-empty name and entityType "
595 "(each at most %d characters).", SX_NAME_MAX);
596 return -1;
597 }
598 if (n_obs > (size_t)env_int("MEMORY_MAX_OBS", MAX_OBS_PER_ENT_DEFAULT,
599 1, 200000))
600 n_obs = (size_t)env_int("MEMORY_MAX_OBS", MAX_OBS_PER_ENT_DEFAULT,
601 1, 200000);
602
603 if (g->n_ent == g->cap_ent) {
604 size_t nc = g->cap_ent ? g->cap_ent * 2 : 32;
605 entity_t *nv = (entity_t *)realloc(g->ent, nc * sizeof *nv);
606 if (!nv) { if (err) snprintf(err, errsz, "out of memory"); return -1; }
607 g->ent = nv;
608 g->cap_ent = nc;
609 }
610 e = &g->ent[g->n_ent++];
611 memset(e, 0, sizeof *e);
612 e->name = dup_or_empty(name);
613 e->etype = dup_or_empty(etype);
614 if (!e->name || !e->etype) {
615 if (err) snprintf(err, errsz, "out of memory");
616 return -1;
617 }
618 cap_obs = n_obs;
619 if (cap_obs) {
620 e->obs = (char **)calloc(cap_obs, sizeof *e->obs);
621 if (!e->obs) { if (err) snprintf(err, errsz, "out of memory"); return -1; }
622 for (i = 0; i < cap_obs; i++) {
623 e->obs[i] = dup_or_empty(obs[i] ? obs[i] : "");
624 if (!e->obs[i]) { if (err) snprintf(err, errsz, "out of memory"); return -1; }
625 }
626 e->n_obs = cap_obs;
627 }
628 return 0;
629}
630
631int rel_add(graph_t *g, const char *from, const char *to,
632 const char *rtype, char *err, size_t errsz)
633{
634 relation_t *r;
635
636 if (g->n_rel >= (size_t)env_int("MEMORY_MAX_RELATIONS",
637 MAX_RELATIONS_DEFAULT, 1, 4000000)) {
638 if (err) snprintf(err, errsz,
639 "The graph is at its relation limit; delete "
640 "relations before adding more.");
641 return -1;
642 }
643 if (!from || !*from || !to || !*to || !rtype || !*rtype ||
644 strlen(from) > (size_t)SX_NAME_MAX || strlen(to) > (size_t)SX_NAME_MAX ||
645 strlen(rtype) > (size_t)SX_TYPE_MAX) {
646 if (err) snprintf(err, errsz,
647 "A relation needs non-empty from, to and "
648 "relationType fields.");
649 return -1;
650 }
651 if (g->n_rel == g->cap_rel) {
652 size_t nc = g->cap_rel ? g->cap_rel * 2 : 64;
653 relation_t *nv = (relation_t *)realloc(g->rel, nc * sizeof *nv);
654 if (!nv) { if (err) snprintf(err, errsz, "out of memory"); return -1; }
655 g->rel = nv;
656 g->cap_rel = nc;
657 }
658 r = &g->rel[g->n_rel++];
659 memset(r, 0, sizeof *r);
660 r->from = dup_or_empty(from);
661 r->to = dup_or_empty(to);
662 r->rtype = dup_or_empty(rtype);
663 if (!r->from || !r->to || !r->rtype) {
664 if (err) snprintf(err, errsz, "out of memory");
665 return -1;
666 }
667 return 0;
668}
669
670void bad_add(graph_t *g, const char *line)
671{
672 size_t cap = (size_t)env_int("MEMORY_MAX_BAD", 5000, 1, 200000);
673 if (g->n_bad >= cap) { g->truncated = 1; return; }
674 if (g->n_bad == g->cap_bad) {
675 size_t nc = g->cap_bad ? g->cap_bad * 2 : 16;
676 char **nv = (char **)realloc(g->bad, nc * sizeof *nv);
677 if (!nv) return;
678 g->bad = nv;
679 g->cap_bad = nc;
680 }
681 g->bad[g->n_bad++] = dup_or_empty(line);
682}
683
684int obs_push(entity_t *e, const char *text)
685{
686 char *d;
687 char **nv;
688 size_t cap = (size_t)env_int("MEMORY_MAX_OBS", MAX_OBS_PER_ENT_DEFAULT,
689 1, 200000);
690 if (e->n_obs >= cap) return 0;
691 d = dup_or_empty(text ? text : "");
692 if (!d) return 0;
693 nv = (char **)realloc(e->obs, (e->n_obs + 1) * sizeof *e->obs);
694 if (!nv) { free(d); return 0; }
695 e->obs = nv;
696 e->obs[e->n_obs++] = d;
697 return 1;
698}
699
700int str_arr_from(yyjson_val *arr, char ***out, size_t *n_out, size_t cap)
701{
702 char **v = NULL;
703 size_t n = 0, i, max;
704
705 *out = NULL;
706 *n_out = 0;
707 if (!arr || !yyjson_is_arr(arr)) return 0;
708 max = yyjson_arr_size(arr);
709 if (max > cap) max = cap;
710 if (max == 0) return 0;
711 v = (char **)calloc(max, sizeof *v);
712 if (!v) return -1;
713 for (i = 0; i < max; i++) {
714 yyjson_val *it = yyjson_arr_get(arr, i);
715 const char *s;
716 if (!it || !yyjson_is_str(it)) continue;
717 s = yyjson_get_str(it);
718 if (!s || strlen(s) > (size_t)OBS_TEXT_MAX) continue;
719 v[n] = dup_or_empty(s);
720 if (v[n]) n++;
721 }
722 *out = v;
723 *n_out = n;
724 return 0;
725}
726
727/* ------------------------------------------------------------------ */
728/* Load */
729/* ------------------------------------------------------------------ */
730
731/* One JSONL line into the graph. 0 = understood, -1 = keep verbatim. */
732static int load_line(graph_t *g, const char *line)
733{
734 yyjson_doc *doc;
735 yyjson_val *root, *type, *v;
736 const char *ty;
737 int rc = -1;
738
739 while (*line == ' ' || *line == '\t' || *line == '\r') line++;
740 if (!*line) return 0; /* blank: not data */
741
742 doc = yyjson_read(line, strlen(line), 0);
743 if (!doc) return -1;
744 root = yyjson_doc_get_root(doc);
745 if (!root || !yyjson_is_obj(root)) { yyjson_doc_free(doc); return -1; }
746
747 type = yyjson_obj_get(root, "type");
748 ty = (type && yyjson_is_str(type)) ? yyjson_get_str(type) : NULL;
749
750 if (ty && strcmp(ty, "entity") == 0) {
751 v = yyjson_obj_get(root, "name");
752 if (yyjson_is_str(v)) {
753 yyjson_val *nmv = v;
754 yyjson_val *et = yyjson_obj_get(root, "entityType");
755 yyjson_val *ob = yyjson_obj_get(root, "observations");
756 if (yyjson_is_str(et) && yyjson_is_arr(ob)) {
757 char **obs = NULL;
758 size_t n_obs = 0, i;
759 char err[128];
760 if (str_arr_from(ob, &obs, &n_obs,
761 (size_t)MAX_OBS_PER_ENT_DEFAULT) == 0) {
762 if (ent_add(g, yyjson_get_str(nmv), yyjson_get_str(et),
763 obs, n_obs, err, sizeof err) == 0)
764 rc = 0;
765 for (i = 0; i < n_obs; i++) free(obs[i]);
766 free(obs);
767 }
768 }
769 }
770 } else if (ty && strcmp(ty, "relation") == 0) {
771 yyjson_val *f = yyjson_obj_get(root, "from");
772 yyjson_val *t = yyjson_obj_get(root, "to");
773 yyjson_val *r = yyjson_obj_get(root, "relationType");
774 if (yyjson_is_str(f) && yyjson_is_str(t) && yyjson_is_str(r)) {
775 char err[128];
776 if (rel_add(g, yyjson_get_str(f), yyjson_get_str(t),
777 yyjson_get_str(r), err, sizeof err) == 0)
778 rc = 0;
779 }
780 }
781
782 yyjson_doc_free(doc);
783 return rc;
784}
785
786int graph_load(void)
787{
788 char *text;
789 size_t len, i, start;
790 graph_t ng;
791
792 graph_clear(&G);
793 g_data_err[0] = '\0';
794 if (!ensure_path()) return -1;
795
796 memset(&ng, 0, sizeof ng);
797 text = read_file_all(g_path, &len);
798 if (!text) {
799 if (file_exists_p(g_path)) {
800 snprintf(g_data_err, sizeof g_data_err,
801 "cannot read the graph file (permission, or larger "
802 "than %d MB)", (int)(FILE_MAX / (1024 * 1024)));
803 return -1;
804 }
805 G = ng; /* no file yet: empty */
806 return 0;
807 }
808
809 i = 0;
810 while (i <= len) {
811 start = i;
812 while (i < len && text[i] != '\n') i++;
813 text[i] = '\0';
814 if (load_line(&ng, text + start) != 0) bad_add(&ng, text + start);
815 i++;
816 }
817 free(text);
818 G = ng;
819 return 0;
820}
821
822/* ------------------------------------------------------------------ */
823/* Save */
824/* ------------------------------------------------------------------ */
825
826static int write_over(const char *path, const char *data, size_t len,
827 char *err, size_t errsz)
828{
829 char tmp[PATH_SZ + SUFFIX_SZ];
830 FILE *f;
831 int mode = -1;
832 struct stat st;
833
834 if (err && errsz) err[0] = '\0';
835 if (stat(path, &st) == 0 && S_ISREG(st.st_mode))
836 mode = (int)(st.st_mode & 0777);
837
838 snprintf(tmp, sizeof tmp, "%s.tmp.%ld", path, (long)
839#if defined(_WIN32)
840 GetCurrentProcessId()
841#else
842 (long)getpid()
843#endif
844 );
845
846 f = fopen(tmp, "wb");
847 if (!f) {
848 if (err) snprintf(err, errsz, "cannot create a temp file beside %s", path);
849 return -1;
850 }
851 if (len && fwrite(data, 1, len, f) != len) {
852 fclose(f);
853#if defined(_WIN32)
854 _unlink(tmp);
855#else
856 unlink(tmp);
857#endif
858 if (err) snprintf(err, errsz, "the graph is too large to write");
859 return -1;
860 }
861 if (fflush(f) != 0) {
862 fclose(f);
863#if defined(_WIN32)
864 _unlink(tmp);
865#else
866 unlink(tmp);
867#endif
868 if (err) snprintf(err, errsz, "cannot flush the graph to disk");
869 return -1;
870 }
871#if !defined(_WIN32)
872 (void)fsync(fileno(f));
873#endif
874 fclose(f);
875
876 /* rename() gives the new file the process umask; restore the operator's
877 * own bits so a 0600 graph does not come back world-readable. */
878 if (mode >= 0) {
879#if !defined(_WIN32)
880 (void)chmod(tmp, (mode_t)mode);
881#else
882 (void)_chmod(tmp, (mode_t)mode);
883#endif
884 }
885
886#if defined(_WIN32)
887 if (!MoveFileExA(tmp, path, MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)) {
888 _unlink(tmp);
889 if (err) snprintf(err, errsz, "cannot replace the graph file");
890 return -1;
891 }
892#else
893 if (rename(tmp, path) != 0) {
894 unlink(tmp);
895 if (err) snprintf(err, errsz, "cannot replace the graph file");
896 return -1;
897 }
898#endif
899 return 0;
900}
901
902int graph_save(char *err, size_t errsz)
903{
904 buf_t b;
905 size_t i, j;
906 int rc;
907
908 if (!ensure_path()) {
909 snprintf(err, errsz, "%s", g_data_err[0] ? g_data_err
910 : "the graph file is not reachable");
911 return -1;
912 }
913 buf_init(&b);
914 for (i = 0; i < G.n_ent; i++) {
915 buf_puts(&b, "{\"type\":\"entity\",\"name\":");
916 json_str(&b, G.ent[i].name);
917 buf_puts(&b, ",\"entityType\":");
918 json_str(&b, G.ent[i].etype);
919 buf_puts(&b, ",\"observations\":[");
920 for (j = 0; j < G.ent[i].n_obs; j++) {
921 if (j) buf_putc(&b, ',');
922 json_str(&b, G.ent[i].obs[j] ? G.ent[i].obs[j] : "");
923 }
924 buf_puts(&b, "]}\n");
925 }
926 for (i = 0; i < G.n_rel; i++) {
927 buf_puts(&b, "{\"type\":\"relation\",\"from\":");
928 json_str(&b, G.rel[i].from);
929 buf_puts(&b, ",\"to\":");
930 json_str(&b, G.rel[i].to);
931 buf_puts(&b, ",\"relationType\":");
932 json_str(&b, G.rel[i].rtype);
933 buf_puts(&b, "}\n");
934 }
935 /* Unreadable lines last, byte for byte, so a round trip is lossless. */
936 for (i = 0; i < G.n_bad; i++) {
937 buf_puts(&b, G.bad[i] ? G.bad[i] : "");
938 buf_putc(&b, '\n');
939 }
940 rc = write_over(g_path, buf_str(&b), b.n, err, errsz);
941 buf_free(&b);
942 return rc;
943}