Skip to content

Commit

Permalink
first commit
Browse files Browse the repository at this point in the history
  • Loading branch information
jhaynie committed Feb 2, 2025
0 parents commit df9a48d
Show file tree
Hide file tree
Showing 54 changed files with 4,431 additions and 0 deletions.
26 changes: 26 additions & 0 deletions .github/workflows/go.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
name: Go
on:
push:
branches: [main]
pull_request:
branches: [main]
concurrency:
group: ${{ github.ref }}
cancel-in-progress: true
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up Go
uses: actions/setup-go@v5
with:
go-version: "stable"
- name: Check vulnerabilities
run: |
go install golang.org/x/vuln/cmd/govulncheck@latest
govulncheck ./...
- name: Build
run: go build -v ./...
- name: Test
run: go test -v ./...
19 changes: 19 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
Copyright 2025 Agentuity, Inc.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

---

Some code was originally adapted from and relicensed under the same. https://github.com/shopmonkeyus/go-common

Copyright 2023-2024 Shopmonkey, Inc.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
15 changes: 15 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
.PHONY: all lint test vet tidy

all: test

lint:
@go fmt ./...

vet:
@go vet ./...

tidy:
@go mod tidy

test: tidy lint vet
@go test -v -count=1 ./...
21 changes: 21 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<!-- markdownlint-disable-file MD024 MD025 MD041 -->

# Overview

This repository contains the public shared utility code for Agenuity as a Golang module.

## Requirements

You will need [Golang](https://go.dev/dl/) version 1.23 or later to use this package.

## Usage

You should import these files using the Go package with the following:

```go
import "github.com/agentuity/go-common"
```

## License

All files in this repository are licensed under the [MIT license](https://opensource.org/licenses/MIT). See the [LICENSE](./LICENSE) file for details.
28 changes: 28 additions & 0 deletions cache/cache.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package cache

import (
"time"
)

type Cache interface {
// Get a value from the cache and return true if found, any is the value if found and nil if no error.
Get(key string) (bool, any, error)

// Set a value into the cache with a cache expiration.
Set(key string, val any, expires time.Duration) error

// Hits returns the number of times a key has been accessed.
Hits(key string) (bool, int)

// Expire will expire a key in the cache.
Expire(key string) (bool, error)

// Close will shutdown the cache.
Close() error
}

type value struct {
object any
expires time.Time
hits int
}
125 changes: 125 additions & 0 deletions cache/inmemory.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
package cache

import (
"context"
"sync"
"time"
)

type inMemoryCache struct {
ctx context.Context
cancel context.CancelFunc
cache map[string]*value
mutex sync.Mutex
waitGroup sync.WaitGroup
once sync.Once
expiryCheck time.Duration
}

var _ Cache = (*inMemoryCache)(nil)

func (c *inMemoryCache) Get(key string) (bool, any, error) {
c.mutex.Lock()
val, ok := c.cache[key]
if ok {
val.hits++
}
c.mutex.Unlock()
if ok {
if val.expires.Before(time.Now()) {
c.mutex.Lock()
delete(c.cache, key)
c.mutex.Unlock()
return false, nil, nil
}
return true, val.object, nil
}
return false, nil, nil
}

// Hits returns the number of times a key has been accessed.
func (c *inMemoryCache) Hits(key string) (bool, int) {
c.mutex.Lock()
var val int
var found bool
if v, ok := c.cache[key]; ok {
val = v.hits
found = true
}
c.mutex.Unlock()
return found, val
}

func (c *inMemoryCache) Set(key string, val any, expires time.Duration) error {
c.mutex.Lock()
if v, ok := c.cache[key]; ok {
v.hits = 0
v.expires = time.Now().Add(expires)
v.object = val
} else {
c.cache[key] = &value{val, time.Now().Add(expires), 0}
}
c.mutex.Unlock()
return nil
}

func (c *inMemoryCache) Expire(key string) (bool, error) {
c.mutex.Lock()
_, ok := c.cache[key]
if ok {
delete(c.cache, key)
}
c.mutex.Unlock()
return ok, nil
}

func (c *inMemoryCache) Close() error {
c.once.Do(func() {
c.cancel()
c.waitGroup.Wait()
})
return nil
}

func (c *inMemoryCache) run() {
c.waitGroup.Add(1)
timer := time.NewTicker(c.expiryCheck)
defer func() {
timer.Stop()
c.waitGroup.Done()
}()
for {
select {
case <-c.ctx.Done():
return
case <-timer.C:
now := time.Now()
c.mutex.Lock()
var expired []string
for key, val := range c.cache {
if val.expires.Before(now) {
expired = append(expired, key)
}
}
if len(expired) > 0 {
for _, key := range expired {
delete(c.cache, key)
}
}
c.mutex.Unlock()
}
}
}

// New returns a new Cache implementation
func NewInMemory(parent context.Context, expiryCheck time.Duration) Cache {
ctx, cancel := context.WithCancel(parent)
c := &inMemoryCache{
ctx: ctx,
cancel: cancel,
cache: make(map[string]*value),
expiryCheck: expiryCheck,
}
go c.run()
return c
}
85 changes: 85 additions & 0 deletions cache/inmemory_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
package cache

import (
"context"
"testing"
"time"

"github.com/stretchr/testify/assert"
)

func TestSimpleCache(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
cache := NewInMemory(ctx, time.Second)
cache.Close()
cancel()
}

func TestSetGetCache(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
cache := NewInMemory(ctx, time.Minute)
found, val, err := cache.Get("test")
assert.NoError(t, err)
assert.False(t, found)
assert.Nil(t, val)
assert.NoError(t, cache.Set("test", "value", time.Millisecond*10))
found, val, err = cache.Get("test")
assert.NoError(t, err)
assert.True(t, found)
assert.Equal(t, "value", val)
ok, hits := cache.Hits("test")
assert.True(t, ok)
assert.Equal(t, 1, hits)
time.Sleep(time.Millisecond * 11)
found, val, err = cache.Get("test")
assert.NoError(t, err)
assert.False(t, found)
assert.Nil(t, val)
ok, hits = cache.Hits("test")
assert.False(t, ok)
assert.Equal(t, 0, hits)
cache.Close()
cancel()
}

func TestCacheBackgroundExpire(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
cache := NewInMemory(ctx, time.Millisecond*100)
found, val, err := cache.Get("test")
assert.NoError(t, err)
assert.False(t, found)
assert.Nil(t, val)
assert.NoError(t, cache.Set("test", "value", 90*time.Millisecond))
found, val, err = cache.Get("test")
assert.NoError(t, err)
assert.True(t, found)
assert.Equal(t, "value", val)
time.Sleep(time.Millisecond * 200)
c := cache.(*inMemoryCache)
c.mutex.Lock()
defer c.mutex.Unlock()
assert.Empty(t, c.cache)
cache.Close()
cancel()
}

func TestCacheExpire(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
cache := NewInMemory(ctx, time.Millisecond*100)
found, val, err := cache.Get("test")
assert.NoError(t, err)
assert.False(t, found)
assert.Nil(t, val)
assert.NoError(t, cache.Set("test", "value", 90*time.Millisecond))
found, val, err = cache.Get("test")
assert.NoError(t, err)
assert.True(t, found)
assert.Equal(t, "value", val)
cache.Expire("test")
c := cache.(*inMemoryCache)
c.mutex.Lock()
defer c.mutex.Unlock()
assert.Empty(t, c.cache)
cache.Close()
cancel()
}
Loading

0 comments on commit df9a48d

Please sign in to comment.