2021-09-17 21:55:24 +00:00
|
|
|
package logs
|
2020-09-16 14:03:52 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"io"
|
|
|
|
|
2020-09-18 00:34:03 +00:00
|
|
|
lru "github.com/hashicorp/golang-lru"
|
2024-02-15 05:46:47 +00:00
|
|
|
"github.com/prysmaticlabs/prysm/v5/async/event"
|
|
|
|
lruwrpr "github.com/prysmaticlabs/prysm/v5/cache/lru"
|
|
|
|
"github.com/prysmaticlabs/prysm/v5/crypto/rand"
|
2020-09-16 14:03:52 +00:00
|
|
|
)
|
|
|
|
|
2020-10-06 13:32:48 +00:00
|
|
|
const (
|
2020-12-18 18:03:24 +00:00
|
|
|
// The number of log entries to keep in memory.
|
|
|
|
logCacheSize = 20
|
2020-10-06 13:32:48 +00:00
|
|
|
)
|
2020-09-18 00:34:03 +00:00
|
|
|
|
2020-10-06 13:32:48 +00:00
|
|
|
var (
|
2020-12-18 18:03:24 +00:00
|
|
|
// Compile time interface checks.
|
|
|
|
_ = io.Writer(&StreamServer{})
|
|
|
|
_ = Streamer(&StreamServer{})
|
2020-10-06 13:32:48 +00:00
|
|
|
)
|
2020-09-16 14:03:52 +00:00
|
|
|
|
2020-12-18 18:03:24 +00:00
|
|
|
// Streamer defines a struct which can retrieve and stream process logs.
|
|
|
|
type Streamer interface {
|
|
|
|
GetLastFewLogs() [][]byte
|
|
|
|
LogsFeed() *event.Feed
|
|
|
|
}
|
|
|
|
|
2023-04-18 22:01:27 +00:00
|
|
|
// StreamServer defines a websocket server which can receive events from
|
2020-09-16 14:03:52 +00:00
|
|
|
// a feed and write them to open websocket connections.
|
|
|
|
type StreamServer struct {
|
2020-12-18 18:03:24 +00:00
|
|
|
feed *event.Feed
|
|
|
|
cache *lru.Cache
|
2020-09-16 14:03:52 +00:00
|
|
|
}
|
|
|
|
|
2020-12-18 18:03:24 +00:00
|
|
|
// NewStreamServer initializes a new stream server capable of
|
|
|
|
// streaming log events.
|
|
|
|
func NewStreamServer() *StreamServer {
|
2020-09-16 14:03:52 +00:00
|
|
|
ss := &StreamServer{
|
2020-12-18 18:03:24 +00:00
|
|
|
feed: new(event.Feed),
|
2021-09-02 10:36:54 +00:00
|
|
|
cache: lruwrpr.New(logCacheSize),
|
2020-09-16 14:03:52 +00:00
|
|
|
}
|
|
|
|
addLogWriter(ss)
|
|
|
|
return ss
|
|
|
|
}
|
|
|
|
|
2020-12-18 18:03:24 +00:00
|
|
|
// GetLastFewLogs returns the last few entries of logs stored in an LRU cache.
|
|
|
|
func (ss *StreamServer) GetLastFewLogs() [][]byte {
|
|
|
|
messages := make([][]byte, 0)
|
2020-09-18 00:34:03 +00:00
|
|
|
for _, k := range ss.cache.Keys() {
|
|
|
|
d, ok := ss.cache.Get(k)
|
|
|
|
if ok {
|
2020-12-18 18:03:24 +00:00
|
|
|
messages = append(messages, d.([]byte))
|
2020-09-18 00:34:03 +00:00
|
|
|
}
|
|
|
|
}
|
2020-12-18 18:03:24 +00:00
|
|
|
return messages
|
|
|
|
}
|
|
|
|
|
2023-04-18 22:01:27 +00:00
|
|
|
// LogsFeed returns a feed callers can subscribe to receive logs via a channel.
|
2020-12-18 18:03:24 +00:00
|
|
|
func (ss *StreamServer) LogsFeed() *event.Feed {
|
|
|
|
return ss.feed
|
2020-10-06 13:32:48 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Write a binary message and send over the event feed.
|
|
|
|
func (ss *StreamServer) Write(p []byte) (n int, err error) {
|
|
|
|
ss.feed.Send(p)
|
|
|
|
ss.cache.Add(rand.NewGenerator().Uint64(), p)
|
|
|
|
return len(p), nil
|
|
|
|
}
|