File size: 27,079 Bytes
860fd4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
"""Read-only HTTP access to the problem/insight library used by ideaX."""
from __future__ import annotations

import argparse
from contextlib import contextmanager
import copy
import hashlib
import hmac
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import json
import os
from pathlib import Path
import re
import secrets
import sqlite3
import threading
import time
from urllib.parse import parse_qs, unquote, urlsplit

from library_query import tokens
from library_api_index import FIELDS, INDEX_VERSION, arxiv_id, fingerprint, supporting_paper_count


class APIError(Exception):
    def __init__(self, status, code, message):
        self.status, self.code, self.message = status, code, message


def bounded_integer(value, name, default, low, high):
    if value is None:
        return default
    try:
        number = int(value)
    except (ValueError, TypeError):
        raise APIError(400, 'invalid_parameter', f'{name} must be an integer') from None
    if not low <= number <= high:
        raise APIError(400, 'invalid_parameter', f'{name} must be between {low} and {high}')
    return number


class Library:
    def __init__(self, database, index, query_timeout=5.0):
        self.path = Path(database).resolve(strict=True)
        self.index = Path(index).resolve(strict=True)
        self.query_timeout = query_timeout
        self._domain_catalog = None
        self._domain_catalog_lock = threading.Lock()
        with sqlite3.connect(self.index.as_uri() + '?mode=ro', uri=True) as con:
            if con.execute("SELECT value FROM metadata WHERE key='version'").fetchone()[0] != INDEX_VERSION:
                raise ValueError('Search index version is unsupported; rebuild the index')
            self.source_fingerprint = json.loads(con.execute("SELECT value FROM metadata WHERE key='source'").fetchone()[0])
        if self.source_fingerprint != fingerprint(self.path):
            raise ValueError('Search index is stale; rebuild it for this library snapshot')
        with self.connect() as con:
            for table in ('entries', 'papers', 'search'):
                if not con.execute('SELECT 1 FROM sqlite_master WHERE name=?', (table,)).fetchone():
                    raise ValueError(f'Missing required library table: {table}')

    @contextmanager
    def connect(self):
        if self.source_fingerprint != fingerprint(self.path):
            raise APIError(503, 'stale_index', 'Library snapshot changed; search index must be rebuilt')
        con = sqlite3.connect(self.path.as_uri() + '?mode=ro', uri=True, timeout=2.0)
        try:
            con.execute('PRAGMA query_only=ON')
            con.execute('ATTACH DATABASE ? AS idx', (self.index.as_uri() + '?mode=ro',))
            deadline = time.monotonic() + self.query_timeout
            con.set_progress_handler(lambda: time.monotonic() > deadline, 1000)
            yield con
        finally:
            con.close()

    def stats(self):
        with self.connect() as con:
            counts = dict(con.execute('SELECT kind,count(*) FROM entries GROUP BY kind'))
            return dict(entries=sum(counts.values()), by_kind=counts,
                        units=con.execute('SELECT count(DISTINCT unit) FROM entries').fetchone()[0],
                        domains=con.execute('SELECT count(*) FROM idx.domains').fetchone()[0],
                        papers=con.execute('SELECT count(*) FROM idx.papers').fetchone()[0],
                        source_cards=con.execute('SELECT count(*) FROM main.papers').fetchone()[0],
                        snapshot_modified_at=int(self.path.stat().st_mtime))

    def domains(self, params):
        if set(params) - {'q', 'limit', 'offset'}:
            raise APIError(400, 'invalid_parameter', 'Unknown domain query parameter')
        limit = bounded_integer(params.get('limit'), 'limit', 50, 1, 100)
        offset = bounded_integer(params.get('offset'), 'offset', 0, 0, 10000)
        terms = tokens(params.get('q', ''))
        result = []
        for identifier, data in self.domain_catalog().items():
            text = (identifier + ' ' + data.get('name', '')).lower()
            if terms and not all(t in text for t in terms):
                continue
            result.append(data)
        total = len(result)
        return copy.deepcopy(result[offset:offset + limit]), {'count': len(result[offset:offset + limit]), 'total': total, 'limit': limit,
                                               'has_more': offset + limit < total,
                                               'next_offset': offset + limit if offset + limit < total else None}

    def domain_catalog(self):
        """Reuse exact counts for the verified read-only source, never a stale index.

        Thirty scouts used to repeat whole-library GROUP BY joins on each page.
        Check the source fingerprint on every use, and build once under a lock.
        """
        if self.source_fingerprint != fingerprint(self.path):
            raise APIError(503, 'stale_index', 'Library snapshot changed; search index must be rebuilt')
        with self._domain_catalog_lock:
            if self._domain_catalog is None:
                self._domain_catalog = self._load_domain_catalog()
            return self._domain_catalog

    def _load_domain_catalog(self):
        with self.connect() as con:
            kinds = {}
            for unit, kind, count in con.execute('SELECT unit,kind,count(*) FROM entries GROUP BY unit,kind'):
                kinds.setdefault(unit, {})[kind] = count
            paper_counts = {r[0]: (r[1], r[2]) for r in con.execute(
                'SELECT d.domain_id,count(*),sum(p.has_source_card) FROM idx.domain_papers d JOIN idx.papers p ON p.id=d.paper_id GROUP BY d.domain_id')}
            result = {}
            for identifier, raw in con.execute('SELECT id,data FROM idx.domains ORDER BY id'):
                data = json.loads(raw)
                paper_count, card_count = paper_counts.get(identifier, (0, 0))
                data['counts'] = {'problems': kinds.get(identifier, {}).get('problem', 0),
                                  'insights': kinds.get(identifier, {}).get('insight', 0),
                                  'papers': paper_count, 'source_cards': card_count}
                result[identifier] = data
        return result

    def domain(self, identifier):
        data = self.domain_catalog().get(identifier)
        if data is None:
            raise APIError(404, 'not_found', 'Unknown research domain')
        return copy.deepcopy(data)

    def domain_papers(self, identifier, params):
        self.domain(identifier)
        if set(params) - {'q', 'limit', 'after'}:
            raise APIError(400, 'invalid_parameter', 'Use q,limit,after for domain papers')
        limit = bounded_integer(params.get('limit'), 'limit', 20, 1, 100)
        sql = 'SELECT p.id,p.data FROM idx.domain_papers d JOIN idx.papers p ON p.id=d.paper_id WHERE d.domain_id=?'
        args = [identifier]
        if params.get('after'):
            sql += ' AND p.id>?'
            args.append(params['after'])
        for term in tokens(params.get('q', '')):
            sql += " AND lower(json_extract(p.data,'$.title')) LIKE ?"
            args.append('%' + term + '%')
        sql += ' ORDER BY p.id LIMIT ?'
        args.append(limit + 1)
        with self.connect() as con:
            rows = con.execute(sql, args).fetchall()
        more, rows = len(rows) > limit, rows[:limit]
        data = [{k: v for k, v in json.loads(row[1]).items() if k != 'abstract'} for row in rows]
        return data, {'count': len(data), 'limit': limit, 'has_more': more, 'next_after': rows[-1][0] if more else None}

    def units(self):
        with self.connect() as con:
            counts = {}
            for unit, kind, count in con.execute('SELECT unit,kind,count(*) FROM entries GROUP BY unit,kind'):
                counts.setdefault(unit, {'id': unit, 'problem': 0, 'insight': 0})[kind] = count
            # One indexed lookup per unit avoids decoding every entry's JSON.
            for unit, value in counts.items():
                data = con.execute('SELECT data FROM entries WHERE unit=? AND kind=? LIMIT 1',
                                   (unit, 'problem' if value['problem'] else 'insight')).fetchone()[0]
                value['name'] = json.loads(data).get('unit_name', unit)
            return [counts[key] for key in sorted(counts)]

    def get(self, table, identifier):
        if table not in ('entries', 'papers'):
            raise ValueError('Unsupported resource')
        with self.connect() as con:
            row = con.execute(f'SELECT data FROM {table} WHERE id=?', (identifier,)).fetchone()
            if table == 'papers':
                meta = con.execute('SELECT data FROM idx.papers WHERE id=?', (identifier,)).fetchone()
                if row or meta:
                    data = json.loads(meta[0]) if meta else {}
                    data.update(json.loads(row[0]) if row else {})
                    data['source_card_available'] = row is not None
                    data['domains'] = [x[0] for x in con.execute('SELECT domain_id FROM idx.domain_papers WHERE paper_id=? ORDER BY domain_id', (identifier,))]
                    return data
        if row is None:
            raise APIError(404, 'not_found', 'No matching resource')
        data = json.loads(row[0])
        data['paper_count'] = supporting_paper_count(data)
        return data

    def by_arxiv(self, identifier):
        normalized = arxiv_id(identifier)
        if not normalized:
            raise APIError(400, 'invalid_parameter', 'Invalid arXiv ID')
        with self.connect() as con:
            rows = con.execute('SELECT id FROM idx.papers WHERE arxiv=? ORDER BY id',
                               (normalized,)).fetchall()
        if not rows:
            raise APIError(404, 'not_found', 'No paper matches this arXiv ID')
        return [self.get('papers', row[0]) for row in rows]

    def batch(self, identifiers):
        if not isinstance(identifiers, list) or not 1 <= len(identifiers) <= 50:
            raise APIError(400, 'invalid_parameter', 'ids must contain 1–50 numeric paper IDs')
        if any(isinstance(x, bool) or not isinstance(x, (str, int)) or not re.fullmatch(r'[0-9]{1,20}', str(x)) for x in identifiers):
            raise APIError(400, 'invalid_parameter', 'Each paper ID must be numeric')
        identifiers = list(dict.fromkeys(str(x) for x in identifiers))
        papers, missing = [], []
        for identifier in identifiers:
            try:
                papers.append(self.get('papers', identifier))
            except APIError as exc:
                if exc.status != 404:
                    raise
                missing.append(identifier)
        return {'papers': papers, 'missing_ids': missing}

    def entries(self, params):
        unknown = set(params) - {'q', 'kind', 'unit', 'limit', 'offset', 'after', 'mode', 'fields', 'sort'}
        if unknown:
            raise APIError(400, 'invalid_parameter', 'Unknown query parameter')
        limit = bounded_integer(params.get('limit'), 'limit', 20, 1, 100)
        offset = bounded_integer(params.get('offset'), 'offset', 0, 0, 10000)
        kind = params.get('kind')
        if kind is not None and kind not in ('problem', 'insight'):
            raise APIError(400, 'invalid_parameter', 'kind must be problem or insight')
        query = params.get('q')
        sort = params.get('sort', 'relevance' if query is not None else 'id')
        if sort not in ('id', 'relevance', 'paper_count'):
            raise APIError(400, 'invalid_parameter', 'sort must be id, relevance or paper_count')
        if sort == 'relevance' and query is None:
            raise APIError(400, 'invalid_parameter', 'sort=relevance requires q')
        mode = params.get('mode', 'all')
        if mode not in ('all', 'any'):
            raise APIError(400, 'invalid_parameter', 'mode must be all or any')
        fields = params.get('fields', ','.join(FIELDS)).split(',')
        if not fields or not set(fields) <= set(FIELDS):
            raise APIError(400, 'invalid_parameter', 'fields must be a comma-separated subset of: ' + ','.join(FIELDS))
        terms = tokens(query) if query is not None else []
        if query is not None and (not terms or len(query) > 500 or len(terms) > 64):
            raise APIError(400, 'invalid_parameter', 'q needs 1–64 searchable terms and at most 500 characters')
        if 'after' in params and (query is not None or offset or sort != 'id'):
            raise APIError(400, 'invalid_parameter', 'after requires ID-ordered browsing without q or offset; use offset for paper_count sorting')
        predicates, args = [], []
        sql = 'SELECT e.id,e.data,s.paper_count'
        if terms:
            sql += ',bm25(entry_fts)'
        sql += ' FROM idx.entries s JOIN main.entries e ON e.id=s.id'
        if terms:
            sql += ' JOIN idx.entry_fts ON entry_fts.id=s.id'
            predicates.append('entry_fts MATCH ?')
            operator = ' AND ' if mode == 'all' else ' OR '
            args.append('{' + ' '.join(fields) + '}: (' + operator.join('"' + term + '"' for term in terms) + ')')
        for key in ('kind', 'unit'):
            if params.get(key) is not None:
                predicates.append(f's.{key}=?')
                args.append(params[key])
        if params.get('after'):
            predicates.append('s.id>?')
            args.append(params['after'])
        if predicates:
            sql += ' WHERE ' + ' AND '.join(predicates)
        ordering = {'paper_count': 's.paper_count DESC,s.id', 'relevance': 'bm25(entry_fts),s.id', 'id': 's.id'}
        sql += ' ORDER BY ' + ordering[sort] + ' LIMIT ? OFFSET ?'
        args += [limit + 1, offset]
        with self.connect() as con:
            rows = con.execute(sql, args).fetchall()
        more, rows = len(rows) > limit, rows[:limit]
        output_fields = ('id', 'kind', 'unit', 'unit_name', 'statement', 'mechanism', 'scope', 'techniques', 'supporting_papers')
        data = [{key: entry.get(key) for key in output_fields} for entry in (json.loads(row[1]) for row in rows)]
        for value, row in zip(data, rows):
            value['paper_count'] = row[2]
            if terms:
                value['score'] = row[3]
        page = dict(limit=limit, count=len(data), has_more=more, sort=sort)
        if terms or offset or sort == 'paper_count':
            page['next_offset'] = offset + limit if more and offset + limit <= 10000 else None
        else:
            page['next_after'] = rows[-1][0] if more else None
        return data, page


