mirror of
https://github.com/datarhei/core.git
synced 2025-10-20 22:49:50 +08:00

By providing CORE_SESSIONS_SESSION_LOG_PATH_PATTERN (e.g. "/log/%Y-%m-%d.log") all finished sessions will be logged to a file according to the provided strftime-pattern. The actual value is calculated from when the session closed. CORE_SESSIONS_PERSIST must be set. Default: not set. Set CORE_SESSIONS_SESSION_LOG_BUFFER_SEC to the number of seconds the log should be buffered in memory before persisted to disk. Default 15 seconds.
95 lines
1.6 KiB
Go
95 lines
1.6 KiB
Go
package session
|
|
|
|
import (
|
|
"bytes"
|
|
"io"
|
|
"os"
|
|
|
|
"github.com/datarhei/core/v16/io/fs"
|
|
)
|
|
|
|
type SnapshotSource interface {
|
|
io.ReadCloser
|
|
}
|
|
|
|
type SnapshotSink interface {
|
|
io.WriteCloser
|
|
|
|
Cancel() error
|
|
}
|
|
|
|
type Snapshot interface {
|
|
Persist(sink SnapshotSink) error
|
|
Release()
|
|
}
|
|
|
|
type historySource struct {
|
|
fs fs.Filesystem
|
|
path string
|
|
data *bytes.Reader
|
|
}
|
|
|
|
// NewHistorySource returns a new SnapshotSource which reads the previously stored
|
|
// session history. If there's no data, a nil source with a nil error will be returned.
|
|
// If there's data, a non-nil source with a nil error will be returned. Otherwise
|
|
// the source will be nil and the error non-nil.
|
|
func NewHistorySource(fs fs.Filesystem, path string) (SnapshotSource, error) {
|
|
s := &historySource{
|
|
fs: fs,
|
|
path: path,
|
|
}
|
|
|
|
if _, err := s.fs.Stat(s.path); err == os.ErrNotExist {
|
|
return nil, nil
|
|
}
|
|
|
|
data, err := s.fs.ReadFile(s.path)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
s.data = bytes.NewReader(data)
|
|
|
|
return s, nil
|
|
}
|
|
|
|
func (s *historySource) Read(p []byte) (int, error) {
|
|
return s.data.Read(p)
|
|
}
|
|
|
|
func (s *historySource) Close() error {
|
|
s.data = nil
|
|
return nil
|
|
}
|
|
|
|
type historySink struct {
|
|
fs fs.Filesystem
|
|
path string
|
|
data *bytes.Buffer
|
|
}
|
|
|
|
func NewHistorySink(fs fs.Filesystem, path string) (SnapshotSink, error) {
|
|
s := &historySink{
|
|
fs: fs,
|
|
path: path,
|
|
data: &bytes.Buffer{},
|
|
}
|
|
|
|
return s, nil
|
|
}
|
|
|
|
func (s *historySink) Write(p []byte) (int, error) {
|
|
return s.data.Write(p)
|
|
}
|
|
|
|
func (s *historySink) Close() error {
|
|
_, _, err := s.fs.WriteFileSafe(s.path, s.data.Bytes())
|
|
s.data = nil
|
|
return err
|
|
}
|
|
|
|
func (s *historySink) Cancel() error {
|
|
s.data = nil
|
|
return nil
|
|
}
|