package namespace import ( "caj-larsson/bog/util" "fmt" "time" ) type Clock interface { Now() time.Time } type NamespaceService struct { repo Repository outboxes []func(util.Event) logger util.Logger clock Clock default_ttl time.Duration default_quota_bytes int64 } func NewNamespaceService(repo Repository, logger util.Logger, clock Clock, default_ttl time.Duration, default_quota_bytes int64) *NamespaceService { return &NamespaceService{ repo, nil, logger, clock, default_ttl, default_quota_bytes, } } func (s *NamespaceService) GetOrCreateNs(name string) *Namespace { ns, err := s.repo.GetByName(name) if err == ErrNotExists { new_ns := Namespace{ 0, name, s.clock.Now(), s.default_ttl, FileSizeQuota{s.default_quota_bytes, 0}, FileStat{0, 0}, FileStat{0, 0}, } created_ns, err := s.repo.Create(new_ns) if err != nil { panic(err) } return created_ns } if err != nil { panic(err) } return ns } func (s *NamespaceService) Wire(reg func(string, util.EventHandler), outbox func(ev util.Event)) { reg("FileUsed", s.handleFileUsed) s.outboxes = append(s.outboxes, outbox) reg("FileUsed", s.handleFileUsed) reg("FileDeleted", s.handleFileDeleted) reg("FileRecieved", s.handleFileRecieved) } func (s *NamespaceService) All() []Namespace { nss, err := s.repo.All() if err != nil { panic(err) } return nss } func (s *NamespaceService) handleFileUsed(payload interface{}) { var payload_s = payload.(struct { Name string Size int64 }) fmt.Printf("file used %v\n", payload_s) ns := s.GetOrCreateNs(payload_s.Name) ns.FileQuota = ns.FileQuota.Add(payload_s.Size) s.repo.Update(ns.ID, *ns) } func (s *NamespaceService) handleFileDeleted(payload interface{}) { var payload_s = payload.(struct { Name string Size int64 }) fmt.Printf("file deleted %v\n", payload_s) ns := s.GetOrCreateNs(payload_s.Name) ns.FileQuota = ns.FileQuota.Add(-payload_s.Size) fmt.Printf("file usage %v\n", ns.FileQuota) s.repo.Update(ns.ID, *ns) } func (s *NamespaceService) handleFileRecieved(payload interface{}) { var payload_s = payload.(struct { Name string Size int64 }) fmt.Printf("file recieved %v\n", payload_s) ns := s.GetOrCreateNs(payload_s.Name) ns.FileQuota = ns.FileQuota.Add(payload_s.Size) fmt.Printf("file usage %v\n", ns.FileQuota) s.repo.Update(ns.ID, *ns) }