Skip to content
pi-c Documentation
Login

Documentation

/* Asks: see ask.h and docs/dev/asks.md. Core: the record, the one answer, the wait. */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

#include "ask.h"
#include "net.h"
#include "platform.h"
#include "wake.h"

static long long ask_now_ms(void) { return pic_wake_now_ms(); }

static int ask_sql_fail(pic_store *s) {
    (void)snprintf(s->err, sizeof s->err, "sql: %s", sqlite3_errmsg(s->db));
    return -1;
}

static int ask_fail(pic_store *s, int rc, const char *msg) {
    (void)snprintf(s->err, sizeof s->err, "%s", msg);
    return rc;
}

/* Whether this journal has asks at all: a journal no pic of this version opened fully has none. */
static int ask_table(pic_store *s) {
    sqlite3_stmt *q = NULL;
    int has = 0;
    if (sqlite3_prepare_v2(s->db, "SELECT 1 FROM sqlite_schema WHERE type = 'table' AND name = 'pic_ask'", -1, &q, NULL) == SQLITE_OK) {
        has = sqlite3_step(q) == SQLITE_ROW;
    }
    sqlite3_finalize(q);
    return has;
}

/* The next version: every open and close of an ask takes one, so a reader follows them by index. */
#define ASK_NEXT_VERSION "(SELECT coalesce(max(version), 0) + 1 FROM pic_ask)"

int pic_ask_open(pic_store *s, const pic_ask_new *a, long long *id) {
    sqlite3_stmt *q = NULL;
    char sid[64] = "";
    long long now = ask_now_ms();
    int rc;
    const char *kind = a->kind ? a->kind : "";
    *id = 0;
    if (!a->key || !*a->key || strlen(a->key) > 200) {
        return ask_fail(s, 1, "an ask needs a key");
    }
    if (strcmp(kind, "confirm") != 0 && strcmp(kind, "select") != 0 && strcmp(kind, "input") != 0) {
        return ask_fail(s, 1, "an ask is a confirm, a select or an input");
    }
    if (!a->title || !*a->title || strlen(a->title) > PIC_ASK_TEXT_CAP || (a->body && strlen(a->body) > PIC_ASK_TEXT_CAP) ||
        (a->placeholder && strlen(a->placeholder) > PIC_ASK_TEXT_CAP)) {
        return ask_fail(s, 1, "an ask needs a title, and its texts are at most 4000 bytes");
    }
    if (!ask_table(s)) {
        return ask_fail(s, 1, "this journal keeps no asks: a pic of this version has not opened it");
    }
    if (pic_begin(s) != 0) {
        return -1;
    }
    if (sqlite3_prepare_v2(s->db, "SELECT id FROM pic_ask WHERE ask_key = ?1", -1, &q, NULL) != SQLITE_OK) {
        rc = ask_sql_fail(s);
        pic_rollback(s);
        return rc;
    }
    sqlite3_bind_text(q, 1, a->key, -1, SQLITE_STATIC);
    if (sqlite3_step(q) == SQLITE_ROW) {
        *id = sqlite3_column_int64(q, 0);
    }
    sqlite3_finalize(q);
    q = NULL;
    if (*id) { /* asked already: the same question */
        return pic_commit(s) == 0 ? 0 : (pic_rollback(s), -1);
    }
    if (pic_session_resolve(s, a->session, sid, sizeof sid) != 0) {
        pic_rollback(s);
        return 1;
    }
    /* a select's options: a JSON array of one to 32 strings, none empty or too long */
    if (sqlite3_prepare_v2(s->db,
                           "INSERT INTO pic_ask(ask_key, session_id, kind, title, body, spec, created_ms, expires_ms, state, version)"
                           " SELECT ?1, ?2, ?3, ?4, nullif(?5, ''), CASE ?3 WHEN 'select' THEN json_object('options', json(?6))"
                           " WHEN 'input' THEN iif(?7 IS NULL, NULL, json_object('placeholder', ?7)) END, ?8, ?9, 'open', " ASK_NEXT_VERSION
                           " WHERE ?3 != 'select' OR (json_valid(?6) AND json_type(?6) = 'array' AND json_array_length(?6) BETWEEN 1 AND 32"
                           " AND NOT EXISTS (SELECT 1 FROM json_each(?6) WHERE type != 'text' OR length(value) = 0 OR length(CAST(value AS BLOB)) > 4000))",
                           -1, &q, NULL) != SQLITE_OK) {
        rc = ask_sql_fail(s);
        pic_rollback(s);
        return rc;
    }
    sqlite3_bind_text(q, 1, a->key, -1, SQLITE_STATIC);
    sqlite3_bind_text(q, 2, sid, -1, SQLITE_STATIC);
    sqlite3_bind_text(q, 3, kind, -1, SQLITE_STATIC);
    sqlite3_bind_text(q, 4, a->title, -1, SQLITE_STATIC);
    sqlite3_bind_text(q, 5, a->body ? a->body : "", -1, SQLITE_STATIC);
    sqlite3_bind_text(q, 6, a->options ? a->options : "null", -1, SQLITE_STATIC);
    if (a->placeholder) {
        sqlite3_bind_text(q, 7, a->placeholder, -1, SQLITE_STATIC);
    }
    sqlite3_bind_int64(q, 8, now);
    sqlite3_bind_int64(q, 9, a->expires_ms > 0 ? a->expires_ms : now + PIC_ASK_EXPIRY_MS);
    rc = sqlite3_step(q);
    sqlite3_finalize(q);
    if (rc != SQLITE_DONE) {
        rc = ask_sql_fail(s);
        pic_rollback(s);
        return rc;
    }
    if (sqlite3_changes(s->db) == 0) {
        pic_rollback(s);
        return ask_fail(s, 1, "a select needs one to 32 options, each a string that is not empty");
    }
    *id = sqlite3_last_insert_rowid(s->db);
    if (pic_commit(s) != 0) {
        pic_rollback(s);
        return -1;
    }
    return 0;
}

