1
0
Fork 0
mirror of https://github.com/diamondburned/cchat-mock.git synced 2024-09-20 01:01:39 +00:00
cchat-mock/internet.go

45 lines
913 B
Go
Raw Normal View History

2020-07-03 23:53:46 +00:00
package mock
import (
"context"
"math/rand"
"time"
"github.com/pkg/errors"
)
var (
// channel.go @ simulateAustralianInternet
internetCanFail = true
// 500ms ~ 3s
internetMinLatency = 500
internetMaxLatency = 3000
)
// ErrTimedOut is returned when the simulated IO decides to fail.
var ErrTimedOut = errors.New("Australian Internet unsupported.")
// simulate network latency
func simulateAustralianInternet() error {
return simulateAustralianInternetCtx(context.Background())
}
func simulateAustralianInternetCtx(ctx context.Context) (err error) {
var ms = randClamp(internetMinLatency, internetMaxLatency)
select {
case <-time.After(time.Duration(ms) * time.Millisecond):
// noop
case <-ctx.Done():
return ctx.Err()
}
// because australia, drop packet 20% of the time if internetCanFail is
// true.
if internetCanFail && rand.Intn(100) < 20 {
return ErrTimedOut
}
return nil
}