github.com/clubpay/ronykit/kit@v0.14.4-0.20240515065620-d0dace45cbc7/service.go (about) 1 package kit 2 3 type ServiceDescriptor interface { 4 Generate() Service 5 } 6 7 // Service defines a set of RPC handlers which usually they are related to one service. 8 // Name must be unique per each Gateway. 9 type Service interface { 10 // Name of the service which must be unique per EdgeServer. 11 Name() string 12 // Contracts return a list of APIs which this service provides. 13 Contracts() []Contract 14 } 15 16 // ServiceWrapper lets you add customizations to your service. A specific case of it is serviceInterceptor 17 // which can add Pre- and Post-handlers to all the Contracts of the Service. 18 type ServiceWrapper interface { 19 Wrap(s Service) Service 20 } 21 22 type ServiceWrapperFunc func(Service) Service 23 24 func (sw ServiceWrapperFunc) Wrap(svc Service) Service { 25 return sw(svc) 26 } 27 28 // WrapService wraps a service, this is useful for adding middlewares to the service. 29 // Some middlewares like OpenTelemetry, Logger, ... could be added to the service using 30 // this function. 31 func WrapService(svc Service, wrappers ...ServiceWrapper) Service { 32 for _, w := range wrappers { 33 svc = w.Wrap(svc) 34 } 35 36 return svc 37 } 38 39 func WrapServiceContracts(svc Service, wrapper ...ContractWrapper) Service { 40 sw := &serviceWrap{ 41 name: svc.Name(), 42 } 43 44 for _, c := range svc.Contracts() { 45 for _, w := range wrapper { 46 c = w.Wrap(c) 47 } 48 sw.contracts = append(sw.contracts, c) 49 } 50 51 return sw 52 } 53 54 // serviceWrap implements Service interface and is useful when we need to wrap another 55 // service. 56 type serviceWrap struct { 57 name string 58 contracts []Contract 59 } 60 61 var _ Service = (*serviceWrap)(nil) 62 63 func (sw serviceWrap) Contracts() []Contract { 64 return sw.contracts 65 } 66 67 func (sw serviceWrap) Name() string { 68 return sw.name 69 }