AntaresSimulatorTeam / AntaREST

API REST and WebUI for Antares_Simulator
Apache License 2.0
12 stars 6 forks source link

Lock all endpoints when the maintenance mode is activated #790

Open Hyralc opened 2 years ago

Hyralc commented 2 years ago

Currently the API can be used even if the server is in maintenance mode. We should add checks in all the endpoints to verify the API is not in maintenance mode.

Warning: the /core/maintenance endpoint must not be locked.

NOTE: The HyperText Transfer Protocol (HTTP) 503 Service Unavailable server error response code indicates that the server is not ready to handle the request. Common causes are a server that is down for maintenance or that is overloaded.

laurent-laporte-pro commented 1 year ago

Pour implémenter un middleware de maintenance dans votre application web basée sur FastAPI, vous pouvez suivre ces étapes :

  1. Créez une nouvelle fonction de middleware qui vérifie l'état de maintenance en utilisant un booléen ou une variable globale.
  2. Si le service est en maintenance, utilisez la fonction abort() de FastAPI pour renvoyer une réponse HTTP 503 (Service Unavailable) avec un message approprié.
  3. Ajoutez cette fonction de middleware à l'application FastAPI en utilisant la méthode .middleware()

Voici un exemple de code qui implémente cette fonctionnalité :

from fastapi import FastAPI, HTTPException

app = FastAPI()

MAINTENANCE_MODE = True

@app.middleware("http")
async def maintenance_middleware(request: Request, call_next):
    if MAINTENANCE_MODE:
        raise HTTPException(status_code=503, detail="We're under maintenance. Please come back later.")
    response = await call_next(request)
    return response

En utilisant cette méthode, toutes les requêtes entrantes passeront par ce middleware avant d'atteindre les routes de l'application, ce qui permet de vérifier l'état de maintenance avant de traiter la requête.

laurent-laporte-pro commented 1 year ago

In the AntaREST application, we setup the middleware functions/classes in the antarest.main.fastapi_app function. The maintenance middleware can be inserted anywhere but it is better to put it in the first ones to block the requests as soon as possible.

This middleware must use the get_maintenance_status method which is accessible from the MaintenanceService instance created when calling the create_services utility function. The status is True when in maintenance and False otherwise.

When in maintenance, an error message must be returned. We can use the MaintenanceService.get_message_info method to get the message indicating the reason for the maintenance. Be careful, the operator performing the maintenance can express himself in French.