Flask-socketio misses events while copying file in background thread
<p>(Complete test app on github: <a href="https://github.com/olingerc/socketio-copy-large-file" rel="nofollow">https://github.com/olingerc/socketio-copy-large-file</a>)</p>

<p>I am using Flask together with the Flask-SocketIO plugin. My clients can ask the server to copy files via websocket but while the files are copying, I want the clients to be able to communicate with the server to ask it to do other things. My solution is to run the copy process (shutil) in a background thread. This is the function:</p>

<pre><code>def copy_large_file():
    source = "/home/christophe/Desktop/largefile"
    destination = "/home/christophe/Desktop/largefile2"
    try:
        os.remove(destination)
    except:
        pass
    print("Before copy")
    socketio.emit('my_response',
                  {'data': 'Thread says: before'}, namespace='/test')
    shutil.copy(source, destination)
    print("After copy")
    socketio.emit('my_response',
                  {'data': 'Thread says: after'}, namespace='/test')
</code></pre>

<p>I observe the following behavior:
When starting the function using the native socketio method:</p>

<pre><code>socketio.start_background_task(target=copy_large_file)
</code></pre>

<p>all incoming events while a large file is being copied are delayed until the file is finished and a next file is started. I gues shutil is not relasing the GIL or something like that, so I tested with threading:</p>

<pre><code>thread = threading.Thread(target=copy_large_file)
thread.start()
</code></pre>

<p>same behaviour. Maybe multiprocessing?</p>

<pre><code>thread = multiprocessing.Process(target=copy_large_file)
thread.start()
</code></pre>

<p>Ah! That works and signals emitted via socketio within the copy_large_file function are correctly received.
BUT:
If a user starts to copy a very large file, closes their browser and comes back 2 minutes later, the socket no longer connects to the same socketio "session?" and thus no longer receives messages emitted from the background process.</p>

<p>I guess the main question is: How can I copy large files in the background without blocking flask-socketio but still being able to emit signals to the client from within the background process.</p>

<p>The test app can be used to reproduce the behaviour:</p>

<ul>
<li>clone <a href="https://github.com/olingerc/socketio-copy-large-file" rel="nofollow">https://github.com/olingerc/socketio-copy-large-file</a></li>
<li>Install requirements</li>
<li>Choose method in the copy_file function (line 42)</li>
<li>Start with ./app.py</li>
</ul>

<p>In the browser:</p>

<ul>
<li>go to localhost:5000</li>
<li>Click on Copy file</li>
<li>Click on Ping to send a message while the file is being copied</li>
<li>Also watch for other signals from background thread</li>
</ul>

<p>You are asking two separate questions.</p>

<p>First, let's discuss the actual copying of the file.</p>

<p>It looks like you are using eventlet for your server. While this framework provides asynchronous replacements for network I/O functions, disk I/O is much more complicated to do in a non-blocking fashion, in particular on Linux (some info on the problem <a href="http://davmac.org/davpage/linux/async-io.html" rel="nofollow">here</a>). So doing I/O on files even with the standard library monkey patched causes blocking, as you have noticed. This is the same with gevent, by the way.</p>

<p>A typical solution to perform non-blocking I/O on files is to use a thread pool. With eventlet, the <a href="http://eventlet.net/doc/threading.html#eventlet.tpool.execute" rel="nofollow">eventlet.tpool.execute</a> function can do this. So basically, instead of calling <code>copy_large_file()</code> directly, you will call <code>tpool.execute(copy_large_file)</code>. This will enable other green threads in your application to run while the copy takes place in another system thread. Your solution of using another process is also valid, by the way, but it may be overkill depending on how many times and how frequently you need to do one of these copies.</p>

<p>Your second question is related to "remembering" a client that starts a long file copy, even if the browser is closed and reopened.</p>

<p>This is really something your application needs to handle by storing the state that is necessary to restore a returning client. Presumably your clients have a way to identify with your application, either with a token or some other identification. When the server starts one of these file copies, it can assign an id to the operation, and store that id in a database, associated with the client that requested it. If the client goes away and then returns, you can find if there are any ongoing file copies for it, and that way sync the client back to the way it was before it closed the browser.</p>

<p>Hope this helps!</p>

python multithreading multiprocessing eventlet flask-socketio