File size: 8,672 Bytes
5da7ffb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77e20da
5da7ffb
 
 
77e20da
 
 
 
 
5da7ffb
 
 
 
a3a9968
 
 
 
5da7ffb
 
 
 
 
 
 
 
 
 
 
 
 
9e7cba5
 
 
 
5da7ffb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
263fc8e
 
 
 
 
5da7ffb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
263fc8e
5da7ffb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
#!/usr/bin/env python3
"""Single-container FalkorDB + Gradio supervisor for CPU-only Spaces.

--prepare: fetch/verify pinned public sources, no database.
--build: load and save an image seed, no UI.
Default: restore seed, initialize if needed, give UI read-only credentials,
and stop both children on SIGTERM/SIGINT or if either process fails.
"""
import argparse
import hashlib
import importlib.util
import json
import os
from pathlib import Path
import secrets
import shutil
import signal
import subprocess
import sys
import time
from urllib.request import Request, urlopen

from redis.exceptions import RedisError
from falkordb import FalkorDB
import falkordb_ingest as ingest

ROOT = Path(__file__).resolve().parent
GRAPH = 'careercompass_onet_31_0'


def sources(folder):
    """Never accept a corrupt download or silently change a pinned release."""
    folder.mkdir(parents=True, exist_ok=True)
    records = json.loads((ROOT / 'sources.json').read_text())['files']
    vendor = ROOT / 'vendor'
    for item in records:
        path = folder / item['name']
        if not path.exists():
            vendored = vendor / item['name']
            if vendored.is_file() and hashlib.sha256(vendored.read_bytes()).hexdigest() == item['sha256']:
                print('Using vendored source:', item['name'], flush=True)
                shutil.copyfile(vendored, path)
                continue
            print('Downloading official source:', item['name'], flush=True)
            last = None
            for attempt in range(3):
                try:
                    req = Request(item['url'], headers={
                        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36',
                        'Accept': '*/*',
                    })
                    with urlopen(req, timeout=45) as response:
                        data = response.read(30 * 1024 * 1024 + 1)
                    if len(data) > 30 * 1024 * 1024 or hashlib.sha256(data).hexdigest() != item['sha256']:
                        raise ValueError('Source checksum mismatch: ' + item['name'])
                    temporary = path.with_suffix(path.suffix + '.part')
                    temporary.write_bytes(data)
                    temporary.replace(path)
                    break
                except OSError as exc:
                    last = exc
                    if attempt < 2:
                        time.sleep(attempt + 1)
            else:
                if item.get('optional'):
                    print('WARNING: optional source unavailable, continuing without it:',
                          item['name'], flush=True)
                    continue
                raise RuntimeError('Official source unavailable: ' + item['url']) from last
        if hashlib.sha256(path.read_bytes()).hexdigest() != item['sha256']:
            raise ValueError('Source checksum mismatch: ' + str(path))
    print('Verified', len(records), 'official source files', flush=True)


def fingerprint():
    digest = hashlib.sha256()
    for name in ('sources.json', 'falkordb_ingest.py', 'schema.cypher', 'requirements.txt'):
        digest.update((ROOT / name).read_bytes())
    return digest.hexdigest()


def ready_graph(db, graph, source_dir):
    expected = fingerprint()
    ready = []
    if db.connection.exists(GRAPH):
        ready = graph.ro_query('MATCH (d:Dataset {id:"onet-31.0"}) RETURN d.ready_fingerprint').result_set
    if ready != [[expected]]:
        print('Initializing graph from inspected sources', flush=True)
        sources(source_dir)
        model = ingest.build(ingest.inspect_all(source_dir))
        wage_path = source_dir / 'oesm25nat.zip'
        if wage_path.is_file():
            ingest.add_wages(model, wage_path)
        else:
            print('No wage file available; annual wages will be unavailable', flush=True)
        ingest.load(db, graph, model, ROOT / 'schema.cypher', 500)
        del model
        # Mark ready only after all batches and counts pass.
        verify_graph(graph)
        graph.query('MATCH (d:Dataset {id:"onet-31.0"}) SET d.ready_fingerprint=$value', params={'value': expected})
        db.connection.save()
        print('Graph initialized and snapshot saved', flush=True)
    else:
        verify_graph(graph)
        print('Verified existing graph; ingestion skipped', flush=True)


