Added docs to new functionality

This commit is contained in:
Samuel Hawksby-Robinson 2022-10-12 15:09:28 +01:00
parent 70bc492779
commit a88ebe3a9f
3 changed files with 23 additions and 5 deletions

View File

@ -5,12 +5,14 @@ import (
"sync"
)
// portManager is responsible for maintaining segregated access to the port field via the use of portWait sync.Mutex
type portManger struct {
port int
afterPortChanged func(port int)
portWait *sync.Mutex
}
// newPortManager returns a newly initialised portManager with a pre-Locked portManger.portWait sync.Mutex
func newPortManager(afterPortChanged func(int)) portManger {
pm := portManger{
afterPortChanged: afterPortChanged,
@ -20,26 +22,43 @@ func newPortManager(afterPortChanged func(int)) portManger {
return pm
}
// SetPort sets the internal portManger.port field to the given port value
// next triggers any given portManger.afterPortChanged function
// additionally portManger.portWait.Unlock() is called, releasing any calls to MustGetPort
func (p *portManger) SetPort(port int) error {
// TryLock, multiple portManager.SetPort calls trigger `fatal error: sync: unlock of unlocked mutex`
// In the case of concurrent
// TODO fix this horrible thing
p.portWait.TryLock()
if port == 0 {
return fmt.Errorf("port can not be `0`, use ResetPort() instead")
}
p.port = port
if p.afterPortChanged != nil {
p.afterPortChanged(port)
}
p.portWait.Unlock()
return nil
}
// ResetPort attempts to reset portManger.port to 0
// if portManger.portWait is already locked the function returns after doing nothing
func (p *portManger) ResetPort() {
if p.portWait.TryLock() {
p.port = 0
}
}
// GetPort gets the current value of portManager.port without any concern for the state of its value
// and therefore does not block until portManager.portWait.Unlock() is called
func (p *portManger) GetPort() int {
return p.port
}
// MustGetPort only returns portManager.port if portManager.portWait is unlocked.
// This presupposes that portManger.portWait has a default state of locked and SetPort unlock portManager.portWait
func (p *portManger) MustGetPort() int {
p.portWait.Lock()
defer p.portWait.Unlock()

View File

@ -61,10 +61,6 @@ func (s *Server) listenAndServe() {
return
}
if s.afterPortChanged != nil {
s.afterPortChanged(s.MustGetPort())
}
s.isRunning = true
err = s.server.Serve(listener)

View File

@ -40,13 +40,16 @@ func (s *ServerURLSuite) SetupTest() {
}}
go func() {
time.Sleep(waitTime)
s.serverNoPort.port = 0
s.serverNoPort.portWait.Unlock()
}()
s.testStart = time.Now()
}
// testNoPort takes two strings and compares expects them both to be equal
// then compares ServerURLSuite.testStart to the current time
// the difference must be greater than waitTime.
// This is caused by the ServerURLSuite.SetupTest waiting waitTime before unlocking the portWait sync.Mutex
func (s *ServerURLSuite) testNoPort(expected string, actual string) {
s.Require().Equal(expected, actual)
s.Require().Greater(time.Now().Sub(s.testStart), waitTime)