/* Processed by ecpg (15.18 (Debian 15.18-0+deb12u1)) */
/* These include files are added by the preprocessor */
#include <ecpglib.h>
#include <ecpgerrno.h>
#include <sqlca.h>
/* End of automatic include section */

#line 1 "app/online/cm_ol_0026.pgc"
/* @tier medium @module cm @transform common-online */
/*
 * cm_ol_0026.pgc - 캐시 무효화 요청 처리 서비스 (CM_OL_0026)  [tier=medium]
 *
 * 캐시키(CKEY) 유효성을 검증한 뒤 무효화 이벤트를 로그로 남기고, 운영
 * 파라미터(cm_param)의 캐시버전(cache_ver)을 1 증가시켜 하위 노드의 캐시
 * 재적재를 유도한다. 증가된 버전과 무효화 결과를 응답한다.
 * (ATMI void SVC(TPSVCINFO*) 대응)
 */
#include <stdio.h>
#include <string.h>

#include "txcore.h"
#include "txcore_dbio.h"
#include "acq_util.h"
#include "cm_core.h"


#line 1 "/usr/include/postgresql/sqlca.h"
#ifndef POSTGRES_SQLCA_H
#define POSTGRES_SQLCA_H

#ifndef PGDLLIMPORT
#if  defined(WIN32) || defined(__CYGWIN__)
#define PGDLLIMPORT __declspec (dllimport)
#else
#define PGDLLIMPORT
#endif							/* __CYGWIN__ */
#endif							/* PGDLLIMPORT */

#define SQLERRMC_LEN	150

#ifdef __cplusplus
extern "C"
{
#endif

struct sqlca_t
{
	char		sqlcaid[8];
	long		sqlabc;
	long		sqlcode;
	struct
	{
		int			sqlerrml;
		char		sqlerrmc[SQLERRMC_LEN];
	}			sqlerrm;
	char		sqlerrp[8];
	long		sqlerrd[6];
	/* Element 0: empty						*/
	/* 1: OID of processed tuple if applicable			*/
	/* 2: number of rows processed				*/
	/* after an INSERT, UPDATE or				*/
	/* DELETE statement					*/
	/* 3: empty						*/
	/* 4: empty						*/
	/* 5: empty						*/
	char		sqlwarn[8];
	/* Element 0: set to 'W' if at least one other is 'W'	*/
	/* 1: if 'W' at least one character string		*/
	/* value was truncated when it was			*/
	/* stored into a host variable.             */

	/*
	 * 2: if 'W' a (hopefully) non-fatal notice occurred
	 */	/* 3: empty */
	/* 4: empty						*/
	/* 5: empty						*/
	/* 6: empty						*/
	/* 7: empty						*/

	char		sqlstate[5];
};

struct sqlca_t *ECPGget_sqlca(void);

#ifndef POSTGRES_ECPG_INTERNAL
#define sqlca (*ECPGget_sqlca())
#endif

#ifdef __cplusplus
}
#endif

#endif

#line 18 "app/online/cm_ol_0026.pgc"


/* 캐시키 형식 검증: 영숫자/'_'/'.' 만 허용, 길이 3~30 */
static int cm_ckey_is_valid(const char *k)
{
    int i;
    int n = (int)strlen(k);

    if (n < 3 || n > 30)
        return 0;
    for (i = 0; i < n; i++) {
        char c = k[i];
        if (!((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') ||
              (c >= '0' && c <= '9') || c == '_' || c == '.')) {
            return 0;
        }
    }
    return 1;
}

TX_SERVICE(CM_OL_0026, ctx)
{
    /* exec sql begin declare section */
     
     
     
    
#line 41 "app/online/cm_ol_0026.pgc"
 char h_ckey [ 32 ] ;
 
#line 42 "app/online/cm_ol_0026.pgc"
 long h_ver ;
 
#line 43 "app/online/cm_ol_0026.pgc"
 long newver ;
/* exec sql end declare section */
#line 44 "app/online/cm_ol_0026.pgc"


    char ckey[32];

    tx_log(TX_LOG_INFO, "[CM_OL_0026] 캐시 무효화 요청 처리 진입");

    if (tx_buf_get(ctx->in, "CKEY", ckey, sizeof(ckey)) != TX_OK) {
        tx_log(TX_LOG_ERROR, "[CM_OL_0026] CKEY 누락");
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }

    if (!cm_ckey_is_valid(ckey)) {
        tx_log(TX_LOG_WARN, "[CM_OL_0026] 캐시키 형식 오류 ckey=%s", ckey);
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }

    memset(&h_ckey, 0, sizeof(h_ckey));
    strncpy(h_ckey, ckey, sizeof(h_ckey) - 1);
    h_ver = 0;

    /* 현재 캐시버전 조회 */
    { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "select cache_ver from cm_param where param_key = $1 ", 
	ECPGt_char,(h_ckey),(long)32,(long)1,(32)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EOIT, 
	ECPGt_long,&(h_ver),(long)1,(long)1,sizeof(long), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EORT);}
#line 71 "app/online/cm_ol_0026.pgc"


    if (sqlca.sqlcode == TX_SQL_NOTFOUND) {
        tx_log(TX_LOG_WARN, "[CM_OL_0026] 캐시 대상 없음 ckey=%s", ckey);
        tx_return(ctx, TX_ENOENT, ctx->out);
        return;
    }
    if (sqlca.sqlcode != TX_SQL_OK) {
        TX_DBIO_LOG_ERR("CM_OL_0026 SELECT cm_param");
        tx_return(ctx, TX_EDB, ctx->out);
        return;
    }

    newver = h_ver + 1;

    /* 무효화 이벤트 기록 후 버전 증가 반영 */
    tx_log(TX_LOG_INFO, "[CM_OL_0026] 캐시 무효화 이벤트 ckey=%s %ld->%ld xid=%ld",
           ckey, h_ver, newver, tx_current_xid());

    if (tx_begin() != TX_OK) {
        tx_return(ctx, TX_FAIL, ctx->out);
        return;
    }

    { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "update cm_param set cache_ver = $1  , upd_ts = SYSTIMESTAMP where param_key = $2 ", 
	ECPGt_long,&(newver),(long)1,(long)1,sizeof(long), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, 
	ECPGt_char,(h_ckey),(long)32,(long)1,(32)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EOIT, ECPGt_EORT);}
#line 99 "app/online/cm_ol_0026.pgc"


    if (sqlca.sqlcode != TX_SQL_OK) {
        TX_DBIO_LOG_ERR("CM_OL_0026 UPDATE cm_param");
        tx_abort();
        tx_return(ctx, TX_EDB, ctx->out);
        return;
    }

    tx_commit();

    tx_buf_reset(ctx->out);
    tx_buf_sets(ctx->out, "CKEY", ckey);
    tx_buf_setlong(ctx->out, "NEWVER", newver);
    tx_buf_sets(ctx->out, "RESULT", "INVALIDATED");
    tx_log(TX_LOG_INFO, "[CM_OL_0026] 무효화 완료 ckey=%s newver=%ld", ckey, newver);
    tx_return(ctx, TX_OK, ctx->out);
}
