view scid/page-api-todo.c @ 20:f98ea578b1ef

misc: revamp database
author David Demelier <markand@malikania.fr>
date Tue, 19 Jul 2022 21:52:42 +0200
parents scid/page-api-jobs.c@600204c31bf0
children dd078aea5d02
line wrap: on
line source

/*
 * page-api-todo.c -- /api/v?/todo route
 *
 * Copyright (c) 2021 David Demelier <markand@malikania.fr>
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include <sys/types.h>
#include <assert.h>
#include <stdarg.h>
#include <stdint.h>
#include <string.h>

#include <kcgi.h>
#include <jansson.h>

#include "config.h"
#include "db.h"
#include "log.h"
#include "page-api-todo.h"
#include "page.h"
#include "types.h"
#include "util.h"

static void
list(struct kreq *r, const struct job *jobs, size_t jobsz)
{
	json_t *doc;
	char *dump;

	doc = job_to(jobs, jobsz);
	dump = json_dumps(doc, JSON_COMPACT);

	khttp_puts(r, dump);
	free(dump);
	json_decref(doc);
}

#if 0

static int
save(const char *json)
{
	struct jobresult res = {0};
	int ret = -1;

	json_t *doc;
	json_error_t err;

	if (!(doc = json_loads(json, 0, &err)))
		log_warn("api/post: invalid JSON input: %s", err.text);
	else if (jobresult_from(&res, 1, doc) < 0)
		log_warn("api/post: failed to decode parameters");
	else if (db_jobresult_add(&res) < 0)
		log_warn("api/post: database save error");
	else
		ret = 0;

	json_decref(doc);

	return ret;
}

#endif

/*
 * GET /api/v1/todo/<worker-name>
 * ----------------
 *
 * Retrieve a list of jobs to perform for this worker name.
 */
static void
get(struct kreq *r)
{
	struct job jobs[SCI_JOB_LIST_MAX];
	ssize_t jobsz;
	struct worker wk = {0};

	if (db_worker_find(&wk, util_basename(r->path)) < 0) {
		page(r, NULL, KHTTP_404, KMIME_APP_JSON, NULL);
		return;
	}

	if ((jobsz = db_job_todo(jobs, UTIL_SIZE(jobs), wk.id)) < 0)
		page(r, NULL, KHTTP_500, KMIME_APP_JSON, NULL);
	else {
		khttp_head(r, kresps[KRESP_CONTENT_TYPE], "%s", kmimetypes[KMIME_APP_JSON]);
		khttp_head(r, kresps[KRESP_STATUS], "%s", khttps[KHTTP_200]);
		khttp_body(r);
		list(r, jobs, jobsz);
		khttp_free(r);
	}

	for (ssize_t i = 0; i < jobsz; ++i)
		job_finish(&jobs[i]);
}

void
page_api_v1_jobs(struct kreq *r)
{
	assert(r);

	switch (r->method) {
	case KMETHOD_GET:
		get(r);
		break;
	default:
		page(r, NULL, KHTTP_400, KMIME_APP_JSON, NULL);
		break;
	}
}