Skip to content
pi-c Documentation
Login

Documentation

/* Retention: image bytes are dropped once no request will send them again,
 * or after imageRetentionDays; the row (hash, type, size) stays, so the
 * journal still says an image was there. Stored file bytes (rewind) are
 * dropped once no change or restore names them. */
#include <stdio.h>
#include <stdlib.h>

#include "pic.h"
#include "platform.h"
#include "userdb.h"

#define DAY_MS 86400000LL

/* Images with bytes that nothing live holds (?1 = 1: also those unused
 * since ?2 ms, unless a queued message holds them). An entry is live when
 * some conversation's path reaches it at or after the kept point of that
 * path's latest compaction (what PIC_CONTEXT_CTE sends); a queued message
 * while it is still queued. */
static const char prunable_sql[] =
    "WITH RECURSIVE p(sid, seq) AS (SELECT id, head_seq FROM pic_session WHERE head_seq IS NOT NULL"
    "   UNION ALL SELECT p.sid, x.parent_seq FROM pic_entry x JOIN p ON x.seq = p.seq WHERE x.parent_seq IS NOT NULL),"
    " c(sid, cseq) AS (SELECT p.sid, max(p.seq) FROM p JOIN pic_entry x ON x.seq = p.seq WHERE x.kind = 'compaction'"
    "   GROUP BY p.sid),"
    " k(sid, kept) AS (SELECT c.sid, coalesce(x.first_kept_seq, 0) FROM c JOIN pic_entry x ON x.seq = c.cseq),"
    " live(seq) AS (SELECT DISTINCT p.seq FROM p LEFT JOIN k ON k.sid = p.sid WHERE p.seq >= coalesce(k.kept, 0)),"
    " used(hash, ms, live, queued) AS ("
    "   SELECT a.image, coalesce(e.created_ms, 0), a.entry_seq IN (SELECT seq FROM live), 0"
    "     FROM pic_attachment a JOIN pic_entry e ON e.seq = a.entry_seq"
    "   UNION ALL SELECT a.image, q.created_ms, q.state = 'queued', q.state = 'queued'"
    "     FROM pic_attachment a JOIN pic_queued q ON q.id = a.queued_id)"
    " SELECT i.hash, i.sz FROM pic_image i WHERE i.data IS NOT NULL AND"
    " (NOT EXISTS (SELECT 1 FROM used u WHERE u.hash = i.hash AND u.live)"
    "  OR (?1 AND NOT EXISTS (SELECT 1 FROM used u WHERE u.hash = i.hash AND (u.queued OR u.ms >= ?2))))";

int pic_prune(pic_store *s, int dry_run, long long *count, long long *bytes) {
    sqlite3_stmt *q = NULL, *drop = NULL;
    long long now = (long long)(pic_platform_get()->wall_ns() / 1000000), days = 30;
    char *setting = pic_setting("imageRetentionDays");
    int step, rc = 0;
    *count = *bytes = 0;
    if (setting) {
        char *end;
        long long v = strtoll(setting, &end, 10);
        if (end != setting && *end == '\0' && v >= 0) {
            days = v;
        }
        free(setting);
    }
    if (pic_begin(s) != 0) {
        return -1;
    }
    if (sqlite3_prepare_v2(s->db, prunable_sql, -1, &q, NULL) != SQLITE_OK) {
        (void)snprintf(s->err, sizeof s->err, "sql: %s", sqlite3_errmsg(s->db));
        pic_rollback(s);
        return -1;
    }
    sqlite3_bind_int(q, 1, days > 0);
    sqlite3_bind_int64(q, 2, now - days * DAY_MS);
    while ((step = sqlite3_step(q)) == SQLITE_ROW) {
        ++*count;
        *bytes += sqlite3_column_int64(q, 1);
    }
    sqlite3_finalize(q);
    if (step == SQLITE_DONE && !dry_run && *count > 0) {
        char *sql = sqlite3_mprintf("UPDATE pic_image SET data = NULL WHERE hash IN (SELECT hash FROM (%s))", prunable_sql);
        if (!sql || sqlite3_prepare_v2(s->db, sql, -1, &drop, NULL) != SQLITE_OK) {
            rc = -1;
        } else {
            sqlite3_bind_int(drop, 1, days > 0);
            sqlite3_bind_int64(drop, 2, now - days * DAY_MS);
            rc = sqlite3_step(drop) == SQLITE_DONE ? 0 : -1;
        }
        sqlite3_finalize(drop);
        sqlite3_free(sql);
    }
    if (rc != 0 || step != SQLITE_DONE) {
        (void)snprintf(s->err, sizeof s->err, "prune: %s", sqlite3_errmsg(s->db));
        pic_rollback(s);
        return -1;
    }
    if (dry_run) {
        pic_rollback(s);
        return 0;
    }
    pic_fault("in-prune"); /* bytes dropped, not yet committed */
    {
        char sql[128];
        (void)snprintf(sql, sizeof sql, "INSERT OR REPLACE INTO pic_meta(key, value) VALUES('last_prune_ms', '%lld')", now);
        if (pic_exec(s, sql) != 0 || pic_commit(s) != 0) {
            pic_rollback(s);
            return -1;
        }
    }
    return 0;
}

