Skip to content

Commit

Permalink
Merge pull request #3 from WangYihang/add-comments-for-status
Browse files Browse the repository at this point in the history
docs: add comments for status
  • Loading branch information
WangYihang authored Apr 26, 2024
2 parents 07873a7 + d86bada commit 9c67820
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 9 deletions.
3 changes: 3 additions & 0 deletions .github/workflows/go.yml
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,9 @@ jobs:
- name: Test
run: go test -v ./...

- name: Run coverage
run: go test -race -coverprofile=coverage.txt -covermode=atomic ./...

-
name: Upload coverage reports to Codecov
uses: codecov/[email protected]
Expand Down
32 changes: 23 additions & 9 deletions status.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"time"
)

// Status represents the status of the job.
type Status struct {
Timestamp string `json:"timestamp"`
NumFailed int64 `json:"num_failed"`
Expand All @@ -31,12 +32,22 @@ func newStatusManager() *statusManager {
}
}

func (sm *statusManager) notify() {
status := sm.Snapshot()
for _, ch := range sm.statusChans {
ch <- status
}
}

// Start starts the status manager.
// It will notify all the status channels every second.
func (sm *statusManager) Start() {
for range sm.ticker.C {
sm.notify()
}
}

// Stop stops the status manager.
func (sm *statusManager) Stop() {
sm.notify()
sm.ticker.Stop()
Expand All @@ -45,46 +56,49 @@ func (sm *statusManager) Stop() {
}
}

// IncFailed increments the number of failed jobs.
func (sm *statusManager) IncFailed() {
sm.mutex.Lock()
sm.numFailed++
sm.mutex.Unlock()
}

// IncSucceed increments the number of succeed jobs.
func (sm *statusManager) IncSucceed() {
sm.mutex.Lock()
sm.numSucceed++
sm.mutex.Unlock()
}

// SetTotal sets the total number of jobs.
// It should be called before the job starts.
func (sm *statusManager) SetTotal(total int64) {
sm.mutex.Lock()
sm.numTotal = total
sm.mutex.Unlock()
}

// StatusChan returns a channel that will receive the status of the job.
// The status will be sent every second. It should be called before the job starts.
// You can call it multiple times to get multiple channels.
func (sm *statusManager) StatusChan() <-chan Status {
ch := make(chan Status)
sm.statusChans = append(sm.statusChans, ch)
return ch
}

// Snapshot returns the current status of the job.
func (sm *statusManager) Snapshot() Status {
sm.mutex.Lock()
defer func() func() {
sm.mutex.Lock()
return func() { sm.mutex.Unlock() }
}()()
status := Status{
Timestamp: time.Now().Format(time.RFC3339),
NumFailed: sm.numFailed,
NumSucceed: sm.numSucceed,
NumFinished: sm.numFailed + sm.numSucceed,
NumTotal: sm.numTotal,
}
sm.mutex.Unlock()
return status
}

func (sm *statusManager) notify() {
status := sm.Snapshot()
for _, ch := range sm.statusChans {
ch <- status
}
}

0 comments on commit 9c67820

Please sign in to comment.