class Credentials:
    """Load only token hashes on the server; replacing the file revokes keys immediately."""
    def __init__(self, path):
        self.path = Path(path).resolve(strict=True)
        self.clients()

    def clients(self):
        value = json.loads(self.path.read_text())
        clients = value.get('clients', {})
        if not clients or any(not re.fullmatch(r'[a-f0-9]{64}', digest) for digest in clients.values()):
            raise ValueError('Credentials must contain named SHA-256 token hashes')
        return clients

    def authenticate(self, authorization):
        if not authorization or not authorization.startswith('Bearer '):
            raise APIError(401, 'unauthorized', 'A Bearer API key is required')
        digest = hashlib.sha256(authorization[7:].encode()).hexdigest()
        for name, expected in self.clients().items():
            if hmac.compare_digest(digest, expected):
                return name
        raise APIError(401, 'unauthorized', 'Invalid API key')


class Server(ThreadingHTTPServer):
    daemon_threads = True
    allow_reuse_address = True

    def __init__(self, address, library, credentials=None):
        self.library, self.credentials = library, credentials
        self.queries = threading.BoundedSemaphore(16)
        super().__init__(address, Handler)


class Handler(BaseHTTPRequestHandler):
    server_version = 'ideaX-library-api/1'
    sys_version = ''

    def setup(self):
        super().setup()
        self.connection.settimeout(10)

    def log_message(self, *args):
        pass

    def reply(self, status, body, extra=None):
        is_text = isinstance(body, str)
        data = body.encode() if is_text else json.dumps(body, ensure_ascii=False, separators=(',', ':')).encode()
        self.send_response(status)
        for key, value in {'Content-Type': 'text/plain; charset=utf-8' if is_text else 'application/json; charset=utf-8',
                           'Content-Length': str(len(data)), 'Cache-Control': 'no-store',
                           'X-Content-Type-Options': 'nosniff', **(extra or {})}.items():
            self.send_header(key, value)
        self.end_headers()
        if self.command != 'HEAD':
            self.wfile.write(data)

    def do_HEAD(self):
        self.do_GET()

    def do_GET(self):
        acquired = False
        try:
            if len(self.path) > 4096:
                raise APIError(414, 'uri_too_long', 'Request URI is too long')
            parsed = urlsplit(self.path)
            route = unquote(parsed.path)
            if route in ('/healthz', '/health'):
                return self.reply(200, {'ok': True, 'service': 'ideaX library', 'read_only': True})
            if route in ('/', '/llms.txt', '/openapi.json'):
                from library_api_docs import llms_text, openapi
                return self.reply(200, openapi(bool(self.server.credentials)) if route == '/openapi.json' else llms_text(bool(self.server.credentials)))
            if self.server.credentials:
                self.server.credentials.authenticate(self.headers.get('Authorization'))
            if route.startswith('/api/v1/'):
                route = route[4:]
            acquired = self.server.queries.acquire(blocking=False)
            if not acquired:
                raise APIError(503, 'busy', 'Too many concurrent queries; retry later')
            raw = parse_qs(parsed.query, keep_blank_values=True, max_num_fields=16)
            if any(len(v) != 1 for v in raw.values()):
                raise APIError(400, 'invalid_parameter', 'Query parameters must not be repeated')
            params = {k: v[0] for k, v in raw.items()}
            page = None
            domain_match = re.fullmatch(r'/v1/domains/([a-zA-Z0-9_.-]{1,200})(?:/(problems|insights|papers))?', route)
            if route == '/v1/domains':
                data, page = self.server.library.domains(params)
            elif domain_match:
                identifier, resource = domain_match.groups()
                if resource is None:
                    if params:
                        raise APIError(400, 'invalid_parameter', 'Domain detail takes no query parameters')
                    data = self.server.library.domain(identifier)
                elif resource == 'papers':
                    data, page = self.server.library.domain_papers(identifier, params)
                else:
                    self.server.library.domain(identifier)
                    if 'kind' in params or 'unit' in params:
                        raise APIError(400, 'invalid_parameter', 'Domain and kind are fixed by this endpoint')
                    data, page = self.server.library.entries(dict(params, unit=identifier, kind=resource[:-1]))
            elif route in ('/v1/entries', '/v1/search'):
                if route == '/v1/search' and 'q' not in params:
                    raise APIError(400, 'invalid_parameter', 'q is required for search')
                data, page = self.server.library.entries(params)
            elif route == '/v1/papers/by-arxiv':
                if set(params) != {'id'}:
                    raise APIError(400, 'invalid_parameter', 'Only the id parameter is required')
                data = self.server.library.by_arxiv(params['id'])
            elif params:
                raise APIError(400, 'invalid_parameter', 'This endpoint does not accept query parameters')
            elif route == '/v1/stats':
                data = self.server.library.stats()
            elif route == '/v1/units':
                data = self.server.library.units()
            elif re.fullmatch(r'/v1/entries/[a-zA-Z0-9_.-]{1,200}', route):
                data = self.server.library.get('entries', route.rsplit('/', 1)[1])
            elif re.fullmatch(r'/v1/papers/[0-9]{1,20}', route):
                data = self.server.library.get('papers', route.rsplit('/', 1)[1])
            else:
                raise APIError(404, 'not_found', 'Unknown endpoint')
            result = {'ok': True, 'data': data}
            if page is not None:
                result['page'] = page
            self.reply(200, result)
        except APIError as exc:
            self.reply(exc.status, {'ok': False, 'error': {'code': exc.code, 'message': exc.message}},
                       {'WWW-Authenticate': 'Bearer'} if exc.status == 401 else None)
        except ValueError:
            self.reply(400, {'ok': False, 'error': {'code': 'invalid_request', 'message': 'Invalid request'}})
        except sqlite3.OperationalError:
            self.reply(503, {'ok': False, 'error': {'code': 'query_unavailable', 'message': 'Query timed out or database unavailable'}})
        except (BrokenPipeError, ConnectionResetError, TimeoutError):
            pass
        except Exception:
            self.reply(500, {'ok': False, 'error': {'code': 'internal_error', 'message': 'Internal server error'}})
        finally:
            if acquired:
                self.server.queries.release()

    def reject_write(self):
        self.close_connection = True
        self.reply(405, {'ok': False, 'error': {'code': 'read_only', 'message': 'No data mutations are supported'}},
                   {'Allow': 'GET, HEAD', 'Connection': 'close'})

    def do_POST(self):
        acquired = False
        try:
            if self.path not in ('/api/v1/papers/batch', '/v1/papers/batch'):
                return self.reject_write()
            if self.server.credentials:
                self.server.credentials.authenticate(self.headers.get('Authorization'))
            if self.headers.get('Transfer-Encoding') or len(self.headers.get_all('Content-Length', [])) != 1:
                raise APIError(400, 'invalid_request', 'One Content-Length header is required')
            if self.headers.get('Content-Type', '').split(';')[0].strip().lower() != 'application/json':
                raise APIError(415, 'invalid_content_type', 'Use application/json')
            size = bounded_integer(self.headers.get('Content-Length'), 'Content-Length', 0, 1, 8192)
            body = json.loads(self.rfile.read(size))
            if not isinstance(body, dict) or set(body) != {'ids'}:
                raise APIError(400, 'invalid_request', 'Expected an object with only the ids field')
            acquired = self.server.queries.acquire(blocking=False)
            if not acquired:
                raise APIError(503, 'busy', 'Too many concurrent queries; retry later')
            self.reply(200, {'ok': True, 'data': self.server.library.batch(body['ids'])})
        except APIError as exc:
            self.close_connection = True
            self.reply(exc.status, {'ok': False, 'error': {'code': exc.code, 'message': exc.message}})
        except (ValueError, UnicodeError):
            self.close_connection = True
            self.reply(400, {'ok': False, 'error': {'code': 'invalid_json', 'message': 'Invalid JSON body'}})
        except sqlite3.OperationalError:
            self.reply(503, {'ok': False, 'error': {'code': 'query_unavailable', 'message': 'Database unavailable'}})
        except (BrokenPipeError, ConnectionResetError, TimeoutError):
            self.close_connection = True
        except Exception:
            self.reply(500, {'ok': False, 'error': {'code': 'internal_error', 'message': 'Internal server error'}})
        finally:
            if acquired:
                self.server.queries.release()

    do_PUT = do_PATCH = do_DELETE = do_OPTIONS = reject_write


