/*
    Copyright (c) 2018, WSO2 Inc. (http://wso2.com) All Rights Reserved.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
*/

@App:name('APIM_REQUEST_PROCESSOR')
@App:description('Receive the request stream and load the configuration tables to in memeory.')

-- Streams
@source(type = 'mgwfile', wso2.stream.id = 'org.wso2.apimgt.statistics.request:3.0.0', @map(type = 'wso2event'))
@source(type = 'wso2event', wso2.stream.id = 'org.wso2.apimgt.statistics.request:3.0.0', @map(type = 'wso2event'))
define stream InComingRequestStream (meta_clientType string,
    applicationConsumerKey string, 
    applicationName string,
    applicationId string,
    applicationOwner string, 
    apiContext string,
    apiName string,
    apiVersion string,
    apiResourcePath string,
    apiResourceTemplate string,
    apiMethod string,
    apiCreator string,
    apiCreatorTenantDomain string,
    apiTier string,
    apiHostname string, 
    username string,
    userTenantDomain string,
    userIp string,
    userAgent string, 
    requestTimestamp long,
    throttledOut bool,
    responseTime long,
    serviceTime long,
    backendTime long,
    responseCacheHit bool,
    responseSize long,
    protocol string,
    responseCode int,
    destination string,
    securityLatency long,
    throttlingLatency long,
    requestMedLat long,
    responseMedLat long,
    backendLatency long,
    otherLatency long, 
    gatewayType string,
    label string);
    
@sink(type='inMemory' , topic='APIM_REQUEST')
define stream Request (meta_clientType string, applicationConsumerKey string, applicationName string, applicationId string, applicationOwner string, apiContext string,apiName string, apiVersion string, apiResourcePath string, apiResourceTemplate string, apiMethod string, apiCreator string, apiCreatorTenantDomain string, apiTier string, apiHostname string, username string, userTenantDomain string, userIp string, userAgent string, requestTimestamp long, throttledOut bool, responseTime long, serviceTime long, backendTime long, responseCacheHit bool, responseSize long, protocol string, responseCode int, destination string, securityLatency long, throttlingLatency long, requestMedLat long, responseMedLat long, backendLatency long, otherLatency long, gatewayType string, label string);

@sink(type ='inMemory', topic = 'APIM_REQUEST_ALERT_INFO')
define stream RequestAlertInfoStream (apiContext string,apiName string, apiVersion string, apiResourceTemplate string, apiMethod string, apiCreator string, apiCreatorTenantDomain string, requestTimestamp long, responseTime long, backendTime long, thresholdBackendTime long, thresholdResponseTime long,responseCode int );

@PrimaryKey('apiName', 'apiVersion','apiCreator', 'apiCreatorTenantDomain')
@store(type = 'rdbms', datasource = 'APIM_ANALYTICS_DB')
define table ApiCreatorAlertConfiguration (apiName string, apiVersion string, apiCreator string, apiCreatorTenantDomain string, thresholdResponseTime long, thresholdBackendTime long);

@PrimaryKey('apiName', 'apiVersion','apiCreator', 'apiCreatorTenantDomain')
define table ApiCreatorAlertConfigurationInMemoryTable (apiName string, apiVersion string, apiCreator string, apiCreatorTenantDomain string, thresholdResponseTime long, thresholdBackendTime long);

@PrimaryKey('applicationId','apiName', 'apiVersion')
@store(type = 'rdbms', datasource = 'APIM_ANALYTICS_DB')
define table ApiSubAlertConf (applicationId string, subscriber string, apiName string, apiVersion string, thresholdRequestCountPerMin int);

@PrimaryKey('applicationId','apiName', 'apiVersion')
define table ApiSubscriberAlertConfigurationInMemoryTable (applicationId string, subscriber string, apiName string, apiVersion string, thresholdRequestCountPerMin int);

define trigger MinTriggerEventStream at every 1 min;
define stream MinTriggerEventStream (triggered_time long);

-- Loading creator configuration tables in memory.
from MinTriggerEventStream as T join ApiCreatorAlertConfiguration as C
select C.apiName, C.apiVersion, C.apiCreator, C.apiCreatorTenantDomain, C.thresholdResponseTime, C.thresholdBackendTime
update or insert into ApiCreatorAlertConfigurationInMemoryTable
set ApiCreatorAlertConfigurationInMemoryTable.thresholdResponseTime = thresholdResponseTime, ApiCreatorAlertConfigurationInMemoryTable.thresholdBackendTime = thresholdBackendTime
on ApiCreatorAlertConfigurationInMemoryTable.apiName == apiName and ApiCreatorAlertConfigurationInMemoryTable.apiVersion == apiVersion and ApiCreatorAlertConfigurationInMemoryTable.apiCreator == apiCreator and ApiCreatorAlertConfigurationInMemoryTable.apiCreatorTenantDomain == apiCreatorTenantDomain;

-- Insert the recieving request events into a in memory stream.
from InComingRequestStream
select * 
insert into Request;

-- Join the request stream with in memory configuration tables to get threashold values.
@info(name = 'creatorConfigurationInfoRetrievQuery')
from Request as R left outer join ApiCreatorAlertConfigurationInMemoryTable as C
on(R.apiName == C.apiName and R.apiVersion == C.apiVersion and R.apiCreatorTenantDomain == C.apiCreatorTenantDomain )
select R.apiContext, R.apiName, R.apiVersion,  R.apiResourceTemplate, R.apiMethod, ifThenElse(R.apiCreatorTenantDomain == 'carbon.super', str:concat(R.apiCreator, "@carbon.super"), R.apiCreator) as apiCreator, R.apiCreatorTenantDomain, R.requestTimestamp, R.responseTime, R.backendTime, C.thresholdBackendTime, C.thresholdResponseTime,R.responseCode
insert into RequestAlertInfoStream;