int pic_ask_state(pic_store *s, long long id, char *state, size_t cap, char **value) {
    sqlite3_stmt *q = NULL;
    int rc;
    state[0] = '\0';
    if (value) {
        *value = NULL;
    }
    if (sqlite3_prepare_v2(s->db,
                           "SELECT iif(state = 'open' AND expires_ms <= ?2, 'expired', state), answer FROM pic_ask WHERE id = ?1", -1,
                           &q, NULL) != SQLITE_OK) {
        return ask_table(s) ? ask_sql_fail(s) : 0;
    }
    sqlite3_bind_int64(q, 1, id);
    sqlite3_bind_int64(q, 2, ask_now_ms());
    rc = sqlite3_step(q);
    if (rc == SQLITE_ROW) {
        (void)snprintf(state, cap, "%s", (const char *)sqlite3_column_text(q, 0));
        if (value && sqlite3_column_type(q, 1) != SQLITE_NULL) {
            *value = strdup((const char *)sqlite3_column_text(q, 1));
        }
    }
    sqlite3_finalize(q);
    return rc == SQLITE_ROW || rc == SQLITE_DONE ? 0 : ask_sql_fail(s);
}

int pic_ask_wait(pic_store *s, long long id, char *state, size_t cap, char **value) {
    for (;;) {
        if (pic_ask_state(s, id, state, cap, value) != 0) {
            return -1;
        }
        if (strcmp(state, "open") != 0) {
            return state[0] ? 0 : ask_fail(s, -1, "no such ask");
        }
        if (pic_interrupted) {
            return 1;
        }
        struct timespec ts = {0, 100000000L};
        (void)nanosleep(&ts, NULL);
    }
}

