1 // Copyright 2019 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
12 "golang.org/x/mod/module"
13 "golang.org/x/mod/sumdb/note"
14 "golang.org/x/mod/sumdb/tlog"
17 // NewTestServer constructs a new TestServer
18 // that will sign its tree with the given signer key
19 // (see golang.org/x/mod/sumdb/note)
20 // and fetch new records as needed by calling gosum.
21 func NewTestServer(signer string, gosum func(path, vers string) ([]byte, error)) *TestServer {
22 return &TestServer{signer: signer, gosum: gosum}
25 // A TestServer is an in-memory implementation of Server for testing.
26 type TestServer struct {
28 gosum func(path, vers string) ([]byte, error)
33 lookup map[string]int64
36 // testHashes implements tlog.HashReader, reading from a slice.
37 type testHashes []tlog.Hash
39 func (h testHashes) ReadHashes(indexes []int64) ([]tlog.Hash, error) {
41 for _, id := range indexes {
42 list = append(list, h[id])
47 func (s *TestServer) Signed(ctx context.Context) ([]byte, error) {
51 size := int64(len(s.records))
52 h, err := tlog.TreeHash(size, s.hashes)
56 text := tlog.FormatTree(tlog.Tree{N: size, Hash: h})
57 signer, err := note.NewSigner(s.signer)
61 return note.Sign(¬e.Note{Text: string(text)}, signer)
64 func (s *TestServer) ReadRecords(ctx context.Context, id, n int64) ([][]byte, error) {
69 for i := int64(0); i < n; i++ {
70 if id+i >= int64(len(s.records)) {
71 return nil, fmt.Errorf("missing records")
73 list = append(list, s.records[id+i])
78 func (s *TestServer) Lookup(ctx context.Context, m module.Version) (int64, error) {
81 id, ok := s.lookup[key]
87 // Look up module and compute go.sum lines.
88 data, err := s.gosum(m.Path, m.Version)
96 // We ran the fetch without the lock.
97 // If another fetch happened and committed, use it instead.
98 id, ok = s.lookup[key]
104 id = int64(len(s.records))
105 s.records = append(s.records, data)
107 s.lookup = make(map[string]int64)
110 hashes, err := tlog.StoredHashesForRecordHash(id, tlog.RecordHash([]byte(data)), s.hashes)
114 s.hashes = append(s.hashes, hashes...)
119 func (s *TestServer) ReadTileData(ctx context.Context, t tlog.Tile) ([]byte, error) {
123 return tlog.ReadTileData(t, s.hashes)