File size: 3,505 Bytes
d598032
 
 
 
 
 
7f72224
 
 
 
 
 
 
 
 
 
 
 
d598032
 
 
7f72224
d598032
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aa5687d
 
 
 
 
 
 
 
 
 
 
 
d598032
 
 
7f72224
 
d598032
 
 
 
 
 
 
 
 
aa5687d
d598032
 
 
 
7f72224
d598032
 
 
 
 
 
 
 
 
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
"""C3: mount every C1 App router by name, recording a failed import instead of raising it."""
from __future__ import annotations

from importlib import import_module

import app_templates
from fastapi import APIRouter, Depends
from deps import Session, require_session, running_main


availability_router = APIRouter(prefix="/api/v1/applications", tags=["applications"])


@availability_router.get("/{app_id}/availability")
def app_availability(app_id: str, session: Session = Depends(require_session)):
    """Read one App's availability through the authenticated tenant and App walls."""
    import application_registry
    return application_registry.opening(session, app_id)


def _failures_record():
    main = running_main()
    record = getattr(main, "ROUTER_MOUNT_FAILURES", None) if main is not None else None
    return record if isinstance(record, dict) else app_templates.ROUTER_MOUNT_FAILURES


def _flat(routes):
    """Every route, descending into a router FastAPI keeps as one included entry."""
    for route in routes:
        yield route
        inner = getattr(route, "original_router", None)
        if inner is not None:
            yield from _flat(inner.routes)


def _included(app, router):
    endpoints = {getattr(route, "endpoint", None) for route in _flat(router.routes)}
    endpoints.discard(None)
    return any(getattr(route, "original_router", None) is router
               or getattr(route, "endpoint", None) in endpoints for route in _flat(app.routes))


def held_dependencies(kind):
    """Router dependencies that answer 404 on every route of a held kind (R11), else none."""
    if not app_templates.held(kind):
        return []
    from fastapi import Depends
    from deps import err

    def refuse_held():
        raise err(404, "app_held", "This App is not available yet.")
    return [Depends(refuse_held)]


def mount_app_routers(app, failures=None):
    """Include each C1 `router` once, with main.py `_mount_router` semantics; returns those mounted."""
    record = failures if isinstance(failures, dict) else _failures_record()
    if not _included(app, availability_router):
        app.include_router(availability_router)
    mounted = []
    for row in app_templates.TEMPLATES:
        name = row["router"]
        if not name:
            continue
        try:
            router = import_module(name).router
            # An already included router (Competitor watch, mounted by main.py) is not added twice.
            if not _included(app, router):
                app.include_router(router, dependencies=held_dependencies(row["kind"]))
        except Exception as exc:  # Boot must answer even when a router cannot load.
            failure = {"error": type(exc).__name__,
                       "missing_module": exc.name if isinstance(exc, ModuleNotFoundError) else ""}
            record.setdefault(name, []).append(failure)
            if record is not app_templates.ROUTER_MOUNT_FAILURES:
                # The offer predicate reads main.py's record and this one, never a caller's own dict.
                app_templates.ROUTER_MOUNT_FAILURES.setdefault(name, []).append(failure)
            # Exception messages can contain configuration values; report the class/module only.
            print(f"[aios-api] ROUTER MOUNT FAILED: {name}: {failure}; "
                  "its App template is withheld until the router mounts")
            continue
        app_templates.MOUNTED_ROUTERS.add(name)
        mounted.append(name)
    return mounted