summaryrefslogtreecommitdiff
path: root/vendor/codeberg.org/gruf/go-runners/process.go
blob: 908e6edca4fdb4237cc48457ca2f9eeb168d3d2f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package runners

import (
	"fmt"
	"sync"
)

// Processable defines a runnable process with error return
// that can be passed to a Processor instance for managed running.
type Processable func() error

// Processor acts similarly to a sync.Once object, except that it is reusable. After
// the first call to Process(), any further calls before this first has returned will
// block until the first call has returned, and return the same error. This ensures
// that only a single instance of it is ever running at any one time.
type Processor struct {
	mutex sync.Mutex
	state uint32
	wait  sync.WaitGroup
	err   *error
}

// Process will process the given function if first-call, else blocking until
// the first function has returned, returning the same error result.
func (p *Processor) Process(proc Processable) (err error) {
	// Acquire state lock.
	p.mutex.Lock()

	if p.state != 0 {
		// Already running.
		//
		// Get current err ptr.
		errPtr := p.err

		// Wait until finish.
		p.mutex.Unlock()
		p.wait.Wait()
		return *errPtr
	}

	// Reset error ptr.
	p.err = new(error)

	// Set started.
	p.wait.Add(1)
	p.state = 1
	p.mutex.Unlock()

	defer func() {
		if r := recover(); r != nil {
			if err != nil {
				rOld := r // wrap the panic so we don't lose existing returned error
				r = fmt.Errorf("panic occured after error %q: %v", err.Error(), rOld)
			}

			// Catch any panics and wrap as error.
			err = fmt.Errorf("caught panic: %v", r)
		}

		// Store error.
		*p.err = err

		// Mark done.
		p.wait.Done()

		// Set stopped.
		p.mutex.Lock()
		p.state = 0
		p.mutex.Unlock()
	}()

	// Run process.
	err = proc()
	return
}