-
Notifications
You must be signed in to change notification settings - Fork 9
/
filesync.go
82 lines (64 loc) · 2.1 KB
/
filesync.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
// Copyright 2022 Namespace Labs Inc; All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
package filesync
import (
"context"
"fmt"
"io/fs"
"log"
"net"
"os"
"path/filepath"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"namespacelabs.dev/foundation/internal/fnfs/workspace/wsremote"
"namespacelabs.dev/foundation/internal/wscontents"
)
func StartFileSyncServer(configuration *FileSyncConfiguration) {
if configuration.RootDir == "" {
log.Fatal("root_dir is missing")
}
grpcServer := grpc.NewServer()
wsremote.RegisterFileSyncServiceServer(grpcServer, sinkServer{configuration})
filesyncHost := fmt.Sprintf("0.0.0.0:%d", configuration.Port)
lis, err := net.Listen("tcp", filesyncHost)
if err != nil {
log.Fatal(err)
}
log.Printf("FileSync listening on %s. Root dir: \"%s\"", filesyncHost, configuration.RootDir)
if err := grpcServer.Serve(lis); err != nil {
log.Fatal(err)
}
}
type sinkServer struct {
configuration *FileSyncConfiguration
}
func (s sinkServer) Push(ctx context.Context, req *wsremote.PushRequest) (*wsremote.PushResponse, error) {
pkg := filepath.Join(req.GetSignature().GetModuleName(), req.GetSignature().GetRel())
basePath := filepath.Join(s.configuration.RootDir, pkg)
for k, ev := range req.FileEvent {
if ev.Path == "" {
return nil, status.Errorf(codes.InvalidArgument, "file_event[%d]: no path", k)
}
filePath := filepath.Join(basePath, ev.Path)
switch ev.Event {
case wscontents.FileEvent_WRITE:
if err := os.WriteFile(filePath, ev.NewContents, fs.FileMode(ev.Mode)); err != nil {
return nil, err
}
case wscontents.FileEvent_REMOVE:
if err := os.Remove(filePath); err != nil {
return nil, err
}
case wscontents.FileEvent_MKDIR:
if err := os.Mkdir(filePath, fs.FileMode(ev.Mode)); err != nil {
return nil, err
}
default:
return nil, status.Errorf(codes.InvalidArgument, "file_event[%d]: unrecognized event type: %s", k, ev.Event)
}
}
return &wsremote.PushResponse{}, nil
}