Skip to content

Commit

Permalink
Merge pull request #5 from notatallshaw/Move-simple-api-mirror-to-/si…
Browse files Browse the repository at this point in the history
…mple-and-add-shutdown-endpoint

Move simple API to /simple and add shutdown endpoint
  • Loading branch information
notatallshaw authored Oct 20, 2024
2 parents 115ab14 + 47d3257 commit 79a169a
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 3 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ pip-timemachine 2023-10-18T12:00:00

And then point pip (or any other installer) to use this server as an index:
```bash
pip install requests --index http://127.0.0.1:8040
pip install requests --index http://127.0.0.1:8040/simple
```

### CLI Options
Expand Down
26 changes: 24 additions & 2 deletions src/pip_timemachine/main.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import datetime as dt
import logging
import threading
from functools import cache

import niquests
Expand All @@ -22,6 +23,7 @@
app = FastAPI()

# Global Vars
UNICORN_SERVER: uvicorn.Server | None = None
MOMENT: Instant = Instant.now()
INDEX: str = "https://pypi.org/simple"
REQUIRED_API_VERSION = (1, 1)
Expand Down Expand Up @@ -78,7 +80,23 @@ def filter_files_by_moment(files: list[dict]) -> tuple[list, dict]:
return modified_files, modified_versions


@app.get("/{package_name}")
@app.get("/shutdown-pip-timemachine-server")
async def shutdown_pip_timemachine_server():
"""
Endpoint to gracefully shut down the FastAPI server.
"""
def shutdown():
if UNICORN_SERVER:
UNICORN_SERVER.should_exit = True

# Run the shutdown in a separate thread to allow the response to return first
shutdown_thread = threading.Thread(target=shutdown)
shutdown_thread.start()

return JSONResponse({"message": "Server is shutting down."})


@app.get("/simple/{package_name}")
async def get_pypi_package_info(package_name: str, request: Request) -> Response:
# Determine content type based on "Accept" header
accept_header = request.headers.get("Accept")
Expand Down Expand Up @@ -125,10 +143,14 @@ async def get_pypi_package_info(package_name: str, request: Request) -> Response
def run_server(moment: dt.datetime, index: str = INDEX, port: int = 8040):
global MOMENT
global INDEX
global UNICORN_SERVER
MOMENT = Instant.from_py_datetime(moment.replace(tzinfo=dt.UTC))
INDEX = index.rstrip("/")

uvicorn.run("pip_timemachine.main:app", port=port)
UNICORN_SERVER = uvicorn.Server(
uvicorn.Config("pip_timemachine.main:app", port=port)
)
UNICORN_SERVER.run()


def main():
Expand Down

0 comments on commit 79a169a

Please sign in to comment.