@@ -154,12 +154,33 @@ protected static function ensureFactory()
154154 static ::$ factory = new Database ();
155155 }
156156
157+ /**
158+ * Validate database connections for worker mode at the start of a request.
159+ * Checks if connections are alive and reconnects if needed.
160+ *
161+ * This should be called at the beginning of each request in worker mode,
162+ * before the application runs.
163+ */
164+ public static function validateForWorkerMode (WorkerMode $ config ): void
165+ {
166+ if ($ config ->databaseStrategy !== 'keep-alive ' ) {
167+ return ;
168+ }
169+
170+ foreach (static ::$ instances as $ connection ) {
171+ if (! $ connection ->ping ()) {
172+ $ connection ->reconnect ();
173+ }
174+ }
175+ }
176+
157177 /**
158178 * Reset database connections for worker mode.
159- * Behavior controlled by WorkerMode config.
160179 *
161180 * This method handles connection state management between requests
162181 * in long-running worker processes.
182+ *
183+ * Called at the END of each request to clean up state.
163184 */
164185 public static function resetForWorkerMode (WorkerMode $ config ): void
165186 {
@@ -184,11 +205,6 @@ public static function resetForWorkerMode(WorkerMode $config): void
184205 if ($ connection ->transDepth > 0 ) {
185206 log_message ('warning ' , "Database connection has uncommitted transactions after cleanup: {$ group }" );
186207 }
187-
188- if (! $ connection ->ping ()) {
189- log_message ('info ' , "Database connection dead, reconnecting: {$ group }" );
190- $ connection ->reconnect ();
191- }
192208 break ;
193209 }
194210 }
0 commit comments