/* Unnamed bytes stored at or before the mark (?1, a pic_blob rowid). */
#define UNNAMED(rowid_le)                                                                                              \
    "FROM pic_blob b WHERE b.rowid <= " rowid_le " AND NOT EXISTS (SELECT 1 FROM pic_file_change c"                    \
    " WHERE c.pre_hash = b.hash OR (c.restore_id IS NOT NULL AND c.post_hash = b.hash))"

static long long meta_int(pic_store *s, const char *key) {
    sqlite3_stmt *q = NULL;
    long long v = -1;
    if (sqlite3_prepare_v2(s->db, "SELECT CAST(value AS INTEGER) FROM pic_meta WHERE key = ?", -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_text(q, 1, key, -1, SQLITE_STATIC);
        if (sqlite3_step(q) == SQLITE_ROW) {
            v = sqlite3_column_int64(q, 0);
        }
    }
    sqlite3_finalize(q);
    return v;
}

int pic_prune_files(pic_store *s, int dry_run, long long *count, long long *bytes) {
    sqlite3_stmt *q = NULL;
    long long now = (long long)(pic_platform_get()->wall_ns() / 1000000), mark = meta_int(s, "blob_mark"),
              at = meta_int(s, "blob_mark_ms");
    int rc = 0;
    *count = *bytes = 0;
    if (pic_begin(s) != 0) {
        return -1;
    }
    /* Unnamed since the previous mark, which is at least an hour old: a
     * restore stores bytes in one transaction and names them in the next, and
     * is done with that in seconds (a stored blob it reuses is given a new
     * row). A first run, or a clock gone back, only sets the mark. */
    if (mark >= 0 && at >= 0 && now - at >= 3600000LL && sqlite3_prepare_v2(s->db,
            "SELECT count(*), coalesce(sum(b.sz), 0) " UNNAMED("?1"), -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_int64(q, 1, mark);
        if (sqlite3_step(q) == SQLITE_ROW) {
            *count = sqlite3_column_int64(q, 0);
            *bytes = sqlite3_column_int64(q, 1);
        }
        sqlite3_finalize(q);
        if (!dry_run && *count > 0) {
            if (sqlite3_prepare_v2(s->db, "DELETE FROM pic_blob WHERE rowid IN (SELECT b.rowid " UNNAMED("?1") ")", -1, &q,
                                   NULL) != SQLITE_OK) {
                rc = -1;
            } else {
                sqlite3_bind_int64(q, 1, mark);
                rc = sqlite3_step(q) == SQLITE_DONE ? 0 : -1;
                sqlite3_finalize(q);
            }
        }
    }
    if (rc == 0 && !dry_run && (mark < 0 || at < 0 || now - at >= 3600000LL || now < at)) {
        char sql[256];
        (void)snprintf(sql, sizeof sql,
                       "INSERT OR REPLACE INTO pic_meta(key, value) VALUES('blob_mark', (SELECT coalesce(max(rowid), 0) FROM pic_blob)),"
                       " ('blob_mark_ms', '%lld')",
                       now);
        rc = pic_exec(s, sql);
    }
    if (rc != 0 || (dry_run ? (pic_rollback(s), 0) : pic_commit(s)) != 0) {
        (void)snprintf(s->err, sizeof s->err, "prune: %s", sqlite3_errmsg(s->db));
        pic_rollback(s);
        return -1;
    }
    return 0;
}