fanout / django-eventstream

Server-Sent Events for Django
MIT License
664 stars 88 forks source link

send_event triggers too many events #88

Closed xtlc closed 2 years ago

xtlc commented 2 years ago

Not sure what exactly the issues is here, but I need some help:

When using the function:

msg = "<h1>tesst</h1>"
send_event("mychannel", "message", msg, json_encode = False)

the string inside the html returned to the frontend is always "" escaped. ( -> "tesst" instead of tesst, but <h1> is applied correctly):

"
<b>tesst</b>
"

I hacked a little bit in the code and found sse_encode_event(event_type, data, event_id=None, escape=False, json_encode=True) and I added a print(f"event_type: {event_type}, json_encode: {json_encode}) statement at the start of the function to see what one call does:


> event_type: message, data: <b>tesst</b>, json_encode: False
> event_type: message, data: <b>tesst</b>, json_encode: True
> event_type: message, data: <b>tesst</b>, json_encode: True
> event_type: message, data: <b>tesst</b>, json_encode: True
> event_type: message, data: <b>tesst</b>, json_encode: True

What I did to get it working is add json_encode = False in the utils.py sse_encode_event() function for testing.

So I tested that with adding a reply() function where send_event() is being called like this:

def reply(msg):
    logging.error("reply triggered")
    send_event("mychannel", "message", "<b>tesst</b>")

This produces:

> reply calledevent_type: message, data: <b>tesst</b>, json_encode: Falseevent_type: message, data: <b>tesst</b>, json_encode: Trueevent_type: message, data: <b>tesst</b>, json_encode: True
> event_type: message, data: <b>tesst</b>, json_encode: True
> event_type: message, data: <b>tesst</b>, json_encode: True
> event_type: message, data: <b>tesst</b>, json_encode: True
> event_type: message, data: <b>tesst</b>, json_encode: True
> event_type: message, data: <b>tesst</b>, json_encode: True

So what happens is, that there are multiple events being sent out instead of a single one and all but the first ones ignore the json_encode setting.

jkarneges commented 2 years ago

Thanks for the report. I've figured out what is going on. The number of calls to sse_encode_event is as expected (once for each connected client and once for django_grip). The problem is as the codebase has grown, the json_encode option hasn't been respected in various places. I suspect setting json_encode=False right now results in all kinds of misbehavior and shouldn't be used.

I'll fix this very soon.

jkarneges commented 2 years ago

Fixed in 4.4.1.