88from eoapi .vector .app import app
99from eoapi .vector .config import PostgresSettings
1010from mangum import Mangum
11+ from snapshot_restore_py import register_after_restore , register_before_snapshot
1112from tipg .collections import register_collection_catalog
1213from tipg .database import connect_to_db
1314from tipg .settings import DatabaseSettings
2627 # We allow non-spatial tables
2728 spatial = False ,
2829)
30+ postgres_settings = PostgresSettings ()
31+
32+ _connection_initialized = False
33+
34+
35+ @register_before_snapshot
36+ def on_snapshot ():
37+ """
38+ Runtime hook called by Lambda before taking a snapshot.
39+ We close database connections that shouldn't be in the snapshot.
40+ """
41+
42+ if hasattr (app , "state" ) and hasattr (app .state , "pool" ) and app .state .pool :
43+ try :
44+ app .state .pool .close ()
45+ app .state .pool = None
46+ except Exception as e :
47+ print (f"SnapStart: Error closing database pool: { e } " )
48+
49+ return {"statusCode" : 200 }
50+
51+
52+ @register_after_restore
53+ def on_snap_restore ():
54+ """
55+ Runtime hook called by Lambda after restoring from a snapshot.
56+ We recreate database connections that were closed before the snapshot.
57+ """
58+ global _connection_initialized
59+
60+ try :
61+ try :
62+ loop = asyncio .get_running_loop ()
63+ except RuntimeError :
64+ loop = asyncio .new_event_loop ()
65+ asyncio .set_event_loop (loop )
66+
67+ if hasattr (app .state , "pool" ) and app .state .pool :
68+ try :
69+ app .state .pool .close ()
70+ except Exception as e :
71+ print (f"SnapStart: Error closing stale pool: { e } " )
72+ app .state .pool = None
73+
74+ loop .run_until_complete (
75+ connect_to_db (
76+ app ,
77+ schemas = ["pgstac" , "public" ],
78+ user_sql_files = list (CUSTOM_SQL_DIRECTORY .glob ("*.sql" )), # type: ignore
79+ settings = postgres_settings ,
80+ )
81+ )
82+
83+ loop .run_until_complete (
84+ register_collection_catalog (
85+ app ,
86+ db_settings = db_settings ,
87+ )
88+ )
89+
90+ _connection_initialized = True
91+
92+ except Exception as e :
93+ print (f"SnapStart: Failed to initialize database connection: { e } " )
94+ raise
95+
96+ return {"statusCode" : 200 }
2997
3098
3199@app .on_event ("startup" )
@@ -36,7 +104,7 @@ async def startup_event() -> None:
36104 # We enable both pgstac and public schemas (pgstac will be used by custom functions)
37105 schemas = ["pgstac" , "public" ],
38106 user_sql_files = list (CUSTOM_SQL_DIRECTORY .glob ("*.sql" )), # type: ignore
39- settings = PostgresSettings () ,
107+ settings = postgres_settings ,
40108 )
41109 await register_collection_catalog (app , db_settings = db_settings )
42110
0 commit comments