Rookv1.0
РусскийRUGet started

Catalog relay

interface RecordData {
    values number[]
    description string
    revision number
}

struct SharedRecord {
    mu rwMutex
    values number[]
    description string
    revision number
}

async func copyWorker(jobs <-chan RecordData, results chan<- RecordData) {
    for record in jobs {
        for i in 0..record.values.length {
            record.values[i]++
        }
        record.revision++
        results <- record
    }
}

async func deltaWorker(jobs <-chan number[], results chan<- number[]) {
    for values in jobs {
        results <- values.map(value => value + 1)
    }
}

async func sharedWorker(record SharedRecord, jobs <-chan bool, results chan<- bool) {
    for _ in jobs {
        await record.mu.mute()
        for i in 0..record.values.length {
            record.values[i]++
        }
        record.revision++
        record.mu.unmute()
        results <- typeof document == 'undefined'
    }
}

comp Benchmark() {
    ref payloadSelect
    ref stepsSelect
    state busy = false
    state size = 1024
    state rounds = 256
    state report = 'Choose a workload and run the comparison.'
    state timings number[] = []
    state cells number[] = Array.from({length: 144}, () => 0)
    state shardRevisions number[] = [0, 0, 0, 0]
    state active = -1
    const modes = ['Copied objects', 'Delta messages', 'Shared struct']

    async func run() {
        busy = true
        timings = []
        report = 'Warming up workers…'
        try {
            const lanes = [0, 1, 2, 3]
            const samples number[][] = [[], [], []]
            for trial in 0..5 {
                for position in 0..3 {
                    const mode = (position + trial) % 3
                    active = mode
                    report = `${modes[mode]} · sample ${trial + 1} / 5`
                    await <-after(20)
                    const initial = Array.from({length: 144}, () => 0)
                    const description = 'Catalog metadata'.repeat(size * 64)
                    const records = lanes.map(lane => {
                        const values = initial.filter((_, index) => index % 4 == lane)
                        return {values: values, description: description, revision: 0} as RecordData
                    })
                    const shared = records.map(record => SharedRecord{
                        values: [...record.values], description: record.description, revision: 0,
                    })
                    const copyJobs = lanes.map(_ => chan<RecordData>())
                    const copyResults = lanes.map(_ => chan<RecordData>())
                    const deltaJobs = lanes.map(_ => chan<number[]>())
                    const deltaResults = lanes.map(_ => chan<number[]>())
                    const sharedJobs = lanes.map(_ => chan<bool>())
                    const sharedResults = lanes.map(_ => chan<bool>())
                    // Each long-lived goroutine owns one independent shard and its lock.
                    const tasks = lanes.map(lane => mode == 0
                        ? go copyWorker(copyJobs[lane], copyResults[lane])
                        : mode == 1 ? go deltaWorker(deltaJobs[lane], deltaResults[lane])
                        : go sharedWorker(shared[lane], sharedJobs[lane], sharedResults[lane]))
                    try {
                        // Warm every lane with the real channel protocol, outside the timer.
                        await Promise.all(lanes.map(async lane => {
                            if mode == 0 { copyJobs[lane] <- records[lane] } else if mode == 1 { deltaJobs[lane] <- records[lane].values } else { sharedJobs[lane] <- true }
                        }))
                        let runningInWorkers = true
                        for lane in lanes {
                            if mode == 0 { <-copyResults[lane] } else if mode == 1 { <-deltaResults[lane] } else if !(<-sharedResults[lane]) {
                                runningInWorkers = false
                            }
                        }
                        if !runningInWorkers {
                            throw error('Shared memory is unavailable; enable cross-origin isolation')
                        }
                        // Warmup edits are reset before the measured workload.
                        for lane in lanes {
                            shared[lane].values = [...records[lane].values]
                            shared[lane].revision = 0
                        }
                        const start = performance.now()
                        for wave in 0..(rounds / 4) {
                            await Promise.all(lanes.map(async lane => {
                                if mode == 0 { copyJobs[lane] <- records[lane] } else if mode == 1 { deltaJobs[lane] <- records[lane].values } else { sharedJobs[lane] <- true }
                            }))
                            for lane in lanes {
                                if mode == 0 {
                                    const updated = <-copyResults[lane]
                                    if updated != null { records[lane] = updated }
                                } else if mode == 1 {
                                    records[lane].values = <-deltaResults[lane]
                                    records[lane].revision++
                                } else { <-sharedResults[lane] }
                            }
                        }
                        samples[mode].push(performance.now() - start)
                    } finally {
                        for lane in lanes {
                            close(copyJobs[lane])
                            close(deltaJobs[lane])
                            close(sharedJobs[lane])
                        }
                        await Promise.all(tasks)
                        for lane in lanes {
                            close(copyResults[lane])
                            close(deltaResults[lane])
                            close(sharedResults[lane])
                        }
                    }
                    const result = initial.map((_, index) => mode == 2
                        ? shared[index % 4].values[Math.floor(index / 4)]
                        : records[index % 4].values[Math.floor(index / 4)])
                    const revision = lanes.reduce((sum, lane) => sum + (mode == 2 ? shared[lane].revision : records[lane].revision), 0)
                    const matches = result.every((value, i) => value == 0 + rounds / 4)
                    if !matches || revision != rounds {
                        throw error('Result verification failed')
                    }
                    cells = result
                    shardRevisions = lanes.map(lane => mode == 2 ? shared[lane].revision : records[lane].revision)
                    timings = samples.map(values => values.length > 0
                        ? [...values].sort((a, b) => a - b)[Math.floor(values.length / 2)] : 0)
                }
            }
            timings = samples.map(values => [...values].sort((a, b) => a - b)[2])
            report = 'Verified · median of 5 runs · workers and sharing warmed up'
        } catch error {
            report = String(error)
        } finally {
            active = -1
            busy = false
        }
    }

    return <section class="worker-lab" data-memory-benchmark="true" data-running={busy} data-mode={String(active)}>
        <header class="lab-heading">
            <h2>Catalog relay</h2>
            <p>Four long-lived goroutines update independent catalog shards through channels.</p>
        </header>
        <div class="lab-catalog" aria-label="Catalog split into four independent shards">
            {for lane in [0, 1, 2, 3] {
                <section class="lab-shard" data-active={busy}>
                    <header class="lab-shard-head">
                        <div class="lab-shard-title">
                            <span class="lab-rook" aria-hidden="true">♜</span>
                            <span><strong>Shard {lane + 1}</strong><small>Worker {lane + 1} · 36 records</small></span>
                        </div>
                        <span class="lab-revision"><small>rev</small><strong>{shardRevisions[lane]}</strong></span>
                    </header>
                    <div
                        class="lab-tiles"
                        role="img"
                        aria-label={`Shard ${lane + 1}: 36 records at ${cells[lane]} updates each`}
                    >
                        {for item in 0..36 {
                            const value = cells[item * 4 + lane]
                            <span
                                class="lab-tile"
                                style={`--tile-level: ${value / Math.max(1, rounds / 4)}`}
                                title={`Record ${item * 4 + lane + 1}: ${value}`}
                            ></span>
                        }}
                    </div>
                </section>
            }}
        </div>
        <div class="lab-controls">
            <label>Payload per worker <select ref={payloadSelect} disabled={busy} value={String(size)} onChange={size = Number(payloadSelect.value)}>
                <option selected={size == 8} value="8">8 KiB</option><option selected={size == 64} value="64">64 KiB</option><option selected={size == 256} value="256">256 KiB</option><option selected={size == 1024} value="1024">1 MiB</option>
            </select></label>
            <label>Steps <select ref={stepsSelect} disabled={busy} value={String(rounds)} onChange={rounds = Number(stepsSelect.value)}>
                <option selected={rounds == 16} value="16">16</option><option selected={rounds == 64} value="64">64</option><option selected={rounds == 256} value="256">256</option>
            </select></label>
            <button class="lab-run" disabled={busy} onClick={run()}>{busy ? 'Running…' : 'Run benchmark'}<span aria-hidden="true"> ↗</span></button>
        </div>
        <div class="lab-results" aria-busy={busy}>
            <p class="lab-status" role="status">{report}</p>
            {for i, mode in modes {
                <div class="lab-result" data-strategy={String(i)} data-active={active == i}>
                    <div class="lab-result-label"><strong>{mode}</strong><span>{timings.length > i && timings[i] > 0 ? `${timings[i].toFixed(2)} ms` : active == i ? 'Measuring…' : '—'}</span></div>
                    <div class="lab-track" role="meter" aria-label={mode} aria-valuemin={0} aria-valuemax={timings.length > 0 ? Math.max(...timings) : 1} aria-valuenow={timings.length > i ? timings[i] : 0}>
                        <div style={`width: ${timings.length > i ? timings[i] / Math.max(1, ...timings) * 100 : 0}%`}></div>
                    </div>
                </div>
            }}
        </div>
        <details class="lab-method">
            <summary>How this is measured</summary>
            <p>Median of five runs with identical inputs and every cell verified. Worker warmup and initial sharing are excluded. Channels feed four long-lived goroutines, each with its own shard and mutex. Animation indicates measurement state. Result updates happen outside the timer.</p>
        </details>
    </section>
}

document.body.append(<Benchmark />)

Catalog relay

Four long-lived goroutines update independent catalog shards through channels.

Shard 1Worker 1 · 36 records
rev0
Shard 2Worker 2 · 36 records
rev0
Shard 3Worker 3 · 36 records
rev0
Shard 4Worker 4 · 36 records
rev0

Choose a workload and run the comparison.

Copied objects—
Delta messages—
Shared struct—
How this is measured

Median of five runs with identical inputs and every cell verified. Worker warmup and initial sharing are excluded. Channels feed four long-lived goroutines, each with its own shard and mutex. Animation indicates measurement state. Result updates happen outside the timer.

The program printed nothing to the console.