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 log.Debug(es.subscriptions)
93 if _, ok := es.subscriptions[subscriptionId]; ok {
94 es.deleteSubscription(subscriptionId)
97 return ctx.NoContent(http.StatusNoContent)
100 func (es *EventService) deleteSubscription(subscriptionId string) {
101 log.Debug("Deleting subscription", subscriptionId)
103 defer es.lock.Unlock()
104 delete(es.subscriptions, subscriptionId)
107 func getEventSubscriptionFromRequest(ctx echo.Context) (eventsapi.EventSubscription, error) {
108 var subscription eventsapi.EventSubscription
109 err := ctx.Bind(&subscription)
111 return eventsapi.EventSubscription{}, fmt.Errorf("invalid format for subscription")
113 return subscription, nil
116 func (es *EventService) handleEvent(event eventsapi.EventNotification) {
117 subsIds := es.getMatchingSubs(event)
118 for _, subId := range subsIds {
119 go es.sendEvent(event, subId)
123 func (es *EventService) sendEvent(event eventsapi.EventNotification, subscriptionId string) {
124 event.SubscriptionId = subscriptionId
125 e, _ := json.Marshal(event)
126 if error := restclient.Put(string(es.subscriptions[subscriptionId].NotificationDestination), []byte(e), es.client); error != nil {
127 log.Error("Unable to send event")
131 func (es *EventService) getMatchingSubs(event eventsapi.EventNotification) []string {
133 defer es.lock.Unlock()
134 matchingTypeSubs := es.filterOnEventType(event)
135 matchingSubs := []string{}
136 for _, subId := range matchingTypeSubs {
137 subscription := es.subscriptions[subId]
138 if subscription.EventFilters == nil || event.EventDetail == nil {
139 matchingSubs = append(matchingSubs, subId)
140 } else if matchesFilters(event.EventDetail.ApiIds, *subscription.EventFilters, getApiIdsFromFilter) &&
141 matchesFilters(event.EventDetail.ApiInvokerIds, *subscription.EventFilters, getInvokerIdsFromFilter) &&
142 matchesFilters(getAefIdsFromEvent(event.EventDetail.ServiceAPIDescriptions), *subscription.EventFilters, getAefIdsFromFilter) {
143 matchingSubs = append(matchingSubs, subId)
150 func (es *EventService) filterOnEventType(event eventsapi.EventNotification) []string {
151 matchingSubs := []string{}
152 for subId, subInfo := range es.subscriptions {
153 if slices.Contains(asStrings(subInfo.Events), string(event.Events)) {
154 matchingSubs = append(matchingSubs, subId)
160 func matchesFilters(eventIds *[]string, filters []eventsapi.CAPIFEventFilter, getIds func(eventsapi.CAPIFEventFilter) *[]string) bool {
161 if len(filters) == 0 || eventIds == nil {
164 for _, id := range *eventIds {
166 filterIds := getIds(filter)
167 if filterIds == nil || len(*filterIds) == 0 {
168 return matchesFilters(eventIds, filters[1:], getIds)
170 return slices.Contains(*getIds(filter), id) && matchesFilters(eventIds, filters[1:], getIds)
175 func getApiIdsFromFilter(filter eventsapi.CAPIFEventFilter) *[]string {
179 func getInvokerIdsFromFilter(filter eventsapi.CAPIFEventFilter) *[]string {
180 return filter.ApiInvokerIds
183 func getAefIdsFromEvent(serviceAPIDescriptions *[]publishserviceapi.ServiceAPIDescription) *[]string {
185 if serviceAPIDescriptions == nil {
188 for _, serviceDescription := range *serviceAPIDescriptions {
189 if serviceDescription.AefProfiles == nil {
192 for _, profile := range *serviceDescription.AefProfiles {
193 aefIds = append(aefIds, profile.AefId)
199 func getAefIdsFromFilter(filter eventsapi.CAPIFEventFilter) *[]string {
203 func asStrings(events []eventsapi.CAPIFEvent) []string {
204 asStrings := make([]string, len(events))
205 for i, event := range events {
206 asStrings[i] = string(event)
211 func (es *EventService) getSubscriptionId(subscriberId string) string {
213 return subscriberId + strconv.FormatUint(uint64(es.idCounter), 10)
216 func (es *EventService) addSubscription(subId string, subscription eventsapi.EventSubscription) {
218 defer es.lock.Unlock()
219 es.subscriptions[subId] = subscription
222 func (es *EventService) getSubscription(subId string) *eventsapi.EventSubscription {
224 defer es.lock.Unlock()
225 if sub, ok := es.subscriptions[subId]; ok {
232 // This function wraps sending of an error in the Error format, and
233 // handling the failure to marshal that.
234 func sendCoreError(ctx echo.Context, code int, message string) error {
235 pd := common29122.ProblemDetails{
239 err := ctx.JSON(code, pd)