/* * graph.c - storage engine for plugin_memory. * * The graph is one JSONL file: one JSON object per line, tagged * {"type":"entity",...} or {"type":"relation",...}. This file owns the * location of that file, the loader, the atomic writer, the in-memory store * and the little utilities the other units share. * * Two properties are load-bearing: * * 1. A save stages a temp file in the SAME directory (so the rename stays * on one filesystem), fsyncs it, restores the target's permission bits * and renames it over the graph. A kill -9 halfway through leaves the * previous graph intact and a stray .tmp behind - never a truncated * graph. The temp file is removed on every failure path. * * 2. A line the loader cannot parse is not dropped. It is kept verbatim in * G.bad and written back unchanged, so a hand-edited or half-imported * graph survives a round trip. Silently losing someone's data would be * worse than reporting it, so the count is also reported in stats. * * MIT License. Copyright (c) 2026 SCORPIOX INC. */ #if defined(_WIN32) && !defined(_WIN32_WINNT) # define _WIN32_WINNT 0x0601 #endif #if !defined(_WIN32) # define _POSIX_C_SOURCE 200809L # define _DEFAULT_SOURCE 1 # if defined(__APPLE__) # define _DARWIN_C_SOURCE 1 # endif #endif #include #include #include #include #include #include #include #if defined(_WIN32) # define WIN32_LEAN_AND_MEAN # include # include # include # include /* _O_CREAT/_O_EXCL/_O_WRONLY/_O_BINARY on MinGW */ # include # include #else # include # include # include # include #endif #include "memory.h" /* ------------------------------------------------------------------ */ /* Growable byte buffer */ /* ------------------------------------------------------------------ */ void buf_init(buf_t *b) { b->p = NULL; b->n = 0; b->cap = 0; } int buf_need(buf_t *b, size_t extra) { size_t want = b->n + extra + 1; char *np; if (want <= b->cap) return 1; if (b->cap == 0) b->cap = 1024; while (b->cap < want) { if (b->cap > (size_t)128 * 1024 * 1024) return 0; /* hard ceiling */ b->cap *= 2; } np = (char *)realloc(b->p, b->cap); if (!np) return 0; b->p = np; return 1; } void buf_add(buf_t *b, const char *s, size_t n) { if (!s || n == 0) return; if (!buf_need(b, n)) return; memcpy(b->p + b->n, s, n); b->n += n; b->p[b->n] = '\0'; } void buf_puts(buf_t *b, const char *s) { if (s) buf_add(b, s, strlen(s)); } void buf_putc(buf_t *b, int c) { char ch = (char)c; buf_add(b, &ch, 1); } const char *buf_str(const buf_t *b) { return b->p ? b->p : ""; } void buf_free(buf_t *b) { free(b->p); b->p = NULL; b->n = b->cap = 0; } /* ------------------------------------------------------------------ */ /* Small helpers */ /* ------------------------------------------------------------------ */ void str_copy(char *dst, size_t dsz, const char *src) { size_t i; if (!dst || dsz == 0) return; dst[0] = '\0'; if (!src) return; for (i = 0; i + 1 < dsz && src[i]; i++) dst[i] = src[i]; dst[i] = '\0'; } /* Case-insensitive substring: the reference search is a plain includes() * over lower-cased fields, so this is the whole matching rule. */ int str_icontains(const char *hay, const char *needle) { if (!needle || !*needle) return 1; if (!hay) return 0; for (; *hay; hay++) { const char *h = hay, *n = needle; while (*h && *n && tolower((unsigned char)*h) == tolower((unsigned char)*n)) { h++; n++; } if (!*n) return 1; } return 0; } void json_str(buf_t *b, const char *s) { buf_putc(b, '"'); if (s) { for (; *s; s++) { unsigned char c = (unsigned char)*s; if (c == '"') buf_puts(b, "\\\""); else if (c == '\\') buf_puts(b, "\\\\"); else if (c == '\n') buf_puts(b, "\\n"); else if (c == '\r') buf_puts(b, "\\r"); else if (c == '\t') buf_puts(b, "\\t"); else if (c == '\b') buf_puts(b, "\\b"); else if (c == '\f') buf_puts(b, "\\f"); else if (c < 0x20) { char tmp[8]; snprintf(tmp, sizeof tmp, "\\u%04x", (unsigned)c); buf_puts(b, tmp); } else buf_putc(b, (char)c); } } buf_putc(b, '"'); } char *dup_or_null(const char *s) { char *p; size_t n; if (!s) return NULL; n = strlen(s); p = (char *)malloc(n + 1); if (!p) return NULL; memcpy(p, s, n + 1); return p; } int env_int(const char *name, int dflt, int lo, int hi) { const char *v = getenv(name); long n; char *end; if (!v || !*v) return dflt; errno = 0; n = strtol(v, &end, 10); if (end == v || errno != 0) return dflt; if (n < lo) n = lo; if (n > hi) n = hi; return (int)n; } /* ------------------------------------------------------------------ */ /* Filesystem helpers */ /* ------------------------------------------------------------------ */ static int file_exists_p(const char *p) { struct stat st; return p && *p && stat(p, &st) == 0; } static int is_dir_p(const char *p) { struct stat st; return p && *p && stat(p, &st) == 0 && S_ISDIR(st.st_mode); } static void path_join(char *out, size_t osz, const char *a, const char *b) { size_t la; if (!a || !*a) { str_copy(out, osz, b ? b : ""); return; } la = strlen(a); if (a[la - 1] == '/' || a[la - 1] == '\\') snprintf(out, osz, "%s%s", a, b ? b : ""); else snprintf(out, osz, "%s/%s", a, b ? b : ""); } /* mkdir -p with 0700 - the graph holds the operator's notes about their own * projects, so it is never world-readable. Returns 1 when it exists after. */ static int mkdirs(const char *path) { char tmp[PATH_SZ]; size_t i, n; if (!path || !*path) return 0; if (is_dir_p(path)) return 1; str_copy(tmp, sizeof tmp, path); n = strlen(tmp); while (n > 1 && (tmp[n - 1] == '/' || tmp[n - 1] == '\\')) tmp[--n] = '\0'; for (i = 1; i < n; i++) { if (tmp[i] == '/' || tmp[i] == '\\') { char save = tmp[i]; tmp[i] = '\0'; if (!is_dir_p(tmp)) { #if defined(_WIN32) (void)_mkdir(tmp); #else (void)mkdir(tmp, 0700); #endif } tmp[i] = save; } } if (!is_dir_p(tmp)) { #if defined(_WIN32) (void)_mkdir(tmp); #else (void)mkdir(tmp, 0700); #endif } return is_dir_p(tmp); } static char *read_file_all(const char *path, size_t *len_out) { FILE *f; long sz; char *mem; size_t got; if (len_out) *len_out = 0; if (!path || !*path) return NULL; f = fopen(path, "rb"); if (!f) return NULL; if (fseek(f, 0, SEEK_END) != 0) { fclose(f); return NULL; } sz = ftell(f); if (sz < 0) { fclose(f); return NULL; } if ((size_t)sz > (size_t)FILE_MAX) { fclose(f); return NULL; } if (fseek(f, 0, SEEK_SET) != 0) { fclose(f); return NULL; } mem = (char *)malloc((size_t)sz + 1); if (!mem) { fclose(f); return NULL; } got = fread(mem, 1, (size_t)sz, f); fclose(f); mem[got] = '\0'; if (len_out) *len_out = got; return mem; } /* ------------------------------------------------------------------ */ /* Where the graph lives */ /* ------------------------------------------------------------------ */ static void connector_dir(char *out, size_t osz) { const char *env; struct stat st; env = getenv("MEMORY_CONNECTOR_DIR"); if (env && *env) { str_copy(out, osz, env); return; } /* BotCloud containers lose their rootfs on stop -> start, so /workspace * is the durable place and wins whenever it exists. */ if (stat("/workspace", &st) == 0 && S_ISDIR(st.st_mode)) { str_copy(out, osz, "/workspace/.scorpiox/connectors/" PLUGIN_ID); return; } #if defined(_WIN32) { const char *la = getenv("LOCALAPPDATA"); if (la && *la) { snprintf(out, osz, "%s\\scorpiox\\connectors\\%s", la, PLUGIN_ID); return; } } #endif env = getenv("HOME"); if (!env || !*env) env = "."; snprintf(out, osz, "%s/.scorpiox/connectors/%s", env, PLUGIN_ID); } static void expand_home(char *out, size_t osz, const char *in) { const char *h; if (!in) { out[0] = '\0'; return; } h = getenv("HOME"); if (strcmp(in, "~") == 0) { str_copy(out, osz, (h && *h) ? h : "."); return; } if (in[0] == '~' && (in[1] == '/' || in[1] == '\\')) { snprintf(out, osz, "%s%s", (h && *h) ? h : ".", in + 1); return; } str_copy(out, osz, in); } static int path_is_abs(const char *p) { if (!p || !*p) return 0; if (p[0] == '/') return 1; #if defined(_WIN32) if (p[0] == '\\' || (isalpha((unsigned char)p[0]) && p[1] == ':')) return 1; #endif return 0; } static char g_path[PATH_SZ]; static int g_path_resolved; /* Resolve the graph path and create its parent. 1 on success. */ static int ensure_path(void) { const char *env; char dir[PATH_SZ]; char cand[PATH_SZ]; if (g_path_resolved) return 1; connector_dir(dir, sizeof dir); env = getenv("MEMORY_FILE_PATH"); if (env && *env) { const char *slash; expand_home(cand, sizeof cand, env); if (path_is_abs(cand)) { char d[PATH_SZ]; size_t dn; slash = strrchr(cand, '/'); #if defined(_WIN32) { const char *bs = strrchr(cand, '\\'); if (!slash || (bs && bs > slash)) slash = bs; } #endif if (!slash) { str_copy(g_data_err, sizeof g_data_err, "MEMORY_FILE_PATH must name a file, not a bare name"); return 0; } dn = (size_t)(slash - cand); if (dn == 0) dn = 1; /* keep the root slash */ if (dn >= sizeof d) dn = sizeof d - 1; memcpy(d, cand, dn); d[dn] = '\0'; if (!mkdirs(d)) { str_copy(g_data_err, sizeof g_data_err, "cannot create the directory for MEMORY_FILE_PATH"); return 0; } str_copy(g_path, sizeof g_path, cand); g_path_resolved = 1; return 1; } /* A relative MEMORY_FILE_PATH lands inside the connector dir, exactly * like the reference server resolving against its package dir. */ if (strstr(cand, "..")) { str_copy(g_data_err, sizeof g_data_err, "MEMORY_FILE_PATH may not contain '..'"); return 0; } if (!mkdirs(dir)) { str_copy(g_data_err, sizeof g_data_err, "cannot create the connector data directory"); return 0; } path_join(g_path, sizeof g_path, dir, cand); g_path_resolved = 1; return 1; } if (!mkdirs(dir)) { str_copy(g_data_err, sizeof g_data_err, "cannot create the connector data directory"); return 0; } path_join(g_path, sizeof g_path, dir, "memory.jsonl"); g_path_resolved = 1; return 1; } const char *graph_path(void) { if (!g_path_resolved && !ensure_path()) return ""; return g_path; } int graph_path_info(long long *size, int *exists) { struct stat st; const char *p = graph_path(); if (size) *size = 0; if (exists) *exists = 0; if (!p || !*p) return -1; if (stat(p, &st) != 0) return 0; if (exists) *exists = 1; if (size) *size = (long long)st.st_size; return 0; } /* ------------------------------------------------------------------ */ /* A best-effort cross-process lock */ /* */ /* Every mutation is a read-modify-write of the whole file, so two */ /* concurrent agents could otherwise lose one of their writes. The */ /* reference server uses an O_EXCL lock file with a stale-break; this */ /* is the same idea in twenty lines. It is deliberately best-effort: */ /* if the lock cannot be taken we still serve the request, because */ /* losing a node's memory over a stuck lock file is the worse failure. */ /* ------------------------------------------------------------------ */ static int g_lock_fd = -1; static char g_lock_path[PATH_SZ + SUFFIX_SZ]; static void lock_remove(void) { if (g_lock_path[0]) { #if defined(_WIN32) _unlink(g_lock_path); #else unlink(g_lock_path); #endif g_lock_path[0] = '\0'; } } static int lock_try_once(void) { int fd; long stale_ms; struct stat st; time_t now; snprintf(g_lock_path, sizeof g_lock_path, "%s.lock", graph_path()); /* Break a lock left behind by a killed process. */ if (stat(g_lock_path, &st) == 0) { stale_ms = (long)env_int("MEMORY_LOCK_STALE_MS", 10000, 100, 600000); time(&now); if ((long)(now - st.st_mtime) * 1000 > stale_ms) lock_remove(); } #if defined(_WIN32) fd = _open(g_lock_path, _O_CREAT | _O_EXCL | _O_WRONLY | _O_BINARY, _S_IREAD | _S_IWRITE); #else fd = open(g_lock_path, O_CREAT | O_EXCL | O_WRONLY, 0600); #endif if (fd < 0) return -1; { char pid[32]; int n = snprintf(pid, sizeof pid, "%ld\n", (long) #if defined(_WIN32) GetCurrentProcessId() #else (long)getpid() #endif ); if (n > 0) { #if defined(_WIN32) ssize_t w = _write(fd, pid, (unsigned)n); #else ssize_t w = write(fd, pid, (size_t)n); #endif (void)w; } } #if defined(_WIN32) _close(fd); #else close(fd); #endif g_lock_fd = 0; return 0; } void graph_lock(void) { int tries, timeout_ms; if (!ensure_path()) return; timeout_ms = env_int("MEMORY_LOCK_TIMEOUT_MS", 2000, 0, 30000); tries = timeout_ms / 10 + 1; while (tries-- > 0) { if (lock_try_once() == 0) return; #if defined(_WIN32) Sleep(10); #else { struct timespec ts; ts.tv_sec = 0; ts.tv_nsec = 10 * 1000 * 1000L; nanosleep(&ts, NULL); } #endif } /* Best effort: proceed unlocked rather than failing the user's write. */ g_lock_path[0] = '\0'; } void graph_unlock(void) { if (g_lock_fd == 0) lock_remove(); g_lock_fd = -1; } /* ------------------------------------------------------------------ */ /* The store */ /* ------------------------------------------------------------------ */ graph_t G; char g_data_err[256]; static char *dup_or_empty(const char *s) { return dup_or_null(s ? s : ""); } void graph_clear(graph_t *g) { size_t i, j; for (i = 0; i < g->n_ent; i++) { free(g->ent[i].name); free(g->ent[i].etype); for (j = 0; j < g->ent[i].n_obs; j++) free(g->ent[i].obs[j]); free(g->ent[i].obs); } free(g->ent); for (i = 0; i < g->n_rel; i++) { free(g->rel[i].from); free(g->rel[i].to); free(g->rel[i].rtype); } free(g->rel); for (i = 0; i < g->n_bad; i++) free(g->bad[i]); free(g->bad); memset(g, 0, sizeof *g); } entity_t *ent_find(graph_t *g, const char *name) { size_t i; if (!name) return NULL; for (i = 0; i < g->n_ent; i++) if (strcmp(g->ent[i].name, name) == 0) return &g->ent[i]; return NULL; } int ent_add(graph_t *g, const char *name, const char *etype, char **obs, size_t n_obs, char *err, size_t errsz) { entity_t *e; size_t i, cap_obs; if (g->n_ent >= (size_t)env_int("MEMORY_MAX_ENTITIES", MAX_ENTITIES_DEFAULT, 1, 2000000)) { if (err) snprintf(err, errsz, "The graph is at its entity limit; delete entities " "before adding more."); return -1; } if (!name || !*name || strlen(name) > (size_t)SX_NAME_MAX || !etype || !*etype || strlen(etype) > (size_t)SX_TYPE_MAX) { if (err) snprintf(err, errsz, "An entity needs a non-empty name and entityType " "(each at most %d characters).", SX_NAME_MAX); return -1; } if (n_obs > (size_t)env_int("MEMORY_MAX_OBS", MAX_OBS_PER_ENT_DEFAULT, 1, 200000)) n_obs = (size_t)env_int("MEMORY_MAX_OBS", MAX_OBS_PER_ENT_DEFAULT, 1, 200000); if (g->n_ent == g->cap_ent) { size_t nc = g->cap_ent ? g->cap_ent * 2 : 32; entity_t *nv = (entity_t *)realloc(g->ent, nc * sizeof *nv); if (!nv) { if (err) snprintf(err, errsz, "out of memory"); return -1; } g->ent = nv; g->cap_ent = nc; } e = &g->ent[g->n_ent++]; memset(e, 0, sizeof *e); e->name = dup_or_empty(name); e->etype = dup_or_empty(etype); if (!e->name || !e->etype) { if (err) snprintf(err, errsz, "out of memory"); return -1; } cap_obs = n_obs; if (cap_obs) { e->obs = (char **)calloc(cap_obs, sizeof *e->obs); if (!e->obs) { if (err) snprintf(err, errsz, "out of memory"); return -1; } for (i = 0; i < cap_obs; i++) { e->obs[i] = dup_or_empty(obs[i] ? obs[i] : ""); if (!e->obs[i]) { if (err) snprintf(err, errsz, "out of memory"); return -1; } } e->n_obs = cap_obs; } return 0; } int rel_add(graph_t *g, const char *from, const char *to, const char *rtype, char *err, size_t errsz) { relation_t *r; if (g->n_rel >= (size_t)env_int("MEMORY_MAX_RELATIONS", MAX_RELATIONS_DEFAULT, 1, 4000000)) { if (err) snprintf(err, errsz, "The graph is at its relation limit; delete " "relations before adding more."); return -1; } if (!from || !*from || !to || !*to || !rtype || !*rtype || strlen(from) > (size_t)SX_NAME_MAX || strlen(to) > (size_t)SX_NAME_MAX || strlen(rtype) > (size_t)SX_TYPE_MAX) { if (err) snprintf(err, errsz, "A relation needs non-empty from, to and " "relationType fields."); return -1; } if (g->n_rel == g->cap_rel) { size_t nc = g->cap_rel ? g->cap_rel * 2 : 64; relation_t *nv = (relation_t *)realloc(g->rel, nc * sizeof *nv); if (!nv) { if (err) snprintf(err, errsz, "out of memory"); return -1; } g->rel = nv; g->cap_rel = nc; } r = &g->rel[g->n_rel++]; memset(r, 0, sizeof *r); r->from = dup_or_empty(from); r->to = dup_or_empty(to); r->rtype = dup_or_empty(rtype); if (!r->from || !r->to || !r->rtype) { if (err) snprintf(err, errsz, "out of memory"); return -1; } return 0; } void bad_add(graph_t *g, const char *line) { size_t cap = (size_t)env_int("MEMORY_MAX_BAD", 5000, 1, 200000); if (g->n_bad >= cap) { g->truncated = 1; return; } if (g->n_bad == g->cap_bad) { size_t nc = g->cap_bad ? g->cap_bad * 2 : 16; char **nv = (char **)realloc(g->bad, nc * sizeof *nv); if (!nv) return; g->bad = nv; g->cap_bad = nc; } g->bad[g->n_bad++] = dup_or_empty(line); } int obs_push(entity_t *e, const char *text) { char *d; char **nv; size_t cap = (size_t)env_int("MEMORY_MAX_OBS", MAX_OBS_PER_ENT_DEFAULT, 1, 200000); if (e->n_obs >= cap) return 0; d = dup_or_empty(text ? text : ""); if (!d) return 0; nv = (char **)realloc(e->obs, (e->n_obs + 1) * sizeof *e->obs); if (!nv) { free(d); return 0; } e->obs = nv; e->obs[e->n_obs++] = d; return 1; } int str_arr_from(yyjson_val *arr, char ***out, size_t *n_out, size_t cap) { char **v = NULL; size_t n = 0, i, max; *out = NULL; *n_out = 0; if (!arr || !yyjson_is_arr(arr)) return 0; max = yyjson_arr_size(arr); if (max > cap) max = cap; if (max == 0) return 0; v = (char **)calloc(max, sizeof *v); if (!v) return -1; for (i = 0; i < max; i++) { yyjson_val *it = yyjson_arr_get(arr, i); const char *s; if (!it || !yyjson_is_str(it)) continue; s = yyjson_get_str(it); if (!s || strlen(s) > (size_t)OBS_TEXT_MAX) continue; v[n] = dup_or_empty(s); if (v[n]) n++; } *out = v; *n_out = n; return 0; } /* ------------------------------------------------------------------ */ /* Load */ /* ------------------------------------------------------------------ */ /* One JSONL line into the graph. 0 = understood, -1 = keep verbatim. */ static int load_line(graph_t *g, const char *line) { yyjson_doc *doc; yyjson_val *root, *type, *v; const char *ty; int rc = -1; while (*line == ' ' || *line == '\t' || *line == '\r') line++; if (!*line) return 0; /* blank: not data */ doc = yyjson_read(line, strlen(line), 0); if (!doc) return -1; root = yyjson_doc_get_root(doc); if (!root || !yyjson_is_obj(root)) { yyjson_doc_free(doc); return -1; } type = yyjson_obj_get(root, "type"); ty = (type && yyjson_is_str(type)) ? yyjson_get_str(type) : NULL; if (ty && strcmp(ty, "entity") == 0) { v = yyjson_obj_get(root, "name"); if (yyjson_is_str(v)) { yyjson_val *nmv = v; yyjson_val *et = yyjson_obj_get(root, "entityType"); yyjson_val *ob = yyjson_obj_get(root, "observations"); if (yyjson_is_str(et) && yyjson_is_arr(ob)) { char **obs = NULL; size_t n_obs = 0, i; char err[128]; if (str_arr_from(ob, &obs, &n_obs, (size_t)MAX_OBS_PER_ENT_DEFAULT) == 0) { if (ent_add(g, yyjson_get_str(nmv), yyjson_get_str(et), obs, n_obs, err, sizeof err) == 0) rc = 0; for (i = 0; i < n_obs; i++) free(obs[i]); free(obs); } } } } else if (ty && strcmp(ty, "relation") == 0) { yyjson_val *f = yyjson_obj_get(root, "from"); yyjson_val *t = yyjson_obj_get(root, "to"); yyjson_val *r = yyjson_obj_get(root, "relationType"); if (yyjson_is_str(f) && yyjson_is_str(t) && yyjson_is_str(r)) { char err[128]; if (rel_add(g, yyjson_get_str(f), yyjson_get_str(t), yyjson_get_str(r), err, sizeof err) == 0) rc = 0; } } yyjson_doc_free(doc); return rc; } int graph_load(void) { char *text; size_t len, i, start; graph_t ng; graph_clear(&G); g_data_err[0] = '\0'; if (!ensure_path()) return -1; memset(&ng, 0, sizeof ng); text = read_file_all(g_path, &len); if (!text) { if (file_exists_p(g_path)) { snprintf(g_data_err, sizeof g_data_err, "cannot read the graph file (permission, or larger " "than %d MB)", (int)(FILE_MAX / (1024 * 1024))); return -1; } G = ng; /* no file yet: empty */ return 0; } i = 0; while (i <= len) { start = i; while (i < len && text[i] != '\n') i++; text[i] = '\0'; if (load_line(&ng, text + start) != 0) bad_add(&ng, text + start); i++; } free(text); G = ng; return 0; } /* ------------------------------------------------------------------ */ /* Save */ /* ------------------------------------------------------------------ */ static int write_over(const char *path, const char *data, size_t len, char *err, size_t errsz) { char tmp[PATH_SZ + SUFFIX_SZ]; FILE *f; int mode = -1; struct stat st; if (err && errsz) err[0] = '\0'; if (stat(path, &st) == 0 && S_ISREG(st.st_mode)) mode = (int)(st.st_mode & 0777); snprintf(tmp, sizeof tmp, "%s.tmp.%ld", path, (long) #if defined(_WIN32) GetCurrentProcessId() #else (long)getpid() #endif ); f = fopen(tmp, "wb"); if (!f) { if (err) snprintf(err, errsz, "cannot create a temp file beside %s", path); return -1; } if (len && fwrite(data, 1, len, f) != len) { fclose(f); #if defined(_WIN32) _unlink(tmp); #else unlink(tmp); #endif if (err) snprintf(err, errsz, "the graph is too large to write"); return -1; } if (fflush(f) != 0) { fclose(f); #if defined(_WIN32) _unlink(tmp); #else unlink(tmp); #endif if (err) snprintf(err, errsz, "cannot flush the graph to disk"); return -1; } #if !defined(_WIN32) (void)fsync(fileno(f)); #endif fclose(f); /* rename() gives the new file the process umask; restore the operator's * own bits so a 0600 graph does not come back world-readable. */ if (mode >= 0) { #if !defined(_WIN32) (void)chmod(tmp, (mode_t)mode); #else (void)_chmod(tmp, (mode_t)mode); #endif } #if defined(_WIN32) if (!MoveFileExA(tmp, path, MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)) { _unlink(tmp); if (err) snprintf(err, errsz, "cannot replace the graph file"); return -1; } #else if (rename(tmp, path) != 0) { unlink(tmp); if (err) snprintf(err, errsz, "cannot replace the graph file"); return -1; } #endif return 0; } int graph_save(char *err, size_t errsz) { buf_t b; size_t i, j; int rc; if (!ensure_path()) { snprintf(err, errsz, "%s", g_data_err[0] ? g_data_err : "the graph file is not reachable"); return -1; } buf_init(&b); for (i = 0; i < G.n_ent; i++) { buf_puts(&b, "{\"type\":\"entity\",\"name\":"); json_str(&b, G.ent[i].name); buf_puts(&b, ",\"entityType\":"); json_str(&b, G.ent[i].etype); buf_puts(&b, ",\"observations\":["); for (j = 0; j < G.ent[i].n_obs; j++) { if (j) buf_putc(&b, ','); json_str(&b, G.ent[i].obs[j] ? G.ent[i].obs[j] : ""); } buf_puts(&b, "]}\n"); } for (i = 0; i < G.n_rel; i++) { buf_puts(&b, "{\"type\":\"relation\",\"from\":"); json_str(&b, G.rel[i].from); buf_puts(&b, ",\"to\":"); json_str(&b, G.rel[i].to); buf_puts(&b, ",\"relationType\":"); json_str(&b, G.rel[i].rtype); buf_puts(&b, "}\n"); } /* Unreadable lines last, byte for byte, so a round trip is lossless. */ for (i = 0; i < G.n_bad; i++) { buf_puts(&b, G.bad[i] ? G.bad[i] : ""); buf_putc(&b, '\n'); } rc = write_over(g_path, buf_str(&b), b.n, err, errsz); buf_free(&b); return rc; }