def verify_graph(graph):
    occupations = graph.ro_query('MATCH (o:Occupation) RETURN count(o),count(o.median_annual_wage)').result_set[0]
    edges = graph.ro_query('MATCH ()-[r]->() RETURN count(r)').result_set[0][0]
    if occupations[0] != 1016 or occupations[1] not in (0, 956) or edges != 242797:
        raise RuntimeError(f'Incomplete graph: occupations/wages={occupations}, relationships={edges}')


def reader_credentials(db):
    password = secrets.token_urlsafe(32)
    db.connection.execute_command('ACL', 'SETUSER', 'careercompass_reader', 'reset', 'on',
                                  '>' + password, '~' + GRAPH, '-@all',
                                  '+graph.ro_query', '+ping', '+info', '+client|setinfo', '+client|setname')
    return 'careercompass_reader', password


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--prepare', action='store_true')
    parser.add_argument('--build', action='store_true')
    args = parser.parse_args()
    source_dir = Path(os.getenv('CC_SOURCE_DIR', str(ROOT / 'data'))).resolve()
    if args.prepare:
        sources(source_dir)
        return
    state = Path(os.getenv('CC_STATE_DIR', '/tmp/careercompass')).resolve()
    state.mkdir(parents=True, exist_ok=True)
    seed = ROOT / 'seed' / 'graph.rdb'
    if not (state / 'graph.rdb').exists() and seed.exists():
        shutil.copyfile(seed, state / 'graph.rdb')
    spec = importlib.util.find_spec('redislite')
    if spec is None:
        raise RuntimeError('Install requirements.txt; the FalkorDB binary is missing')
    binary = Path(next(iter(spec.submodule_search_locations))) / 'bin'
    port = int(os.getenv('CC_DB_PORT', '6379'))
    stopping = False

    def stop(*_):
        nonlocal stopping
        stopping = True

    signal.signal(signal.SIGTERM, stop)
    signal.signal(signal.SIGINT, stop)
    children = []
    db = None
    try:
        server = subprocess.Popen([str(binary / 'redis-server'), '--bind', '127.0.0.1',
            '--port', str(port), '--dir', str(state), '--dbfilename', 'graph.rdb',
            '--save', '', '--appendonly', 'no', '--maxmemory', '4gb', '--maxmemory-policy', 'noeviction',
            '--loadmodule', str(binary / 'falkordb.so'), 'THREAD_COUNT', '2'])
        children.append(server)
        deadline = time.monotonic() + 60
        while time.monotonic() < deadline and not stopping:
            if server.poll() is not None:
                raise RuntimeError('FalkorDB exited during startup; inspect the preceding log')
            try:
                db = FalkorDB(host='127.0.0.1', port=port, socket_connect_timeout=2)
                db.connection.ping()
                break
            except RedisError:
                time.sleep(.2)
        else:
            raise RuntimeError('FalkorDB startup interrupted or timed out')
        graph = db.select_graph(GRAPH)
        ready_graph(db, graph, source_dir)
        print('FalkorDB memory:', db.connection.info('memory')['used_memory_human'], flush=True)
        if args.build or stopping:
            return
        username, password = reader_credentials(db)
        env = os.environ.copy()
        env.update(FALKORDB_HOST='127.0.0.1', FALKORDB_PORT=str(port), FALKORDB_GRAPH=GRAPH,
                   FALKORDB_USERNAME=username, FALKORDB_PASSWORD=password, FALKORDB_SSL='false')
        env.setdefault('GRADIO_SERVER_NAME', '0.0.0.0')
        env.setdefault('GRADIO_SERVER_PORT', '7860')
        env.setdefault('GRADIO_ANALYTICS_ENABLED', 'False')
        app = subprocess.Popen([sys.executable, str(ROOT / 'app.py')], cwd=ROOT, env=env)
        children.append(app)
        while not stopping:
            if any(child.poll() is not None for child in children):
                raise RuntimeError('An application child exited; stopping its peer')
            time.sleep(.25)
    finally:
        if db is not None:
            db.connection.close()
        for child in reversed(children):
            if child.poll() is None:
                child.terminate()
                try:
                    child.wait(timeout=10)
                except subprocess.TimeoutExpired:
                    child.kill()
                    child.wait()


if __name__ == '__main__':
    main()