2022-11-19 21:34:49 +01:00
|
|
|
package server
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"encoding/base64"
|
|
|
|
"fmt"
|
|
|
|
|
2023-09-22 15:38:10 +02:00
|
|
|
castorev1pb "code.tvl.fyi/tvix/castore/protos"
|
2022-11-19 21:34:49 +01:00
|
|
|
log "github.com/sirupsen/logrus"
|
|
|
|
)
|
|
|
|
|
|
|
|
type DirectoriesUploader struct {
|
|
|
|
ctx context.Context
|
2023-09-22 15:38:10 +02:00
|
|
|
directoryServiceClient castorev1pb.DirectoryServiceClient
|
|
|
|
directoryServicePutStream castorev1pb.DirectoryService_PutClient
|
2022-11-19 21:34:49 +01:00
|
|
|
}
|
|
|
|
|
2023-09-22 15:38:10 +02:00
|
|
|
func NewDirectoriesUploader(ctx context.Context, directoryServiceClient castorev1pb.DirectoryServiceClient) *DirectoriesUploader {
|
2022-11-19 21:34:49 +01:00
|
|
|
return &DirectoriesUploader{
|
|
|
|
ctx: ctx,
|
|
|
|
directoryServiceClient: directoryServiceClient,
|
|
|
|
directoryServicePutStream: nil,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-09-22 15:38:10 +02:00
|
|
|
func (du *DirectoriesUploader) Put(directory *castorev1pb.Directory) error {
|
2022-11-19 21:34:49 +01:00
|
|
|
directoryDgst, err := directory.Digest()
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("failed calculating directory digest: %w", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Send the directory to the directory service
|
|
|
|
// If the stream hasn't been initialized yet, do it first
|
|
|
|
if du.directoryServicePutStream == nil {
|
|
|
|
directoryServicePutStream, err := du.directoryServiceClient.Put(du.ctx)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("unable to initialize directory service put stream: %v", err)
|
|
|
|
}
|
|
|
|
du.directoryServicePutStream = directoryServicePutStream
|
|
|
|
}
|
|
|
|
|
|
|
|
// send the directory out
|
|
|
|
err = du.directoryServicePutStream.Send(directory)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("error sending directory: %w", err)
|
|
|
|
}
|
2023-09-18 11:04:59 +02:00
|
|
|
log.WithField("digest", base64.StdEncoding.EncodeToString(directoryDgst)).Debug("uploaded directory")
|
2022-11-19 21:34:49 +01:00
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Done is called whenever we're
|
2023-09-22 15:38:10 +02:00
|
|
|
func (du *DirectoriesUploader) Done() (*castorev1pb.PutDirectoryResponse, error) {
|
2022-11-19 21:34:49 +01:00
|
|
|
// only close once, and only if we opened.
|
|
|
|
if du.directoryServicePutStream == nil {
|
|
|
|
return nil, nil
|
|
|
|
}
|
|
|
|
putDirectoryResponse, err := du.directoryServicePutStream.CloseAndRecv()
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("unable to close directory service put stream: %v", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
du.directoryServicePutStream = nil
|
|
|
|
|
|
|
|
return putDirectoryResponse, nil
|
|
|
|
}
|