~ knotless Search/
↑↓ move↵ open⇧↵ all results

socialweb.computer/socialweb-computer-kcp

socialweb.computer: a compute market on atproto (kcp)

1 collaborator
0
0
80 lines · 2.1 KB Raw History
package guestcontrolplane

import (
	"os"
	"path/filepath"
	"regexp"
	"time"

	"github.com/johnandersen777/socialweb-computer-kcp/internal/kit/pinneddownloads"
	"github.com/johnandersen777/socialweb-computer-kcp/internal/kit/sha256sum"
)

var sha256Hex = regexp.MustCompile(`^[0-9a-f]{64}$`)

type fileStamp struct {
	size int64

	mod time.Time
}

func (s *Service) previousDownload(sum, name string) (string, int64, bool) {
	if !sha256Hex.MatchString(sum) {
		return "", 0, false
	}
	s.downloadsMu.Lock()
	defer s.downloadsMu.Unlock()
	for _, path := range s.previousPaths(sum, name) {
		st, err := os.Stat(path)
		if err != nil || !st.Mode().IsRegular() {
			continue
		}
		stamp := fileStamp{size: st.Size(), mod: st.ModTime()}
		if s.mismatched[path] == stamp {
			continue
		}
		got, err := sha256sum.File(path)
		if err != nil || got != sum {
			if s.mismatched == nil {
				s.mismatched = map[string]fileStamp{}
			}
			s.mismatched[path] = stamp
			s.log.Warn("a previous download on this bidder does not have the sha256 a guest asks for", "name", name, "sha256", sum, "path", path, "got", got)
			continue
		}
		s.log.Info("the guest control plane serves a previous binary that a guest asks for", "name", name, "sha256", sum, "path", path, "bytes", st.Size())
		return path, st.Size(), true
	}
	return "", 0, false
}

func (s *Service) previousPaths(sum, name string) []string {
	if s.ownBinary != nil && name == s.ownBinary.Name {
		exe, err := os.Executable()
		if err != nil || filepath.Base(filepath.Dir(exe)) != s.ownBinary.Sha256 {
			return nil
		}
		return []string{filepath.Join(filepath.Dir(filepath.Dir(exe)), sum, filepath.Base(exe))}
	}
	dir := s.downloadsDir()
	if dir == "" {
		return nil
	}
	dir = filepath.Clean(dir)
	root := filepath.Dir(dir)
	entries, err := os.ReadDir(root)
	if err != nil {
		return nil
	}
	var out []string
	for _, e := range entries {
		tree := filepath.Join(root, e.Name())
		if !e.IsDir() || !sha256Hex.MatchString(e.Name()) || tree == dir {
			continue
		}
		if pinned, err := pinneddownloads.SidecarSha256(tree, name); err == nil && pinned == sum {
			out = append(out, filepath.Join(tree, name))
		}
	}
	return out
}