2 // ========================LICENSE_START=================================
5 // Copyright (C) 2022: Nordix Foundation
7 // Licensed under the Apache License, Version 2.0 (the "License");
8 // you may not use this file except in compliance with the License.
9 // You may obtain a copy of the License at
11 // http://www.apache.org/licenses/LICENSE-2.0
13 // Unless required by applicable law or agreed to in writing, software
14 // distributed under the License is distributed on an "AS IS" BASIS,
15 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 // See the License for the specific language governing permissions and
17 // limitations under the License.
18 // ========================LICENSE_END===================================
31 "github.com/labstack/echo/v4"
32 log "github.com/sirupsen/logrus"
33 "k8s.io/utils/strings/slices"
34 "oransc.org/nonrtric/capifcore/internal/common29122"
35 "oransc.org/nonrtric/capifcore/internal/eventsapi"
36 "oransc.org/nonrtric/capifcore/internal/publishserviceapi"
37 "oransc.org/nonrtric/capifcore/internal/restclient"
40 type EventService struct {
41 notificationChannel chan eventsapi.EventNotification
42 client restclient.HTTPClient
43 subscriptions map[string]eventsapi.EventSubscription
48 func NewEventService(c restclient.HTTPClient) *EventService {
50 notificationChannel: make(chan eventsapi.EventNotification),
52 subscriptions: make(map[string]eventsapi.EventSubscription),
58 func (es *EventService) start() {
59 go es.handleIncomingEvents()
62 func (es *EventService) handleIncomingEvents() {
63 for event := range es.notificationChannel {
67 func (es *EventService) GetNotificationChannel() chan<- eventsapi.EventNotification {
68 return es.notificationChannel
71 func (es *EventService) PostSubscriberIdSubscriptions(ctx echo.Context, subscriberId string) error {
72 newSubscription, err := getEventSubscriptionFromRequest(ctx)
73 errMsg := "Unable to register subscription due to %s."
75 return sendCoreError(ctx, http.StatusBadRequest, fmt.Sprintf(errMsg, err))
77 uri := ctx.Request().Host + ctx.Request().URL.String()
78 subId := es.getSubscriptionId(subscriberId)
79 es.addSubscription(subId, newSubscription)
80 ctx.Response().Header().Set(echo.HeaderLocation, ctx.Scheme()+`://`+path.Join(uri, subId))
81 err = ctx.JSON(http.StatusCreated, newSubscription)
83 // Something really bad happened, tell Echo that our handler failed
90 func (es *EventService) DeleteSubscriberIdSubscriptionsSubscriptionId(ctx echo.Context, subscriberId string, subscriptionId string) error {
92 defer es.lock.Unlock()
94 log.Debug(es.subscriptions)
95 if _, ok := es.subscriptions[subscriptionId]; ok {
96 log.Debug("Deleting subscription", subscriptionId)
97 delete(es.subscriptions, subscriptionId)
100 return ctx.NoContent(http.StatusNoContent)
103 func getEventSubscriptionFromRequest(ctx echo.Context) (eventsapi.EventSubscription, error) {
104 var subscription eventsapi.EventSubscription
105 err := ctx.Bind(&subscription)
107 return eventsapi.EventSubscription{}, fmt.Errorf("invalid format for subscription")
109 return subscription, nil
112 func (es *EventService) handleEvent(event eventsapi.EventNotification) {
113 subsIds := es.getMatchingSubs(event)
114 for _, subId := range subsIds {
115 go es.sendEvent(event, subId)
119 func (es *EventService) sendEvent(event eventsapi.EventNotification, subscriptionId string) {
120 event.SubscriptionId = subscriptionId
121 e, _ := json.Marshal(event)
122 if error := restclient.Put(string(es.subscriptions[subscriptionId].NotificationDestination), []byte(e), es.client); error != nil {
123 log.Error("Unable to send event")
127 func (es *EventService) getMatchingSubs(event eventsapi.EventNotification) []string {
129 defer es.lock.Unlock()
130 matchingTypeSubs := es.filterOnEventType(event)
131 matchingSubs := []string{}
132 for _, subId := range matchingTypeSubs {
133 subscription := es.subscriptions[subId]
134 if subscription.EventFilters == nil || event.EventDetail == nil {
135 matchingSubs = append(matchingSubs, subId)
136 } else if matchesFilters(event.EventDetail.ApiIds, *subscription.EventFilters, getApiIdsFromFilter) &&
137 matchesFilters(event.EventDetail.ApiInvokerIds, *subscription.EventFilters, getInvokerIdsFromFilter) &&
138 matchesFilters(getAefIdsFromEvent(event.EventDetail.ServiceAPIDescriptions), *subscription.EventFilters, getAefIdsFromFilter) {
139 matchingSubs = append(matchingSubs, subId)
146 func (es *EventService) filterOnEventType(event eventsapi.EventNotification) []string {
147 matchingSubs := []string{}
148 for subId, subInfo := range es.subscriptions {
149 if slices.Contains(asStrings(subInfo.Events), string(event.Events)) {
150 matchingSubs = append(matchingSubs, subId)
156 func matchesFilters(eventIds *[]string, filters []eventsapi.CAPIFEventFilter, getIds func(eventsapi.CAPIFEventFilter) *[]string) bool {
157 if len(filters) == 0 || eventIds == nil {
160 for _, id := range *eventIds {
162 filterIds := getIds(filter)
163 if filterIds == nil || len(*filterIds) == 0 {
164 return matchesFilters(eventIds, filters[1:], getIds)
166 return slices.Contains(*getIds(filter), id) && matchesFilters(eventIds, filters[1:], getIds)
171 func getApiIdsFromFilter(filter eventsapi.CAPIFEventFilter) *[]string {
175 func getInvokerIdsFromFilter(filter eventsapi.CAPIFEventFilter) *[]string {
176 return filter.ApiInvokerIds
179 func getAefIdsFromEvent(serviceAPIDescriptions *[]publishserviceapi.ServiceAPIDescription) *[]string {
181 if serviceAPIDescriptions == nil {
184 for _, serviceDescription := range *serviceAPIDescriptions {
185 if serviceDescription.AefProfiles == nil {
188 for _, profile := range *serviceDescription.AefProfiles {
189 aefIds = append(aefIds, profile.AefId)
195 func getAefIdsFromFilter(filter eventsapi.CAPIFEventFilter) *[]string {
199 func asStrings(events []eventsapi.CAPIFEvent) []string {
200 asStrings := make([]string, len(events))
201 for i, event := range events {
202 asStrings[i] = string(event)
207 func (es *EventService) getSubscriptionId(subscriberId string) string {
209 return subscriberId + strconv.FormatUint(uint64(es.idCounter), 10)
212 func (es *EventService) addSubscription(subId string, subscription eventsapi.EventSubscription) {
214 es.subscriptions[subId] = subscription
218 func (es *EventService) getSubscription(subId string) *eventsapi.EventSubscription {
220 defer es.lock.Unlock()
221 if sub, ok := es.subscriptions[subId]; ok {
228 // This function wraps sending of an error in the Error format, and
229 // handling the failure to marshal that.
230 func sendCoreError(ctx echo.Context, code int, message string) error {
231 pd := common29122.ProblemDetails{
235 err := ctx.JSON(code, pd)