This repository has been archived by the owner on Aug 4, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathpeer.go
98 lines (78 loc) · 2.13 KB
/
peer.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
// Copyright (C) 2020 Storj Labs, Inc.
// See LICENSE for copying information.
package linksharing
import (
"context"
"errors"
"github.com/oschwald/maxminddb-golang"
"github.com/zeebo/errs"
"go.uber.org/zap"
"golang.org/x/sync/errgroup"
"storj.io/linksharing/httpserver"
"storj.io/linksharing/objectmap"
"storj.io/linksharing/sharing"
)
// Config contains configurable values for sno registration Peer.
type Config struct {
Server httpserver.Config
Handler sharing.Config
// Maxmind geolocation database path.
GeoLocationDB string
}
// Peer is the representation of a Linksharing service itself.
//
// architecture: Peer
type Peer struct {
Log *zap.Logger
Mapper *objectmap.IPDB
Server *httpserver.Server
}
// New is a constructor for Linksharing Peer.
func New(log *zap.Logger, config Config) (_ *Peer, err error) {
peer := &Peer{
Log: log,
}
if config.GeoLocationDB != "" {
reader, err := maxminddb.Open(config.GeoLocationDB)
if err != nil {
return nil, errs.New("unable to open geo location db: %w", err)
}
peer.Mapper = objectmap.NewIPDB(reader)
}
handle, err := sharing.NewHandler(log, peer.Mapper, config.Handler)
if err != nil {
return nil, errs.New("unable to create handler: %w", err)
}
peer.Server, err = httpserver.New(log, handle, config.Server)
if err != nil {
return nil, errs.New("unable to create httpserver: %w", err)
}
return peer, nil
}
// Run runs SNO registration service until it's either closed or it errors.
func (peer *Peer) Run(ctx context.Context) error {
group, ctx := errgroup.WithContext(ctx)
// start SNO registration service as a separate goroutine.
group.Go(func() error {
return ignoreCancel(peer.Server.Run(ctx))
})
return group.Wait()
}
// Close closes all underlying resources.
func (peer *Peer) Close() error {
errlist := errs.Group{}
if peer.Server != nil {
errlist.Add(peer.Server.Close())
}
if peer.Mapper != nil {
errlist.Add(peer.Mapper.Close())
}
return errlist.Err()
}
// we ignore cancellation and stopping errors since they are expected.
func ignoreCancel(err error) error {
if errors.Is(err, context.Canceled) {
return nil
}
return err
}