package cli import ( "context" "errors" "fmt" "net" "net/http" "syscall" httpadapter "gitea.maximumdirect.net/eric/scriptorium/internal/adapter/http" "gitea.maximumdirect.net/eric/scriptorium/internal/defaults" "go.maximumdirect.net/commandkit" "go.maximumdirect.net/promptkit" ) func serveHTTP(invocation commandkit.Invocation, input serveInput) commandkit.Outcome { return serveWithListener(invocation, input, (&net.ListenConfig{}).Listen) } func serveWithListener(invocation commandkit.Invocation, input serveInput, listen func(context.Context, string, string) (net.Listener, error)) commandkit.Outcome { result, err := loadApplication(invocation.Context, input.Selection, input.Application, struct{}{}) explanation := applicationConfigurationDiagnostics(invocation.Reporter(), result, err) if err != nil { return requestFailure(err, explanation) } settings := result.Config.Server reader, err := httpadapter.NewRestrictedArtifactReader(settings.ArtifactRoot, settings.MaxArtifactBytes) if err != nil { return commandkit.Failure("Could not initialize the HTTP artifact reader.").WithCause(err) } engine, err := newEngine(result, promptkit.WithArtifactReader(reader)) if err != nil { return frameworkFailure(invocation.Reporter(), err, explanation) } server := &http.Server{ Addr: settings.Addr, Handler: httpadapter.NewHandlerWithOptions(engine, httpadapter.HandlerOptions{MaxRequestBytes: settings.MaxRequestBytes, MaxResponseBytes: settings.MaxResponseBytes}), ReadHeaderTimeout: defaults.HTTPReadHeaderTimeoutDefault, } listener, err := listen(invocation.Context, "tcp", settings.Addr) if err != nil { return commandkit.Failure(fmt.Sprintf("Could not listen on %q: %s.", settings.Addr, listenerFailureCategory(err))).WithCause(err) } _ = invocation.Reporter().Info(fmt.Sprintf("Serving HTTP on %s.", listener.Addr())) closed := make(chan struct{}) var cancellationCloseErr error stop := context.AfterFunc(invocation.Context, func() { cancellationCloseErr = server.Close(); close(closed) }) serveErr := server.Serve(listener) if !stop() { <-closed } closeErr := errors.Join(cancellationCloseErr, server.Close()) if errors.Is(serveErr, http.ErrServerClosed) && invocation.Context.Err() != nil { return commandkit.Failure("HTTP server stopped after cancellation.").WithCause(errors.Join(invocation.Context.Err(), closeErr)) } return commandkit.Failure("HTTP server stopped unexpectedly.").WithCause(errors.Join(serveErr, closeErr)) } func listenerFailureCategory(err error) string { var address *net.AddrError var dns *net.DNSError switch { case errors.As(err, &address), errors.As(err, &dns): return "invalid or unresolvable address" case errors.Is(err, syscall.EADDRINUSE): return "address already in use" case errors.Is(err, syscall.EACCES), errors.Is(err, syscall.EPERM): return "permission denied" default: return "listener setup failed" } }