Rook
РусскийRUGet started
// Ten files, three at a time. The limit is not a counter: it is three
// uploaders that take files from one queue, each the next one only
// when it is done with its own. A try that takes longer than 2 s is
// aborted, and a file is tried up to three times

interface File {
    name string
    size number                     // KB
}

const FILES File[] = [
    { name: "beach.jpg", size: 1200 },
    { name: "notes.pdf", size: 300 },
    { name: "cat.png", size: 800 },
    { name: "song.mp3", size: 1500 },
    { name: "plan.docx", size: 400 },
    { name: "forest.jpg", size: 1100 },
    { name: "budget.xlsx", size: 250 },
    { name: "talk.mp4", size: 1400 },
    { name: "logo.svg", size: 150 },
    { name: "city.jpg", size: 900 },
]

const TRIES = 3
const TIMEOUT = 2000

// A pretend server that takes 1 ms per KB: one try in four fails, and
// one in six hangs. In a real app it is fetch(url, { body, signal })
async func upload(file File, signal AbortSignal) error {
    const fate = Math.random()
    select {
    case <-after(fate < 1 / 6 ? 60_000 : file.size):
    case <-done(signal):
        return error("timed out")
    }
    if fate > 0.75 {
        return error("server error")
    }
    return null
}

type Status "queued" | "uploading" | "retrying" | "done" | "failed"

interface Row {
    file File
    status Status
    note string
    by number                       // the uploader that took it, 0 before
}

func queued(file File) Row {
    return { file, status: "queued", note: "", by: 0 }
}

comp Uploads() {
    state rows = FILES.map(queued)
    state running = false
    derived sent = rows.filter(row => row.status == "done").length
    derived failed = rows.filter(row => row.status == "failed").length

    func set(i number, by number, status Status, note string) {
        rows = rows.map((row, j) => j == i ? { file: row.file, status, note, by } : row)
    }

    // The file that an uploader is busy with now, if any
    func busy(by number) ?Row {
        for row in rows {
            if row.by == by && (row.status == "uploading" || row.status == "retrying") {
                return row
            }
        }
        return null
    }

    // Tries a file until it goes, at most TRIES times
    async func deliver(i number, by number) {
        for let attempt = 1; attempt <= TRIES; attempt++ {
            set(i, by, "uploading", attempt == 1 ? "" : `try ${attempt}`)
            const start = performance.now()
            // The signal aborts when after() gives its value
            const err = await upload(FILES[i], abortSignal(after(TIMEOUT)))
            if err == null {
                const ms = `${Math.round(performance.now() - start)} ms`
                set(i, by, "done", attempt == 1 ? ms : `try ${attempt}, ${ms}`)
                return
            }
            const last = attempt == TRIES
            set(i, by, last ? "failed" : "retrying", err.message)
            if !last {
                <-after(300 * attempt)  // longer after each failure
            }
        }
    }

    // An uploader takes a file from the queue and does not take the
    // next one until this one is sent or has failed
    async func uploader(by number, queue <-chan number) {
        for i in queue {
            await deliver(i, by)
        }
    }

    async func start() {
        running = true
        rows = FILES.map(queued)
        const queue = chan<number>(FILES.length)
        for i, _ in FILES {
            queue <- i
        }
        close(queue)                // the uploaders stop when it is empty
        // Three uploaders, so three files at a time: that is all the limit
        await Promise.all([uploader(1, queue), uploader(2, queue), uploader(3, queue)])
        running = false
    }

    mount {
        start()
    }

    style {
        .uploads { display: grid; gap: 12px; max-width: 480px; }
        .top { display: flex; align-items: center; gap: 12px; }
        .summary { color: #ffffffb3; font-size: 0.9em; }
        button {
            padding: 6px 14px;
            border: 1px solid #f5a524;
            border-radius: 8px;
            background: #f5a524;
            color: #000;
            font: inherit;
            cursor: pointer;
        }
        button:disabled { opacity: 0.4; cursor: default; }
        .lanes { display: grid; grid-template-columns: repeat(3, 1fr); gap: 8px; }
        .lane {
            display: grid;
            gap: 2px;
            padding: 8px 10px;
            border-top: 3px solid var(--by);
            border-radius: 8px;
            background: #ffffff0d;
            font-size: 0.85em;
        }
        .lane span { color: #ffffff80; }
        .files { display: grid; gap: 4px; margin: 0; padding: 0; list-style: none; }
        .files li {
            display: grid;
            grid-template-columns: 1fr auto 150px;
            gap: 12px;
            padding: 6px 12px;
            border-left: 3px solid var(--by, transparent);
            border-radius: 8px;
            background: #ffffff0a;
            font-size: 0.9em;
        }
        .size { color: #ffffff59; font-variant-numeric: tabular-nums; }
        .status { text-align: right; }
        [data-by="1"] { --by: #f5a524; }
        [data-by="2"] { --by: #5eb1ff; }
        [data-by="3"] { --by: #c48cff; }
        [data-status="queued"] .status { color: #ffffff59; }
        [data-status="uploading"] .status { color: #ffffff; }
        [data-status="retrying"] .status { color: #f5a524; }
        [data-status="done"] .status { color: #6fcf8f; }
        [data-status="failed"] .status { color: #ff7a7a; }
    }

    return <div class="uploads">
        <div class="top">
            <button disabled={running} onClick={start()}>Upload again</button>
            <span class="summary">{sent} sent · {failed} failed</span>
        </div>
        <div class="lanes">
            {for by in [1, 2, 3] {
                const row = busy(by)
                <div class="lane" data-by={by}>
                    <b>Uploader {by}</b>
                    <span>{row != null ? row.file.name : running ? "taking the next" : "done"}</span>
                </div>
            }}
        </div>
        <ul class="files">
            {for row in rows {
                <li data-status={row.status} data-by={row.by}>
                    <span>{row.file.name}</span>
                    <span class="size">{row.file.size} KB</span>
                    <span class="status">
                        {row.status}{row.note == "" ? "" : ` · ${row.note}`}
                    </span>
                </li>
            }}
        </ul>
    </div>
}

document.body.append(<Uploads />)
0 sent · 0 failed
Uploader 1beach.jpg
Uploader 2notes.pdf
Uploader 3cat.png
  • beach.jpg1200 KBuploading
  • notes.pdf300 KBuploading
  • cat.png800 KBuploading
  • song.mp31500 KBqueued
  • plan.docx400 KBqueued
  • forest.jpg1100 KBqueued
  • budget.xlsx250 KBqueued
  • talk.mp41400 KBqueued
  • logo.svg150 KBqueued
  • city.jpg900 KBqueued

The program printed nothing to the console.