chore: import MCTF services
- Added all seven issued service trees without omissions. - Preserved the supplied runtime configuration, binaries, and assets.
This commit is contained in:
commit
13f936bee9
1222 files changed
+21280
No files matched your search
Executable
+18
@@ -0,0 +1,18 @@
|
||||
from pathlib import Path
|
||||
|
||||
SQL = Path(__file__).resolve().parents[2] / "database" / "sql"
|
||||
|
||||
FILES = (
|
||||
"schema/billing.sql",
|
||||
"schema/receipts.sql",
|
||||
"schema/checks.sql",
|
||||
"schema/reports.sql",
|
||||
"functions/checks.sql",
|
||||
"functions/billing.sql",
|
||||
"functions/receipts.sql",
|
||||
"functions/chat.sql",
|
||||
"functions/reports.sql",
|
||||
)
|
||||
|
||||
def sql():
|
||||
return "\n".join((SQL / name).read_text(encoding="utf-8") for name in FILES)
|
||||
Executable
+43
@@ -0,0 +1,43 @@
|
||||
import os
|
||||
|
||||
from typing import Any
|
||||
|
||||
import psycopg
|
||||
|
||||
from psycopg_pool import AsyncConnectionPool
|
||||
|
||||
DSN = os.environ.get(
|
||||
"DATABASE_URL", "postgresql://billing:billing@127.0.0.1:5432/billing"
|
||||
)
|
||||
|
||||
pool: AsyncConnectionPool
|
||||
|
||||
class QueryError(Exception):
|
||||
def __init__(self, sqlstate: str, message: str):
|
||||
super().__init__(message)
|
||||
self.sqlstate = sqlstate
|
||||
self.message = message
|
||||
|
||||
def query_error(exc: psycopg.Error) -> QueryError:
|
||||
message = getattr(exc.diag, "message_primary", None) or str(exc).splitlines()[0]
|
||||
return QueryError(exc.sqlstate or "", message)
|
||||
|
||||
async def open_pool():
|
||||
global pool
|
||||
pool = AsyncConnectionPool(
|
||||
DSN, min_size=1, max_size=8, open=False, kwargs={"autocommit": True},
|
||||
check=AsyncConnectionPool.check_connection,
|
||||
)
|
||||
await pool.open(wait=True)
|
||||
|
||||
async def close_pool():
|
||||
await pool.close()
|
||||
|
||||
async def call(sql: str, params: tuple = ()) -> Any:
|
||||
try:
|
||||
async with pool.connection() as connection:
|
||||
cursor = await connection.execute(sql, params)
|
||||
row = await cursor.fetchone()
|
||||
except psycopg.Error as exc:
|
||||
raise query_error(exc) from None
|
||||
return row[0] if row else None
|
||||
Executable
+27
@@ -0,0 +1,27 @@
|
||||
import asyncio
|
||||
|
||||
import psycopg
|
||||
|
||||
from backend.app.db import bootstrap
|
||||
from backend.app.db.connection import DSN
|
||||
|
||||
STARTUP_ATTEMPTS = 10
|
||||
STARTUP_DELAY = 1.0
|
||||
|
||||
async def initialize():
|
||||
for attempt in range(1, STARTUP_ATTEMPTS + 1):
|
||||
try:
|
||||
async with await psycopg.AsyncConnection.connect(DSN, autocommit=True, connect_timeout=5) as db:
|
||||
async with db.transaction():
|
||||
await db.execute("select pg_advisory_xact_lock(hashtextextended('dark-tariff:bootstrap', 0))")
|
||||
await db.execute(bootstrap.sql())
|
||||
return
|
||||
except psycopg.OperationalError as error:
|
||||
if error.sqlstate and not (error.sqlstate.startswith("08") or error.sqlstate in {"40001", "40P01", "55P03"}):
|
||||
raise
|
||||
if attempt == STARTUP_ATTEMPTS:
|
||||
raise
|
||||
await asyncio.sleep(STARTUP_DELAY)
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(initialize())
|
||||
Executable
+75
@@ -0,0 +1,75 @@
|
||||
import asyncio
|
||||
import base64
|
||||
import secrets
|
||||
|
||||
import psycopg
|
||||
from argon2.low_level import Type, hash_secret_raw
|
||||
from psycopg.types.json import Jsonb
|
||||
|
||||
from backend.app.db import connection
|
||||
from backend.app.db.connection import call
|
||||
|
||||
async def resources():
|
||||
return await call("select billing.resource_types()")
|
||||
|
||||
async def readings():
|
||||
return await call("select billing.reading_list()")
|
||||
|
||||
async def reading_public(reading_id):
|
||||
return await call("select billing.reading_public(%s::bigint)", (reading_id,))
|
||||
|
||||
def calculation_key(reading_id):
|
||||
value = f"{reading_id}|{secrets.randbelow(10000):04d}".encode("ascii")
|
||||
key = hash_secret_raw(value, bytes(16), time_cost=1, memory_cost=8192,
|
||||
parallelism=1, hash_len=32, type=Type.ID, version=19)
|
||||
return base64.b64encode(key).decode("ascii")
|
||||
|
||||
async def add_reading(serial, kind, metrics):
|
||||
try:
|
||||
async with connection.pool.connection() as db:
|
||||
async with db.transaction():
|
||||
cursor = await db.execute(
|
||||
"select billing.reading_add(%s::text, %s::text, %s::jsonb)",
|
||||
(serial, kind, Jsonb(metrics)),
|
||||
)
|
||||
reading = (await cursor.fetchone())[0]
|
||||
key = await asyncio.to_thread(calculation_key, reading["id"])
|
||||
cursor = await db.execute(
|
||||
"select billing.receipt_issue(r, %s::text)"
|
||||
" from billing.reading r where r.id = %s::bigint",
|
||||
(key, reading["id"]),
|
||||
)
|
||||
return reading | (await cursor.fetchone())[0] | {"calculation_id": key}
|
||||
except psycopg.Error as exc:
|
||||
raise connection.query_error(exc) from None
|
||||
|
||||
async def ping():
|
||||
return await call("select 1")
|
||||
|
||||
async def chat_greeting():
|
||||
return await call("select chat.greeting()")
|
||||
|
||||
async def check_start(reading_id):
|
||||
return await call("select chat.check_start(%s::bigint)", (reading_id,))
|
||||
|
||||
async def check_commit(check_id, round, values):
|
||||
return await call("select chat.check_commit(%s::uuid, %s::int, %s::text[])", (check_id, round, values))
|
||||
|
||||
async def check_answer(check_id, round, data):
|
||||
return await call("select chat.check_answer(%s::uuid, %s::int, %s::jsonb)", (check_id, round, Jsonb(data)))
|
||||
|
||||
async def receipts():
|
||||
return await call("select billing.receipt_list()")
|
||||
|
||||
async def open_receipt(receipt_id, calculation_id):
|
||||
return await call("select billing.receipt_open(%s::bigint, %s::text)", (receipt_id, calculation_id))
|
||||
|
||||
async def report_fields(report):
|
||||
return await call("select billing.report_fields(%s::text)", (report,))
|
||||
|
||||
async def finance_report(period=None, fields=None, sort="", group_by="", filter="", having=""):
|
||||
return await call(
|
||||
"select jsonb_build_object('period', coalesce(%s::text, to_char(current_date, 'YYYY-MM')))"
|
||||
" || billing.finance_report(%s::text, %s::text[], %s::text, %s::text, %s::text, %s::text)",
|
||||
(period, period, fields or [], sort, group_by, filter, having),
|
||||
)
|
||||
Reference in new issue
Block a user