Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,9 @@ jobs:
- name: Run FPC router lifetime regression
run: sh tests/fpc-router-lifetime/run-router-lifetime-test.sh

- name: Run FPC HTTPApplication graceful shutdown regression
run: sh tests/fpc-graceful-shutdown/run-graceful-shutdown-test.sh

- name: Run FPC URL decoding regression
run: sh tests/fpc-url-decoding/run-url-decoding-test.sh

Expand Down
1 change: 1 addition & 0 deletions doc/graceful-shutdown.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ The graceful shutdown protocol and drain loop are natively implemented in the fo
* **Daemon Provider** (`Horse.Provider.Daemon`)
* **Lazarus/LCL Provider** (`Horse.Provider.FPC.LCL`)
* **Lazarus Daemon Provider** (`Horse.Provider.FPC.Daemon`)
* **FPC HTTPApplication Provider** (`Horse.Provider.FPC.HTTPApplication`)
* **IOCP Provider** (`Horse.Provider.IOCP`)
* **HTTP.sys Provider** (`Horse.Provider.HttpSys`)

Expand Down
1 change: 1 addition & 0 deletions doc/graceful-shutdown.pt-BR.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ O protocolo de desligamento suave e o ciclo de escoamento de requisições ativa
* **Daemon Provider** (`Horse.Provider.Daemon`)
* **Lazarus/LCL Provider** (`Horse.Provider.FPC.LCL`)
* **Lazarus Daemon Provider** (`Horse.Provider.FPC.Daemon`)
* **FPC HTTPApplication Provider** (`Horse.Provider.FPC.HTTPApplication`)
* **IOCP Provider** (`Horse.Provider.IOCP`)
* **HTTP.sys Provider** (`Horse.Provider.HttpSys`)

Expand Down
113 changes: 112 additions & 1 deletion src/Horse.Provider.FPC.HTTPApplication.pas
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ THorseProvider = class(THorseProviderAbstract)
class var FRunning: Boolean;
class var FListenQueue: Integer;
class var FHTTPApplication: THTTPApplication;
class var FStopRequested: LongInt;
class var FStopFinished: LongInt;
class function GetDefaultHTTPApplication: THTTPApplication;
class function HTTPApplicationIsNil: Boolean;
class procedure SetListenQueue(const AValue: Integer); static;
Expand All @@ -40,6 +42,9 @@ THorseProvider = class(THorseProviderAbstract)
class function GetHost: string; static;
class procedure InternalListen; virtual;
class procedure DoGetModule(Sender: TObject; ARequest: TRequest; var ModuleClass: TCustomHTTPModuleClass);
class procedure DoAcceptIdle(Sender: TObject);
class function StopIsRequested: Boolean;
class procedure StopAccepting(const AApplication: THTTPApplication);
{$IF FPC_FULLVERSION >= 30301}
class procedure EnableServerKeepAlive(const AApplication: THTTPApplication);
class procedure ConfigureServerTransport(const AApplication: THTTPApplication);
Expand All @@ -61,6 +66,8 @@ THorseProvider = class(THorseProviderAbstract)
// PATCH-FPCHTTP-1
class procedure ListenWithConfig(const APort: Integer;
const AConfig: THorseCrossSocketConfig); override;
class procedure StopListen; override;
class procedure StopListenGraceful(const ATimeoutMS: Integer); override;
class function IsRunning: Boolean;
end;
{$ENDIF}
Expand All @@ -71,11 +78,24 @@ implementation

uses
Horse.WebModule,
Horse.Core,
Horse.Response
{$IF FPC_FULLVERSION >= 30301}, custhttpapp, fphttpserver, ssockets{$ENDIF}
{$IF DEFINED(FPC) AND DEFINED(UNIX)}, Sockets{$ENDIF}
{$IF DEFINED(FPC) AND DEFINED(MSWINDOWS)}, WinSock2{$ENDIF};

const
{ The accept loop wakes up this often while idle, so a stop
requested before Run starts accepting (Terminate cannot break an accept loop
that has not started yet) is still honoured on the next idle tick. }
STOP_ACCEPT_IDLE_MS = 100;
STOP_DRAIN_POLL_MS = 50;
{ Listen polls the end of the drain instead of waiting on an OS event: an
event created at unit initialization would break programs that never
stop the server and run without a thread manager (no cthreads). }
STOP_FINISHED_POLL_MS = 10;
DEFAULT_STOP_TIMEOUT_MS = 5000;

