Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

V6 [WIP] #90

Open
wants to merge 10 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,13 @@ jobs:
- name: Set up Go version
uses: actions/setup-go@v3
with:
go-version: '1.18.0'
go-version: '1.21.0'

- name: Go mod
run: go mod tidy

- name: Execute tests
run: go test -coverprofile=coverage.out -count=1 -race ./...
run: make test

- name: SonarQube Scan (Push)
if: github.event_name == 'push'
Expand Down
7 changes: 7 additions & 0 deletions CHANGES
Original file line number Diff line number Diff line change
@@ -1,3 +1,10 @@
v6.0.0 (TBD):
- updated common helpers to be generic
- updated datastructures to be generic
- cleanup package structre and remove deprecated ones
- updated logger with formatting functionality
- modernized test harness & mocks

5.4.0 (Jan 10, 2024)
- Added `Scan` operation to Redis

Expand Down
11 changes: 11 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
GO ?= go
COVERAGE_OUT = coverage.out

.PHONY: test test-norace

test:
$(GO) test ./... -count=1 -race -coverprofile=$(COVERAGE_OUT)

test-norace:
$(GO) test ./... -count=1

4 changes: 2 additions & 2 deletions asynctask/asynctasks.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ import (
"fmt"
"time"

"github.com/splitio/go-toolkit/v5/logging"
"github.com/splitio/go-toolkit/v5/struct/traits/lifecycle"
"github.com/splitio/go-toolkit/v6/logging"
"github.com/splitio/go-toolkit/v6/struct/traits/lifecycle"
)

// AsyncTask is a struct that wraps tasks that should run periodically and can be remotely stopped & started,
Expand Down
50 changes: 15 additions & 35 deletions asynctask/asynctasks_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ import (
"testing"
"time"

"github.com/splitio/go-toolkit/v5/logging"
"github.com/splitio/go-toolkit/v6/logging"
"github.com/stretchr/testify/assert"
)

