The file of the session files' chunks was named by the binary's own
stat key, so every upgrade, and magpie ships several a day, read every
session file again on its first Requests page: on a 15.6k-shard history
warm-up step 2 went from ~0.8-0.9s (read from the file) to 1.6-1.9s and
~1.3GB more allocation. It is named now by the call shards' version
(sessions.CallCacheVersion, which already decides whether a shard of the
calls is read) and a SHA-256 of this package's non-test source, which
the binary carries (go:embed *.go, ~750KB with the tests, which the name
leaves out). Of the last 99 releases, 17 changed that source; the other
82 keep the file. Prices, names and settings are in the file's meta as
before. When the embedded source can't be read the name is the binary's,
as it was.
Measured (real history, sbpairs): one test binary wrote the file, a
second binary at another path (the old key differs) read it: step 2
0.79s and 1001MB alloc, against 1.63s and 2285MB cold.
Run at this tree (89dc16476 + this change):
- go test -race -count=1 ./internal/usage: ok
- go test -count=1 ./internal/sessions ./internal/gui: ok
- GOOS=linux and GOOS=windows go vet -tags nogui ./internal/usage
./internal/sessions, and go build -tags nogui .: ok; gofmt -l clean
- TestRequestDiskNamesItsSource hashes the package's files from disk
and wants the same name. Broken by hand (embed request_*.go only):
red; restored: green.
Not tried: an upgrade of the real app from one release to the next.
343 lines
8.8 KiB
Go
343 lines
8.8 KiB
Go
package usage
|
|
|
|
import (
|
|
"bufio"
|
|
"crypto/sha256"
|
|
"embed"
|
|
"encoding/binary"
|
|
"errors"
|
|
"fmt"
|
|
"hash/crc32"
|
|
"io"
|
|
"io/fs"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
|
|
"github.com/yetone/magpie/internal/sessions"
|
|
)
|
|
|
|
// The session files' chunks are kept on disk between runs (requests-v1.bin).
|
|
// A started magpie opened every session file's call shard (~15.6k of them)
|
|
// and turned each call into a row again before its first Requests page
|
|
// could show, and so did a page asked for once two idle minutes had trimmed
|
|
// the chunks (#3493). An entry stands for its session file while the file's
|
|
// size and mtime are the same, as a call shard does, and the whole file
|
|
// while the code that wrote it and what prices and names a call (the
|
|
// index's root and meta) are the same.
|
|
//
|
|
// The file is a header, then entries one after another, each its length,
|
|
// its CRC-32 and its bytes; a bad entry ends the read, and the entries
|
|
// before it stand.
|
|
|
|
const requestDiskMagic = "magpie-requests-v1\n"
|
|
|
|
func requestDiskPath() string {
|
|
return filepath.Join(filepath.Dir(sessions.CachePath()), "requests-v1.bin")
|
|
}
|
|
|
|
// requestDiskBinary names the code a file was written by: another may make
|
|
// a row of a call differently. It was the binary itself, so every upgrade
|
|
// read every session file again (~15.6k call shards, a cold start's
|
|
// longest step); it is the call shards' version and this package's own
|
|
// source, which 17 of 99 releases changed.
|
|
var requestDiskBinary = sync.OnceValue(func() string {
|
|
h := sha256.New()
|
|
io.WriteString(h, sessions.CallCacheVersion)
|
|
// unread, it is the binary's, as it was
|
|
binary := func() string {
|
|
exe, err := os.Executable()
|
|
if err != nil {
|
|
return ""
|
|
}
|
|
return statKey(exe)
|
|
}
|
|
names, err := fs.Glob(ownSource, "*.go")
|
|
if err != nil || len(names) == 0 {
|
|
return binary()
|
|
}
|
|
for _, name := range names { // in lexical order
|
|
if strings.HasSuffix(name, "_test.go") {
|
|
continue
|
|
}
|
|
b, err := ownSource.ReadFile(name)
|
|
if err != nil {
|
|
return binary()
|
|
}
|
|
fmt.Fprintf(h, "\x00%s\x00%d\x00", name, len(b))
|
|
h.Write(b)
|
|
}
|
|
return fmt.Sprintf("source %x", h.Sum(nil))
|
|
})
|
|
|
|
// ownSource is this package's source, for requestDiskBinary.
|
|
//
|
|
//go:embed *.go
|
|
var ownSource embed.FS
|
|
|
|
// requestDiskLeast is how many session files must want reading before the
|
|
// file is read for them: a page after a call reads one or two again.
|
|
var requestDiskLeast = 64
|
|
|
|
// diskHeader is the file's first entry.
|
|
func diskHeader(binary, root, meta string) []byte {
|
|
var b []byte
|
|
for _, s := range []string{requestDiskMagic, binary, root, meta} {
|
|
b = appendDiskString(b, s)
|
|
}
|
|
return b
|
|
}
|
|
|
|
func appendDiskString(b []byte, s string) []byte {
|
|
b = binary.AppendUvarint(b, uint64(len(s)))
|
|
return append(b, s...)
|
|
}
|
|
|
|
// diskEntry is c as an entry, or nil when it can't be kept: a chunk of
|
|
// another computer's day, or one whose times are in a zone that can't be
|
|
// named again.
|
|
func diskEntry(c *rowChunk) []byte {
|
|
if c.Computer != "" {
|
|
return nil
|
|
}
|
|
archive, locations := c.Archive, c.Locations
|
|
if len(archive) == 0 {
|
|
archive, locations = c.encode(func([]byte) bool { return true })
|
|
}
|
|
var b []byte
|
|
put := func(v uint64) { b = binary.AppendUvarint(b, v) }
|
|
s := c.Source
|
|
for _, t := range []string{s.Path, s.Key, s.Agent} {
|
|
b = appendDiskString(b, t)
|
|
}
|
|
put(uint64(s.Size))
|
|
put(uint64(s.Modified.UnixNano()))
|
|
put(uint64(c.Count))
|
|
put(uint64(c.Latest.UnixNano()))
|
|
put(uint64(len(locations)))
|
|
for _, loc := range locations {
|
|
name, offset := time.Unix(0, 0).In(loc).Zone()
|
|
if loc == time.Local {
|
|
name = "Local"
|
|
} else if loc != time.UTC && loc.String() != name {
|
|
// a zone of the tz database, named by it
|
|
name = "@" + loc.String()
|
|
}
|
|
b = appendDiskString(b, name)
|
|
put(uint64(int64(offset)))
|
|
}
|
|
put(uint64(len(c.codexActors)))
|
|
for _, actor := range c.codexActors {
|
|
b = appendDiskString(b, actor)
|
|
}
|
|
put(uint64(len(archive)))
|
|
return append(b, archive...)
|
|
}
|
|
|
|
var errDiskEntry = errors.New("bad requests entry")
|
|
|
|
// readDiskEntry is the chunk an entry holds.
|
|
func readDiskEntry(b []byte) (*rowChunk, error) {
|
|
take := func() uint64 {
|
|
n, k := binary.Uvarint(b)
|
|
if k <= 0 {
|
|
b = nil
|
|
return 0
|
|
}
|
|
b = b[k:]
|
|
return n
|
|
}
|
|
text := func() (string, bool) {
|
|
n := take()
|
|
if b == nil || n > uint64(len(b)) {
|
|
return "", false
|
|
}
|
|
s := string(b[:n])
|
|
b = b[n:]
|
|
return s, true
|
|
}
|
|
c := &rowChunk{}
|
|
var ok [3]bool
|
|
c.Source.Path, ok[0] = text()
|
|
c.Source.Key, ok[1] = text()
|
|
c.Source.Agent, ok[2] = text()
|
|
if ok != [3]bool{true, true, true} {
|
|
return nil, errDiskEntry
|
|
}
|
|
c.Source.Size = int64(take())
|
|
c.Source.Modified = time.Unix(0, int64(take()))
|
|
c.Count = int(take())
|
|
c.Latest = time.Unix(0, int64(take())).In(time.Local)
|
|
n := take()
|
|
if b == nil || n > uint64(len(b)) {
|
|
return nil, errDiskEntry
|
|
}
|
|
for range n {
|
|
name, good := text()
|
|
offset := int(int64(take()))
|
|
if !good || b == nil {
|
|
return nil, errDiskEntry
|
|
}
|
|
var loc *time.Location
|
|
switch {
|
|
case name == "Local":
|
|
loc = time.Local
|
|
case name == "UTC":
|
|
loc = time.UTC
|
|
case len(name) > 0 && name[0] == '@':
|
|
l, err := time.LoadLocation(name[1:])
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
loc = l
|
|
default:
|
|
loc = time.FixedZone(name, offset)
|
|
}
|
|
c.Locations = append(c.Locations, loc)
|
|
}
|
|
n = take()
|
|
if b == nil || n > uint64(len(b)) {
|
|
return nil, errDiskEntry
|
|
}
|
|
for range n {
|
|
actor, good := text()
|
|
if !good {
|
|
return nil, errDiskEntry
|
|
}
|
|
c.codexActors = append(c.codexActors, actor)
|
|
}
|
|
n = take()
|
|
if b == nil || n != uint64(len(b)) || n == 0 {
|
|
return nil, errDiskEntry
|
|
}
|
|
c.Archive = b
|
|
c.Bytes = int64(len(b)+len(c.Locations)*8) + codexActorBytes(c.codexActors)
|
|
return c, nil
|
|
}
|
|
|
|
// readDiskEntries hands each entry of the file at path to each in turn,
|
|
// while the file is of binary, root and meta. raw is the entry's bytes,
|
|
// whole, to be written on as they are.
|
|
func readDiskEntries(path, binary, root, meta string, each func(raw []byte) bool) {
|
|
in, err := os.Open(path)
|
|
if err != nil {
|
|
return
|
|
}
|
|
defer in.Close()
|
|
r := bufio.NewReaderSize(in, 1<<20)
|
|
header, ok := nextDiskEntry(r)
|
|
if !ok || string(header) != string(diskHeader(binary, root, meta)) {
|
|
return
|
|
}
|
|
for {
|
|
raw, ok := nextDiskEntry(r)
|
|
if !ok || !each(raw) {
|
|
return
|
|
}
|
|
}
|
|
}
|
|
|
|
func nextDiskEntry(r *bufio.Reader) ([]byte, bool) {
|
|
n, err := binary.ReadUvarint(r)
|
|
if err != nil || n == 0 || n > 256<<20 {
|
|
return nil, false
|
|
}
|
|
var sum [4]byte
|
|
if _, err := io.ReadFull(r, sum[:]); err != nil {
|
|
return nil, false
|
|
}
|
|
b := make([]byte, n)
|
|
if _, err := io.ReadFull(r, b); err != nil || crc32.ChecksumIEEE(b) != binary.LittleEndian.Uint32(sum[:]) {
|
|
return nil, false
|
|
}
|
|
return b, true
|
|
}
|
|
|
|
func writeDiskEntry(w *bufio.Writer, b []byte) error {
|
|
var head [binary.MaxVarintLen64 + 4]byte
|
|
n := binary.PutUvarint(head[:], uint64(len(b)))
|
|
binary.LittleEndian.PutUint32(head[n:], crc32.ChecksumIEEE(b))
|
|
if _, err := w.Write(head[:n+4]); err != nil {
|
|
return err
|
|
}
|
|
_, err := w.Write(b)
|
|
return err
|
|
}
|
|
|
|
// fromDisk puts in idx the chunks the file holds of the sources in want,
|
|
// each still the size and mtime it was. idx is a private copy (private).
|
|
func (idx *requestIndex) fromDisk(want map[string]sessions.CallSource) {
|
|
readDiskEntries(requestDiskPath(), requestDiskBinary(), idx.root, idx.meta, func(raw []byte) bool {
|
|
c, err := readDiskEntry(raw)
|
|
if err != nil {
|
|
return false
|
|
}
|
|
s, ok := want[c.Source.Path]
|
|
if !ok || s.Size != c.Source.Size || !s.Modified.Equal(c.Source.Modified) {
|
|
return true
|
|
}
|
|
c.Source = s
|
|
c.serial = nextChunkSerial()
|
|
c.Used = idx.tick
|
|
idx.chunks[s.Path] = c
|
|
return true
|
|
})
|
|
}
|
|
|
|
// toDisk writes chunks, and the entries of the file before it for the
|
|
// paths in on that chunks doesn't hold, as the file for root and meta.
|
|
func toDisk(root, meta string, chunks map[string]*rowChunk, on map[string]bool) error {
|
|
path, binary := requestDiskPath(), requestDiskBinary()
|
|
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
|
|
return err
|
|
}
|
|
out, err := os.CreateTemp(filepath.Dir(path), "requests-*.tmp")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer os.Remove(out.Name())
|
|
w := bufio.NewWriterSize(out, 1<<20)
|
|
err = writeDiskEntry(w, diskHeader(binary, root, meta))
|
|
for _, c := range chunks {
|
|
if err != nil {
|
|
break
|
|
}
|
|
if b := diskEntry(c); b != nil {
|
|
err = writeDiskEntry(w, b)
|
|
}
|
|
}
|
|
if err == nil {
|
|
readDiskEntries(path, binary, root, meta, func(raw []byte) bool {
|
|
p, ok := diskEntryPath(raw)
|
|
if !ok {
|
|
return false
|
|
}
|
|
if on[p] && chunks[p] == nil {
|
|
err = writeDiskEntry(w, raw)
|
|
}
|
|
return err == nil
|
|
})
|
|
}
|
|
if err == nil {
|
|
err = w.Flush()
|
|
}
|
|
if closeErr := out.Close(); err == nil {
|
|
err = closeErr
|
|
}
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return os.Rename(out.Name(), path)
|
|
}
|
|
|
|
// diskEntryPath is the path of the source an entry is of.
|
|
func diskEntryPath(b []byte) (string, bool) {
|
|
n, k := binary.Uvarint(b)
|
|
if k <= 0 || n > uint64(len(b)-k) {
|
|
return "", false
|
|
}
|
|
return string(b[k : k+int(n)]), true
|
|
}
|