palantir / witchcraft-go-server

A highly opinionated Go embedded application server for RESTy APIs

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Ability to shutdown server with error

ryanmcnamara opened this issue · comments

commented

Feature Request

A common pattern is to run background tasks (goroutines) from an init server function (e.g. a controller). When these background tasks fail, (consider the case where due to a programmer bug there is a panic)

It would be nice to write an init func something like

func main() {
    err := startServer()
    if err != nil {
        os.Exit(1)
    }
    os.Exit(0)
}

func startServer() error {
	return witchcraft.NewServer().
		WithInitFunc(initFunc).
		Start()
}

func initFunc(ctx context.Context, info witchcraft.InitInfo) (cleanup func(), rErr error) {
	go func() {
        err := doBackgroundTask(ctx)

        // ... log / handle error

		if err != nil{
			err := info.ShutdownServerWithError(ctx, err)

            // ... handle err

		} else {
            info.ShutdownServer(ctx)
        }
	}()
	return nil, doRun(ctx,conf)
}

And have server.Start() actually return an error as desired.

Strawman proposal would be to add a new method to InitInfo:

	// ShutdownServerWithErr closes the server, waiting for any in-flight requests to finish (or the context to be cancelled).
	// The server is shutdown with an error, causing `Start` to return an error.
	ShutdownServer func(context.Context, err error) error

I'd be happy to implement this if this sounds good.

Thanks for the feedback. Just for clarification, is it the case that the current Close() and Shutdown(context.Context) functions do close/shut down the server, but cause the start function to just return nil rather than an error?

commented

Yup, exactly

Got it. Yes, I think this is reasonable -- would just say that, in the comment/documentation for the function, you should note that the function is the equivalent of calling Shutdown, but will return a non-nil error. I think it would also make sense for the PR to update the implementation of Shutdown to use ShutdownServer with a nil error.