Updating global variables under SwiftNIO

I'm new to SwiftNIO, trying to build a simple HTTP server on top of it.

Say I have a global variable that is a database connection resource used in channel handlers. I want to implement a "hot" reload of the server configuration which may result in the DB connection configuration change. Therefore, I need a safe way of creating a new DB connection and updating the corresponding global variable.

Additionally I want any such update to take effect only for the newly created handlers, whereas the currently running ones should see the previous values. (Because otherwise it would probably make more sense to just gracefully restart the whole server.)

What is the common practice of making such updates in the SwiftNIO environment?

PS. answers with or without structured concurrency will be appreciated. Thanks!

Assuming this is a global variable, this will require a lock that guards access to that variable. It's the only safe way to allow concurrent reads and mutations of global storage like this.

The easiest way to do this is to pass the database connection to the handler constructor, and then never load it from global storage again. That way each handler will only see the value of the database connection at the time that it was constructed.

1 Like