Skip to content

Instantly share code, notes, and snippets.

@pavlo
Created January 11, 2023 13:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pavlo/01fe01993bdcf3ad0cd677d8e7d53560 to your computer and use it in GitHub Desktop.
Save pavlo/01fe01993bdcf3ad0cd677d8e7d53560 to your computer and use it in GitHub Desktop.
package main
import (
"log"
"sync"
"time"
)
var END_OF_TEST_CASE_ID_STREAM_ITEM = ""
func main() {
launcher := NewLauncher(5, "launch-id", []string{"testcase-1", "testcase-2", "testcase-3", "testcase-4"})
launcher.Launch()
}
type Launcher struct {
concurrency int
launchId string
testCaseIds []string
cancelled bool
completedNormally bool
wg sync.WaitGroup
exitChannel chan bool
testCaseIdsChannel chan string
}
func NewLauncher(concurrency int, launchId string, testCaseIds []string) *Launcher {
launcher := &Launcher{
concurrency: concurrency,
launchId: launchId,
testCaseIds: testCaseIds,
cancelled: false,
completedNormally: false,
exitChannel: make(chan bool),
testCaseIdsChannel: make(chan string),
}
return launcher
}
func (l *Launcher) Launch() {
log.Printf("Launch entered. Concurrency=%d, launchId=%s, number of test cases=%d\n", l.concurrency, l.launchId, len(l.testCaseIds))
for i := 0; i < l.concurrency; i++ {
l.wg.Add(1)
go l.process(i)
}
for i := 0; i < len(l.testCaseIds); i++ {
l.testCaseIdsChannel <- l.testCaseIds[i]
}
l.testCaseIdsChannel <- END_OF_TEST_CASE_ID_STREAM_ITEM
l.wg.Wait()
log.Printf("Launch completed; cancelled=%t, completedNormally=%t\n", l.cancelled, l.completedNormally)
}
func (l *Launcher) process(routineId int) {
for {
select {
case testCaseId := <-l.testCaseIdsChannel:
if testCaseId == END_OF_TEST_CASE_ID_STREAM_ITEM {
log.Printf("Routine: #%d completes the launch!\n", routineId)
l.complete()
} else {
log.Printf("Routine: #%d started processing test case %s\n", routineId, testCaseId)
l.callApi(l.launchId, testCaseId)
log.Printf("Routine: #%d completed processing a test case\n", routineId)
}
case <-l.exitChannel:
l.wg.Done()
return
}
}
}
func (l *Launcher) callApi(launchId string, testCaseId string) {
log.Printf("callApi: launchId=%s, testCaseId=%s", launchId, testCaseId)
time.Sleep(1 * time.Second)
/*
1. Then call the launch API passing launchId and testCaseId. If it returns a CANCELLED response (todo) then call "l.cancel()"
2. Start polling server for completion of the test case like this:
for i:= 0; i < 10; i++ { // 10 times, each time for 1 second
call the API, if not compleed then "time.Sleep(1 * time.Second)"
}
*/
}
func (l *Launcher) cancel() {
log.Printf("Launch cancelled!\n")
l.cancelled = true
close(l.exitChannel)
}
func (l *Launcher) complete() {
log.Printf("Launch completed normally!\n")
l.completedNormally = true
close(l.exitChannel)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment