Skip to content

provide writer access to SSE event #3385

Open
@GlenDC

Description

@GlenDC
  • I have looked for existing issues (including closed) about this

Feature Request provide writer access to SSE event

Motivation

For json SSE event data there's a nice function, but in case you have structured data
in a format different then json you are forced to first serialize into something that AsRef<str> (

pub fn data<T>(mut self, data: T) -> Event
where
T: AsRef<str>,
{
if self.flags.contains(EventFlags::HAS_DATA) {
panic!("Called `Event::data` multiple times");
}
for line in memchr_split(b'\n', data.as_ref().as_bytes()) {
self.field("data", line);
}
self.flags.insert(EventFlags::HAS_DATA);
self
}
) so that you can pass it as "string-like" data.

This means that for the datastar rust sdk crate we are forcing users of axum to double allocate or else roll our own SSE which that crate first did.

Proposal

Somehow expose the buffer to write into it. This could be done in an opaque way. E.g. in pseudo code:

// this writer needs to write a new `data: ` prefix when a newline is getting written into it
struct EventWriter<'a>(&'a mut Buffer);

impl Event {
    pub fn data_writer(&mut self) -> EventWriter<'_> {
         // 1. do your same checks if data wasn't written yet
         // 2.if all good write `data:` prefix and set the state that we have data
         // 3.return writer 
}

This could then be used even by the json function.

But even better is that now outside users such as datastar can write data directly into the buffer,
avoiding the extra data allocations for datastar.

Alternatives

Roll our own SSE or accept useless allocations for each event sent...

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions