-
Notifications
You must be signed in to change notification settings - Fork 1
/
iceflake.go
107 lines (98 loc) · 2.4 KB
/
iceflake.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
99
100
101
102
103
104
105
106
107
package app
import (
"context"
"net"
"time"
"github.com/golang/protobuf/proto"
"github.com/istyle-inc/iceflake"
"github.com/istyle-inc/iceflake/foundation"
"github.com/istyle-inc/iceflake/pbdef"
"go.uber.org/zap"
)
// Option struct hold option value
type Option struct {
// ListenerType listen tcp, unix or else
ListenerType string
// WorkerID given worker-id to this app instance
WorkerID uint64
// Addr tcp address or unix socket path
Addr string
// BaseTime
BaseTime time.Time
}
// IceFlake app itself
type IceFlake struct {
// Listener instance of net.Listener implementation
net.Listener
// iceflake.GeneratorService Implant IDGeneratorService
iceflake.GeneratorService
preparing chan interface{}
baseTime time.Time
option *Option
}
func listener(o *Option) (net.Listener, error) {
return net.Listen(o.ListenerType, o.Addr)
}
// New return new IceFlake instance
func New(o *Option) (*IceFlake, error) {
l, err := listener(o)
if err != nil {
return nil, err
}
return &IceFlake{
Listener: l,
GeneratorService: iceflake.New(o.WorkerID, o.BaseTime),
baseTime: o.BaseTime,
option: o,
preparing: make(chan interface{}),
}, nil
}
// Preparing returns channel to notify listener's listened up
func (i *IceFlake) Preparing() chan interface{} {
return i.preparing
}
// Listen process start with listener
func (i *IceFlake) Listen(ctx context.Context) error {
go func() {
<-ctx.Done()
if err := i.Close(); err != nil {
foundation.Logger.Error("error occurred when closing", zap.Error(err))
}
}()
close(i.preparing)
for {
conn, err := i.Accept()
if err != nil {
select {
case <-ctx.Done():
foundation.Logger.Info("Shutting down listener")
return nil
default:
foundation.Logger.Error("error occurred while processing", zap.Error(err))
return err
}
}
go i.handle(ctx, conn)
}
}
func (i *IceFlake) handle(ctx context.Context, conn net.Conn) {
innerCtx, cancel := context.WithCancel(ctx)
defer cancel()
go func() {
<-innerCtx.Done()
_ = conn.Close()
foundation.Logger.Info("connection closed")
}()
id, err := i.Generate()
if err != nil {
foundation.Logger.Error("error with generation id", zap.Error(err))
return
}
flake := pbdef.IceFlake{Id: id}
data, _ := proto.Marshal(&flake)
_, err = conn.Write(data)
if err != nil {
foundation.Logger.Error("error with writing to stream", zap.Error(err))
return
}
}