Merge branch '8784-dir-listings'
[arvados.git] / services / keep-balance / change_set.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package main
6
7 import (
8         "encoding/json"
9         "fmt"
10         "sync"
11
12         "git.curoverse.com/arvados.git/sdk/go/arvados"
13 )
14
15 // Pull is a request to retrieve a block from a remote server, and
16 // store it locally.
17 type Pull struct {
18         arvados.SizedDigest
19         Source *KeepService
20 }
21
22 // MarshalJSON formats a pull request the way keepstore wants to see
23 // it.
24 func (p Pull) MarshalJSON() ([]byte, error) {
25         type KeepstorePullRequest struct {
26                 Locator string   `json:"locator"`
27                 Servers []string `json:"servers"`
28         }
29         return json.Marshal(KeepstorePullRequest{
30                 Locator: string(p.SizedDigest[:32]),
31                 Servers: []string{p.Source.URLBase()}})
32 }
33
34 // Trash is a request to delete a block.
35 type Trash struct {
36         arvados.SizedDigest
37         Mtime int64
38 }
39
40 // MarshalJSON formats a trash request the way keepstore wants to see
41 // it, i.e., as a bare locator with no +size hint.
42 func (t Trash) MarshalJSON() ([]byte, error) {
43         type KeepstoreTrashRequest struct {
44                 Locator    string `json:"locator"`
45                 BlockMtime int64  `json:"block_mtime"`
46         }
47         return json.Marshal(KeepstoreTrashRequest{
48                 Locator:    string(t.SizedDigest[:32]),
49                 BlockMtime: t.Mtime})
50 }
51
52 // ChangeSet is a set of change requests that will be sent to a
53 // keepstore server.
54 type ChangeSet struct {
55         Pulls   []Pull
56         Trashes []Trash
57         mutex   sync.Mutex
58 }
59
60 // AddPull adds a Pull operation.
61 func (cs *ChangeSet) AddPull(p Pull) {
62         cs.mutex.Lock()
63         cs.Pulls = append(cs.Pulls, p)
64         cs.mutex.Unlock()
65 }
66
67 // AddTrash adds a Trash operation
68 func (cs *ChangeSet) AddTrash(t Trash) {
69         cs.mutex.Lock()
70         cs.Trashes = append(cs.Trashes, t)
71         cs.mutex.Unlock()
72 }
73
74 // String implements fmt.Stringer.
75 func (cs *ChangeSet) String() string {
76         cs.mutex.Lock()
77         defer cs.mutex.Unlock()
78         return fmt.Sprintf("ChangeSet{Pulls:%d, Trashes:%d}", len(cs.Pulls), len(cs.Trashes))
79 }