Spaces:
Sleeping

File size: 1,993 Bytes
124816b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
"""Small durable JSON document store; all paths are generated server-side."""
import json
import os
import sqlite3
import uuid
from datetime import datetime, timezone
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
DATA = Path(os.environ.get('SATFORGE_DATA', ROOT / 'data' / 'runtime'))
DATA.mkdir(parents=True, exist_ok=True)
FILES = DATA / 'files'
FILES.mkdir(exist_ok=True)

def now():
    return datetime.now(timezone.utc).isoformat()

def connection():
    con = sqlite3.connect(DATA / 'mission.sqlite', timeout=30)
    con.execute('CREATE TABLE IF NOT EXISTS records (kind TEXT, id TEXT, body TEXT, PRIMARY KEY(kind,id))')
    return con

def put(kind, body, id=None):
    id = id or uuid.uuid4().hex
    body = {**body, 'id': id}
    with connection() as con:
        con.execute('INSERT OR REPLACE INTO records VALUES (?,?,?)', (kind, id, json.dumps(body, allow_nan=False)))
    return body

def get(kind, id):
    with connection() as con:
        row = con.execute('SELECT body FROM records WHERE kind=? AND id=?', (kind, id)).fetchone()
    if row is None:
        raise KeyError(f'{kind} not found')
    return json.loads(row[0])

def all_records(kind):
    with connection() as con:
        rows = con.execute('SELECT body FROM records WHERE kind=? ORDER BY rowid DESC', (kind,)).fetchall()
    return [json.loads(row[0]) for row in rows]

def event(message, provenance='SYSTEM', **details):
    return put('events', {'time': now(), 'message': message, 'provenance': provenance, **details})

def path_for(id, suffix):
    if not id.isalnum() or not suffix.replace('.', '').replace('_','').isalnum():
        raise ValueError('Invalid asset identifier')
    return FILES / f'{id}.{suffix}'

def asset(kind, name, source, **extra):
    return put('assets', {'kind':kind, 'name':name, 'source':source, 'retrieved_at':now(),
        'acquisition_time':None, 'publication_time':None, 'license':'User must verify',
        'processing':[], 'warnings':[], **extra})