/* Closes KEY's open ask as TO (answered, with VALUE and BY; or withdrawn), inside a transaction. */
static int ask_close_key(pic_store *s, const char *key, const char *to, const char *value, const char *by) {
    sqlite3_stmt *q = NULL;
    int rc;
    if (!ask_table(s)) {
        return 0;
    }
    if (sqlite3_prepare_v2(s->db,
                           "UPDATE pic_ask SET state = ?2, answer = ?3, answered_by = ?4, answered_ms = iif(?3 IS NULL AND ?4 IS NULL, NULL, ?5),"
                           " version = " ASK_NEXT_VERSION " WHERE ask_key = ?1 AND state = 'open'",
                           -1, &q, NULL) != SQLITE_OK) {
        return ask_sql_fail(s);
    }
    sqlite3_bind_text(q, 1, key, -1, SQLITE_STATIC);
    sqlite3_bind_text(q, 2, to, -1, SQLITE_STATIC);
    if (value) {
        sqlite3_bind_text(q, 3, value, -1, SQLITE_STATIC);
    }
    if (by) {
        sqlite3_bind_text(q, 4, by, -1, SQLITE_STATIC);
    }
    sqlite3_bind_int64(q, 5, ask_now_ms());
    rc = sqlite3_step(q);
    sqlite3_finalize(q);
    return rc == SQLITE_DONE ? 0 : ask_sql_fail(s);
}

int pic_ask_settle(pic_store *s, const char *key, const char *value, const char *by) {
    return ask_close_key(s, key, "answered", value, by);
}

int pic_ask_withdraw(pic_store *s, const char *key) {
    if (pic_begin(s) != 0) {
        return -1;
    }
    if (ask_close_key(s, key, "withdrawn", NULL, NULL) != 0) {
        pic_rollback(s);
        return -1;
    }
    return pic_commit(s) == 0 ? 0 : (pic_rollback(s), -1);
}

