# store.j - the schema, its migrations, and every query of the shop API# pragma-jennifer-capability: sqluse sql;
use strings;
use hash;
use encoding;
use crypto;
use convert;
import"orm.j"as orm;
import"sqlmigrate.j"as mig;
# Migrations are frozen text: never build an old one from a schema that# keeps changing.exportdefconstMIGRATIONSaslistofmig.Migration init [
mig.Migration{version: "001", description: "api users and tokens",
up: ["CREATE TABLE api_users (id SERIAL PRIMARY KEY," +
" name TEXT NOT NULL UNIQUE, pwhash TEXT NOT NULL," +
" scopes TEXT NOT NULL)",
"CREATE TABLE api_tokens (hash TEXT PRIMARY KEY," +
" user_id INT NOT NULL REFERENCES api_users(id)," +
" created_at TIMESTAMPTZ NOT NULL DEFAULT now())"],
down: ["DROP TABLE api_tokens", "DROP TABLE api_users"]},
mig.Migration{version: "002", description: "orders",
up: ["CREATE TABLE orders (id SERIAL PRIMARY KEY," +
" customer TEXT NOT NULL, lines TEXT NOT NULL," +
" total_cents INT NOT NULL, state TEXT NOT NULL," +
" created_by INT NOT NULL REFERENCES api_users(id))",
orm.createIndex("orders_state", "orders", ["state"], false)],
down: ["DROP TABLE orders"]},
mig.Migration{version: "003", description: "idempotency keys",
up: ["CREATE TABLE idempotency_keys (user_id INT NOT NULL," +
" key TEXT NOT NULL, request_hash TEXT NOT NULL," +
" status INT NOT NULL, body TEXT NOT NULL," +
" created_at TIMESTAMPTZ NOT NULL DEFAULT now()," +
" PRIMARY KEY (user_id, key))"],
down: ["DROP TABLE idempotency_keys"]}
];
# The orders table as orm sees it: queries and CRUD, not DDL.exportfuncorders() {
def s asorm.Schema initorm.schema("orders", "id", orm.Dialect.Postgres);
$s = orm.column($s, "id", orm.ColumnKind.Int);
$s = orm.column($s, "customer", orm.ColumnKind.String);
$s = orm.column($s, "lines", orm.ColumnKind.String);
$s = orm.column($s, "total_cents", orm.ColumnKind.Int);
$s = orm.column($s, "state", orm.ColumnKind.String);
returnorm.column($s, "created_by", orm.ColumnKind.Int);
}
exportdefstruct Filter {
state asstring,
customer asstring,
offset asint,
limit asint
};
# The query behind GET /v1/orders, without paging (for the count).exportfuncfiltered(f as Filter) {
def q asorm.Query initorm.from(orders());
if ($f.state != "") { $q = orm.where($q, "state", "=", $f.state); }
if ($f.customer != "") {
$q = orm.where($q, "customer", "=", $f.customer);
}
return$q;
}
exportfunclistQuery(f as Filter) {
def q asorm.Query initorm.orderBy(filtered($f), "id", "desc");
returnorm.offset(orm.limit($q, $f.limit), $f.offset);
}
exportfunccountQuery(f as Filter) {
returnorm.count(orm.select(filtered($f), []), "n");
}
exportfunclistOrders(conn assql.Connection, f as Filter) {
returnorm.all(orm.session($conn), listQuery($f));
}
exportfunccountOrders(conn assql.Connection, f as Filter) {
def row asmapofstringtostringinitorm.first(orm.session($conn), countQuery($f));
returnconvert.toInt($row["n"]);
}
exportfuncfindOrder(conn assql.Connection, id asstring) {
returnorm.findBy(orm.session($conn), orders(), "id", $id);
}
# --- API users and tokens ---------------------------------------------------exportdefstruct Caller {
found asbool,
id asint,
name asstring,
scopes aslistofstring
};
# A hash of a password nobody has, so an unknown name costs one argon2id# check, like a known one.exportdefconstDUMMY_HASHasstringinit'$argon2id$v=19$m=65536,t=3,p=4$6vCTKdAFRZuXR0SeIrjtZQ$' +
'IKFRWzomJT7xNYPmC7QATHJ/Ko+eu6f549Y0QyH6tWU';
exportfuncaddUser(conn assql.Connection, name asstring, pw asstring,
scopes asstring) {
def h asstringinitcrypto.hashPassword("argon2id", $pw);
def rows assql.Rows initsql.query($conn,
"INSERT INTO api_users (name, pwhash, scopes) VALUES ($1, $2, $3)" +
" RETURNING id", $name, $h, $scopes);
defersql.closeRows($rows);
sql.next($rows);
returnsql.asInt($rows, "id");
}
# The user id for a name and password, or 0.exportfunclogin(conn assql.Connection, name asstring, pw asstring) {
def rows assql.Rows initsql.query($conn,
"SELECT id, pwhash FROM api_users WHERE name = $1", $name);
defersql.closeRows($rows);
if (notsql.next($rows)) {
crypto.verifyPassword($pw, DUMMY_HASH);
return0;
}
if (notcrypto.verifyPassword($pw, sql.asString($rows, "pwhash"))) {
return0;
}
returnsql.asInt($rows, "id");
}
exportfunctokenHash(token asstring) {
returnencoding.toText("hex",
hash.compute("sha256", encoding.encode("utf-8", $token)));
}
# Mint a token: the caller sees it once, the database keeps its hash.exportfuncnewToken(conn assql.Connection, userId asint) {
def token asstringinit"shp_" +
encoding.toText("hex", crypto.randBytes(24));
sql.exec($conn, "INSERT INTO api_tokens (hash, user_id)" +
" VALUES ($1, $2)", tokenHash($token), $userId);
return$token;
}
exportfunccaller(conn assql.Connection, token asstring) {
def rows assql.Rows initsql.query($conn,
"SELECT u.id, u.name, u.scopes FROM api_tokens t" +
" JOIN api_users u ON u.id = t.user_id WHERE t.hash = $1",
tokenHash($token));
defersql.closeRows($rows);
def none aslistofstringinit [];
if (notsql.next($rows)) {
return Caller{found: false, id: 0, name: "", scopes: $none};
}
return Caller{found: true, id: sql.asInt($rows, "id"),
name: sql.asString($rows, "name"),
scopes: strings.split(sql.asString($rows, "scopes"), " ")};
}
# --- idempotency keys -----------------------------------------------------------# Claim a key inside the caller's transaction: true when it is new. A second# request with the same key waits here until the first one commits.exportfuncclaimKey(tx assql.Tx, uid asint, key asstring, reqHash asstring) {
def r assql.Result initsql.exec($tx,
"INSERT INTO idempotency_keys (user_id, key, request_hash, status, body)" +
" VALUES ($1, $2, $3, 0, '') ON CONFLICT DO NOTHING",
$uid, $key, $reqHash);
return$r.affected == 1;
}
exportfuncsaveResponse(tx assql.Tx, uid asint, key asstring, status asint,
body asstring) {
sql.exec($tx, "UPDATE idempotency_keys SET status = $3, body = $4" +
" WHERE user_id = $1 AND key = $2", $uid, $key, $status, $body);
}
exportdefstruct Saved {
requestHash asstring,
status asint,
body asstring
};
exportfuncsavedResponse(conn assql.Connection, uid asint, key asstring) {
def rows assql.Rows initsql.query($conn,
"SELECT request_hash, status, body FROM idempotency_keys" +
" WHERE user_id = $1 AND key = $2", $uid, $key);
defersql.closeRows($rows);
sql.next($rows);
return Saved{requestHash: sql.asString($rows, 0),
status: sql.asInt($rows, 1), body: sql.asString($rows, 2)};
}
# The order row, locked until the transaction ends; {} when there is none.exportfunclockOrder(tx assql.Tx, id asstring) {
def rows assql.Rows initsql.query($tx,
"SELECT * FROM orders WHERE id = $1 FOR UPDATE", $id);
defersql.closeRows($rows);
def row asmapofstringtostringinit {};
if (sql.next($rows)) {
for (def c insql.columns($rows)) {
$row[$c] = sql.asString($rows, $c);
}
}
return$row;
}