Skip to content

Commit

Permalink
Added all Stars API
Browse files Browse the repository at this point in the history
  • Loading branch information
emanuelef committed Sep 23, 2023
1 parent c99c476 commit 1ef3b33
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 20 deletions.
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ module github.com/emanuelef/gh-repo-stats-server
go 1.21.1

require (
github.com/emanuelef/github-repo-activity-stats v0.0.0-20230923185816-65d3c761c2af
github.com/emanuelef/github-repo-activity-stats v0.0.0-20230923193702-4ef241a871d4
github.com/gofiber/contrib/otelfiber v1.0.10
github.com/gofiber/fiber/v2 v2.49.2
github.com/joho/godotenv v1.5.1
Expand Down
6 changes: 2 additions & 4 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,8 @@ github.com/cenkalti/backoff/v4 v4.2.1 h1:y4OZtCnogmCPw98Zjyt5a6+QwPLGkiQsYW5oUqy
github.com/cenkalti/backoff/v4 v4.2.1/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/emanuelef/github-repo-activity-stats v0.0.0-20230923004913-cde3ae9a82b0 h1:6hnWZhBSnHZBiiVzKMPcc6rezVooCw2d1wI0g0rzL+Y=
github.com/emanuelef/github-repo-activity-stats v0.0.0-20230923004913-cde3ae9a82b0/go.mod h1:a4gtH6JdkmHxydIwACgM0k7AgIHGaRGTv8jBkO8rjv0=
github.com/emanuelef/github-repo-activity-stats v0.0.0-20230923185816-65d3c761c2af h1:vT3iksAPlJGRYVRmw8HkTxODeNnCD7z18/sgyrVlcAg=
github.com/emanuelef/github-repo-activity-stats v0.0.0-20230923185816-65d3c761c2af/go.mod h1:a4gtH6JdkmHxydIwACgM0k7AgIHGaRGTv8jBkO8rjv0=
github.com/emanuelef/github-repo-activity-stats v0.0.0-20230923193702-4ef241a871d4 h1:nuVxuqfiLrLv9MwKeQ632cqAK7Az+Hq72jXfsVqpuNo=
github.com/emanuelef/github-repo-activity-stats v0.0.0-20230923193702-4ef241a871d4/go.mod h1:a4gtH6JdkmHxydIwACgM0k7AgIHGaRGTv8jBkO8rjv0=
github.com/felixge/httpsnoop v1.0.3 h1:s/nj+GCswXYzN5v2DpNMuMQYe+0DDwt5WVCU6CWBdXk=
github.com/felixge/httpsnoop v1.0.3/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
Expand Down
66 changes: 51 additions & 15 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,49 +45,51 @@ func bToMb(b uint64) uint64 {
}

// Cache represents an in-memory cache.
type Cache struct {
type Cache[T any] struct {
mu sync.Mutex
items map[string]CacheItem
items map[string]CacheItem[T]
}

// CacheItem represents an item stored in the cache.
type CacheItem struct {
Value *repostats.RepoStats
type CacheItem[T any] struct {
Value T
Expiration time.Time
}

// NewCache creates a new instance of the cache.
func NewCache() *Cache {
return &Cache{
items: make(map[string]CacheItem),
func NewCache[T any]() *Cache[T] {
return &Cache[T]{
items: make(map[string]CacheItem[T]),
}
}

// Set adds an item to the cache with a specified key and expiration time.
func (c *Cache) Set(key string, value *repostats.RepoStats, expiration time.Time) {
func (c *Cache[T]) Set(key string, value T, expiration time.Time) {
c.mu.Lock()
defer c.mu.Unlock()

c.items[key] = CacheItem{
c.items[key] = CacheItem[T]{
Value: value,
Expiration: expiration,
}
}

// Get retrieves an item from the cache by its key.
func (c *Cache) Get(key string) (*repostats.RepoStats, bool) {
func (c *Cache[T]) Get(key string) (T, bool) {
c.mu.Lock()
defer c.mu.Unlock()

item, found := c.items[key]
if !found {
return nil, false
var zero T
return zero, false
}

if item.Expiration.Before(time.Now()) {
// Item has expired, remove it from the cache
delete(c.items, key)
return nil, false
var zero T
return zero, false
}

return item.Value, true
Expand All @@ -107,7 +109,8 @@ func main() {
log.Fatalf("failed to initialize OpenTelemetry: %e", err)
}

cache := NewCache()
cache := NewCache[*repostats.RepoStats]()
cacheStars := NewCache[[]repostats.StarsPerDay]()

tokenSource := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: os.Getenv("PAT")},
Expand All @@ -133,8 +136,6 @@ func main() {
return c.Send(nil)
})

// Basic GET API to show the OtelFiber middleware is taking
// care of creating the span when called
app.Get("/stats", func(c *fiber.Ctx) error {
param := c.Query("repo")
repo, err := url.QueryUnescape(param)
Expand All @@ -158,6 +159,41 @@ func main() {
return c.JSON(result)
})

app.Get("/allStars", func(c *fiber.Ctx) error {
param := c.Query("repo")
repo, err := url.QueryUnescape(param)
if err != nil {
return err
}

if res, hit := cacheStars.Get(repo); hit {
return c.JSON(res)
}

result, err := client.GetAllStats(ctx, repo)
if err != nil {
log.Printf("Error getting all stats %v", err)
return c.Status(404).SendString("Custom 404 Error: Resource not found")
}

updateChannel := make(chan int)

var allStars []repostats.StarsPerDay

go func() {
allStars, _ = client.GetAllStarsHistory(ctx, repo, result.CreatedAt, updateChannel)
}()

for progress := range updateChannel {
fmt.Printf("Progress: %d\n", progress)
}

nextDay := time.Now().UTC().Truncate(24 * time.Hour).Add(24 * time.Hour)

cacheStars.Set(repo, allStars, nextDay)
return c.JSON(allStars)
})

app.Get("/limits", func(c *fiber.Ctx) error {
result, err := client.GetCurrentLimits(ctx)
if err != nil {
Expand Down

0 comments on commit 1ef3b33

Please sign in to comment.