/* {"state","value","answeredBy"} of ask ID, malloc'd. */
static char *ask_standing(pic_store *s, long long id) {
    sqlite3_stmt *q = NULL;
    char *out = NULL;
    if (sqlite3_prepare_v2(s->db,
                           "SELECT json_object('state', iif(state = 'open' AND expires_ms <= ?2, 'expired', state), 'value', json(answer),"
                           " 'answeredBy', answered_by) FROM pic_ask WHERE id = ?1",
                           -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_int64(q, 1, id);
        sqlite3_bind_int64(q, 2, ask_now_ms());
        if (sqlite3_step(q) == SQLITE_ROW) {
            out = strdup((const char *)sqlite3_column_text(q, 0));
        }
    }
    sqlite3_finalize(q);
    return out;
}

/* Whether ask ID was answered by BY with VALUE (the same JSON value): a retry of one's own answer. */
static int ask_mine(pic_store *s, long long id, const char *value, const char *by) {
    sqlite3_stmt *q = NULL;
    int mine = 0;
    if (sqlite3_prepare_v2(s->db,
                           "SELECT 1 FROM pic_ask WHERE id = ?1 AND state = 'answered' AND answered_by = ?2 AND json(answer) = json(?3)", -1,
                           &q, NULL) == SQLITE_OK) {
        sqlite3_bind_int64(q, 1, id);
        sqlite3_bind_text(q, 2, by, -1, SQLITE_STATIC);
        sqlite3_bind_text(q, 3, value, -1, SQLITE_STATIC);
        mine = sqlite3_step(q) == SQLITE_ROW;
    }
    sqlite3_finalize(q);
    return mine;
}

static int ask_already(pic_store *s, long long id, const char *value, const char *by, char **standing) {
    if (ask_mine(s, id, value, by)) {
        return PIC_ASK_ANSWERED;
    }
    if (standing) {
        *standing = ask_standing(s, id);
    }
    return PIC_ASK_ALREADY;
}

int pic_ask_answer(pic_store *s, long long id, const char *value, const char *by, char **standing) {
    sqlite3_stmt *q = NULL;
    char key[220] = "", kind[16] = "", state[16] = "", fit[16] = "";
    long long now = ask_now_ms();
    int rc, yes = 0;
    if (standing) {
        *standing = NULL;
    }
    if (!value || !by || !*by) {
        return ask_fail(s, PIC_ASK_REFUSED, "an answer needs a value");
    }
    if (!ask_table(s)) {
        (void)snprintf(s->err, sizeof s->err, "no ask %lld", id);
        return PIC_ASK_REFUSED;
    }
    /* What it asks, and whether VALUE answers it: "ok", "null" (a dismissal), or "" (not an answer). */
    if (sqlite3_prepare_v2(s->db,
                           "SELECT ask_key, kind, iif(state = 'open' AND expires_ms <= ?3, 'expired', state),"
                           " CASE WHEN NOT json_valid(?2) THEN '' WHEN json_type(?2) = 'null' THEN 'null'"
                           " WHEN kind = 'confirm' AND json_type(?2) IN ('true', 'false') THEN 'ok'"
                           " WHEN kind = 'input' AND json_type(?2) = 'text' AND length(CAST(json_extract(?2, '$') AS BLOB)) <= 4000 THEN 'ok'"
                           " WHEN kind = 'select' AND json_type(?2) = 'text' AND EXISTS (SELECT 1 FROM json_each(spec, '$.options') o"
                           "  WHERE o.value = json_extract(?2, '$')) THEN 'ok' ELSE '' END, json_valid(?2) AND json_type(?2) = 'true' FROM pic_ask WHERE id = ?1",
                           -1, &q, NULL) != SQLITE_OK) {
        return ask_sql_fail(s);
    }
    sqlite3_bind_int64(q, 1, id);
    sqlite3_bind_text(q, 2, value, -1, SQLITE_STATIC);
    sqlite3_bind_int64(q, 3, now);
    if (sqlite3_step(q) == SQLITE_ROW) {
        (void)snprintf(key, sizeof key, "%s", (const char *)sqlite3_column_text(q, 0));
        (void)snprintf(kind, sizeof kind, "%s", (const char *)sqlite3_column_text(q, 1));
        (void)snprintf(state, sizeof state, "%s", (const char *)sqlite3_column_text(q, 2));
        (void)snprintf(fit, sizeof fit, "%s", (const char *)sqlite3_column_text(q, 3));
        yes = sqlite3_column_int(q, 4);
    }
    sqlite3_finalize(q);
    q = NULL;
    if (!key[0]) {
        (void)snprintf(s->err, sizeof s->err, "no ask %lld", id);
        return PIC_ASK_REFUSED;
    }
    if (strcmp(state, "open") != 0) {
        return ask_already(s, id, value, by, standing);
    }
    if (!fit[0]) {
        return ask_fail(s, PIC_ASK_REFUSED,
                        strcmp(kind, "confirm") == 0  ? "a confirm is answered true or false"
                        : strcmp(kind, "select") == 0 ? "a select is answered with one of its options"
                                                      : "an input is answered with text of at most 4000 bytes");
    }
    if (strncmp(key, "wake:", 5) == 0) { /* a loop or goal the model asked for: its decision is the answer */
        if (strcmp(fit, "null") == 0) {
            return ask_fail(s, PIC_ASK_REFUSED, "a loop or goal is approved (true) or declined (false)");
        }
        rc = pic_wake_answer(s, strtoll(key + 5, NULL, 10), yes, by);
        if (rc == 0) {
            return PIC_ASK_ANSWERED;
        }
        if (rc < 0) {
            return -1;
        }
        s->err[0] = '\0';
        return ask_already(s, id, value, by, standing);
    }
    if (pic_begin(s) != 0) {
        return -1;
    }
    /* first writer wins: the row is still open inside this IMMEDIATE transaction, or it is not */
    if (sqlite3_prepare_v2(s->db,
                           "UPDATE pic_ask SET state = 'answered', answer = json(?2), answered_by = ?3, answered_ms = ?4, version = " ASK_NEXT_VERSION
                           " WHERE id = ?1 AND state = 'open' AND expires_ms > ?4",
                           -1, &q, NULL) != SQLITE_OK) {
        rc = ask_sql_fail(s);
        pic_rollback(s);
        return rc;
    }
    sqlite3_bind_int64(q, 1, id);
    sqlite3_bind_text(q, 2, value, -1, SQLITE_STATIC);
    sqlite3_bind_text(q, 3, by, -1, SQLITE_STATIC);
    sqlite3_bind_int64(q, 4, now);
    rc = sqlite3_step(q);
    sqlite3_finalize(q);
    if (rc != SQLITE_DONE) {
        rc = ask_sql_fail(s);
        pic_rollback(s);
        return rc;
    }
    if (sqlite3_changes(s->db) == 0) { /* another answer came first */
        pic_rollback(s);
        return ask_already(s, id, value, by, standing);
    }
    pic_fault("ask_answer");
    if (pic_commit(s) != 0) {
        pic_rollback(s);
        return -1;
    }
    pic_fault("ask_answer");
    return PIC_ASK_ANSWERED;
}

char *pic_ask_list(pic_store *s, const char *session, long long after, int max) {
    sqlite3_stmt *q = NULL;
    char *out = NULL;
    if (!ask_table(s)) {
        out = strdup("[]");
        if (!out) {
            (void)ask_fail(s, -1, "out of memory");
        }
        return out;
    }
    if (sqlite3_prepare_v2(
            s->db,
            "SELECT coalesce(json_group_array(json(j)), '[]') FROM (SELECT json_patch(json_object('id', a.id, 'session', a.session_id,"
            " 'kind', a.kind, 'title', a.title, 'createdMs', a.created_ms, 'expiresMs', a.expires_ms, 'state', iif(a.state = 'open'"
            " AND a.expires_ms <= ?4, 'expired', a.state), 'version', a.version), json_object('body', a.body, 'options',"
            " json_extract(a.spec, '$.options'), 'placeholder', json_extract(a.spec, '$.placeholder'), 'value', json(a.answer),"
            " 'answeredBy', a.answered_by, 'wake', CASE WHEN a.ask_key LIKE 'wake:%' THEN (SELECT upper(substr(w.kind, 1, 1)) || w.id"
            " FROM pic_wake w WHERE w.id = CAST(substr(a.ask_key, 6) AS INTEGER)) END)) AS j FROM pic_ask a"
            " WHERE (?2 < 0 AND a.state = 'open' AND a.expires_ms > ?4 AND (?1 IS NULL OR a.session_id = ?1)) OR (?2 >= 0 AND a.version > ?2)"
            " ORDER BY iif(?2 < 0, a.id, a.version) LIMIT ?3)",
            -1, &q, NULL) != SQLITE_OK) {
        (void)ask_sql_fail(s);
        return NULL;
    }
    if (session) {
        sqlite3_bind_text(q, 1, session, -1, SQLITE_STATIC);
    }
    sqlite3_bind_int64(q, 2, after);
    sqlite3_bind_int(q, 3, max > 0 ? max : 100);
    sqlite3_bind_int64(q, 4, ask_now_ms());
    if (sqlite3_step(q) == SQLITE_ROW) {
        out = strdup((const char *)sqlite3_column_text(q, 0));
    }
    if (!out) {
        (void)ask_sql_fail(s);
    }
    sqlite3_finalize(q);
    return out;
}

/* ---- the commands ---------------------------------------------------------------------- */

static int ask_rpc_open(pic_rpc_call *c, pic_store *s) {
    if (!c->db || !*c->db) {
        (void)snprintf(c->err, sizeof c->err, "no journal");
        return -1;
    }
    if (pic_open_narrow(s, c->db) != 0) {
        (void)snprintf(c->err, sizeof c->err, "%s", s->err);
        pic_close(s);
        return -1;
    }
    return 0;
}

static int rpc_get_asks(pic_rpc_call *c) {
    pic_store s;
    char *session = pic_rpc_text(c, "$.session"), *all = pic_rpc_text(c, "$.all"), *list;
    const char *which = session && *session ? session : c->session;
    int every = all && strcmp(all, "1") == 0;
    free(all);
    if ((!every && (!which || !*which)) || ask_rpc_open(c, &s) != 0) { /* nothing run here yet: none */
        free(session);
        if (c->err[0] && strncmp(c->err, "no journal", 10) != 0) {
            return -1;
        }
        c->err[0] = '\0';
        c->data = strdup("{\"asks\":[]}");
        return c->data ? 0 : -1;
    }
    list = pic_ask_list(&s, every ? NULL : which, -1, 100);
    if (!list) {
        (void)snprintf(c->err, sizeof c->err, "%s", s.err);
    } else {
        size_t n = strlen(list) + 16;
        if ((c->data = malloc(n))) {
            (void)snprintf(c->data, n, "{\"asks\":%s}", list);
        }
    }
    free(list);
    free(session);
    pic_close(&s);
    return c->data ? 0 : -1;
}

/* answer_ask {ask, value}: data {id, state: "answered"} or, when another answer stood first,
 * {id, state: "already_answered", standing}. */
static int rpc_answer_ask(pic_rpc_call *c) {
    pic_store s;
    sqlite3 *mem = NULL;
    sqlite3_stmt *q = NULL;
    char *value = NULL, *standing = NULL;
    long long id = 0;
    int rc = -1;
    if (sqlite3_open(":memory:", &mem) == SQLITE_OK &&
        sqlite3_prepare_v2(mem, "SELECT iif(json_type(?1, '$.ask') = 'integer', json_extract(?1, '$.ask'), 0), ?1 -> '$.value',"
                                " json_type(?1, '$.value') IS NOT NULL",
                           -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_text(q, 1, c->line, -1, SQLITE_STATIC);
        if (sqlite3_step(q) == SQLITE_ROW) {
            id = sqlite3_column_int64(q, 0);
            if (sqlite3_column_int(q, 2)) {
                value = strdup((const char *)sqlite3_column_text(q, 1));
            }
        }
    }
    sqlite3_finalize(q);
    sqlite3_close(mem);
    if (id <= 0 || !value) {
        free(value);
        (void)snprintf(c->err, sizeof c->err, "ask (its id, a number) and value are required");
        return -1;
    }
    if (ask_rpc_open(c, &s) != 0) {
        free(value);
        return -1;
    }
    rc = pic_ask_answer(&s, id, value, "user", &standing);
    if (rc == PIC_ASK_ANSWERED || rc == PIC_ASK_ALREADY) {
        size_t n = (standing ? strlen(standing) : 4) + 96;
        if ((c->data = malloc(n))) {
            if (rc == PIC_ASK_ANSWERED) {
                (void)snprintf(c->data, n, "{\"id\":%lld,\"state\":\"answered\"}", id);
            } else {
                (void)snprintf(c->data, n, "{\"id\":%lld,\"state\":\"already_answered\",\"standing\":%s}", id, standing ? standing : "null");
            }
        }
        rc = c->data ? 0 : -1;
    } else {
        (void)snprintf(c->err, sizeof c->err, "%s", s.err);
        rc = -1;
    }
    free(standing);
    free(value);
    pic_close(&s);
    return rc;
}

const pic_rpc_command pic_get_asks_rpc = {"get_asks", "the questions the conversation waits on a person for; all: true for every conversation's",
                                          PIC_RPC_JOURNAL_FREE | PIC_RPC_IMMEDIATE, rpc_get_asks};
const pic_rpc_command pic_answer_ask_rpc = {"answer_ask", "answer a question: ask (its id), value true or false, an option, text, or null to dismiss",
                                            PIC_RPC_JOURNAL_FREE | PIC_RPC_IMMEDIATE, rpc_answer_ask};