Cowboy 2 - doing cleanup work after connection closes

A part of my app does some work to create a file, sends the file to the client, and then deletes the file.

With Cowboy 1, the following worked fine:

send_file(conn, 200, filename)
File.rm(filename)

Because the file handle was already held by the send_file call, deleting the file right away worked fine in Cowboy 1. But with Cowboy 2, there is a two-processes-per-connection architecture, and the above no longer works.

What should I be doing instead?

2 Likes

@anelixiruser Your best bet is to do what Plug.Upload does and have another process create a temp file and monitor your http process, and then it deletes that file when the http process exits. We extracted the logic into https://github.com/CargoSense/briefly although we really need to handle some issues / update the hex docs for that package.

{:ok, path} = Briefly.create
File.write!(path, "Some Text")
content = File.read!(path)
# When this process exits, the file at `path` is removed

With this, you don’t need to call File.rm explicitly at all.

7 Likes

Thanks for the suggestion! That library is awesome both as an implementation and an example, and it looks like it does a much better job of addressing a bunch of edge cases I have not yet had a chance to deal with.

1 Like