{$IF FPC_FULLVERSION >= 30301}
const
{ Per-request keep-alive lifetime handed to the embedded fphttpserver so its
Expand Down Expand Up @@ -292,9 +312,100 @@ class procedure THorseProvider.InternalListen;
EnableServerKeepAlive(LHTTPApplication);
ConfigureServerTransport(LHTTPApplication);
{$ENDIF}
{ With a positive idle timeout the accept loop polls
DoAcceptIdle, which stops accepting once a stop was requested. }
LHTTPApplication.AcceptIdleTimeout := STOP_ACCEPT_IDLE_MS;
LHTTPApplication.OnAcceptIdle := DoAcceptIdle;
FRunning := True;
DoOnListen;
LHTTPApplication.Run;
try
if not StopIsRequested then
LHTTPApplication.Run;

{ Run returns as soon as the accept loop ends; Listen only returns after
StopListenGraceful finished draining, so callers that exit right after
Listen do not race the drain. }
if StopIsRequested then
while InterlockedCompareExchange(FStopFinished, 0, 0) = 0 do
Sleep(STOP_FINISHED_POLL_MS);
finally
FRunning := False;
InterlockedExchange(FStopFinished, 0);
InterlockedExchange(FStopRequested, 0);
end;
end;

class function THorseProvider.StopIsRequested: Boolean;
begin
Result := InterlockedCompareExchange(FStopRequested, 0, 0) <> 0;
end;

class procedure THorseProvider.DoAcceptIdle(Sender: TObject);
begin
if StopIsRequested then
StopAccepting(GetDefaultHTTPApplication);
end;

class procedure THorseProvider.StopAccepting(const AApplication: THTTPApplication);
{$IF FPC_FULLVERSION >= 30301}
var
LHandler: TFPHTTPServerHandler;
LServer: TEmbeddedHttpServer;
{$ENDIF}
begin
{ Terminate marks the application so Run leaves its loop. It reaches the
handler (and the server) only the first time, so a call made before Run
starts accepting would be lost: the embedded server is also switched off
directly, which is what the idle guard relies on. }
AApplication.Terminate;
{$IF FPC_FULLVERSION >= 30301}
LHandler := AApplication.HTTPHandler;
if LHandler <> nil then
begin
LServer := THorseHTTPServerHandlerAccess(LHandler).HTTPServer;
if LServer <> nil then
begin
{ Idle keep-alive connections re-read KeepConnections on every loop and
leave within the idle poll instead of holding the stop for the whole
keep-alive window; requests in flight are not cut. }
THorseEmbeddedServerAccess(LServer).KeepConnections := False;
LServer.Active := False;
end;
end;
{$ENDIF}
end;

class procedure THorseProvider.StopListen;
begin
StopListenGraceful(DEFAULT_STOP_TIMEOUT_MS);
end;

class procedure THorseProvider.StopListenGraceful(const ATimeoutMS: Integer);
var
LStart: QWord;
begin
{ Documented order (doc/graceful-shutdown.md): mark the
shutdown, stop listening, drain the active requests up to ATimeoutMS, then
release Listen. A stop requested before Listen reaches Run makes Listen
return without serving; a second call is a no-op. }
if InterlockedExchange(FStopRequested, 1) <> 0 then
Exit;

TriggerBeforeStop;
THorseCore.SetIsShuttingDown(True);
try
if not HTTPApplicationIsNil then
StopAccepting(GetDefaultHTTPApplication);

LStart := GetTickCount64;
while (GetDrainActiveRequests > 0) and (GetTickCount64 - LStart < QWord(ATimeoutMS)) do
Sleep(STOP_DRAIN_POLL_MS);

DoOnStopListen;
finally
THorseCore.SetIsShuttingDown(False);
InterlockedExchange(FStopFinished, 1);
end;
end;

class procedure THorseProvider.DoGetModule(Sender: TObject; ARequest: TRequest; var ModuleClass: TCustomHTTPModuleClass);
Expand Down
Loading
Loading