feat(hydra-cleaner): clean authentication_session table

This commit is contained in:
2025-08-21 14:17:25 +02:00
parent a8f2da31c6
commit 680d879d03

View File

@@ -16,10 +16,13 @@ set -o nounset
# -> delete "cascade" on table "flow" cleans access, code, oidc, pkce and refresh tables.
# For table authentication_session, a simple delete on this table is enough.
# Delete all rows without reference from table flow (foreign key)
DSN="${DSN:-postgresql://${HYDRA_DATABASE_USER}:${HYDRA_DATABASE_PASSWORD}@${HYDRA_DATABASE_SERVICE_NAME}:${HYDRA_DATABASE_SERVICE_PORT:-5432}/hydra?sslmode=disable}"
RETENTION_HOURS="${RETENTION_HOURS:-48}"
BATCH_SIZE="${BATCH_SIZE:-50}"
BATCH_SIZE_ORIG="${BATCH_SIZE}"
LIMIT="${LIMIT:-1000}"
BEFORE_DATE="$(date +'%Y-%m-%d %H:%M:%S' --date=@$(($(date +%s) - RETENTION_HOURS * 3600)))"
@@ -66,6 +69,7 @@ where table_schema = 'public'
order by 4 desc;
EOF
log "Cleaning flow table..."
REMAINING_ELMTS="${LIMIT}"
while [ "${REMAINING_ELMTS}" -gt 0 ]; do
@@ -86,7 +90,7 @@ EOF
log "${OUTPUT}"
if ! [[ "${OUTPUT}" =~ '^DELETE ' ]] ; then
log "Output doesn't seems OK..."
log "Output doesn't seem OK..."
break
fi
OUTPUT_NB=$(echo "${OUTPUT}" | cut -d' ' -f 2)
@@ -101,6 +105,73 @@ EOF
fi
done
log "Cleaning authentication_session table..."
BATCH_SIZE="${BATCH_SIZE_ORIG}"
REMAINING_ELMTS="${LIMIT}"
OUTPUT=$(psql "${DSN}" <<EOF
DO \$\$
BEGIN
DROP TABLE IF EXISTS hydra_cleaner.hydra_childless_auth_session;
DROP SCHEMA IF EXISTS hydra_cleaner;
CREATE SCHEMA hydra_cleaner;
CREATE TABLE hydra_cleaner.hydra_childless_auth_session AS
SELECT id
FROM hydra_oauth2_authentication_session
WHERE NOT EXISTS (
SELECT 1
FROM hydra_oauth2_flow
WHERE hydra_oauth2_authentication_session.id = hydra_oauth2_flow.login_session_id
)
LIMIT ${REMAINING_ELMTS};
END \$\$;
EOF
)
log "${OUTPUT}"
while [ "${REMAINING_ELMTS}" -gt 0 ]; do
OUTPUT=$(psql "${DSN}" <<EOF
WITH cte AS (
SELECT id
FROM hydra_cleaner.hydra_childless_auth_session
LIMIT ${BATCH_SIZE}
),
auth_session_deleted as (
DELETE
FROM hydra_oauth2_authentication_session
WHERE hydra_oauth2_authentication_session.id in (select * from cte)
AND NOT EXISTS (
SELECT 1
FROM hydra_oauth2_flow
WHERE hydra_oauth2_authentication_session.id = hydra_oauth2_flow.login_session_id
)
)
DELETE
FROM hydra_cleaner.hydra_childless_auth_session
WHERE hydra_cleaner.hydra_childless_auth_session.id in (select * from cte);
EOF
)
log "${OUTPUT}"
if ! [[ "${OUTPUT}" =~ '^DELETE ' ]] ; then
log "Output doesn't seem OK..."
break
fi
OUTPUT_NB=$(echo "${OUTPUT}" | cut -d' ' -f 2)
if [ "${OUTPUT_NB}" -lt "${BATCH_SIZE}" ]; then
break
fi
REMAINING_ELMTS=$((REMAINING_ELMTS - BATCH_SIZE))
if [ "${REMAINING_ELMTS}" -lt "${BATCH_SIZE}" ]; then
BATCH_SIZE="${REMAINING_ELMTS}"
fi
done
log "Final estimated size:"
psql "${DSN}" <<EOF