mirror of
https://github.com/binwiederhier/ntfy.git
synced 2025-06-16 09:33:18 +02:00
SQLite cache
This commit is contained in:
parent
1c7695c1f3
commit
7b810acfb5
5 changed files with 254 additions and 133 deletions
server
|
@ -1,7 +1,6 @@
|
|||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
"math/rand"
|
||||
"sync"
|
||||
|
@ -12,11 +11,8 @@ import (
|
|||
// can publish a message
|
||||
type topic struct {
|
||||
id string
|
||||
subscribers map[int]subscriber
|
||||
messages []*message
|
||||
last time.Time
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
subscribers map[int]subscriber
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
|
@ -24,15 +20,11 @@ type topic struct {
|
|||
type subscriber func(msg *message) error
|
||||
|
||||
// newTopic creates a new topic
|
||||
func newTopic(id string) *topic {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
func newTopic(id string, last time.Time) *topic {
|
||||
return &topic{
|
||||
id: id,
|
||||
last: last,
|
||||
subscribers: make(map[int]subscriber),
|
||||
messages: make([]*message, 0),
|
||||
last: time.Now(),
|
||||
ctx: ctx,
|
||||
cancel: cancel,
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -55,7 +47,6 @@ func (t *topic) Publish(m *message) error {
|
|||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
t.last = time.Now()
|
||||
t.messages = append(t.messages, m)
|
||||
for _, s := range t.subscribers {
|
||||
if err := s(m); err != nil {
|
||||
log.Printf("error publishing message to subscriber")
|
||||
|
@ -64,38 +55,8 @@ func (t *topic) Publish(m *message) error {
|
|||
return nil
|
||||
}
|
||||
|
||||
func (t *topic) Messages(since time.Time) []*message {
|
||||
func (t *topic) Subscribers() int {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
messages := make([]*message, 0) // copy!
|
||||
for _, m := range t.messages {
|
||||
msgTime := time.Unix(m.Time, 0)
|
||||
if msgTime == since || msgTime.After(since) {
|
||||
messages = append(messages, m)
|
||||
}
|
||||
}
|
||||
return messages
|
||||
}
|
||||
|
||||
func (t *topic) Prune(keep time.Duration) {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
for i, m := range t.messages {
|
||||
msgTime := time.Unix(m.Time, 0)
|
||||
if time.Since(msgTime) < keep {
|
||||
t.messages = t.messages[i:]
|
||||
return
|
||||
}
|
||||
}
|
||||
t.messages = make([]*message, 0)
|
||||
}
|
||||
|
||||
func (t *topic) Stats() (subscribers int, messages int) {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
return len(t.subscribers), len(t.messages)
|
||||
}
|
||||
|
||||
func (t *topic) Close() {
|
||||
t.cancel()
|
||||
return len(t.subscribers)
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue