-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.go
218 lines (198 loc) · 6.24 KB
/
server.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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
// Copyright 2019 Google 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.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package bookstore
import (
"context"
"errors"
"fmt"
"github.com/golang/protobuf/ptypes/empty"
"log"
"net"
"net/http"
"sync"
"google.golang.org/grpc"
)
const (
port = ":50051"
)
//
// The Service type implements a bookstore server.
// All objects are managed in an in-memory non-persistent store.
//
// server is used to implement Bookstoreserver.
type server struct {
// shelves are stored in a map keyed by shelf id
// books are stored in a two level map, keyed first by shelf id and then by book id
Shelves map[int64]*Shelf
Books map[int64]map[int64]*Book
LastShelfID int64 // the id of the last shelf that was added
LastBookID int64 // the id of the last book that was added
Mutex sync.Mutex // global mutex to synchronize service access
}
func (s *server) ListShelves(context.Context, *empty.Empty) (*ListShelvesResponses, error) {
s.Mutex.Lock()
defer s.Mutex.Unlock()
// copy shelf ids from Shelves map keys
shelves := make([]*Shelf, 0, len(s.Shelves))
for _, shelf := range s.Shelves {
shelves = append(shelves, shelf)
}
response := &ListShelvesResponse{}
response.Shelves = shelves
responses := &ListShelvesResponses{
Ok: response,
}
return responses, nil
}
func (s *server) CreateShelf(ctx context.Context, parameters *CreateShelfParameters) (*CreateShelfResponses, error) {
s.Mutex.Lock()
defer s.Mutex.Unlock()
// assign an id and name to a shelf and add it to the Shelves map.
shelf := parameters.Shelf
s.LastShelfID++
sid := s.LastShelfID
s.Shelves[sid] = shelf
responses := &CreateShelfResponses{
Ok: shelf,
}
return responses, nil
}
func (s *server) DeleteShelves(context.Context, *empty.Empty) (*empty.Empty, error) {
s.Mutex.Lock()
defer s.Mutex.Unlock()
// delete everything by reinitializing the Shelves and Books maps.
s.Shelves = make(map[int64]*Shelf)
s.Books = make(map[int64]map[int64]*Book)
s.LastShelfID = 0
s.LastBookID = 0
return nil, nil
}
func (s *server) GetShelf(ctx context.Context, parameters *GetShelfParameters) (*GetShelfResponses, error) {
s.Mutex.Lock()
defer s.Mutex.Unlock()
// look up a shelf from the Shelves map.
shelf, err := s.getShelf(parameters.Shelf)
responses := &GetShelfResponses{}
if err != nil {
responses.Default = &Error{Code: int32(http.StatusNotFound), Message: err.Error()}
return responses, err
}
responses.Ok = shelf
return responses, nil
}
func (s *server) DeleteShelf(ctx context.Context, parameters *DeleteShelfParameters) (*empty.Empty, error) {
s.Mutex.Lock()
defer s.Mutex.Unlock()
// delete a shelf by removing the shelf from the Shelves map and the associated books from the Books map.
delete(s.Shelves, parameters.Shelf)
delete(s.Books, parameters.Shelf)
return nil, nil
}
func (s *server) ListBooks(ctx context.Context, parameters *ListBooksParameters) (responses *ListBooksResponses, err error) {
s.Mutex.Lock()
defer s.Mutex.Unlock()
// list the books in a shelf
_, err = s.getShelf(parameters.Shelf)
responses = &ListBooksResponses{}
if err != nil {
responses.Default = &Error{Code: int32(http.StatusNotFound), Message: err.Error()}
return responses, err
}
shelfBooks := s.Books[parameters.Shelf]
books := make([]*Book, 0, len(shelfBooks))
for _, book := range shelfBooks {
books = append(books, book)
}
response := &ListBooksResponse{}
response.Books = books
responses.Ok = response
return responses, nil
}
func (s *server) CreateBook(ctx context.Context, parameters *CreateBookParameters) (*CreateBookResponses, error) {
s.Mutex.Lock()
defer s.Mutex.Unlock()
// return "not found" if the shelf doesn't exist
_, err := s.getShelf(parameters.Shelf)
responses := &CreateBookResponses{}
if err != nil {
responses.Default = &Error{Code: int32(http.StatusNotFound), Message: err.Error()}
return responses, err
}
// assign an id and name to a book and add it to the Books map.
s.LastBookID++
bid := s.LastBookID
book := parameters.Book
if s.Books[parameters.Shelf] == nil {
s.Books[parameters.Shelf] = make(map[int64]*Book)
}
s.Books[parameters.Shelf][bid] = book
responses.Ok = book
return responses, nil
}
func (s *server) GetBook(ctx context.Context, parameters *GetBookParameters) (*GetBookResponses, error) {
s.Mutex.Lock()
defer s.Mutex.Unlock()
// get a book from the Books map
book, err := s.getBook(parameters.Shelf, parameters.Book)
responses := &GetBookResponses{}
if err != nil {
responses.Default = &Error{Code: int32(http.StatusNotFound), Message: err.Error()}
return responses, err
}
responses.Ok = book
return responses, nil
}
func (s *server) DeleteBook(ctx context.Context, parameters *DeleteBookParameters) (*empty.Empty, error) {
s.Mutex.Lock()
defer s.Mutex.Unlock()
// delete a book by removing the book from the Books map.
delete(s.Books[parameters.Shelf], parameters.Book)
return nil, nil
}
// internal helpers
func (s *server) getShelf(sid int64) (shelf *Shelf, err error) {
shelf, ok := s.Shelves[sid]
if !ok {
return nil, errors.New(fmt.Sprintf("Couldn't find shelf %d", sid))
} else {
return shelf, nil
}
}
func (s *server) getBook(sid int64, bid int64) (book *Book, err error) {
_, err = s.getShelf(sid)
if err != nil {
return nil, err
}
book, ok := s.Books[sid][bid]
if !ok {
return nil, errors.New(fmt.Sprintf("Couldn't find book %d on shelf %d", bid, sid))
} else {
return book, nil
}
}
func RunServer() {
lis, err := net.Listen("tcp", port)
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
s := grpc.NewServer()
fmt.Printf("\nServer listening on port %v \n", port)
RegisterBookstoreServer(s, &server{
Shelves: map[int64]*Shelf{},
Books: map[int64]map[int64]*Book{},
})
if err := s.Serve(lis); err != nil {
log.Fatalf("failed to serve: %v", err)
}
}