refact(session): Replace state start_time/end_time with time range (#5134)

This replaces the start_time, end_time, and previous_end_time columns on
the session_state table with a time range column that records when the
state was active. This allowed for dropping several constraints on the
session_state table that were used to ensure that states for a session
did not overlap. Instead this can be ensured with a single exclusion
constraint. By reducing the number of constraints, it improves the
performance for a number of queries involved with session state. Most
notably when resolving delete cascades of resources related to sessions,
such as targets, where as part of the delete transaction large numbers
of sessions get canceled. Similarly, when sessions get deleted, and the
corresponding session_state rows are deleted, these constraints all must
be checked during the transaction.

The domain layer continues to expose StartTime and EndTime fields on
session.State. However it drops PreviousEndTime, which was never used by
anything calling the domain layer.

See:
    https://www.postgresql.org/docs/current/ddl-constraints.html#DDL-CONSTRAINTS-EXCLUSION
    https://www.postgresql.org/docs/current/rangetypes.html
This commit is contained in:
Timothy Messier authored and GitHub committed 2024-09-30 14:39:19 -04:00
1 parent f6bdbd116e
commit 37bf59243a
14 files changed
+283 -239

No files matched your search

+14 -4
View File
@@ -90,7 +90,7 @@ active_session as (
where
ss.session_id in (select * from unexpired_session) and
ss.state = 'active' and
ss.end_time is null
upper(ss.active_time_range) is null
)
insert into session_connection (
session_id,
@@ -150,7 +150,7 @@ from
where
ss.session_id = @public_id and
ss.state = 'canceling' and
ss.end_time is null
upper(ss.active_time_range) is null
)
update session us
set version = version +1,
@@ -226,7 +226,7 @@ with canceling_session(session_id) as
session_state ss
where
ss.state = 'canceling' and
ss.end_time is null
upper(ss.active_time_range) is null
)
update session us
set termination_reason =
@@ -371,7 +371,7 @@ where
and
session_state.state = 'terminated'
and
session_state.start_time < wt_sub_seconds_from_now(@threshold_seconds)
lower(session_state.active_time_range) < wt_sub_seconds_from_now(@threshold_seconds)
;
`
sessionCredentialRewrapQuery = `
@@ -451,6 +451,16 @@ order by update_time desc, public_id desc;
`
estimateCountSessions = `
select reltuples::bigint as estimate from pg_class where oid in ('session'::regclass)
`
selectStates = `
select session_id,
state,
lower(active_time_range) as start_time,
upper(active_time_range) as end_time
from session_state
where session_id = ?
order by active_time_range desc;
`
)