Prepare verified laboratory 6 implementation and evidence

This commit is contained in:
rey
2026-11-17 17:32:06 +03:00
parent 470d9d6f1e
commit 7d56e52fd0
335 changed files with 31206 additions and 72 deletions
+31
View File
@@ -0,0 +1,31 @@
package server
import (
"context"
"net/http"
"time"
)
type Server struct {
httpServer *http.Server
}
func New(addr string, handler http.Handler) *Server {
return &Server{httpServer: &http.Server{
Addr: addr,
Handler: handler,
ReadHeaderTimeout: 5 * time.Second,
ReadTimeout: 15 * time.Second,
WriteTimeout: 15 * time.Second,
IdleTimeout: 60 * time.Second,
MaxHeaderBytes: 16 << 10,
}}
}
func (s *Server) ListenAndServe() error { return s.httpServer.ListenAndServe() }
// Shutdown сразу закрывает слушающий сокет (новые соединения не принимаются)
// и ждёт завершения начатых запросов, но не дольше ctx.
func (s *Server) Shutdown(ctx context.Context) error { return s.httpServer.Shutdown(ctx) }
func (s *Server) Close() error { return s.httpServer.Close() }
+49
View File
@@ -0,0 +1,49 @@
package server
import (
"context"
"net"
"net/http"
"testing"
"time"
)
func TestForceCloseCancelsActiveRequestAfterDrainExpires(t *testing.T) {
entered, canceled := make(chan struct{}), make(chan struct{})
s := New("127.0.0.1:0", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { close(entered); <-r.Context().Done(); close(canceled) }))
listener, e := net.Listen("tcp", "127.0.0.1:0")
if e != nil {
t.Fatal(e)
}
done := make(chan error, 1)
go func() { done <- s.httpServer.Serve(listener) }()
response := make(chan struct{})
go func() {
defer close(response)
client := &http.Client{Timeout: 2 * time.Second}
r, e := client.Get("http://" + listener.Addr().String())
if e == nil {
r.Body.Close()
}
}()
select {
case <-entered:
case <-time.After(time.Second):
t.Fatal("own request did not start")
}
ctx, cancel := context.WithCancel(context.Background())
cancel()
if e = s.Shutdown(ctx); e == nil {
t.Fatal("canceled drain unexpectedly succeeded")
}
if e = s.Close(); e != nil {
t.Fatal(e)
}
select {
case <-canceled:
case <-time.After(time.Second):
t.Fatal("force close left active request context live")
}
<-response
<-done
}