-
Notifications
You must be signed in to change notification settings - Fork 4
/
container.go
342 lines (280 loc) · 8.69 KB
/
container.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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
/*
* SPDX-FileCopyrightText: Copyright (c) 2003 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
* SPDX-License-Identifier: Apache-2.0
*
* 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 gontainer
import (
"context"
"fmt"
"runtime/debug"
"sync"
)
// Events declaration.
const (
// ContainerStarting declares container starting event.
ContainerStarting = "ContainerStarting"
// ContainerStarted declares container started event.
ContainerStarted = "ContainerStarted"
// ContainerClosing declares container closing event.
ContainerClosing = "ContainerClosing"
// ContainerClosed declares container closed event.
ContainerClosed = "ContainerClosed"
// UnhandledPanic declares unhandled panic in container.
UnhandledPanic = "UnhandledPanic"
)
// New returns new container instance with a set of configured services.
// The `factories` specifies factories for services with dependency resolution.
func New(factories ...*Factory) (result Container, err error) {
// Don't accept the context in args, since it mustn't be cancelled outside.
// Cancel of the root context will trigger cancel of all children contexts, but
// it is unwanted behavior: services should be cancelled in strict reverse order.
// Prepare cancellable app context.
ctx, cancel := context.WithCancel(context.Background())
// Cancel context only when returning an error.
// Otherwise, in will be cancelled by container.
defer func() {
if err != nil {
cancel()
}
}()
// Prepare events broker instance.
events := &events{
mutex: sync.RWMutex{},
events: make(map[string][]handler),
}
// Prepare services registry instance.
registry := ®istry{events: events}
// Prepare service resolver instance.
resolver := &resolver{ctx: ctx, registry: registry}
// Prepare function invoker instance.
invoker := &invoker{resolver: resolver}
// Prepare service container instance.
container := &container{
ctx: ctx,
cancel: cancel,
events: events,
resolver: resolver,
invoker: invoker,
registry: registry,
}
// Trigger panic events in service container.
defer func() {
if recovered := recover(); recovered != nil {
event := NewEvent(UnhandledPanic, recovered, string(debug.Stack()))
_ = container.events.Trigger(event)
panic(recovered)
}
}()
// Register events broker instance in the registry.
if err := registry.registerFactory(ctx, NewService[Events](events)); err != nil {
return nil, fmt.Errorf("failed to register events manager: %w", err)
}
// Register service resolver instance in the registry.
if err := registry.registerFactory(ctx, NewService[Resolver](resolver)); err != nil {
return nil, fmt.Errorf("failed to register service resolver: %w", err)
}
// Register function invoker instance in the registry.
if err := registry.registerFactory(ctx, NewService[Invoker](invoker)); err != nil {
return nil, fmt.Errorf("failed to register function invoker: %w", err)
}
// Register provided factories in the registry.
for _, factory := range factories {
if err := registry.registerFactory(ctx, factory); err != nil {
return nil, fmt.Errorf("failed to register factory: %w", err)
}
}
// Validate all factories in the registry.
if err := registry.validateFactories(); err != nil {
return nil, fmt.Errorf("failed to validate factories: %w", err)
}
// Return service container instance.
return container, nil
}
// Container defines service container interface.
type Container interface {
// Start initializes every service in the container.
Start() error
// Close closes service container with all services.
// Blocks invocation until the container is closed.
Close() error
// Done is closing after closing of all services.
Done() <-chan struct{}
// Factories returns all defined factories.
Factories() []*Factory
// Services returns all spawned services.
Services() []any
// Events returns events broker instance.
Events() Events
// Resolver returns service resolver instance.
Resolver() Resolver
// Invoker returns function invoker instance.
Invoker() Invoker
}
// container implements service container.
type container struct {
ctx context.Context
cancel context.CancelFunc
closer sync.Once
mutex sync.RWMutex
// Events broker.
events Events
// Service resolver.
resolver Resolver
// Function invoker.
invoker Invoker
// Services registry.
registry *registry
}
// Start initializes every service in the container.
func (c *container) Start() (resultErr error) {
// Trigger panic events in service container.
defer func() {
if recovered := recover(); recovered != nil {
_ = c.events.Trigger(NewEvent(UnhandledPanic, recovered, string(debug.Stack())))
_ = c.Close()
panic(recovered)
}
}()
// Close service container immediately on error.
defer func() {
if resultErr != nil {
_ = c.Close()
}
}()
// Acquire write lock.
c.mutex.Lock()
defer c.mutex.Unlock()
// Trigger container starting event.
if err := c.events.Trigger(NewEvent(ContainerStarting)); err != nil {
return fmt.Errorf("failed to trigger container starting event: %w", err)
}
// Start all factories in the container.
startErr := c.registry.produceServices()
// Trigger container started event.
if err := c.events.Trigger(NewEvent(ContainerStarted, startErr)); err != nil {
return fmt.Errorf("failed to trigger container started event: %w", err)
}
// Handle container start error.
if startErr != nil {
return fmt.Errorf("failed to start services in container: %w", startErr)
}
return nil
}
// Close closes service container with all services.
// Blocks invocation until the container is closed.
func (c *container) Close() (err error) {
// Trigger panic events in service container.
defer func() {
if recovered := recover(); recovered != nil {
_ = c.events.Trigger(NewEvent(UnhandledPanic, recovered, string(debug.Stack())))
panic(recovered)
}
}()
// Acquire write lock.
c.mutex.Lock()
defer c.mutex.Unlock()
// Init container close once.
c.closer.Do(func() {
// Close container context independently of errors.
// It will unblock all concurrent close calls.
defer c.cancel()
// Trigger container closing event.
if triggerErr := c.events.Trigger(NewEvent(ContainerClosing)); triggerErr != nil {
err = fmt.Errorf("failed to trigger container closing event: %w", triggerErr)
return
}
// Close all spawned services in the registry.
closeErr := c.registry.closeServices()
if closeErr != nil {
err = fmt.Errorf("failed to close factories: %w", closeErr)
return
}
// Trigger container closed event.
if triggerErr := c.events.Trigger(NewEvent(ContainerClosed, closeErr)); triggerErr != nil {
err = fmt.Errorf("failed to trigger container closed event: %w", triggerErr)
return
}
})
// Await container close, e.g. from concurrent close call.
<-c.ctx.Done()
return nil
}
// Done is closing after closing of all services.
func (c *container) Done() <-chan struct{} {
return c.ctx.Done()
}
// Factories returns all defined factories.
func (c *container) Factories() []*Factory {
// Acquire read lock.
c.mutex.RLock()
defer c.mutex.RUnlock()
return c.registry.factories
}
// Services returns all spawned services.
func (c *container) Services() []any {
// Acquire read lock.
c.mutex.RLock()
defer c.mutex.RUnlock()
select {
case <-c.ctx.Done():
return nil
default:
services := make([]any, 0, len(c.registry.factories))
for _, factory := range c.registry.factories {
if factory.factorySpawned {
for _, serviceValue := range factory.factoryOutValues {
services = append(services, serviceValue.Interface())
}
}
}
return services
}
}
// Events returns events broker instance.
func (c *container) Events() Events {
// Acquire read lock.
c.mutex.RLock()
defer c.mutex.RUnlock()
select {
case <-c.ctx.Done():
return nil
default:
return c.events
}
}
// Resolver returns service resolver instance.
func (c *container) Resolver() Resolver {
// Acquire read lock.
c.mutex.RLock()
defer c.mutex.RUnlock()
select {
case <-c.ctx.Done():
return nil
default:
return c.resolver
}
}
// Invoker returns function invoker instance.
func (c *container) Invoker() Invoker {
// Acquire read lock.
c.mutex.RLock()
defer c.mutex.RUnlock()
select {
case <-c.ctx.Done():
return nil
default:
return c.invoker
}
}