/* The inbox: accepting a message (the sender) and delivering it (the * conversation's worker). See inbox.h and docs/design/grapevine.md. */ #include #include #include #include #include #include #include #include #include #include #include #include "commands.h" #include "events.h" #include "inbox.h" #include "libfossil.h" #include "net.h" #include "platform.h" static long long inbox_now_ms(void) { return (long long)(pic_platform_get()->wall_ns() / 1000000); } static int inbox_fail(pic_store *s, int rc, const char *msg) { (void)snprintf(s->err, sizeof s->err, "%s", msg); return rc; } static int inbox_sql_fail(pic_store *s) { (void)snprintf(s->err, sizeof s->err, "sql: %s", sqlite3_errmsg(s->db)); return -1; } /* ---- the bell ------------------------------------------------------------- */ /* The counter in a bell file, 0 when it has none. */ static long long inbox_bell_read(const char *path) { char buf[32] = ""; int fd = open(path, O_RDONLY | O_CLOEXEC | O_NOFOLLOW); long long n = 0; if (fd >= 0) { ssize_t got = read(fd, buf, sizeof buf - 1); close(fd); n = got > 0 ? strtoll(buf, NULL, 10) : 0; } return n; } /* Creates SESSION's bell (and the lease directory) when missing; when RING, * adds one to its counter, rewritten in place. Advisory: a failure only * leaves the message to the worker's next look. */ static void inbox_bell(pic_store *s, const char *session, int ring, char *path, size_t cap) { char buf[32]; int fd; if (pic_bell_path(s, session, path, cap) != 0) { path[0] = '\0'; return; } if (pic_platform_get() != pic_platform_host()) { return; } (void)mkdir(s->lease_dir, 0700); fd = open(path, O_RDWR | O_CREAT | O_CLOEXEC | O_NOFOLLOW, 0600); /* a planted link is not followed */ if (fd < 0) { return; } if (ring) { ssize_t got = pread(fd, buf, sizeof buf - 1, 0); long long n; int len; buf[got > 0 ? got : 0] = '\0'; n = strtoll(buf, NULL, 10) + 1; len = snprintf(buf, sizeof buf, "%020lld\n", n); /* one width: rewritten in place */ if (pwrite(fd, buf, (size_t)len, 0) != len) { (void)ftruncate(fd, 0); } } close(fd); } /* ---- accepting -------------------------------------------------------------- */ /* A message's identity: its conversation, sender and command, so a key * reused for any other is a conflict, never a retry. */ static void inbox_hash(const char *session, const char *sender, const char *line, char out[65]) { fsl_sha3_cx cx; fsl_sha3_init2(&cx, FSL_SHA3_256); fsl_sha3_update(&cx, session, (unsigned)strlen(session) + 1); /* each with its NUL, so no two split alike */ fsl_sha3_update(&cx, sender, (unsigned)strlen(sender) + 1); fsl_sha3_update(&cx, line, (unsigned)strlen(line)); fsl_sha3_end(&cx); (void)snprintf(out, 65, "%s", (const char *)cx.hex); } static int inbox_random_key(char *out, size_t cap) { unsigned char raw[16]; if (cap < 33 || pic_platform_get()->entropy(raw, sizeof raw) != 0) { return -1; } for (size_t i = 0; i < sizeof raw; i++) { (void)snprintf(out + 2 * i, 3, "%02x", raw[i]); } return 0; } /* The command's type when the inbox takes it (steer and follow_up with a * string message, abort), else NULL with s->err. */ static const char *inbox_type(pic_store *s, const char *line) { sqlite3_stmt *q = NULL; const char *type = NULL; if (sqlite3_prepare_v2(s->db, "SELECT json_valid(?1) AND json_type(?1) = 'object', CASE WHEN json_valid(?1) THEN" " json_extract(?1, '$.type') END, CASE WHEN json_valid(?1) THEN json_type(?1, '$.message') END", -1, &q, NULL) != SQLITE_OK) { (void)inbox_sql_fail(s); return NULL; } sqlite3_bind_text(q, 1, line, -1, SQLITE_STATIC); if (sqlite3_step(q) == SQLITE_ROW) { const char *t = (const char *)sqlite3_column_text(q, 1), *m = (const char *)sqlite3_column_text(q, 2); if (!sqlite3_column_int(q, 0)) { (void)inbox_fail(s, 0, "the command is not a JSON object"); } else if (t && (strcmp(t, "steer") == 0 || strcmp(t, "follow_up") == 0)) { type = strcmp(t, "steer") == 0 ? "steer" : "follow_up"; if (!m || strcmp(m, "text") != 0) { type = NULL; (void)inbox_fail(s, 0, "message must be a string"); } } else if (t && strcmp(t, "abort") == 0) { type = "abort"; } else { (void)snprintf(s->err, sizeof s->err, "the inbox takes steer, follow_up and abort, not %.60s", t ? t : "(no type)"); } } sqlite3_finalize(q); return type; } static int inbox_int(pic_store *s, const char *sql, const char *text, long long *out) { sqlite3_stmt *q = NULL; int rc; *out = 0; if (sqlite3_prepare_v2(s->db, sql, -1, &q, NULL) != SQLITE_OK) { return inbox_sql_fail(s); } sqlite3_bind_text(q, 1, text, -1, SQLITE_STATIC); rc = sqlite3_step(q); if (rc == SQLITE_ROW) { *out = sqlite3_column_int64(q, 0); } sqlite3_finalize(q); return rc == SQLITE_ROW || rc == SQLITE_DONE ? 0 : inbox_sql_fail(s); } int pic_inbox_accept(pic_store *s, const pic_inbox_msg *m, char *key, size_t key_cap, char *state, size_t state_cap) { sqlite3_stmt *q = NULL; const char *type; char hash[65], path[4096]; long long expires_s = m->expires_s, exists = 0, rows = 0, bytes = 0, target = 0, now = inbox_now_ms(); int rc; s->err[0] = '\0'; if (strlen(m->line) > PIC_INBOX_LINE_CAP) { return inbox_fail(s, 1, "the command is longer than 16 MB"); } if (!(type = inbox_type(s, m->line))) { return s->err[0] && strncmp(s->err, "sql:", 4) == 0 ? -1 : 1; } if (expires_s < 0 || expires_s > PIC_INBOX_MAX_SECONDS) { return inbox_fail(s, 1, "--expires is 1 to 604800 seconds"); } if (expires_s == 0) { expires_s = strcmp(type, "follow_up") == 0 ? PIC_INBOX_FOLLOW_UP_SECONDS : PIC_INBOX_STEER_SECONDS; } if (m->key) { if (!*m->key || strlen(m->key) >= key_cap || strlen(m->key) > 200) { return inbox_fail(s, 1, "a key is 1 to 200 bytes"); } (void)snprintf(key, key_cap, "%s", m->key); } else if (inbox_random_key(key, key_cap) != 0) { return inbox_fail(s, -1, "cannot draw a key"); } inbox_hash(m->session, m->sender, m->line, hash); if (pic_begin(s) != 0) { return -1; } /* A known key: the same command is a retry, another a conflict. */ if (sqlite3_prepare_v2(s->db, "SELECT command_hash, state FROM pic_inbox WHERE msg_key = ?", -1, &q, NULL) != SQLITE_OK) { rc = inbox_sql_fail(s); pic_rollback(s); return rc; } sqlite3_bind_text(q, 1, key, -1, SQLITE_STATIC); if (sqlite3_step(q) == SQLITE_ROW) { int same = strcmp((const char *)sqlite3_column_text(q, 0), hash) == 0; (void)snprintf(state, state_cap, "%s", (const char *)sqlite3_column_text(q, 1)); sqlite3_finalize(q); pic_rollback(s); if (!same) { (void)snprintf(s->err, sizeof s->err, "key %.200s was used for another command", key); /* or conversation */ return 1; } return 0; } sqlite3_finalize(q); if (inbox_int(s, "SELECT count(*) FROM pic_session WHERE id = ?", m->session, &exists) != 0 || inbox_int(s, "SELECT count(*) FROM pic_inbox WHERE session_id = ? AND state = 'pending'", m->session, &rows) != 0 || inbox_int(s, "SELECT coalesce(sum(length(CAST(command AS BLOB))), 0) FROM pic_inbox WHERE session_id = ? AND state = 'pending'", m->session, &bytes) != 0 || (strcmp(type, "abort") == 0 && inbox_int(s, "SELECT coalesce(max(id), 0) FROM pic_submission WHERE session_id = ? AND status = 'admitted'", m->session, &target) != 0)) { pic_rollback(s); return -1; } if (!exists || rows >= PIC_INBOX_PENDING_ROWS || bytes + (long long)strlen(m->line) > PIC_INBOX_PENDING_BYTES) { pic_rollback(s); if (!exists) { (void)snprintf(s->err, sizeof s->err, "no conversation %.64s", m->session); } else { (void)snprintf(s->err, sizeof s->err, "the inbox of %.64s is full (%d messages or 64 MB waiting)", m->session, PIC_INBOX_PENDING_ROWS); } return 1; } /* An abort sent while nothing runs can never run: settled at once. */ if (sqlite3_prepare_v2(s->db, "INSERT INTO pic_inbox(msg_key, command_hash, session_id, sender, command, hops, target, created_ms," " expires_ms, state, response, settled_ms) VALUES (?1, ?2, ?3, ?4, ?5, 0, nullif(?6, 0), ?7, ?8," " iif(?9, 'refused', 'pending'), CASE WHEN ?9 THEN json_patch('{}', json_object('id', CASE WHEN" " json_type(?5, '$.id') IS NOT NULL THEN json_extract(?5, '$.id') END, 'type', 'response', 'command'," " 'abort', 'success', json('false'), 'error', 'nothing to abort: no request is running')) END," " CASE WHEN ?9 THEN ?7 END)", -1, &q, NULL) != SQLITE_OK) { rc = inbox_sql_fail(s); pic_rollback(s); return rc; } sqlite3_bind_text(q, 1, key, -1, SQLITE_STATIC); sqlite3_bind_text(q, 2, hash, -1, SQLITE_STATIC); sqlite3_bind_text(q, 3, m->session, -1, SQLITE_STATIC); sqlite3_bind_text(q, 4, m->sender, -1, SQLITE_STATIC); sqlite3_bind_text(q, 5, m->line, -1, SQLITE_STATIC); sqlite3_bind_int64(q, 6, target); sqlite3_bind_int64(q, 7, now); sqlite3_bind_int64(q, 8, now + expires_s * 1000); sqlite3_bind_int(q, 9, strcmp(type, "abort") == 0 && target == 0); rc = sqlite3_step(q); sqlite3_finalize(q); if (rc != SQLITE_DONE) { rc = inbox_sql_fail(s); pic_rollback(s); return rc; } pic_fault("inbox_accept"); if (pic_commit(s) != 0) { pic_rollback(s); return -1; } pic_fault("inbox_accept"); (void)snprintf(state, state_cap, "%s", strcmp(type, "abort") == 0 && target == 0 ? "refused" : "pending"); inbox_bell(s, m->session, 1, path, sizeof path); return 0; } int pic_inbox_status(pic_store *s, const char *key, char *state, size_t cap, char **response) { sqlite3_stmt *q = NULL; int rc; if (response) { *response = NULL; } if (sqlite3_prepare_v2(s->db, "SELECT state, response FROM pic_inbox WHERE msg_key = ?", -1, &q, NULL) != SQLITE_OK) { return inbox_sql_fail(s); } sqlite3_bind_text(q, 1, key, -1, SQLITE_STATIC); rc = sqlite3_step(q); if (rc == SQLITE_ROW) { (void)snprintf(state, cap, "%s", (const char *)sqlite3_column_text(q, 0)); if (response && sqlite3_column_text(q, 1)) { *response = strdup((const char *)sqlite3_column_text(q, 1)); } } sqlite3_finalize(q); return rc == SQLITE_ROW ? 0 : rc == SQLITE_DONE ? 1 : inbox_sql_fail(s); } /* ---- delivering ------------------------------------------------------------- */ /* The watch: a thread waits on the bell (the platform's watch, or a stat * every 200 ms where there is none, and every 30 s regardless) and writes a * byte to a pipe whose read end is pic_watch_fd, which every wait polls. */ static struct { pic_store *s; char session[64]; char bell[4096]; int pipe[2]; pthread_t thread; int running; atomic_int stop; } inbox_w = {.pipe = {-1, -1}}; static void *inbox_watch_main(void *arg) { const pic_platform *p = pic_platform_get(); int fd = p->watch ? p->watch(inbox_w.bell) : -1, ticks = 0; long long last = fd < 0 ? inbox_bell_read(inbox_w.bell) : 0; (void)arg; while (!atomic_load(&inbox_w.stop)) { int ring = 0; if (fd >= 0) { struct pollfd w = {fd, POLLIN, 0}; if (poll(&w, 1, 200) > 0) { if (p->watch_clear) { p->watch_clear(fd); } ring = 1; } } else { struct timespec ts = {0, 200000000L}; long long now; (void)nanosleep(&ts, NULL); now = inbox_bell_read(inbox_w.bell); ring = now != last; /* the counter, not the mtime: two rings in one tick are two */ last = now; } if (++ticks >= 150) { /* 30 s: a sender that died before its ring */ ring = 1; } if (ring) { ticks = 0; (void)write(inbox_w.pipe[1], "b", 1); /* a full pipe already says it */ } } if (fd >= 0) { if (p->watch_end) { p->watch_end(fd); } else { close(fd); } } return NULL; } static void inbox_watch_ready(void) { char buf[64]; while (read(inbox_w.pipe[0], buf, sizeof buf) > 0) { } if (inbox_w.s) { pic_inbox_poll(inbox_w.s); } } void pic_inbox_stop(void) { if (inbox_w.running) { atomic_store(&inbox_w.stop, 1); (void)pthread_join(inbox_w.thread, NULL); inbox_w.running = 0; } for (int i = 0; i < 2; i++) { if (inbox_w.pipe[i] >= 0) { close(inbox_w.pipe[i]); inbox_w.pipe[i] = -1; } } if (pic_watch_ready == inbox_watch_ready) { pic_watch_fd = -1; pic_watch_ready = NULL; } inbox_w.s = NULL; inbox_w.session[0] = '\0'; } static void inbox_watch(pic_store *s, const char *session) { if (inbox_w.s == s && strcmp(inbox_w.session, session) == 0) { return; } pic_inbox_stop(); inbox_w.s = s; (void)snprintf(inbox_w.session, sizeof inbox_w.session, "%s", session); if (pic_platform_get() != pic_platform_host()) { return; /* no other process to hear from */ } inbox_bell(s, session, 0, inbox_w.bell, sizeof inbox_w.bell); if (!inbox_w.bell[0] || pipe(inbox_w.pipe) != 0) { inbox_w.pipe[0] = inbox_w.pipe[1] = -1; return; } for (int i = 0; i < 2; i++) { (void)fcntl(inbox_w.pipe[i], F_SETFD, FD_CLOEXEC); (void)fcntl(inbox_w.pipe[i], F_SETFL, O_NONBLOCK); } atomic_store(&inbox_w.stop, 0); if (pthread_create(&inbox_w.thread, NULL, inbox_watch_main, NULL) != 0) { return; /* turn boundaries still deliver */ } inbox_w.running = 1; pic_watch_fd = inbox_w.pipe[0]; pic_watch_ready = inbox_watch_ready; } /* The response line commands.c gives a delivered command. */ static void inbox_take(void *ctx, const char *response) { char **out = ctx; if (!*out) { *out = strdup(response); } } /* Inside the delivery's transaction: settles row ID. */ static int inbox_settle(pic_store *s, long long id, const char *state, const char *response, long long queued) { sqlite3_stmt *q = NULL; int rc; if (sqlite3_get_autocommit(s->db) || s->nest != 1) { /* the delivery's transaction was lost: settle nothing */ return inbox_fail(s, -1, "the delivery's transaction ended early"); } #ifdef PIC_FAULTS if (getenv("PIC_INBOX_FAIL_SETTLE")) { /* tests: a settle that fails after the command ran */ return inbox_fail(s, -1, "settle failed (PIC_INBOX_FAIL_SETTLE)"); } #endif if (sqlite3_prepare_v2(s->db, "UPDATE pic_inbox SET state = ?2, response = ?3, queued_id = nullif(?4, 0), settled_ms = ?5" " WHERE id = ?1 AND state = 'pending'", -1, &q, NULL) != SQLITE_OK) { return inbox_sql_fail(s); } sqlite3_bind_int64(q, 1, id); sqlite3_bind_text(q, 2, state, -1, SQLITE_STATIC); sqlite3_bind_text(q, 3, response, -1, SQLITE_STATIC); sqlite3_bind_int64(q, 4, queued); sqlite3_bind_int64(q, 5, inbox_now_ms()); rc = sqlite3_step(q); sqlite3_finalize(q); if (rc != SQLITE_DONE) { return inbox_sql_fail(s); } return sqlite3_changes(s->db) == 1 ? 0 : inbox_fail(s, -1, "the message was settled by another process"); } /* Pi's response line for COMMAND: success, or an error. */ static char *inbox_response(pic_store *s, const char *line, const char *type, const char *error) { sqlite3_stmt *q = NULL; char *out = NULL; if (sqlite3_prepare_v2(s->db, "SELECT json_patch('{}', json_object('id', CASE WHEN json_valid(?1) AND json_type(?1) = 'object'" " THEN json_extract(?1, '$.id') END, 'type', 'response', 'command', ?2," " 'success', json(iif(?3 IS NULL, 'true', 'false')), 'error', ?3))", -1, &q, NULL) == SQLITE_OK) { sqlite3_bind_text(q, 1, line, -1, SQLITE_STATIC); sqlite3_bind_text(q, 2, type, -1, SQLITE_STATIC); if (error) { sqlite3_bind_text(q, 3, error, -1, SQLITE_STATIC); } if (sqlite3_step(q) == SQLITE_ROW) { out = strdup((const char *)sqlite3_column_text(q, 0)); } } sqlite3_finalize(q); return out; } /* The events a delivery makes (queue_update, a delivered message) are held * in memory while its write transaction is open, and written only once it * has committed: a slow reader of them never holds the journal's write * lock, and a rolled-back delivery shows nothing. */ typedef struct { pic_events *e; FILE *out, *notes; /* the real streams */ FILE *mem_out, *mem_notes; char *buf_out, *buf_notes; size_t len_out, len_notes; } inbox_held; static void inbox_hold(pic_store *s, inbox_held *h) { if (!s->events || h->e) { return; } h->mem_out = open_memstream(&h->buf_out, &h->len_out); h->mem_notes = s->events->notes ? open_memstream(&h->buf_notes, &h->len_notes) : NULL; if (!h->mem_out || (s->events->notes && !h->mem_notes)) { /* no memory: the events go out as they come */ if (h->mem_out) { fclose(h->mem_out); } if (h->mem_notes) { fclose(h->mem_notes); } free(h->buf_out); free(h->buf_notes); memset(h, 0, sizeof *h); return; } h->e = s->events; h->out = h->e->out; h->notes = h->e->notes; h->e->out = h->mem_out; if (h->notes) { h->e->notes = h->mem_notes; } } static void inbox_release(pic_store *s, inbox_held *h, int committed) { (void)s; if (!h->e) { return; } h->e->out = h->out; h->e->notes = h->notes; fclose(h->mem_out); if (h->mem_notes) { fclose(h->mem_notes); } if (committed) { if (h->len_out) { (void)fwrite(h->buf_out, 1, h->len_out, h->out); (void)fflush(h->out); } if (h->len_notes && h->notes) { (void)fwrite(h->buf_notes, 1, h->len_notes, h->notes); (void)fflush(h->notes); } } free(h->buf_out); free(h->buf_notes); memset(h, 0, sizeof *h); } /* One pending message of SESSION, oldest first: 1 when one was settled, 0 * when none can be now (none pending, or the first waits for a request), * -1 on an error (rolled back). */ static int inbox_deliver_one(pic_store *s, const char *session) { sqlite3_stmt *q = NULL; long long id = 0, expires = 0, target = 0, running = 0, answered = 0, before = 0, after = 0; char *line = NULL, *type = NULL, *response = NULL; const char *state = NULL; int rc = -1, abort_now = 0; int64_t running_was = s->running; inbox_held held = {0}; if (pic_begin_outer(s) != 0) { return -1; } if (sqlite3_prepare_v2(s->db, "SELECT id, command, expires_ms, coalesce(target, 0), json_extract(command, '$.type') FROM pic_inbox" " WHERE session_id = ? AND state = 'pending' ORDER BY id LIMIT 1", -1, &q, NULL) != SQLITE_OK) { (void)inbox_sql_fail(s); goto out; } sqlite3_bind_text(q, 1, session, -1, SQLITE_STATIC); if (sqlite3_step(q) == SQLITE_ROW) { id = sqlite3_column_int64(q, 0); line = strdup((const char *)sqlite3_column_text(q, 1)); expires = sqlite3_column_int64(q, 2); target = sqlite3_column_int64(q, 3); type = sqlite3_column_text(q, 4) ? strdup((const char *)sqlite3_column_text(q, 4)) : strdup(""); } sqlite3_finalize(q); if (!id) { rc = 0; goto out; } if (!line || !type) { (void)inbox_fail(s, -1, "out of memory"); goto out; } if (inbox_int(s, "SELECT coalesce(max(id), 0) FROM pic_submission WHERE session_id = ? AND status = 'admitted'", session, &running) != 0) { goto out; } if (expires <= inbox_now_ms()) { state = "expired"; response = inbox_response(s, line, type, "expired before it was delivered"); } else if (strcmp(type, "abort") == 0) { if (target && running == target) { state = "delivered"; response = inbox_response(s, line, type, NULL); abort_now = 1; } else { state = "refused"; response = inbox_response(s, line, type, "nothing to abort: the request it was sent for is not running"); } } else { /* A steer or follow-up joins the running request, or the answered * one this process just finished (its queue becomes the next). */ sqlite3_stmt *a = NULL; if (!running && sqlite3_prepare_v2(s->db, "SELECT count(*) FROM pic_submission WHERE id = ?1 AND status = 'answered'" " AND session_id = ?2", -1, &a, NULL) == SQLITE_OK) { sqlite3_bind_int64(a, 1, (sqlite3_int64)s->running); sqlite3_bind_text(a, 2, session, -1, SQLITE_STATIC); answered = sqlite3_step(a) == SQLITE_ROW ? sqlite3_column_int64(a, 0) : 0; sqlite3_finalize(a); } if ((!running && !answered) || !pic_commands_active()) { rc = 0; /* it waits for a request */ goto out; } if (inbox_int(s, "SELECT coalesce(max(id), 0) FROM pic_queued WHERE ?1 IS NOT NULL", session, &before) != 0) { goto out; } pic_commands_sink(inbox_take, &response); inbox_hold(s, &held); pic_commands_line(line); pic_commands_sink(NULL, NULL); if (inbox_int(s, "SELECT coalesce(max(id), 0) FROM pic_queued WHERE ?1 IS NOT NULL", session, &after) != 0) { goto out; } if (!response) { response = inbox_response(s, line, type, "the command was not answered"); } { long long ok = 0; if (inbox_int(s, "SELECT coalesce(json_extract(?1, '$.success'), 0)", response ? response : "{}", &ok) != 0) { goto out; } state = ok ? "delivered" : "refused"; } } if (!response) { (void)inbox_fail(s, -1, "out of memory"); goto out; } if (inbox_settle(s, id, state, response, strcmp(state, "delivered") == 0 && after > before ? after : 0) != 0) { goto out; } pic_fault("inbox_deliver"); if (pic_commit(s) != 0) { goto out; } pic_fault("inbox_deliver"); if (abort_now && !pic_interrupted) { /* Ctrl-C's cancel, at the loop's next step */ pic_interrupted = 2; } rc = 1; out: if (rc != 1) { pic_rollback(s); s->running = running_was; /* a follow-up's admitted request is gone with the rollback */ } inbox_release(s, &held, rc == 1); free(line); free(type); free(response); return rc; } void pic_inbox_poll(pic_store *s) { char sid[64] = "", saved[PIC_ERR_CAP]; sqlite3_stmt *q = NULL; int rc; if (!s->running || !s->db || !sqlite3_get_autocommit(s->db)) { return; } if (sqlite3_prepare_v2(s->db, "SELECT session_id FROM pic_submission WHERE id = ?", -1, &q, NULL) != SQLITE_OK) { return; } sqlite3_bind_int64(q, 1, (sqlite3_int64)s->running); if (sqlite3_step(q) == SQLITE_ROW && sqlite3_column_text(q, 0)) { (void)snprintf(sid, sizeof sid, "%s", (const char *)sqlite3_column_text(q, 0)); } sqlite3_finalize(q); if (!sid[0] || !pic_leased(s, sid)) { return; } inbox_watch(s, sid); (void)snprintf(saved, sizeof saved, "%s", s->err); while ((rc = inbox_deliver_one(s, sid)) == 1) { } if (rc < 0) { /* the message stays pending for the next look */ fprintf(stderr, "pic: inbox: %s\n", s->err); } (void)snprintf(s->err, sizeof s->err, "%s", saved); } /* Inside a transaction: pending rows past their expiry (KEY's alone, when * not NULL) settled as expired. Changes no request, so needs no lease; a * worker delivering reads the state again in its own transaction. */ static int inbox_expire(pic_store *s, const char *key, long long now_ms) { sqlite3_stmt *q = NULL; int rc; if (sqlite3_prepare_v2( s->db, "UPDATE pic_inbox SET state = 'expired', settled_ms = ?1, response = json_patch('{}', json_object('id'," " CASE WHEN json_valid(command) AND json_type(command) = 'object' THEN json_extract(command, '$.id') END," " 'type', 'response', 'command', json_extract(command, '$.type'), 'success', json('false')," " 'error', 'expired before it was delivered')) WHERE state = 'pending' AND expires_ms <= ?1" " AND (?2 IS NULL OR msg_key = ?2)", -1, &q, NULL) != SQLITE_OK) { return inbox_sql_fail(s); } sqlite3_bind_int64(q, 1, now_ms); if (key) { sqlite3_bind_text(q, 2, key, -1, SQLITE_STATIC); } rc = sqlite3_step(q); sqlite3_finalize(q); return rc == SQLITE_DONE ? 0 : inbox_sql_fail(s); } int pic_inbox_expire(pic_store *s, const char *key) { long long due = 0; /* A read first: a waiter polls this, and must not take the write lock to learn nothing. */ if (inbox_int(s, "SELECT count(*) FROM pic_inbox WHERE msg_key = ?1 AND state = 'pending'" " AND expires_ms <= CAST(unixepoch('subsec') * 1000 AS INTEGER)", key, &due) != 0) { return -1; } if (!due) { return 0; } if (pic_begin(s) != 0) { return -1; } if (inbox_expire(s, key, inbox_now_ms()) != 0) { pic_rollback(s); return -1; } return pic_commit(s); } int pic_inbox_retain(pic_store *s, long long now_ms) { sqlite3_stmt *q = NULL; int rc; if (pic_begin(s) != 0) { return -1; } if (inbox_expire(s, NULL, now_ms) != 0) { pic_rollback(s); return -1; } if (sqlite3_prepare_v2(s->db, "UPDATE pic_inbox SET command = NULL, response = NULL WHERE state != 'pending'" " AND command IS NOT NULL AND settled_ms <= ?1", -1, &q, NULL) != SQLITE_OK) { rc = inbox_sql_fail(s); pic_rollback(s); return rc; } sqlite3_bind_int64(q, 1, now_ms - PIC_INBOX_KEEP_MS); rc = sqlite3_step(q); sqlite3_finalize(q); if (rc != SQLITE_DONE) { rc = inbox_sql_fail(s); pic_rollback(s); return rc; } return pic_commit(s); }