/* Short-lived cron worker. Network work never runs in the rendering worker. */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>

#include "conf.h"
#include "db.h"
#include "timestamp.h"
#include "util.h"

static int
attempt(PGconn *pg, const struct conf *cf, PGresult *job)
{
	struct timestamp_reply reply;
	char path[700], sha[65], hex[TIMESTAMP_MAX_REPLY * 2 + 1];
	const char *p[7], *error = "document_changed";
	PGresult *res;
	size_t i;
	long timeout;
	struct timespec begin, now;
	int success = 0;

	p[0] = PQgetvalue(job, 0, 0);
	p[1] = PQgetvalue(job, 0, 1);
	p[2] = PQgetvalue(job, 0, 2);
	p[3] = PQgetvalue(job, 0, 3);
	p[4] = NULL;
	p[5] = NULL;
	if (clock_gettime(CLOCK_MONOTONIC, &begin) == -1)
		return -1;
	timeout = atol(PQgetvalue(job, 0, 4));
	if (timeout > 10000)
		timeout = 10000;
	if (is_uuid(p[0]) && snprintf(path, sizeof(path), "%s/docs/%s/final.pdf",
	    conf_get(cf, "data_dir", "/var/lib/signet"), p[0]) < (int)sizeof(path) &&
	    sha256_file(path, sha) == 0 && strcmp(sha, p[2]) == 0) {
		if (clock_gettime(CLOCK_MONOTONIC, &now) == -1)
			return -1;
		timeout -= (now.tv_sec - begin.tv_sec) * 1000 + (now.tv_nsec - begin.tv_nsec) / 1000000;
		success = timestamp_fetch(conf_get(cf, "timestamp.url", ""),
		    conf_get(cf, "timestamp.ca_file", ""),
		    conf_get(cf, "timestamp.tls_ca_file", ""), sha, timeout, &reply) == 0;
		error = reply.error;
	}
	if (success) {
		for (i = 0; i < reply.size; i++)
			snprintf(hex + i * 2, 3, "%02x", reply.data[i]);
		p[4] = hex;
		p[5] = reply.at;
	}
	p[6] = error;
	res = db_q(pg, success
	    ? "UPDATE document_timestamps t SET state='timestamped', timestamped_at=$6::timestamptz, "
	      "response=decode($5,'hex'), next_attempt_at=NULL, last_error=$7 "
	      "WHERE doc_id=$1 AND revision=$2::int AND pdf_sha256=$3 AND attempts=$4::int "
	      "AND state='pending' AND deadline>clock_timestamp() AND EXISTS "
	      "(SELECT 1 FROM documents d WHERE d.id=t.doc_id AND d.status='RELEASED' "
	      "AND d.revision=t.revision AND d.final_sha256=t.pdf_sha256) RETURNING doc_id"
	    : "UPDATE document_timestamps SET state=CASE WHEN attempts=4 OR deadline<=clock_timestamp() "
	      "THEN 'unavailable' ELSE 'pending' END, last_error=$7 "
	      "WHERE doc_id=$1 AND revision=$2::int AND pdf_sha256=$3 AND attempts=$4::int "
	      "AND $5::text IS NULL AND $6::text IS NULL AND state='pending' RETURNING doc_id",
	    7, p);
	if (res == NULL)
		return -1;
	if (!success)
		log_err("timestamp attempt failed (%s)", error);
	PQclear(res);
	return 0;
}

