|
| 1 | +/* |
| 2 | + * Copyright 2019 Expedia, Inc |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * https://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +package com.expediagroup.graphql.spring.execution |
| 18 | + |
| 19 | +import com.expediagroup.graphql.spring.GraphQLConfigurationProperties |
| 20 | +import com.expediagroup.graphql.spring.model.GraphQLRequest |
| 21 | +import com.expediagroup.graphql.spring.model.SubscriptionOperationMessage |
| 22 | +import com.expediagroup.graphql.spring.model.SubscriptionOperationMessage.ClientMessages.GQL_CONNECTION_INIT |
| 23 | +import com.expediagroup.graphql.spring.model.SubscriptionOperationMessage.ClientMessages.GQL_CONNECTION_TERMINATE |
| 24 | +import com.expediagroup.graphql.spring.model.SubscriptionOperationMessage.ClientMessages.GQL_START |
| 25 | +import com.expediagroup.graphql.spring.model.SubscriptionOperationMessage.ClientMessages.GQL_STOP |
| 26 | +import com.expediagroup.graphql.spring.model.SubscriptionOperationMessage.ServerMessages.GQL_COMPLETE |
| 27 | +import com.expediagroup.graphql.spring.model.SubscriptionOperationMessage.ServerMessages.GQL_CONNECTION_ACK |
| 28 | +import com.expediagroup.graphql.spring.model.SubscriptionOperationMessage.ServerMessages.GQL_CONNECTION_ERROR |
| 29 | +import com.expediagroup.graphql.spring.model.SubscriptionOperationMessage.ServerMessages.GQL_CONNECTION_KEEP_ALIVE |
| 30 | +import com.expediagroup.graphql.spring.model.SubscriptionOperationMessage.ServerMessages.GQL_DATA |
| 31 | +import com.expediagroup.graphql.spring.model.SubscriptionOperationMessage.ServerMessages.GQL_ERROR |
| 32 | +import com.fasterxml.jackson.databind.ObjectMapper |
| 33 | +import com.fasterxml.jackson.module.kotlin.convertValue |
| 34 | +import com.fasterxml.jackson.module.kotlin.readValue |
| 35 | +import org.reactivestreams.Subscription |
| 36 | +import org.slf4j.LoggerFactory |
| 37 | +import org.springframework.web.reactive.socket.WebSocketSession |
| 38 | +import reactor.core.publisher.Flux |
| 39 | +import java.time.Duration |
| 40 | +import java.util.concurrent.ConcurrentHashMap |
| 41 | + |
| 42 | +class ApolloSubscriptionProtocolHandler( |
| 43 | + private val config: GraphQLConfigurationProperties, |
| 44 | + private val subscriptionHandler: SubscriptionHandler, |
| 45 | + private val objectMapper: ObjectMapper |
| 46 | +) { |
| 47 | + // Keep Alive subscriptions are saved by web socket session id since they are sent on connection init |
| 48 | + private val keepAliveSubscriptions = ConcurrentHashMap<String, Subscription>() |
| 49 | + // Data subscriptions are saved by SubscriptionOperationMessage.id |
| 50 | + private val subscriptions = ConcurrentHashMap<String, Subscription>() |
| 51 | + |
| 52 | + private val logger = LoggerFactory.getLogger(ApolloSubscriptionProtocolHandler::class.java) |
| 53 | + private val keepAliveMessage = SubscriptionOperationMessage(type = GQL_CONNECTION_KEEP_ALIVE.type) |
| 54 | + |
| 55 | + @Suppress("Detekt.TooGenericExceptionCaught") |
| 56 | + fun handle(payload: String, session: WebSocketSession): Flux<SubscriptionOperationMessage> { |
| 57 | + try { |
| 58 | + val operationMessage: SubscriptionOperationMessage = objectMapper.readValue(payload) |
| 59 | + |
| 60 | + return when { |
| 61 | + operationMessage.type == GQL_CONNECTION_INIT.type -> { |
| 62 | + val flux = Flux.just(SubscriptionOperationMessage(GQL_CONNECTION_ACK.type)) |
| 63 | + val keepAliveInterval = config.subscriptions.keepAliveInterval |
| 64 | + if (keepAliveInterval != null) { |
| 65 | + // Send the GQL_CONNECTION_KEEP_ALIVE message every interval until the connection is closed or terminated |
| 66 | + val keepAliveFlux = Flux.interval(Duration.ofMillis(keepAliveInterval)) |
| 67 | + .map { keepAliveMessage } |
| 68 | + .doOnSubscribe { |
| 69 | + keepAliveSubscriptions[session.id] = it |
| 70 | + } |
| 71 | + return flux.concatWith(keepAliveFlux) |
| 72 | + } |
| 73 | + |
| 74 | + return flux |
| 75 | + } |
| 76 | + operationMessage.type == GQL_START.type -> startSubscription(operationMessage, session) |
| 77 | + operationMessage.type == GQL_STOP.type -> { |
| 78 | + stopSubscription(operationMessage, session) |
| 79 | + Flux.empty() |
| 80 | + } |
| 81 | + operationMessage.type == GQL_CONNECTION_TERMINATE.type -> { |
| 82 | + stopSubscription(operationMessage, session) |
| 83 | + session.close() |
| 84 | + Flux.empty() |
| 85 | + } |
| 86 | + else -> { |
| 87 | + logger.error("Unknown subscription operation $operationMessage") |
| 88 | + Flux.just(SubscriptionOperationMessage(type = GQL_CONNECTION_ERROR.type, id = operationMessage.id)) |
| 89 | + } |
| 90 | + } |
| 91 | + } catch (exception: Exception) { |
| 92 | + logger.error("Error parsing the subscription message", exception) |
| 93 | + return Flux.just(SubscriptionOperationMessage(type = GQL_CONNECTION_ERROR.type)) |
| 94 | + } |
| 95 | + } |
| 96 | + |
| 97 | + @Suppress("Detekt.TooGenericExceptionCaught") |
| 98 | + private fun startSubscription(operationMessage: SubscriptionOperationMessage, session: WebSocketSession): Flux<SubscriptionOperationMessage> { |
| 99 | + if (operationMessage.id == null) { |
| 100 | + logger.error("Operation id is required") |
| 101 | + return Flux.just(SubscriptionOperationMessage(type = GQL_CONNECTION_ERROR.type)) |
| 102 | + } |
| 103 | + |
| 104 | + val payload = operationMessage.payload |
| 105 | + |
| 106 | + if (payload == null) { |
| 107 | + logger.error("Payload was null instead of a GraphQLRequest object") |
| 108 | + return Flux.just(SubscriptionOperationMessage(type = GQL_CONNECTION_ERROR.type, id = operationMessage.id)) |
| 109 | + } |
| 110 | + |
| 111 | + return try { |
| 112 | + val request = objectMapper.convertValue<GraphQLRequest>(payload) |
| 113 | + subscriptionHandler.executeSubscription(request) |
| 114 | + .map { |
| 115 | + if (it.errors?.isNotEmpty() == true) { |
| 116 | + SubscriptionOperationMessage(type = GQL_ERROR.type, id = operationMessage.id, payload = it) |
| 117 | + } else { |
| 118 | + SubscriptionOperationMessage(type = GQL_DATA.type, id = operationMessage.id, payload = it) |
| 119 | + } |
| 120 | + } |
| 121 | + .concatWith(Flux.just(SubscriptionOperationMessage(type = GQL_COMPLETE.type, id = operationMessage.id))) |
| 122 | + .doOnSubscribe { |
| 123 | + logger.trace("WebSocket GraphQL subscription subscribe, WebSocketSessionID=${session.id} OperationMessageID=${operationMessage.id}") |
| 124 | + subscriptions[operationMessage.id] = it |
| 125 | + } |
| 126 | + .doOnCancel { logger.trace("WebSocket GraphQL subscription cancel, WebSocketSessionID=${session.id} OperationMessageID=${operationMessage.id}") } |
| 127 | + .doOnComplete { logger.trace("WebSocket GraphQL subscription complete, WebSocketSessionID=${session.id} OperationMessageID=${operationMessage.id}") } |
| 128 | + } catch (exception: Exception) { |
| 129 | + logger.error("Error running graphql subscription", exception) |
| 130 | + Flux.just(SubscriptionOperationMessage(type = GQL_CONNECTION_ERROR.type, id = operationMessage.id)) |
| 131 | + } |
| 132 | + } |
| 133 | + |
| 134 | + private fun stopSubscription(operationMessage: SubscriptionOperationMessage, session: WebSocketSession) { |
| 135 | + if (operationMessage.id != null) { |
| 136 | + keepAliveSubscriptions[session.id]?.cancel() |
| 137 | + subscriptions[operationMessage.id]?.cancel() |
| 138 | + } |
| 139 | + } |
| 140 | +} |
0 commit comments