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

feat/cache ttl #99

Closed
wants to merge 16 commits into from
Closed
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
203 changes: 184 additions & 19 deletions api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"log/slog"
"reflect"
"slices"
"time"

"github.com/charmbracelet/log"

Expand All @@ -22,12 +23,18 @@ const (
CacheNamespaceTasks cache.Namespace = "tasks"
CacheNamespaceTasksList cache.Namespace = "tasks-list"
CacheNamespaceTasksView cache.Namespace = "tasks-view"

TTL = 10
GarbageCollectorInterval = 5
)

type Api struct {
Clickup *clickup.Client
Cache *cache.Cache
logger *log.Logger

gcCloseChan chan struct{}
interval time.Duration
}

func NewApi(logger *log.Logger, cache *cache.Cache, token string) Api {
Expand All @@ -39,10 +46,33 @@ func NewApi(logger *log.Logger, cache *cache.Cache, token string) Api {
slog.New(log.WithPrefix(log.GetPrefix()+"/ClickUp")),
)

return Api{
Clickup: clickup,
logger: log,
Cache: cache,
api := Api{
Clickup: clickup,
logger: log,
Cache: cache,
gcCloseChan: make(chan struct{}),
interval: GarbageCollectorInterval * time.Second,
}

go api.garbageCollector()
return api
}

func (m *Api) garbageCollector() {
ticker := time.NewTicker(m.interval)
defer ticker.Stop()

for {
select {
case <-ticker.C:
m.logger.Debug("Garbage Collector: starting")
// now := time.Now().Unix()
if err := m.InvalidateCache(); err != nil {
panic(err)
}
case <-m.gcCloseChan:
return
}
}
}

Expand All @@ -61,6 +91,25 @@ func (m *Api) GetSpaces(teamId string) ([]clickup.Space, error) {
return data, nil
}

func (m *Api) syncSpaces(entry cache.Entry) error {
m.logger.Debug("Sync spaces for a team", "teamId", entry.Key)

client := m.Clickup

m.logger.Debugf("Fetching spaces from API")
data, err := client.GetSpacesFromTeam(entry.Key.String())
if err != nil {
return err
}
m.logger.Debugf("Found %d spaces for team: %s", len(data), entry.Key)

entry.UpdatedTs = time.Now().Unix()
entry.Value = data
m.Cache.Update(entry)

return nil
}

// Alias for GetTeams since they are the same thing
func (m *Api) GetWorkspaces() ([]clickup.Workspace, error) {
return m.GetTeams()
Expand All @@ -81,6 +130,25 @@ func (m *Api) GetTeams() ([]clickup.Team, error) {
return data, nil
}

func (m *Api) syncTeams(entry cache.Entry) error {
m.logger.Debug("Sync Authorized Teams (Workspaces)")

client := m.Clickup

m.logger.Debugf("Fetching teams from API")
data, err := client.GetTeams()
if err != nil {
return err
}
m.logger.Debugf("Found %d teams", len(data))

entry.UpdatedTs = time.Now().Unix()
entry.Value = data
m.Cache.Update(entry)

return nil
}

func (m *Api) GetFolders(spaceId string) ([]clickup.Folder, error) {
m.logger.Debug("Getting folders for a space", "space", spaceId)

Expand All @@ -96,6 +164,26 @@ func (m *Api) GetFolders(spaceId string) ([]clickup.Folder, error) {
return data, nil
}

func (m *Api) syncFolders(entry cache.Entry) error {
spaceId := entry.Key.String()
m.logger.Debug("Sync folders for a space", "space", spaceId)

client := m.Clickup

m.logger.Debugf("Fetching folders from API")
data, err := client.GetFolders(spaceId)
if err != nil {
return err
}
m.logger.Debugf("Found %d folders for space: %s", len(data), spaceId)

entry.UpdatedTs = time.Now().Unix()
entry.Value = data
m.Cache.Update(entry)

return nil
}

func (m *Api) GetLists(folderId string) ([]clickup.List, error) {
m.logger.Debug("Getting lists for a folder", "folderId", folderId)

Expand All @@ -111,6 +199,26 @@ func (m *Api) GetLists(folderId string) ([]clickup.List, error) {
return data, nil
}

func (m *Api) syncLists(entry cache.Entry) error {
folderId := entry.Key.String()
m.logger.Debug("Getting lists for a folder", "folderId", folderId)

client := m.Clickup

m.logger.Debugf("Fetching lists from API")
data, err := client.GetListsFromFolder(folderId)
if err != nil {
return err
}
m.logger.Debugf("Found %d lists for folder: %s", len(data), folderId)

entry.UpdatedTs = time.Now().Unix()
entry.Value = data
m.Cache.Update(entry)

return nil
}

func (m *Api) GetTask(taskId string) (clickup.Task, error) {
m.logger.Debug("Getting a task", "taskId", taskId)

Expand All @@ -126,6 +234,26 @@ func (m *Api) GetTask(taskId string) (clickup.Task, error) {
return data, nil
}

func (m *Api) syncTask(entry cache.Entry) error {
taskId := entry.Key.String()
m.logger.Debug("Sync a task", "taskId", taskId)

client := m.Clickup

m.logger.Debug("Fetching task from API")
data, err := client.GetTask(taskId)
if err != nil {
return err
}
m.logger.Debug("Found task", "task", taskId)

entry.UpdatedTs = time.Now().Unix()
entry.Value = data
m.Cache.Update(entry)

return nil
}

func (m *Api) GetTasksFromList(listId string) ([]clickup.Task, error) {
m.logger.Debug("Getting tasks for a list", "listId", listId)

Expand Down Expand Up @@ -156,6 +284,26 @@ func (m *Api) GetTasksFromView(viewId string) ([]clickup.Task, error) {
return data, nil
}

func (m *Api) syncTasksFromView(entry cache.Entry) error {
viewId := entry.Key.String()
m.logger.Debug("Sync tasks for a view", "viewId", viewId)

client := m.Clickup

m.logger.Debug("Fetching tasks from API")
data, err := client.GetTasksFromView(viewId)
if err != nil {
return err
}
m.logger.Debugf("Found %d tasks in view %s", len(data), viewId)

entry.UpdatedTs = time.Now().Unix()
entry.Value = data
m.Cache.Update(entry)

return nil
}

func (m *Api) GetViewsFromFolder(folderId string) ([]clickup.View, error) {
m.logger.Debug("Getting views for folder", "folder", folderId)

Expand Down Expand Up @@ -265,31 +413,48 @@ func (m *Api) InvalidateCache() error {
entries := m.Cache.GetEntries()
m.logger.Debug("Found cache entries", "count", len(entries))

if err := m.Cache.Invalidate(); err != nil {
m.logger.Error("Failed to invalidate cache", "error", err)
return err
}
// if err := m.Cache.Invalidate(); err != nil {
// m.logger.Error("Failed to invalidate cache", "error", err)
// return err
// }

now := time.Now().Unix()
for _, entry := range entries {
m.logger.Debug("Invalidating cache", "namespace", entry.Namespace, "key", entry.Key.String())
if entry.UpdatedTs+TTL > now {
continue
}

var err error

m.logger.Debug("Invalidating cache", "namespace", entry.Namespace, "key", entry.Key.String())

switch entry.Namespace {
case CacheNamespaceTeams:
_, err = m.GetTeams()
err = m.syncTeams(entry)
case CacheNamespaceSpaces:
_, err = m.GetSpaces(entry.Key.String())
err = m.syncSpaces(entry)
case CacheNamespaceFolders:
_, err = m.GetFolders(entry.Key.String())
err = m.syncFolders(entry)
case CacheNamespaceLists:
_, err = m.GetLists(entry.Key.String())
case CacheNamespaceViews:
_, err = m.GetViewsFromSpace(entry.Key.String())
case CacheNamespaceTasksList:
_, err = m.GetTasksFromList(entry.Key.String())
err = m.syncLists(entry)

// TODO:
// case CacheNamespaceViews:
// m.logger.Debug("Invalidating views cache")
// _, err := m.GetViewsFromSpace(entry.Key)
// if err != nil {
// m.logger.Error("Failed to invalidate views cache", "error", err)
// }
// case CacheNamespaceTasksList:
// m.logger.Debug("Invalidating tasks cache")
// _, err := m.GetTasksFromList(entry.Key)
// if err != nil {
// m.logger.Error("Failed to invalidate tasks cache", "error", err)
// }
case CacheNamespaceTasksView:
_, err = m.GetTasksFromView(entry.Key.String())
err = m.syncTasksFromView(entry)
case CacheNamespaceTasks:
_, err = m.GetTask(entry.Key.String())
err = m.syncTask(entry)
}

if err != nil {
Expand Down
1 change: 1 addition & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,7 @@ func main() {
logger.Info("Initializing program...")
p := tea.NewProgram(mainModel, tea.WithAltScreen())
if _, err := p.Run(); err != nil {
cache.Close()
termLogger.Fatal(err)
}
}
Expand Down
16 changes: 16 additions & 0 deletions ui/common/commands.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,3 +91,19 @@ func ErrCmd(err ErrMsg) tea.Cmd {
return err
}
}

type UITickMsg int64

func UITickCmd(ts int64) tea.Cmd {
return func() tea.Msg {
return UITickMsg(ts)
}
}

type RefreshMsg string

func RefreshCmd() tea.Cmd {
return func() tea.Msg {
return RefreshMsg("")
}
}
6 changes: 5 additions & 1 deletion ui/components/tasks-sidebar/tasksidebar.go
Original file line number Diff line number Diff line change
Expand Up @@ -146,15 +146,19 @@ func (m Model) renderTask(task clickup.Task) string {
divider := strings.Repeat("-", runewidth.StringWidth(header))
s.WriteString(divider)

r, _ := glamour.NewTermRenderer(
r, err := glamour.NewTermRenderer(
glamour.WithAutoStyle(),
glamour.WithWordWrap(m.viewport.Width),
)
if err != nil {
return err.Error()
}

out, err := r.Render(task.MarkdownDescription)
if err != nil {
return err.Error()
}

s.WriteString(out)

return s.String()
Expand Down
12 changes: 12 additions & 0 deletions ui/ui.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package ui

import (
"strings"
"time"

"github.com/charmbracelet/bubbles/key"
tea "github.com/charmbracelet/bubbletea"
Expand Down Expand Up @@ -73,6 +74,16 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
"width", msg.Width,
"height", msg.Height)
m.ctx.WindowSize.Set(msg.Width, msg.Height)

case common.UITickMsg:
ts := int64(msg)
if time.Now().Unix() > ts {
m.log.Debug("Fire refresh tick")
cmds = append(cmds, common.UITickCmd(time.Now().Unix()+3))
cmds = append(cmds, common.RefreshCmd())
return m, tea.Batch(cmds...)
}
cmds = append(cmds, common.UITickCmd(ts))
}

cmds = append(cmds,
Expand Down Expand Up @@ -128,5 +139,6 @@ func (m Model) Init() tea.Cmd {
return tea.Batch(
m.viewCompact.Init(),
m.dialogHelp.Init(),
common.UITickCmd(time.Now().Unix()+3),
)
}
Loading
Loading