Debian Codegraph @

micro/service.go

raw
1 // Copyright 2022-2023 The NATS Authors
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package micro
15
16 import (
17 "encoding/json"
18 "errors"
19 "fmt"
20 "regexp"
21 "strings"
22 "sync"
23 "time"
24
25 "github.com/nats-io/nats.go"
26 "github.com/nats-io/nuid"
27 )
28
29 type (
30
31 // Service exposes methods to operate on a service instance.
32 Service interface {
33 // AddEndpoint registers endpoint with given name on a specific subject.
34 AddEndpoint(string, Handler, ...EndpointOpt) error
35
36 // AddGroup returns a Group interface, allowing for more complex endpoint topologies.
37 // A group can be used to register endpoints with given prefix.
38 AddGroup(string, ...GroupOpt) Group
39
40 // Info returns the service info.
41 Info() Info
42
43 // Stats returns statistics for the service endpoint and all monitoring endpoints.
44 Stats() Stats
45
46 // Reset resets all statistics (for all endpoints) on a service instance.
47 Reset()
48
49 // Stop drains the endpoint subscriptions and marks the service as stopped.
50 Stop() error
51
52 // Stopped informs whether [Stop] was executed on the service.
53 Stopped() bool
54 }
55
56 // Group allows for grouping endpoints on a service.
57 //
58 // Endpoints created using AddEndpoint will be grouped under common prefix (group name)
59 // New groups can also be derived from a group using AddGroup.
60 Group interface {
61 // AddGroup creates a new group, prefixed by this group's prefix.
62 AddGroup(string, ...GroupOpt) Group
63
64 // AddEndpoint registers new endpoints on a service.
65 // The endpoint's subject will be prefixed with the group prefix.
66 AddEndpoint(string, Handler, ...EndpointOpt) error
67 }
68
69 EndpointOpt func(*endpointOpts) error
70 GroupOpt func(*groupOpts)
71
72 endpointOpts struct {
73 subject string
74 metadata map[string]string
75 queueGroup string
76 qgDisabled bool
77 msgLimit int
78 bytesLimit int
79 }
80
81 groupOpts struct {
82 queueGroup string
83 qgDisabled bool
84 }
85
86 // ErrHandler is a function used to configure a custom error handler for a service,
87 ErrHandler func(Service, *NATSError)
88
89 // DoneHandler is a function used to configure a custom done handler for a service.
90 DoneHandler func(Service)
91
92 // StatsHandler is a function used to configure a custom STATS endpoint.
93 // It should return a value which can be serialized to JSON.
94 StatsHandler func(*Endpoint) any
95
96 // ServiceIdentity contains fields helping to identity a service instance.
97 ServiceIdentity struct {
98 Name string `json:"name"`
99 ID string `json:"id"`
100 Version string `json:"version"`
101 Metadata map[string]string `json:"metadata"`
102 }
103
104 // Stats is the type returned by STATS monitoring endpoint.
105 // It contains stats of all registered endpoints.
106 Stats struct {
107 ServiceIdentity
108 Type string `json:"type"`
109 Started time.Time `json:"started"`
110 Endpoints []*EndpointStats `json:"endpoints"`
111 }
112
113 // EndpointStats contains stats for a specific endpoint.
114 EndpointStats struct {
115 Name string `json:"name"`
116 Subject string `json:"subject"`
117 QueueGroup string `json:"queue_group"`
118 NumRequests int `json:"num_requests"`
119 NumErrors int `json:"num_errors"`
120 LastError string `json:"last_error"`
121 ProcessingTime time.Duration `json:"processing_time"`
122 AverageProcessingTime time.Duration `json:"average_processing_time"`
123 Data json.RawMessage `json:"data,omitempty"`
124 }
125
126 // Ping is the response type for PING monitoring endpoint.
127 Ping struct {
128 ServiceIdentity
129 Type string `json:"type"`
130 }
131
132 // Info is the basic information about a service type.
133 Info struct {
134 ServiceIdentity
135 Type string `json:"type"`
136 Description string `json:"description"`
137 Endpoints []EndpointInfo `json:"endpoints"`
138 }
139
140 EndpointInfo struct {
141 Name string `json:"name"`
142 Subject string `json:"subject"`
143 QueueGroup string `json:"queue_group"`
144 Metadata map[string]string `json:"metadata"`
145 }
146
147 // Endpoint manages a service endpoint.
148 Endpoint struct {
149 EndpointConfig
150 Name string
151
152 service *service
153
154 stats EndpointStats
155 subscription *nats.Subscription
156 }
157
158 group struct {
159 service *service
160 prefix string
161 queueGroup string
162 queueGroupDisabled bool
163 }
164
165 // Verb represents a name of the monitoring service.
166 Verb int64
167
168 // Config is a configuration of a service.
169 Config struct {
170 // Name represents the name of the service.
171 Name string `json:"name"`
172
173 // Endpoint is an optional endpoint configuration.
174 // More complex, multi-endpoint services can be configured using
175 // Service.AddGroup and Service.AddEndpoint methods.
176 Endpoint *EndpointConfig `json:"endpoint"`
177
178 // Version is a SemVer compatible version string.
179 Version string `json:"version"`
180
181 // Description of the service.
182 Description string `json:"description"`
183
184 // Metadata annotates the service
185 Metadata map[string]string `json:"metadata,omitempty"`
186
187 // QueueGroup can be used to override the default queue group name.
188 QueueGroup string `json:"queue_group"`
189
190 // QueueGroupDisabled disables the queue group for the service.
191 QueueGroupDisabled bool `json:"queue_group_disabled"`
192
193 // StatsHandler is a user-defined custom function.
194 // used to calculate additional service stats.
195 StatsHandler StatsHandler
196
197 // DoneHandler is invoked when all service subscription are stopped.
198 DoneHandler DoneHandler
199
200 // ErrorHandler is invoked on any nats-related service error.
201 ErrorHandler ErrHandler
202 }
203
204 EndpointConfig struct {
205 // Subject on which the endpoint is registered.
206 Subject string
207
208 // Handler used by the endpoint.
209 Handler Handler
210
211 // Metadata annotates the service
212 Metadata map[string]string `json:"metadata,omitempty"`
213
214 // QueueGroup can be used to override the default queue group name.
215 QueueGroup string `json:"queue_group"`
216
217 // QueueGroupDisabled disables the queue group for the endpoint.
218 QueueGroupDisabled bool `json:"queue_group_disabled"`
219 }
220
221 // NATSError represents an error returned by a NATS Subscription.
222 // It contains a subject on which the subscription failed, so that
223 // it can be linked with a specific service endpoint.
224 NATSError struct {
225 Subject string
226 Description string
227 err error
228 }
229
230 // service represents a configured NATS service.
231 // It should be created using [Add] in order to configure the appropriate NATS subscriptions
232 // for request handler and monitoring.
233 service struct {
234 // Config contains a configuration of the service
235 Config
236
237 m sync.Mutex
238 id string
239 endpoints []*Endpoint
240 verbSubs map[string]*nats.Subscription
241 started time.Time
242 nc *nats.Conn
243 natsHandlers handlers
244 stopped bool
245
246 asyncDispatcher asyncCallbacksHandler
247 }
248
249 handlers struct {
250 closed nats.ConnHandler
251 asyncErr nats.ErrHandler
252 }
253
254 asyncCallbacksHandler struct {
255 cbQueue chan func()
256 closed bool
257 }
258 )
259
260 const (
261 // Queue Group name used across all services
262 DefaultQueueGroup = "q"
263
264 // APIPrefix is the root of all control subjects
265 APIPrefix = "$SRV"
266 )
267
268 // Service Error headers
269 const (
270 ErrorHeader = "Nats-Service-Error"
271 ErrorCodeHeader = "Nats-Service-Error-Code"
272 )
273
274 // Verbs being used to set up a specific control subject.
275 const (
276 PingVerb Verb = iota
277 StatsVerb
278 InfoVerb
279 )
280
281 const (
282 InfoResponseType = "io.nats.micro.v1.info_response"
283 PingResponseType = "io.nats.micro.v1.ping_response"
284 StatsResponseType = "io.nats.micro.v1.stats_response"
285 )
286
287 var (
288 // this regular expression is suggested regexp for semver validation: https://semver.org/
289 semVerRegexp = regexp.MustCompile(`^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$`)
290 nameRegexp = regexp.MustCompile(`^[A-Za-z0-9\-_]+$`)
291 subjectRegexp = regexp.MustCompile(`^[^ >]*[>]?$`)
292 )
293
294 // Common errors returned by the Service framework.
295 var (
296 // ErrConfigValidation is returned when service configuration is invalid
297 ErrConfigValidation = errors.New("validation")
298
299 // ErrVerbNotSupported is returned when invalid [Verb] is used (PING, INFO, STATS)
300 ErrVerbNotSupported = errors.New("unsupported verb")
301
302 // ErrServiceNameRequired is returned when attempting to generate control subject with ID but empty name
303 ErrServiceNameRequired = errors.New("service name is required to generate ID control subject")
304 )
305
306 func (s Verb) String() string {
307 switch s {
308 case PingVerb:
309 return "PING"
310 case StatsVerb:
311 return "STATS"
312 case InfoVerb:
313 return "INFO"
314 default:
315 return ""
316 }
317 }
318
319 // AddService adds a microservice.
320 // It will enable internal common services (PING, STATS and INFO).
321 // Request handlers have to be registered separately using Service.AddEndpoint.
322 // A service name, version and Endpoint configuration are required to add a service.
323 // AddService returns a [Service] interface, allowing service management.
324 // Each service is assigned a unique ID.
325 func AddService(nc *nats.Conn, config Config) (Service, error) {
326 if err := config.valid(); err != nil {
327 return nil, err
328 }
329
330 if config.Metadata == nil {
331 config.Metadata = map[string]string{}
332 }
333
334 id := nuid.Next()
335 svc := &service{
336 Config: config,
337 nc: nc,
338 id: id,
339 asyncDispatcher: asyncCallbacksHandler{
340 cbQueue: make(chan func(), 100),
341 },
342 verbSubs: make(map[string]*nats.Subscription),
343 endpoints: make([]*Endpoint, 0),
344 }
345
346 // Add connection event (closed, error) wrapper handlers. If the service has
347 // custom callbacks, the events are queued and invoked by the same
348 // goroutine, starting now.
349 go svc.asyncDispatcher.run()
350 svc.wrapConnectionEventCallbacks()
351
352 if config.Endpoint != nil {
353 opts := []EndpointOpt{WithEndpointSubject(config.Endpoint.Subject)}
354 if config.Endpoint.Metadata != nil {
355 opts = append(opts, WithEndpointMetadata(config.Endpoint.Metadata))
356 }
357 if config.Endpoint.QueueGroup != "" {
358 opts = append(opts, WithEndpointQueueGroup(config.Endpoint.QueueGroup))
359 } else if config.QueueGroup != "" {
360 opts = append(opts, WithEndpointQueueGroup(config.QueueGroup))
361 }
362 if err := svc.AddEndpoint("default", config.Endpoint.Handler, opts...); err != nil {
363 svc.asyncDispatcher.close()
364 return nil, err
365 }
366 }
367
368 // Setup internal subscriptions.
369 pingResponse := Ping{
370 ServiceIdentity: svc.serviceIdentity(),
371 Type: PingResponseType,
372 }
373
374 handleVerb := func(verb Verb, valuef func() any) func(req Request) {
375 return func(req Request) {
376 response, _ := json.Marshal(valuef())
377 if err := req.Respond(response); err != nil {
378 if err := req.Error("500", fmt.Sprintf("Error handling %s request: %s", verb, err), nil); err != nil && config.ErrorHandler != nil {
379 svc.asyncDispatcher.push(func() {
380 config.ErrorHandler(svc, &NATSError{Subject: req.Subject(), Description: err.Error(), err: err})
381 })
382 }
383 }
384 }
385 }
386
387 for verb, source := range map[Verb]func() any{
388 InfoVerb: func() any { return svc.Info() },
389 PingVerb: func() any { return pingResponse },
390 StatsVerb: func() any { return svc.Stats() },
391 } {
392 handler := handleVerb(verb, source)
393 if err := svc.addVerbHandlers(nc, verb, handler); err != nil {
394 svc.asyncDispatcher.close()
395 return nil, err
396 }
397 }
398
399 svc.started = time.Now().UTC()
400 return svc, nil
401 }
402
403 func (s *service) AddEndpoint(name string, handler Handler, opts ...EndpointOpt) error {
404 var options endpointOpts
405 for _, opt := range opts {
406 if err := opt(&options); err != nil {
407 return err
408 }
409 }
410 subject := name
411 if options.subject != "" {
412 subject = options.subject
413 }
414 queueGroup, noQueue := resolveQueueGroup(options.queueGroup, s.Config.QueueGroup, options.qgDisabled, s.Config.QueueGroupDisabled)
415 return addEndpoint(s, name, subject, handler, options.metadata, queueGroup, noQueue, options.msgLimit, options.bytesLimit)
416 }
417
418 func addEndpoint(s *service, name, subject string, handler Handler, metadata map[string]string, queueGroup string, noQueue bool, msgLimit, bytesLimit int) error {
419 if !nameRegexp.MatchString(name) {
420 return fmt.Errorf("%w: invalid endpoint name", ErrConfigValidation)
421 }
422 if !subjectRegexp.MatchString(subject) {
423 return fmt.Errorf("%w: invalid endpoint subject", ErrConfigValidation)
424 }
425 if !subjectRegexp.MatchString(queueGroup) {
426 return fmt.Errorf("%w: invalid endpoint queue group", ErrConfigValidation)
427 }
428 endpoint := &Endpoint{
429 service: s,
430 EndpointConfig: EndpointConfig{
431 Subject: subject,
432 Handler: handler,
433 Metadata: metadata,
434 QueueGroup: queueGroup,
435 QueueGroupDisabled: noQueue,
436 },
437 Name: name,
438 }
439
440 var sub *nats.Subscription
441 var err error
442 var options = endpointOpts{
443 msgLimit: msgLimit,
444 bytesLimit: bytesLimit,
445 }
446
447 if !noQueue {
448 sub, err = s.nc.QueueSubscribe(
449 subject,
450 queueGroup,
451 func(m *nats.Msg) {
452 s.reqHandler(endpoint, &request{msg: m})
453 },
454 )
455 } else {
456 sub, err = s.nc.Subscribe(
457 subject,
458 func(m *nats.Msg) {
459 s.reqHandler(endpoint, &request{msg: m})
460 },
461 )
462 }
463 if err != nil {
464 return err
465 }
466
467 // Apply pending limits if configured
468 if options.msgLimit != 0 || options.bytesLimit != 0 {
469 if err := sub.SetPendingLimits(options.msgLimit, options.bytesLimit); err != nil {
470 return err
471 }
472 }
473
474 s.m.Lock()
475 endpoint.subscription = sub
476 s.endpoints = append(s.endpoints, endpoint)
477 endpoint.stats = EndpointStats{
478 Name: name,
479 Subject: subject,
480 QueueGroup: queueGroup,
481 }
482 s.m.Unlock()
483 return nil
484 }
485
486 func (s *service) AddGroup(name string, opts ...GroupOpt) Group {
487 var o groupOpts
488 for _, opt := range opts {
489 opt(&o)
490 }
491 queueGroup, noQueue := resolveQueueGroup(o.queueGroup, s.Config.QueueGroup, o.qgDisabled, s.Config.QueueGroupDisabled)
492 return &group{
493 service: s,
494 prefix: name,
495 queueGroup: queueGroup,
496 queueGroupDisabled: noQueue,
497 }
498 }
499
500 // dispatch is responsible for calling any async callbacks
501 func (ac *asyncCallbacksHandler) run() {
502 for {
503 f, ok := <-ac.cbQueue
504 if !ok || f == nil {
505 return
506 }
507 f()
508 }
509 }
510
511 // dispatch is responsible for calling any async callbacks
512 func (ac *asyncCallbacksHandler) push(f func()) {
513 ac.cbQueue <- f
514 }
515
516 func (ac *asyncCallbacksHandler) close() {
517 if ac.closed {
518 return
519 }
520 close(ac.cbQueue)
521 ac.closed = true
522 }
523
524 func (c *Config) valid() error {
525 if !nameRegexp.MatchString(c.Name) {
526 return fmt.Errorf("%w: service name: name should not be empty and should consist of alphanumerical characters, dashes and underscores", ErrConfigValidation)
527 }
528 if !semVerRegexp.MatchString(c.Version) {
529 return fmt.Errorf("%w: version: version should not be empty should match the SemVer format", ErrConfigValidation)
530 }
531 if c.QueueGroup != "" && !subjectRegexp.MatchString(c.QueueGroup) {
532 return fmt.Errorf("%w: queue group: invalid queue group name", ErrConfigValidation)
533 }
534
535 return nil
536 }
537
538 func (s *service) wrapConnectionEventCallbacks() {
539 s.m.Lock()
540 defer s.m.Unlock()
541 s.natsHandlers.closed = s.nc.ClosedHandler()
542 if s.natsHandlers.closed != nil {
543 s.nc.SetClosedHandler(func(c *nats.Conn) {
544 s.Stop()
545 s.natsHandlers.closed(c)
546 })
547 } else {
548 s.nc.SetClosedHandler(func(c *nats.Conn) {
549 s.Stop()
550 })
551 }
552
553 s.natsHandlers.asyncErr = s.nc.ErrorHandler()
554 if s.natsHandlers.asyncErr != nil {
555 s.nc.SetErrorHandler(func(c *nats.Conn, sub *nats.Subscription, err error) {
556 if sub == nil {
557 s.natsHandlers.asyncErr(c, sub, err)
558 return
559 }
560 endpoint, match := s.matchSubscriptionSubject(sub.Subject)
561 if !match {
562 s.natsHandlers.asyncErr(c, sub, err)
563 return
564 }
565 if s.Config.ErrorHandler != nil {
566 s.Config.ErrorHandler(s, &NATSError{
567 Subject: sub.Subject,
568 Description: err.Error(),
569 err: err,
570 })
571 }
572 s.m.Lock()
573 if endpoint != nil {
574 endpoint.stats.NumErrors++
575 endpoint.stats.LastError = err.Error()
576 }
577 s.m.Unlock()
578 if stopErr := s.Stop(); stopErr != nil {
579 s.natsHandlers.asyncErr(c, sub, errors.Join(err, fmt.Errorf("stopping service: %w", stopErr)))
580 } else {
581 s.natsHandlers.asyncErr(c, sub, err)
582 }
583 })
584 } else {
585 s.nc.SetErrorHandler(func(c *nats.Conn, sub *nats.Subscription, err error) {
586 if sub == nil {
587 return
588 }
589 endpoint, match := s.matchSubscriptionSubject(sub.Subject)
590 if !match {
591 return
592 }
593 if s.Config.ErrorHandler != nil {
594 s.Config.ErrorHandler(s, &NATSError{
595 Subject: sub.Subject,
596 Description: err.Error(),
597 err: err,
598 })
599 }
600 s.m.Lock()
601 if endpoint != nil {
602 endpoint.stats.NumErrors++
603 endpoint.stats.LastError = err.Error()
604 }
605 s.m.Unlock()
606 s.Stop()
607 })
608 }
609 }
610
611 func unwrapConnectionEventCallbacks(nc *nats.Conn, handlers handlers) {
612 if nc.IsClosed() {
613 return
614 }
615 nc.SetClosedHandler(handlers.closed)
616 nc.SetErrorHandler(handlers.asyncErr)
617 }
618
619 func (s *service) matchSubscriptionSubject(subj string) (*Endpoint, bool) {
620 s.m.Lock()
621 defer s.m.Unlock()
622 for _, verbSub := range s.verbSubs {
623 if verbSub.Subject == subj {
624 return nil, true
625 }
626 }
627 for _, e := range s.endpoints {
628 if matchEndpointSubject(e.Subject, subj) {
629 return e, true
630 }
631 }
632 return nil, false
633 }
634
635 func matchEndpointSubject(endpointSubject, literalSubject string) bool {
636 subjectTokens := strings.Split(literalSubject, ".")
637 endpointTokens := strings.Split(endpointSubject, ".")
638 if len(endpointTokens) > len(subjectTokens) {
639 return false
640 }
641 for i, et := range endpointTokens {
642 if i == len(endpointTokens)-1 && et == ">" {
643 return true
644 }
645 if et != subjectTokens[i] && et != "*" {
646 return false
647 }
648 }
649 // Without a trailing ">", every subject token must be consumed; otherwise a
650 // shorter endpoint would over-match a longer subject (e.g. "foo" vs
651 // "foo.bar").
652 return len(endpointTokens) == len(subjectTokens)
653 }
654
655 // addVerbHandlers generates control handlers for a specific verb.
656 // Each request generates 3 subscriptions, one for the general verb
657 // affecting all services written with the framework, one that handles
658 // all services of a particular kind, and finally a specific service instance.
659 func (svc *service) addVerbHandlers(nc *nats.Conn, verb Verb, handler HandlerFunc) error {
660 name := fmt.Sprintf("%s-all", verb.String())
661 if err := svc.addInternalHandler(nc, verb, "", "", name, handler); err != nil {
662 return err
663 }
664 name = fmt.Sprintf("%s-kind", verb.String())
665 if err := svc.addInternalHandler(nc, verb, svc.Config.Name, "", name, handler); err != nil {
666 return err
667 }
668 return svc.addInternalHandler(nc, verb, svc.Config.Name, svc.id, verb.String(), handler)
669 }
670
671 // addInternalHandler registers a control subject handler.
672 func (s *service) addInternalHandler(nc *nats.Conn, verb Verb, kind, id, name string, handler HandlerFunc) error {
673 subj, err := ControlSubject(verb, kind, id)
674 if err != nil {
675 if stopErr := s.Stop(); stopErr != nil {
676 return errors.Join(err, fmt.Errorf("stopping service: %w", stopErr))
677 }
678 return err
679 }
680
681 s.verbSubs[name], err = nc.Subscribe(subj, func(msg *nats.Msg) {
682 handler(&request{msg: msg})
683 })
684 if err != nil {
685 if stopErr := s.Stop(); stopErr != nil {
686 return errors.Join(err, fmt.Errorf("stopping service: %w", stopErr))
687 }
688 return err
689 }
690 return nil
691 }
692
693 // reqHandler invokes the service request handler and modifies service stats
694 func (s *service) reqHandler(endpoint *Endpoint, req *request) {
695 start := time.Now()
696 endpoint.Handler.Handle(req)
697 s.m.Lock()
698 endpoint.stats.NumRequests++
699 endpoint.stats.ProcessingTime += time.Since(start)
700 avgProcessingTime := endpoint.stats.ProcessingTime.Nanoseconds() / int64(endpoint.stats.NumRequests)
701 endpoint.stats.AverageProcessingTime = time.Duration(avgProcessingTime)
702
703 if req.respondError != nil {
704 endpoint.stats.NumErrors++
705 endpoint.stats.LastError = req.respondError.Error()
706 }
707 s.m.Unlock()
708 }
709
710 // Stop drains the endpoint subscriptions and marks the service as stopped.
711 func (s *service) Stop() error {
712 s.m.Lock()
713 defer s.m.Unlock()
714 if s.stopped {
715 return nil
716 }
717 // make a copy of s.endpoints to range over in order to stop
718 // since *Endpoint.stop manipulates s.endpoints!
719 endpointsToStop := append(make([]*Endpoint, 0, len(s.endpoints)), s.endpoints...)
720 for _, e := range endpointsToStop {
721 if err := e.stop(); err != nil {
722 return err
723 }
724 }
725 var keys []string
726 for key, sub := range s.verbSubs {
727 keys = append(keys, key)
728 if err := sub.Drain(); err != nil {
729 // connection is closed so draining is not possible
730 if errors.Is(err, nats.ErrConnectionClosed) {
731 break
732 }
733 return fmt.Errorf("draining subscription for subject %q: %w", sub.Subject, err)
734 }
735 }
736 for _, key := range keys {
737 delete(s.verbSubs, key)
738 }
739 unwrapConnectionEventCallbacks(s.nc, s.natsHandlers)
740 s.stopped = true
741 if s.DoneHandler != nil {
742 s.asyncDispatcher.push(func() { s.DoneHandler(s) })
743 }
744 s.asyncDispatcher.close()
745 return nil
746 }
747
748 func (s *service) serviceIdentity() ServiceIdentity {
749 return ServiceIdentity{
750 Name: s.Config.Name,
751 ID: s.id,
752 Version: s.Config.Version,
753 Metadata: s.Config.Metadata,
754 }
755 }
756
757 // Info returns information about the service
758 func (s *service) Info() Info {
759 s.m.Lock()
760 defer s.m.Unlock()
761
762 endpoints := make([]EndpointInfo, 0, len(s.endpoints))
763 for _, e := range s.endpoints {
764 endpoints = append(endpoints, EndpointInfo{
765 Name: e.Name,
766 Subject: e.Subject,
767 QueueGroup: e.QueueGroup,
768 Metadata: e.Metadata,
769 })
770 }
771
772 return Info{
773 ServiceIdentity: s.serviceIdentity(),
774 Type: InfoResponseType,
775 Description: s.Config.Description,
776 Endpoints: endpoints,
777 }
778 }
779
780 // Stats returns statistics for the service endpoint and all monitoring endpoints.
781 func (s *service) Stats() Stats {
782 s.m.Lock()
783 defer s.m.Unlock()
784
785 stats := Stats{
786 ServiceIdentity: s.serviceIdentity(),
787 Endpoints: make([]*EndpointStats, 0),
788 Type: StatsResponseType,
789 Started: s.started,
790 }
791 for _, endpoint := range s.endpoints {
792 endpointStats := &EndpointStats{
793 Name: endpoint.stats.Name,
794 Subject: endpoint.stats.Subject,
795 QueueGroup: endpoint.stats.QueueGroup,
796 NumRequests: endpoint.stats.NumRequests,
797 NumErrors: endpoint.stats.NumErrors,
798 LastError: endpoint.stats.LastError,
799 ProcessingTime: endpoint.stats.ProcessingTime,
800 AverageProcessingTime: endpoint.stats.AverageProcessingTime,
801 }
802 if s.StatsHandler != nil {
803 data, _ := json.Marshal(s.StatsHandler(endpoint))
804 endpointStats.Data = data
805 }
806 stats.Endpoints = append(stats.Endpoints, endpointStats)
807 }
808 return stats
809 }
810
811 // Reset resets all statistics on a service instance.
812 func (s *service) Reset() {
813 s.m.Lock()
814 for _, endpoint := range s.endpoints {
815 endpoint.reset()
816 }
817 s.started = time.Now().UTC()
818 s.m.Unlock()
819 }
820
821 // Stopped informs whether [Stop] was executed on the service.
822 func (s *service) Stopped() bool {
823 s.m.Lock()
824 defer s.m.Unlock()
825 return s.stopped
826 }
827
828 func (e *NATSError) Error() string {
829 return fmt.Sprintf("%q: %s", e.Subject, e.Description)
830 }
831
832 // Unwrap returns the underlying error if any.
833 func (e *NATSError) Unwrap() error {
834 return e.err
835 }
836
837 // Is reports whether the target error is equal to this error.
838 func (e *NATSError) Is(target error) bool {
839 if e == nil {
840 return false
841 }
842 if t, ok := target.(*NATSError); ok {
843 return e.Subject == t.Subject && e.Description == t.Description
844 }
845 return e.err != nil && errors.Is(e.err, target)
846 }
847
848 func (g *group) AddEndpoint(name string, handler Handler, opts ...EndpointOpt) error {
849 var options endpointOpts
850 for _, opt := range opts {
851 if err := opt(&options); err != nil {
852 return err
853 }
854 }
855 subject := name
856 if options.subject != "" {
857 subject = options.subject
858 }
859 endpointSubject := fmt.Sprintf("%s.%s", g.prefix, subject)
860 if g.prefix == "" {
861 endpointSubject = subject
862 }
863 queueGroup, noQueue := resolveQueueGroup(options.queueGroup, g.queueGroup, options.qgDisabled, g.queueGroupDisabled)
864
865 return addEndpoint(g.service, name, endpointSubject, handler, options.metadata, queueGroup, noQueue, options.msgLimit, options.bytesLimit)
866 }
867
868 func resolveQueueGroup(customQG, parentQG string, disabled, parentDisabled bool) (string, bool) {
869 if disabled {
870 return "", true
871 }
872 if customQG != "" {
873 return customQG, false
874 }
875 if parentDisabled {
876 return "", true
877 }
878 if parentQG != "" {
879 return parentQG, false
880 }
881 return DefaultQueueGroup, false
882 }
883
884 func (g *group) AddGroup(name string, opts ...GroupOpt) Group {
885 var o groupOpts
886 for _, opt := range opts {
887 opt(&o)
888 }
889 queueGroup, noQueue := resolveQueueGroup(o.queueGroup, g.queueGroup, o.qgDisabled, g.queueGroupDisabled)
890
891 parts := make([]string, 0, 2)
892 if g.prefix != "" {
893 parts = append(parts, g.prefix)
894 }
895 if name != "" {
896 parts = append(parts, name)
897 }
898 prefix := strings.Join(parts, ".")
899
900 return &group{
901 service: g.service,
902 prefix: prefix,
903 queueGroup: queueGroup,
904 queueGroupDisabled: noQueue,
905 }
906 }
907
908 func (e *Endpoint) stop() error {
909 // Drain the subscription. If the connection is closed, draining is not possible
910 // but we should still remove the endpoint from the service.
911 if err := e.subscription.Drain(); err != nil && !errors.Is(err, nats.ErrConnectionClosed) {
912 return fmt.Errorf("draining subscription for request handler: %w", err)
913 }
914 for i := 0; i < len(e.service.endpoints); i++ {
915 if e.service.endpoints[i].Subject == e.Subject {
916 if i != len(e.service.endpoints)-1 {
917 e.service.endpoints = append(e.service.endpoints[:i], e.service.endpoints[i+1:]...)
918 } else {
919 e.service.endpoints = e.service.endpoints[:i]
920 }
921 i++
922 }
923 }
924 return nil
925 }
926
927 func (e *Endpoint) reset() {
928 e.stats = EndpointStats{
929 Name: e.stats.Name,
930 Subject: e.stats.Subject,
931 }
932 }
933
934 // ControlSubject returns monitoring subjects used by the Service.
935 // Providing a verb is mandatory (it should be one of Ping, Info or Stats).
936 // Depending on whether kind and id are provided, ControlSubject will return one of the following:
937 // - verb only: subject used to monitor all available services
938 // - verb and kind: subject used to monitor services with the provided name
939 // - verb, name and id: subject used to monitor an instance of a service with the provided ID
940 func ControlSubject(verb Verb, name, id string) (string, error) {
941 verbStr := verb.String()
942 if verbStr == "" {
943 return "", fmt.Errorf("%w: %q", ErrVerbNotSupported, verbStr)
944 }
945 if name == "" && id != "" {
946 return "", ErrServiceNameRequired
947 }
948 if name == "" && id == "" {
949 return fmt.Sprintf("%s.%s", APIPrefix, verbStr), nil
950 }
951 if id == "" {
952 return fmt.Sprintf("%s.%s.%s", APIPrefix, verbStr, name), nil
953 }
954 return fmt.Sprintf("%s.%s.%s.%s", APIPrefix, verbStr, name, id), nil
955 }
956
957 func WithEndpointSubject(subject string) EndpointOpt {
958 return func(e *endpointOpts) error {
959 e.subject = subject
960 return nil
961 }
962 }
963
964 func WithEndpointMetadata(metadata map[string]string) EndpointOpt {
965 return func(e *endpointOpts) error {
966 e.metadata = metadata
967 return nil
968 }
969 }
970
971 // WithEndpointMetadataKey adds a key-value pair to the endpoints's metadata.
972 // Prefer using WithEndpointMetadata when you have all the key-value pairs you
973 // want to add at once or when you want to replace any existing metadata.
974 func WithEndpointMetadataKey(key, value string) EndpointOpt {
975 return func(e *endpointOpts) error {
976 if e.metadata == nil {
977 e.metadata = map[string]string{}
978 }
979 e.metadata[key] = value
980 return nil
981 }
982 }
983
984 func WithEndpointQueueGroup(queueGroup string) EndpointOpt {
985 return func(e *endpointOpts) error {
986 e.queueGroup = queueGroup
987 return nil
988 }
989 }
990
991 func WithEndpointQueueGroupDisabled() EndpointOpt {
992 return func(e *endpointOpts) error {
993 e.qgDisabled = true
994 return nil
995 }
996 }
997
998 // WithEndpointPendingLimits sets the pending limits for the endpoint's
999 // subscription. These limits how many messages and/or bytes can be buffered in
1000 // memory before the subscription is terminated with nats.ErrSlowConsumer.
1001 // Either limit can be set to -1 to indicate no limit.
1002 func WithEndpointPendingLimits(msgLimit, bytesLimit int) EndpointOpt {
1003 return func(e *endpointOpts) error {
1004 if msgLimit == 0 && bytesLimit == 0 {
1005 return fmt.Errorf("%w: at least one pending limit must be non-zero", ErrConfigValidation)
1006 }
1007 e.msgLimit = msgLimit
1008 e.bytesLimit = bytesLimit
1009 return nil
1010 }
1011 }
1012
1013 func WithGroupQueueGroup(queueGroup string) GroupOpt {
1014 return func(g *groupOpts) {
1015 g.queueGroup = queueGroup
1016 }
1017 }
1018
1019 func WithGroupQueueGroupDisabled() GroupOpt {
1020 return func(g *groupOpts) {
1021 g.qgDisabled = true
1022 }
1023 }