github.com/adevinta/lava@v0.7.2/internal/engine/store.go (about)

     1  // Copyright 2023 Adevinta
     2  
     3  package engine
     4  
     5  import (
     6  	"fmt"
     7  	"log/slog"
     8  	"maps"
     9  	"sync"
    10  	"time"
    11  
    12  	"github.com/adevinta/vulcan-agent/storage"
    13  	report "github.com/adevinta/vulcan-report"
    14  )
    15  
    16  // reportStore stores the reports generated by the Vulcan agent in
    17  // memory. It implements [storage.Store].
    18  type reportStore struct {
    19  	mu      sync.Mutex
    20  	reports map[string]report.Report
    21  }
    22  
    23  var _ storage.Store = &reportStore{}
    24  
    25  // UploadCheckData decodes the provided content and stores it in
    26  // memory indexed by checkID. If kind is "reports", it decodes content
    27  // as [report.Report]. If kind is "logs", the data is ignored.
    28  func (rs *reportStore) UploadCheckData(checkID, kind string, startedAt time.Time, content []byte) (link string, err error) {
    29  	rs.mu.Lock()
    30  	defer rs.mu.Unlock()
    31  
    32  	logger := slog.With("checkID", checkID)
    33  
    34  	if rs.reports == nil {
    35  		rs.reports = make(map[string]report.Report)
    36  	}
    37  
    38  	switch kind {
    39  	case "reports":
    40  		logger.Debug("received reports from check", "content", fmt.Sprintf("%#q", content))
    41  
    42  		var r report.Report
    43  		if err := r.UnmarshalJSONTimeAsString(content); err != nil {
    44  			return "", fmt.Errorf("decode content: %w", err)
    45  		}
    46  		rs.reports[checkID] = r
    47  	case "logs":
    48  		logger.Debug("received logs from check", "content", fmt.Sprintf("%#q", content))
    49  	default:
    50  		return "", fmt.Errorf("unknown data kind: %v", kind)
    51  	}
    52  	return "", nil
    53  }
    54  
    55  // Summary returns a human-readable summary per report.
    56  func (rs *reportStore) Summary() []string {
    57  	rs.mu.Lock()
    58  	defer rs.mu.Unlock()
    59  
    60  	var sums []string
    61  	for _, r := range rs.reports {
    62  		s := fmt.Sprintf("checktype=%v target=%v start=%v status=%v", r.ChecktypeName, r.Target, r.StartTime, r.Status)
    63  		sums = append(sums, s)
    64  	}
    65  	return sums
    66  }
    67  
    68  // Reports returns the stored reports.
    69  func (rs *reportStore) Reports() map[string]report.Report {
    70  	rs.mu.Lock()
    71  	defer rs.mu.Unlock()
    72  
    73  	return maps.Clone(rs.reports)
    74  }