FooSoft / anki-connect

Anki plugin to expose a remote API for creating flash cards.
https://foosoft.net/projects/anki-connect/
Other
1.92k stars 218 forks source link

Proposal: close client connection after handling request/response #402

Open Darkclainer opened 12 months ago

Darkclainer commented 12 months ago

Hello, thank you for great project!

I propose closing client connection after response without trying to reuse it.

Recently I tried using anki-connect with Go http client under heavy CPU load and discovered the anki-connect can't reuse connections properly every time. The reason probably in a way how client connections updated^ https://github.com/FooSoft/anki-connect/blob/master/plugin/__init__.py#L72 . Probably more reliable way to deal with socket is to use some event loop, but this can be unrealistic because anki-connect is plugin for Anki.

Anyway this behavior can be replicated with curl:

curl -vI 127.0.0.1:8765 --next 127.0.0.1:8765
* processing: 127.0.0.1:8765
*   Trying 127.0.0.1:8765...
* Connected to 127.0.0.1 (127.0.0.1) port 8765
> HEAD / HTTP/1.1
> Host: 127.0.0.1:8765
> User-Agent: curl/8.2.1
> Accept: */*
>
< HTTP/1.1 200 OK
HTTP/1.1 200 OK
< Content-Type: text/json
Content-Type: text/json
< Access-Control-Allow-Origin: http://localhost
Access-Control-Allow-Origin: http://localhost
< Access-Control-Allow-Headers: *
Access-Control-Allow-Headers: *
< Content-Length: 15
Content-Length: 15

<
* Excess found: excess = 15 url = / (zero-length body)
* Connection #0 to host 127.0.0.1 left intact
* processing: 127.0.0.1:8765
* Found bundle for host: 0x55e498c03d30 [serially]
* Can not multiplex, even if we wanted to
* Connection 0 seems to be dead
* Closing connection
* Hostname 127.0.0.1 was found in DNS cache
*   Trying 127.0.0.1:8765...
* Connected to 127.0.0.1 (127.0.0.1) port 8765
> GET / HTTP/1.1
> Host: 127.0.0.1:8765
> User-Agent: curl/8.2.1
> Accept: */*
>
< HTTP/1.1 200 OK
< Content-Type: text/json
< Access-Control-Allow-Origin: http://localhost
< Access-Control-Allow-Headers: *
< Content-Length: 15
<
* Connection #1 to host 127.0.0.1 left intact
AnkiConnect v.6

Consider how second request is handled:

* Connection #0 to host 127.0.0.1 left intact
* processing: 127.0.0.1:8765
* Found bundle for host: 0x55e498c03d30 [serially]
* Can not multiplex, even if we wanted to
* Connection 0 seems to be dead
* Closing connection
* Hostname 127.0.0.1 was found in DNS cache
*   Trying 127.0.0.1:8765...

curl attempted to reuse Connection #0 but had no response on it, therefore opened new connection. I suggest that correct behavior for anki-connect would be either close Connection #0 immediately after response, or reuse it properly.

Thank you for attention! I should say that there is easy workaround on client side: just close connection after getting response.