package main import ( "context" "errors" "fmt" "slices" "strings" "sync" "unicode/utf8" ) // FakeSummarizer builds each node with a line of fakeLine. It fails each task // while failing is true, and each task waits for gate when gate is not nil. type FakeSummarizer struct { mutex sync.Mutex gate chan struct{} failing bool active int peak int tasks []Task } func (f *FakeSummarizer) Summarize(ctx context.Context, task Task) (string, error) { f.mutex.Lock() f.tasks = append(f.tasks, task) f.active++ f.peak = max(f.peak, f.active) fail := f.failing f.mutex.Unlock() defer func() { f.mutex.Lock() f.active-- f.mutex.Unlock() }() if f.gate != nil { select { case <-f.gate: case <-ctx.Done(): return "", ctx.Err() } } if fail { return "", errors.New("fake failure") } return fakeLine(task), nil } // SetFailing makes the next tasks fail or not. func (f *FakeSummarizer) SetFailing(failing bool) { f.mutex.Lock() defer f.mutex.Unlock() f.failing = failing } // Active returns the number of tasks that run now. func (f *FakeSummarizer) Active() int { f.mutex.Lock() defer f.mutex.Unlock() return f.active } // Tasks returns the tasks so far. func (f *FakeSummarizer) Tasks() []Task { f.mutex.Lock() defer f.mutex.Unlock() return slices.Clone(f.tasks) } // fakeLine returns a line of nodeBytes bytes or less that names the node and // starts with the input. A real line of this size makes each merge a model // call. func fakeLine(task Task) string { count := 1 << task.Level line := fmt.Sprintf("summary %d+%d: %s", task.Index*count, count, strings.Join(task.Input, " ")) line = strings.ReplaceAll(line, "\n", " ") for len(line) > nodeBytes-12 { _, size := utf8.DecodeLastRuneInString(line) line = line[:len(line)-size] } return line } func newFakeSummarizer() *FakeSummarizer { return &FakeSummarizer{} }