func TestAsyncTaskNormalOperation(t *testing.T) {
Expand All @@ -29,27 +30,14 @@ func TestAsyncTaskNormalOperation(t *testing.T) {

task1.Start()
time.Sleep(1 * time.Second)
if !task1.IsRunning() {
t.Error("Task should be running")
}
time.Sleep(1 * time.Second)
assert.True(t, task1.IsRunning())

time.Sleep(1 * time.Second)
task1.Stop(true)
if task1.IsRunning() {
t.Error("Task should be stopped")
}

if !onInit.Load().(bool) {
t.Error("Initialization hook not executed")
}

if !onExecution.Load().(bool) {
t.Error("Main task function not executed")
}

if !onStop.Load().(bool) {
t.Error("After execution function not executed")
}
assert.False(t, task1.IsRunning())
assert.True(t, onInit.Load().(bool))
assert.True(t, onExecution.Load().(bool))
assert.True(t, onStop.Load().(bool))
}

func TestAsyncTaskPanics(t *testing.T) {
Expand Down Expand Up @@ -94,15 +82,10 @@ func TestAsyncTaskPanics(t *testing.T) {
task3.Start()
time.Sleep(time.Second * 2)
task3.Stop(true)
if task1.IsRunning() {
t.Error("Task1 is running and should be stopped")
}
if task2.IsRunning() {
t.Error("Task2 is running and should be stopped")
}
if task3.IsRunning() {
t.Error("Task3 is running and should be stopped")
}

assert.False(t, task1.IsRunning())
assert.False(t, task2.IsRunning())
assert.False(t, task3.IsRunning())
}

func TestAsyncTaskErrors(t *testing.T) {
Expand Down Expand Up @@ -138,9 +121,8 @@ func TestAsyncTaskErrors(t *testing.T) {

task2.Start()
time.Sleep(2 * time.Second)
if res.Load().(int) != 0 {
t.Error("Task should have never executed if there was an error when calling onInit()")
}

assert.Equal(t, int(0), res.Load().(int))
}

func TestAsyncTaskWakeUp(t *testing.T) {
Expand All @@ -163,7 +145,5 @@ func TestAsyncTaskWakeUp(t *testing.T) {
_ = task1.WakeUp()
_ = task1.Stop(true)

if atomic.LoadInt32(&res) != 3 {
t.Errorf("Task shuld have executed 4 times. It ran %d times", res)
}
assert.Equal(t, int32(3), atomic.LoadInt32(&res))
}
30 changes: 9 additions & 21 deletions backoff/backoff_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,32 +3,20 @@ package backoff
import (
"testing"
"time"
"github.com/stretchr/testify/assert"
)

func TestBackoff(t *testing.T) {
base := int64(10)
maxAllowed := 60 * time.Second
backoff := New(base, maxAllowed)
if backoff.base != base {
t.Error("It should be equals to 10")
}
if backoff.maxAllowed != maxAllowed {
t.Error("It should be equals to 60")
}
if backoff.Next() != 1*time.Second {
t.Error("It should be 1 second")
}
if backoff.Next() != 10*time.Second {
t.Error("It should be 10 seconds")
}
if backoff.Next() != 60*time.Second {
t.Error("It should be 60 seconds")
}
assert.Equal(t, base, backoff.base)
assert.Equal(t, maxAllowed, backoff.maxAllowed)
assert.Equal(t, 1*time.Second, backoff.Next())
assert.Equal(t, 10*time.Second, backoff.Next())
assert.Equal(t, 60*time.Second, backoff.Next())

backoff.Reset()
if backoff.current != 0 {
t.Error("It should be zero")
}
if backoff.Next() != 1*time.Second {
t.Error("It should be 1 second")
}
assert.Equal(t, int64(0), backoff.current)
assert.Equal(t, 1*time.Second, backoff.Next())
}
17 changes: 12 additions & 5 deletions backoff/mocks/mocks.go
Original file line number Diff line number Diff line change
@@ -1,16 +1,23 @@
package mocks

import "time"
import (
"github.com/splitio/go-toolkit/v6/backoff"
"github.com/stretchr/testify/mock"
"time"
)

type BackoffMock struct {
NextCall func() time.Duration
ResetCall func()
mock.Mock
}

// Next implements backoff.Interface.
func (b *BackoffMock) Next() time.Duration {
return b.NextCall()
return b.Called().Get(0).(time.Duration)
}

// Reset implements backoff.Interface.
func (b *BackoffMock) Reset() {
b.ResetCall()
b.Called()
}

var _ backoff.Interface = (*BackoffMock)(nil)
111 changes: 111 additions & 0 deletions common/common.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
package common

import "cmp"

// New helpers to be used when with newer go versions.
// the rest of the common package should be removed in v3, and consumers of the lib
// should only rely on these functions

// Ref creates a copy of `x` in heap and returns a pointer to it
func Ref[T any](x T) *T {
return &x
}

// RefOrNil returns a pointer to the value supplied if it's not the default value, nil otherwise
func RefOrNil[T comparable](x T) *T {
var t T
if x == t {
return nil
}
return &x
}

// PointerOf performs a type-assertion to T and returns a pointer if successful, nil otherwise.
func PointerOf[T any](x interface{}) *T {
if x == nil {
return nil
}

ta, ok := x.(T)
if !ok {
return nil
}

return &ta
}

// DerefOr returns value pointed by `tp` or the fallback supplied
func DerefOr[T any](tp *T, fallback T) T {
if tp == nil {
return fallback
}
return *tp
}

// PartitionSliceByLength partitions a slice into multiple slices of up to `maxItems` size
func PartitionSliceByLength[T comparable](items []T, maxItems int) [][]T {
var splitted [][]T
for i := 0; i < len(items); i += maxItems {
end := i + maxItems
if end > len(items) {
end = len(items)
}
splitted = append(splitted, items[i:end])
}
return splitted
}

// DedupeInNewSlice creates a new slice from `items` without duplicate elements
func UnorderedDedupedCopy[T comparable](items []T) []T {
present := make(map[T]struct{}, len(items))
for idx := range items {
present[items[idx]] = struct{}{}
}

ret := make([]T, 0, len(present))
for key := range present {
ret = append(ret, key)
}

return ret
}

// ValueOr returns the supplied value if it has something other than the default value
// for type T. Returns `fallback` otherwise
func ValueOr[T comparable](in T, fallback T) T {
var t T
if in == t {
return fallback
}
return in
}

// Max returns the greatest item of all supplied
func Max[T cmp.Ordered](i1 T, rest ...T) T {
max := i1
for idx := range rest {
if rest[idx] > max {
max = rest[idx]
}
}
return max
}

// Min returns the minimum item of all supplied
func Min[T cmp.Ordered](i1 T, rest ...T) T {
min := i1
for idx := range rest {
if rest[idx] < min {
min = rest[idx]
}
}
return min
}

func AsInterfaceSlice[T any](in []T) []interface{} {
out := make([]interface{}, len(in))
for idx := range in {
out[idx] = in[idx]
}
return out
}
Loading
Loading