Skip to content

Commit

Permalink
refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
zippoxer committed Jun 17, 2018
1 parent e4a3c15 commit f56ad46
Show file tree
Hide file tree
Showing 5 changed files with 337 additions and 137 deletions.
92 changes: 92 additions & 0 deletions cache.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
package main

import (
"sync"

"github.com/zippoxer/george/forge"
)

type cache struct {
client *forge.Client
servers []forge.Server
serversMu sync.Mutex
sites map[int][]forge.Site // Map of server id to it's sites.
sitesMu sync.Mutex
}

func newCache(client *forge.Client) *cache {
return &cache{
client: client,
sites: make(map[int][]forge.Site),
}
}

func (c *cache) Servers() ([]forge.Server, error) {
c.serversMu.Lock()
ok := c.servers != nil
c.serversMu.Unlock()
if ok {
return c.servers, nil
}
servers, err := c.client.Servers().List()
if err != nil {
return nil, err
}
c.serversMu.Lock()
c.servers = servers
c.serversMu.Unlock()
return servers, nil
}

func (c *cache) Sites(serverId int) ([]forge.Site, error) {
c.sitesMu.Lock()
sites, ok := c.sites[serverId]
c.sitesMu.Unlock()
if ok {
return sites, nil
}
sites, err := c.client.Sites(serverId).List()
if err != nil {
return nil, err
}
c.sitesMu.Lock()
c.sites[serverId] = sites
c.sitesMu.Unlock()
return sites, nil
}

type ServerSites struct {
forge.Server
Sites []forge.Site
}

func (c *cache) ServerSites(servers []forge.Server) ([]ServerSites, error) {
if servers == nil {
var err error
servers, err = c.Servers()
if err != nil {
return nil, err
}
}
dataChan := make(chan ServerSites)
errChan := make(chan error, len(servers))
for _, server := range servers {
go func(server forge.Server) {
sites, err := c.Sites(server.Id)
if err != nil {
errChan <- err
}
dataChan <- ServerSites{Server: server, Sites: sites}
}(server)
}
results := make([]ServerSites, 0, len(servers))
for i := 0; i < len(servers); i++ {
select {
case data := <-dataChan:
results = append(results, data)
case err := <-errChan:
return nil, err
}
}
return results, nil
}
4 changes: 4 additions & 0 deletions forge/sites.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (

type Site struct {
Id int `json:"id"`
ServerId int `json:"server_id"`
Name string `json:"name"`
Directory string `json:"directory"`
Wildcards bool `json:"wildcards"`
Expand Down Expand Up @@ -40,5 +41,8 @@ func (s *Sites) List() ([]Site, error) {
if err != nil {
return nil, err
}
for i := range resp.Sites {
resp.Sites[i].ServerId = s.serverId
}
return resp.Sites, nil
}
Loading

0 comments on commit f56ad46

Please sign in to comment.