int
main(int argc, char **argv)
{
	struct conf cf;
	PGconn *pg;
	PGresult *job, *lock;
	struct timespec start, now;
	const char *path = CONF_PATH_DEFAULT;
	int c, n, rv = 0;

	while ((c = getopt(argc, argv, "c:")) != -1) {
		if (c != 'c')
			return 1;
		path = optarg;
	}
	log_open("signet-timestamp");
	if (conf_load(&cf, path) == -1)
		return 1;
	if (*conf_get(&cf, "timestamp.url", "") == '\0' ||
	    *conf_get(&cf, "timestamp.ca_file", "") == '\0')
		return 0;
	if ((pg = db_get(&cf)) == NULL || clock_gettime(CLOCK_MONOTONIC, &start) == -1)
		return 1;
	/* One cron runner per database, including overlapping/restarted invocations.
	 * Session lock disappears on crash; no document row is held over HTTPS. */
	lock = db_q(pg, "SELECT pg_try_advisory_lock(1936289381,1953721965)", 0, NULL);
	if (lock == NULL)
		return 1;
	c = PQgetvalue(lock, 0, 0)[0] == 't';
	PQclear(lock);
	if (!c)
		return 0;
	/* A predecessor may have died after HTTP but before its final delay. */
	sleep(1);
	if (db_do(pg, "INSERT INTO document_timestamps "
	    "(doc_id,revision,pdf_sha256,started_at,deadline,next_attempt_at) "
	    "SELECT id,revision,final_sha256,released_at,released_at+interval '1 hour',released_at "
	    "FROM documents WHERE status='RELEASED' AND final_sha256 IS NOT NULL "
	    "AND released_at>clock_timestamp()-interval '1 hour' AND released_at<=clock_timestamp() "
	    "AND NOT EXISTS (SELECT 1 FROM document_timestamps t WHERE t.doc_id=documents.id) "
	    "ORDER BY released_at LIMIT 256 ON CONFLICT (doc_id) DO NOTHING", 0, NULL) == -1 ||
	    db_do(pg, "UPDATE document_timestamps SET state='unavailable',next_attempt_at=NULL "
	    "WHERE state='pending' AND (deadline<=clock_timestamp() OR attempts=4)", 0, NULL) == -1)
		return 1;
	for (n = 0; n < 20; n++) {
		if (clock_gettime(CLOCK_MONOTONIC, &now) == -1 || now.tv_sec - start.tv_sec >= 20)
			break;
		/* Claim/consume an attempt BEFORE I/O. Crashes cannot reset the budget.
		 * Slots are anchored to release, not to process starts or retry failures. */
		job = db_q(pg, "WITH due AS (SELECT t.doc_id FROM document_timestamps t "
		    "JOIN documents d ON d.id=t.doc_id AND d.status='RELEASED' AND d.revision=t.revision "
		    "AND d.final_sha256=t.pdf_sha256 WHERE t.state='pending' AND t.attempts<4 "
		    "AND t.next_attempt_at<=clock_timestamp() AND t.deadline>clock_timestamp() "
		    "ORDER BY t.next_attempt_at,t.doc_id LIMIT 1 FOR UPDATE OF t SKIP LOCKED) "
		    "UPDATE document_timestamps t SET attempts=attempts+1, "
		    "next_attempt_at=CASE t.attempts "
		    "WHEN 0 THEN greatest(started_at+interval '5 minutes',clock_timestamp()+interval '1 minute') "
		    "WHEN 1 THEN greatest(started_at+interval '20 minutes',clock_timestamp()+interval '1 minute') "
		    "WHEN 2 THEN greatest(started_at+interval '55 minutes',clock_timestamp()+interval '1 minute') "
		    "ELSE NULL END FROM due WHERE t.doc_id=due.doc_id "
		    "RETURNING t.doc_id::text,t.revision::text,t.pdf_sha256,t.attempts::text, "
		    "floor(extract(epoch FROM t.deadline-clock_timestamp())*1000)::bigint::text", 0, NULL);
		if (job == NULL) {
			rv = 1;
			break;
		}
		if (PQntuples(job) == 0) {
			PQclear(job);
			break;
		}
		if (attempt(pg, &cf, job) == -1)
			rv = 1;
		PQclear(job);
		if (rv != 0)
			break;
		sleep(1); /* At most one request/second, including quick failures. */
	}
	return rv;
}
