starfederation / datastar

A real-time hypermedia framework.
https://data-star.dev/
MIT License
732 stars 41 forks source link

Sending lots of requests when backend not reachable #130

Closed gocmarek closed 2 months ago

gocmarek commented 2 months ago

When backend occurred some problem like no answer or wrong answer

such as:

then datastar starting to repeat requesting last request with no any kind of timeout or number or trying

image

delaneyj commented 2 months ago

Per our discussion need a reproducible Go handler to add exponential backoff

gocmarek commented 2 months ago

As mentioned already the problem with go endpoint was on my side. This part is also removed from this issue.

delaneyj commented 2 months ago

Ok please open again if you run into it again and can repro

gocmarek commented 2 months ago

please open it again... reproduction code below

const express = require('express')
const app = express()
const port = 8000

app.get('/', (req, res) => {
    res.send(`
    <!DOCTYPE html>
    <html lang="en">
        <head>
            <meta charset="UTF-8"/>
            <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
            <script type="module" defer src="https://cdn.jsdelivr.net/npm/@sudodevnull/datastar"></script>
            <title>Document</title>
        </head>
        <body>
        <button data-on-click="$$get('/put')">Send State</button>
        <div id="output"></div>
        </body>
    </html>
    `)
})
app.get("/put", (req, res) => {
    setHeaders(res);
    const output = `<h1>Funny DataStar Text</h1>`;
    let frag = `<div id="output">${output}</div>`;
    sendSSE({
        res,
        frag,
        end: true,
    });
});

app.listen(port, () => {
    console.log(`Example app listening on port ${port}`)
})

function sendSSE({ res, frag, selector, mergeType, end }) {
    res.write("event: datastar-fragment\n");
    // this is going to generate error because inner_html is not a valid merge type <= this should be also corrected in documentation; should be inner_element
    // 
    // WHEN ENDPOINT IS GETTING ERROR DATASTAR IS STARTING TO REPEAT THE SAME REQUEST OVER AND OVER AGAIN
    res.write("data: merge inner_html\n");
    /////////////////////////////
    if (selector) res.write(`data: selector ${selector}\n`);
    if (mergeType?.length) res.write(`data: merge ${mergeType}\n`);
    res.write(`data: fragment ${frag}\n\n`);
    if (end) res.end();
}

function setHeaders(res) {
    res.set({
      "Cache-Control": "no-cache",
      "Content-Type": "text/event-stream",
      Connection: "keep-alive",
    });
    res.flushHeaders();
  }