// The writer whose reader has gone: one handoff and one stream, four versions.
// go run reader.go
package main

import (
	"bytes"
	"fmt"
	"runtime"
	"runtime/pprof"
	"strings"
	"time"
)

// The handoff, as in Kubernetes' finishReq: a helper computes one result,
// the caller waits for it at most one millisecond.
func handoff(capacity int) {
	ch := make(chan int, capacity) // 0: unbuffered, a rendezvous
	go func() {
		time.Sleep(2 * time.Millisecond) // the work, longer than the wait
		ch <- 42                         // waits for a receiver or a free slot
	}()
	select {
	case r := <-ch:
		_ = r
	case <-time.After(time.Millisecond):
		// the caller gives up and returns; nothing tells the helper
	}
}

// The stream, as in `yes | head -3`: a writer produces lines forever,
// the reader takes three and returns.
func stream(capacity int) {
	ch := make(chan int, capacity)
	go func() {
		for i := 1; ; i++ {
			ch <- i
		}
	}()
	for i := 0; i < 3; i++ {
		<-ch
	}
}

// The stream with a second channel, done, that the reader closes when it leaves:
// the writer's send and the reader's departure are one choice.
func streamDone() {
	ch := make(chan int)
	done := make(chan struct{})
	go func() {
		for i := 1; ; i++ {
			select {
			case ch <- i:
			case <-done:
				return // the reader has gone: stop writing
			}
		}
	}()
	defer close(done) // runs when the reader returns
	for i := 0; i < 3; i++ {
		<-ch
	}
}

func run(name string, call func()) {
	before := runtime.NumGoroutine()
	for i := 0; i < 1000; i++ {
		call()
	}
	time.Sleep(50 * time.Millisecond) // let every helper finish what it can
	fmt.Printf("%-24s 1000 calls, writers still blocked: %d\n", name, runtime.NumGoroutine()-before)
}

func main() {
	run("handoff, unbuffered", func() { handoff(0) })
	run("handoff, buffer of 1", func() { handoff(1) })
	run("stream, buffer of 1", func() { stream(1) })
	run("stream, done channel", streamDone)

	// Go's goroutine leak profile (experimental in Go 1.26): the garbage collector
	// finds the goroutines blocked on a channel that no running goroutine can reach.
	if p := pprof.Lookup("goroutineleak"); p != nil {
		var b bytes.Buffer
		p.WriteTo(&b, 1)
		fmt.Println(strings.SplitN(b.String(), "\n", 2)[0])
	}
}
