arcology/localapi.org

510 lines
18 KiB
Org Mode

:PROPERTIES:
:ID: 20240313T153901.656967
:END:
#+TITLE: A Localhost API for the Arcology
#+FILETAGS: :Project:
#+ARCOLOGY_KEY: arcology/localapi
#+ARROYO_EMACS_MODULE: arcology-localapi-commands
#+AUTO_TANGLE: t
By moving the database out of EmacSQL and in to Django, I have hobbled some of the Arcology's [[id:knowledge_base][Knowledge Management]] [[id:e79d4cdc-082f-4b1d-ae08-d979802f09ee][Living Systems]] and meta-cognitive skills. =arroyo-db-query= no longer existing means that things like the [[id:20230526T105534.711282][Direnv arroyo-db integration]] stopped working, and the helpers in [[id:cce/my_nixos_configuration][My NixOS configuration]] and elsewhere rely on the stringly-typed [[id:20231217T154938.132553][Arcology generate Command]] and a =nix run= invocation to function.
I think it's worth building a small HTTP JSON API which can serve some of the common queries, to at least see if it's worth the trouble..
Here's how to use this from Emacs Lisp:
- =(arcology-localapi-call method path)= is an API helper which given an API path will fetch the data and return a deserialized JSON structure
- these interactive commands will fetch a URL, putting it on your kill ring or clipboard if you call it with =M-x= or equivalent:
- =(arcology-key-to-url page-key &optional heading-id)= will take an =ARCOLOGY_KEY= and return a URL
- =(arcology-file-to-url file-path &optional heading-id)= will do the same with a file path from =(buffer-file-name)= or so.
- =(arcology-url-at-point)= gets the org-id of the heading your cursor is in if it has one, and makes a URL that links directly to that.
- =(arcology-read-url)= pops up a list of all the org-roam headings, and returns a URL to it.
* Server view and Arroyo Emacs lisp scaffolding
I probably should use Django REST Framework for this, but. I'm just gonna beat two stones together until a JSON API falls out. This will probably change the first time I add a =POST= call or want to do more complex auth stuff.
The API will be simple, with a bearer token provided by a local state file:
#+begin_src emacs-lisp :tangle ~/org/cce/arcology-localapi-commands.el
(use-package plz)
(defun arcology-fetch-localapi-bearer-token ()
(interactive)
(customize-save-variable
'arcology-localapi-bearer-token
(or (getenv "ARCOLOGY_LOCALAPI_BEARER_TOKEN")
(thread-last
". ~/sync/private-files/.arcology-env && echo $ARCOLOGY_LOCALAPI_BEARER_TOKEN"
(shell-command-to-string)
(s-chop-suffix "\n" )))))
(defcustom arcology-api-base "http://127.0.0.1:29543/api/v1"
"localapi base url")
(defun arcology-localapi-call (method path &rest plz-args)
(let ((plz-args (or plz-args '(:as json-read))))
(apply 'plz method (format "%s%s" arcology-api-base path)
:headers `(("Authorization" . ,(format "Bearer %s" arcology-localapi-bearer-token)))
plz-args)))
#+end_src
These are the API URLs and basic imports... nothing to concern yourself with, probably!
#+begin_src python :tangle localapi/urls.py :mkdirp yes
from django.contrib import admin
from django.urls import path, re_path, include
from localapi import views
urlpatterns = [
path("", views.index),
path("generate/<slug:module>/<slug:role>", views.generate, name="keyword_by_key"),
path("generate/<slug:module>", views.generate, name="keyword_by_key"),
path("keywords/<slug:key>", views.keyword_by_key, name="keyword_by_key"),
re_path("keywords/(?P<key>[0-9a-zA-Z_-]+)/(?P<value>[0-9a-zA-Z/_\-]+)", views.keyword_by_key_value, name="keyword_by_key"),
re_path("page/(?P<route_key>[0-9a-zA-Z/_\-]+)", views.page_metadata, name="page_metadata"),
re_path("file/(?P<file_path>[0-9a-zA-Z/_\-\.]+)", views.file_metadata, name="file_metadata"),
]
#+end_src
#+begin_src python :tangle localapi/views.py
from django.http import HttpRequest, HttpResponse, HttpResponseNotFound, Http404, JsonResponse
from django.shortcuts import render, get_object_or_404
from arcology.models import Page, Feed, Site
from roam.models import Link
from localapi.auth import authenticated
from prometheus_client import Counter, Histogram
import logging
logger = logging.getLogger(__name__)
#+end_src
The API is fairly simple and built-to-purpose, we start with an endpoint that can be queried to validate that the API Bearer token is valid:
#+begin_src python :tangle localapi/views.py
@authenticated
def index(request):
return JsonResponse(dict(state="ok :)"))
#+end_src
** DONE Local API Auth Middleware
:PROPERTIES:
:ID: 20240313T170425.687381
:END:
:LOGBOOK:
- State "DONE" from [2024-03-13 Wed 17:01]
:END:
This API should be secured from CSRF and local scanners, we'll just put a bearer token on it. Since the API is meant to only be running on a CCE endpoint, and not on [[id:20211120T220054.226284][The Wobserver]] the API authentication can be smoothed out a bit and hopefully made transparent to the user. The Bearer token is set in the [[id:arcology/django/config][Arcology Project Configuration]], and can be overridden in an environment variable =ARCOLOGY_LOCALAPI_BEARER_TOKEN=. The NixOS endpoint configuration module for this API will include token generation and placement so that this should be transparent to a local command user. Decorating a view with =@authenticated= will add this bearer token authentication to the view.
#+begin_src python :tangle localapi/auth.py
import re
from django.conf import settings
from django.http import HttpRequest, JsonResponse
def authenticate_request(request: HttpRequest):
r = re.compile(r'Bearer (\S+)')
bearer = request.headers.get("Authorization", "")
match = r.match(bearer)
if not match:
return False
tok = match.group(1)
if tok != settings.LOCALAPI_BEARER_TOKEN:
return False
return True
def authenticated(func):
def wrapper(*args, **kwargs):
request=args[0]
if not authenticate_request(request):
return JsonResponse(dict(state="no :("), status=401)
return func(*args, **kwargs)
return wrapper
#+end_src
* Keyword metadata
There is a simple set of HTTP GET APIs to query the file/key/value store:
#+begin_src python :tangle localapi/views.py
import roam.models
def _json_keywords(keywords):
return [
dict(path=kw.path.path, keyword=kw.keyword, value=kw.value)
for kw in keywords
]
#+end_src
** /keywords/{key}
=GET http://127.0.0.1:8000/api/v1/keywords/ARCOLOGY_KEY=
#+begin_src python :tangle localapi/views.py
@authenticated
def keyword_by_key(request, key):
keywords = roam.models.Keyword.objects.filter(keyword=key).all()
return JsonResponse(dict(
state="ok :)",
key=key,
keywords=_json_keywords(keywords),
))
#+end_src
** /keywords/{key}/{value}
=GET http://127.0.0.1:8000/api/v1/keywords/ARCOLOGY_KEY/arcology/localapi=
#+begin_src python :tangle localapi/views.py
@authenticated
def keyword_by_key_value(request, key, value):
keywords = roam.models.Keyword.objects.filter(keyword=key, value=value).all()
return JsonResponse(dict(
state="ok :)",
key=key,
value=value,
keywords=_json_keywords(keywords),
))
#+end_src
** NEXT add elisp APIs
* Page and File metadata
And some really simple APIs to get information about =Page= and =File= objects out of the database:
#+begin_src python :tangle localapi/views.py
import arcology.models
def _json_page(page):
return dict(
title=page.title,
url=page.to_url(),
site=page.site.title,
)
#+end_src
=GET http://127.0.0.1:8000/api/v1/page/arcology/localapi= or this Emacs Lisp command:
A command which will take an =ARCOLOGY_KEY= and the ID of a heading on that page, and return a URL for it:
#+begin_src emacs-lisp :tangle ~/org/cce/arcology-localapi-commands.el
(defun arcology-key-to-url (page-key &optional heading-id)
(interactive "sKey: \nsHeading ID: ")
(let ((url (concat
(thread-last
(arcology-localapi-call 'get (format "/page/%s" page-key))
(alist-get 'page)
(alist-get 'url))
(when heading-id (format "#%s" heading-id)))))
(when (called-interactively-p)
(kill-new url)
(message "%s" url))
url))
#+end_src
#+begin_src python :tangle localapi/views.py
@authenticated
def page_metadata(request, route_key):
page = arcology.models.Page.objects.get(route_key=route_key)
keywords = page.file.keyword_set.all()
return JsonResponse(dict(
state="ok :)",
route_key=route_key,
file=page.file.path,
page=_json_page(page),
keywords=_json_keywords(keywords)
))
#+end_src
=GET http://127.0.0.1:8000/api/v1/file/arcology-django/localapi.org= and the Emacs Lisp command which will do the same:
#+begin_src emacs-lisp :tangle ~/org/cce/arcology-localapi-commands.el
(defun arcology-file-to-url (file-path &optional heading-id)
(interactive "fKey: \nsHeading ID: ")
(let ((url (concat
(thread-last
(file-relative-name file-path org-roam-directory)
(format "http://127.0.0.1:8000/api/v1/file/%s")
(arcology-localapi-call 'get)
(alist-get 'file)
(alist-get 'page)
(alist-get 'url))
(when heading-id (format "#%s" heading-id)))))
(when (called-interactively-p)
(kill-new url)
(message "%s" url))
url))
#+end_src
#+begin_src python :tangle localapi/views.py
from django.conf import settings
@authenticated
def file_metadata(request, file_path):
final_path = settings.ARCOLOGY_BASE_DIR.joinpath(file_path)
the_file = roam.models.File.objects.get(path=final_path)
page = the_file.page_set.first()
return JsonResponse(dict(
state="ok :)",
file_path=file_path,
file=dict(
path=the_file.path,
page=_json_page(page),
),
))
#+end_src
* Some more ELisp helpers
:PROPERTIES:
:ID: 20240313T212950.461285
:END:
#+begin_src emacs-lisp :tangle ~/org/cce/arcology-localapi-commands.el
(defun arcology-url-at-point (pom)
(interactive "m")
(let ((url (arcology-key-to-url
(thread-last
(org-collect-keywords '("ARCOLOGY_KEY"))
(first)
(second))
(and (> (org-outline-level) 0)
(org-id-get)))))
(when (called-interactively-p)
(kill-new url)
(message "%s" url))
url))
#+end_src
A command which will get the URL for a heading you can select using your =completing-read=:
#+begin_src emacs-lisp :tangle ~/org/cce/arcology-localapi-commands.el
(defun arcology-read-url ()
(interactive)
(let* ((node (org-roam-node-read))
(url (arcology-file-to-url (org-roam-node-file node)
(and (> (org-outline-level) 0)
(org-id-get)))))
(when (called-interactively-p)
(kill-new url)
(message "%s" url))))
#+end_src
* DONE [[id:20231217T154938.132553][Arcology generate Command]]
:LOGBOOK:
- State "DONE" from "NEXT" [2024-03-13 Wed 23:56]
:END:
emacs-lisp code along with the HTTP endpoints to populate things from the Generators
#+begin_src emacs-lisp :tangle ~/org/cce/arcology-localapi-commands.el
(defun arcology-api-generator (module &optional role destination do-sort)
(interactive)
(let ((url (format "/generate/%s%s" module
(if role (format "/%s" role) ""))))
(let ((gen-text (with-current-buffer
(arcology-localapi-call 'get url :as 'buffer)
(buffer-substring-no-properties (point-min) (point-max))))
(buf (if destination
(find-file destination)
(get-buffer-create (format "*%s out*" module)))))
(with-current-buffer buf
(erase-buffer)
(insert gen-text)
(when do-sort
(sort-lines nil (point-min) (point-max)))
(when destination
(save-buffer))
(when (called-interactively-p)
(display-buffer))
(buffer-string)))))
#+end_src
#+begin_src emacs-lisp :tangle ~/org/cce/arcology-localapi-commands.el
(provide 'cce/arcology-localapi-commands)
#+end_src
#+begin_src python :tangle localapi/views.py
import tempfile
from django.core.management import call_command
@authenticated
def generate(request, module, role=None):
f = tempfile.NamedTemporaryFile()
fn = f.name
# i hate this!!!
if role:
call_command('generate', destination=fn, module=module, role=role)
else:
call_command('generate', destination=fn, module=module)
f.seek(0)
return HttpResponse(f)
#+end_src
this is all full of jank. having to pass to a temporary file because the generate commands are locked away in a django management command is silly, i should refactor all of this. the branch is silly, too. But it's very easy now to get my literate programming helpers to quickly generate the code imports and whatnot as soon as the local server is running.
* INPROGRESS [[id:cce/home-manager][home-manager]] deployment
:LOGBOOK:
- State "INPROGRESS" from "NEXT" [2024-03-18 Mon 16:08]
:END:
This thing needs to run as a =systemd= User Unit for the local tangles and whatnot to work. Bootstrapping this will be Fun, we'll just end up needing a bootstrap script to put the =systemd= user units in place for future deployments...
This is just the configurable module; the configuration itself is in the [[id:arcology/django/config][Arcology Project Configuration]] page like the Wobserver module.
#+ARROYO_HOME_MODULE: hm/arcology-localapi.nix
#+ARROYO_SYSTEM_ROLE: endpoint
: #+ARROYO_SYSTEM_ROLE: droid # need to make sure there is a wrapper script to launch this
#+begin_src nix :tangle ~/arroyo-nix/hm/arcology-localapi-mod.nix
{ pkgs, config, lib, ... }:
let
cfg = config.services.arcology2;
arcology = cfg.packages.arcology;
env = [
"ARCOLOGY_BASE_DIR=${cfg.orgDir}"
"ARCOLOGY_DB_PATH=${cfg.dataDir}/db.sqlite3"
"ARCOLOGY_LOG_LEVEL=${cfg.logLevel}"
"ARCOLOGY_CACHE_PATH=${cfg.cacheDir}"
"GUNICORN_CMD_ARGS='--bind=${cfg.address}:${toString cfg.port} -w ${toString cfg.workerCount}'"
];
pyenv = pkgs.python3.withPackages(pp: [arcology]);
preStartScript = pkgs.writeScriptBin "arcology-watchsync-prestart" ''
mkdir -p ${cfg.dataDir}
${arcology}/bin/arcology migrate
${arcology}/bin/arcology seed || true
'';
watchsyncScript = pkgs.writeScriptBin "arcology-watchsync" ''
${arcology}/bin/arcology watchsync -f ${cfg.folderId}
'';
localapiScript = pkgs.writeScriptBin "arcology-localapi" ''
${pyenv}/bin/python -m gunicorn arcology.wsgi
'';
in {
options.services.arcology2 = with lib; {
enable = mkEnableOption (mdDoc "Arcology Local API");
packages.arcology = mkOption {
type = types.package;
description = mdDoc ''
'';
};
address = mkOption {
type = types.str;
default = "localhost";
description = lib.mdDoc "Web interface address.";
};
port = mkOption {
type = types.port;
default = 29543;
description = lib.mdDoc "Web interface port.";
};
workerCount = mkOption {
type = types.number;
default = 4;
description = lib.mdDoc "gunicorn worker count; they recommend 2-4 workers per core.";
};
logLevel = mkOption {
type = types.enum ["ERROR" "WARN" "INFO" "DEBUG"];
default = "INFO";
description = mdDoc ''
Set the Django root logging level
'';
};
orgDir = mkOption {
type = types.str;
default = "~/org";
description = mdDoc ''
Directory containing the org-mode documents.
Arcology needs read-only access to this directory.
'';
};
environmentFile = mkOption {
type = types.path;
default = "${cfg.dataDir}/env";
description = mdDoc ''
A file containing environment variables you may not want to put in the nix store.
For example, you could put a syncthing key
and a bearer token for the Local API in there:
ARCOLOGY_SYNCTHING_KEY=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA;
ARCOLOGY_LOCALAPI_BEARER_TOKEN=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA;
'';
};
folderId = mkOption {
type = types.str;
description = mdDoc ''
Syncthing folder ID containing the org files.
'';
};
cacheDir = mkOption {
type = types.str;
default = "~/.cache/arcology2/";
description = mdDoc ''
Location to cache HTML files and the like.
'';
};
dataDir = mkOption {
type = types.str;
default = "~/.config/arcology2/";
description = mdDoc ''
Location to store the arcology metadata store.
'';
};
};
config = {
systemd.user.services = {
arcology-watchsync = {
Unit.Description = "Dynamically update the Arcology database.";
Service = {
ExecStartPre = "${pkgs.stdenv.shell} ${preStartScript}/bin/arcology-watchsync-prestart";
ExecStart = "${pkgs.stdenv.shell} ${watchsyncScript}/bin/arcology-watchsync";
Restart = "on-failure";
Environment = env;
EnvironmentFile = cfg.environmentFile;
};
Install.WantedBy = ["default.target"];
};
arcology-web = {
Unit.Description = "Local hosted version of the Arcology";
Service = {
ExecStart = "${pkgs.stdenv.shell} ${localapiScript}/bin/arcology-localapi";
Restart = "on-failure";
Environment = env;
EnvironmentFile = cfg.environmentFile;
};
Install.WantedBy = ["default.target"];
};
};
};
}
#+end_src
** NEXT DRY this between here and the [[id:20240213T124300.774781][Deploying the Arcology]] work.
** NEXT is the arcology wobserver deployment better as a systemd user unit?
still need nixos module for the vhosts etc, but... hm.