def create_key(auth_file, client_file, name):
    import fcntl
    if not re.fullmatch(r'[a-zA-Z0-9_.-]{1,64}', name):
        raise ValueError('Invalid client name')
    auth_file, client_file = Path(auth_file), Path(client_file)
    auth_file.parent.mkdir(parents=True, exist_ok=True)
    client_file.parent.mkdir(parents=True, exist_ok=True)
    if client_file.exists():
        raise ValueError('Client file already exists; refusing to overwrite')
    with open(str(auth_file) + '.lock', 'a') as lock:
        fcntl.flock(lock, fcntl.LOCK_EX)
        document = json.loads(auth_file.read_text()) if auth_file.exists() else {'clients': {}}
        if name in document['clients']:
            raise ValueError('Client name already exists')
        token = secrets.token_urlsafe(32)
        document['clients'][name] = hashlib.sha256(token.encode()).hexdigest()
        fd = os.open(client_file, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
        with os.fdopen(fd, 'w') as out:
            json.dump({'name': name, 'token': token}, out)
            out.write('\n')
        temporary = auth_file.with_name(auth_file.name + '.' + secrets.token_hex(8) + '.tmp')
        fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
        with os.fdopen(fd, 'w') as out:
            json.dump(document, out, indent=2)
            out.write('\n')
        os.replace(temporary, auth_file)
    print(json.dumps({'created': name, 'client_file': str(client_file), 'auth_file': str(auth_file)}))


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    sub = parser.add_subparsers(dest='command', required=True)
    key = sub.add_parser('create-key')
    key.add_argument('--auth-file', required=True)
    key.add_argument('--client-file', required=True)
    key.add_argument('--name', required=True)
    serve = sub.add_parser('serve')
    serve.add_argument('--db', required=True)
    serve.add_argument('--index', required=True)
    access = serve.add_mutually_exclusive_group(required=True)
    access.add_argument('--auth-file')
    access.add_argument('--public', action='store_true', help='Allow unauthenticated read access to this library')
    serve.add_argument('--host', default='127.0.0.1')
    serve.add_argument('--port', type=int, default=8895)
    args = parser.parse_args()
    if args.command == 'create-key':
        create_key(args.auth_file, args.client_file, args.name)
        return
    library = Library(args.db, args.index)
    # Prepare shared counts before accepting the initial burst of scout reads.
    library.domain_catalog()
    server = Server((args.host, args.port), library, Credentials(args.auth_file) if args.auth_file else None)
    print(f'ideaX read-only library API: http://{args.host}:{server.server_port}', flush=True)
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        pass
    finally:
        server.server_close()


if __name__ == '__main__':
    main()