File size: 2,342 Bytes
1e04d49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

import os
import time
from pathlib import Path

from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse, PlainTextResponse


LOG_PATH = Path("/tmp/minimal-space.log")
START_TS = time.strftime("%Y-%m-%dT%H:%M:%S%z")


def log(message: str) -> None:
    line = f"[{time.strftime('%Y-%m-%dT%H:%M:%S%z')}] {message}"
    print(line, flush=True)
    try:
        with LOG_PATH.open("a", encoding="utf-8") as f:
            f.write(line + "\n")
    except Exception:
        pass


log("minimal_static_app module import begin")
app = FastAPI()
log("FastAPI app object created")


@app.on_event("startup")
async def startup() -> None:
    log("startup event begin")
    log(f"python={os.sys.version.split()[0]}")
    log(f"cwd={os.getcwd()}")
    log("startup event end")


@app.middleware("http")
async def request_logger(request: Request, call_next):
    log(f"request start method={request.method} path={request.url.path}")
    response = await call_next(request)
    log(f"request end method={request.method} path={request.url.path} status={response.status_code}")
    return response


@app.get("/health")
def health() -> dict[str, str]:
    log("health handler")
    return {"status": "ok", "started_at": START_TS}


@app.get("/logs")
def logs() -> PlainTextResponse:
    log("logs handler")
    try:
        return PlainTextResponse(LOG_PATH.read_text(encoding="utf-8"))
    except FileNotFoundError:
        return PlainTextResponse("no log file yet\n")


@app.get("/", response_class=HTMLResponse)
def root() -> str:
    log("root handler")
    return f"""
<!doctype html>
<html>
  <head>
    <meta charset=\"utf-8\">
    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">
    <title>Minimal Space</title>
    <style>
      body {{ font-family: sans-serif; max-width: 800px; margin: 40px auto; padding: 0 16px; }}
      code, pre {{ background: #f4f4f4; padding: 2px 6px; border-radius: 4px; }}
      pre {{ padding: 12px; overflow: auto; }}
    </style>
  </head>
  <body>
    <h1>Minimal Space is alive</h1>
    <p>Started at: <code>{START_TS}</code></p>
    <p><a href=\"/health\">/health</a></p>
    <p><a href=\"/logs\">/logs</a></p>
    <pre>This page is intentionally minimal.</pre>
  </body>
</html>
"""


log("minimal_static_app module import end")