@@ -15,6 +15,9 @@ class TaskRepository implements TaskRepositoryInterface
1515 const RESET_TASKS_AFTER_SECONDS = 60 ; // seconds to retry failed tasks
1616 const RESET_TASKS_LIMIT = 20 ; // how many tasks to reset at once
1717
18+ const REBALANCE_LIMIT = 1000 ; // how many tasks to rebalance at once
19+ const REBALANCE_TIME_IN_FUTURE = 3600 ; // seconds in future tasks to rebalance
20+
1821 /**
1922 * @var \PDO
2023 */
@@ -100,6 +103,30 @@ private function fetchTasks($status, $olderThanSeconds, $limit)
100103 }, $ stmt ->fetchAll ());
101104 }
102105
106+ /**
107+ * @param array $availableHostnames
108+ * @return array|int[]
109+ */
110+ public function findTasksForRebalance (array $ availableHostnames )
111+ {
112+ $ query = sprintf ('SELECT task_id FROM %s
113+ WHERE
114+ identifier NOT IN (:availableHostnames) AND status=:status AND ts_created <= :ts_created
115+ ORDER BY ts_created ASC LIMIT :limit ' ,
116+ Consts::TASKS_TABLE_NAME
117+ );
118+
119+ $ stmt = $ this ->pdo ->prepare ($ query );
120+ $ stmt ->bindValue (':availableHostnames ' , implode (', ' , $ availableHostnames ));
121+ $ stmt ->bindValue (':status ' , Consts::STATUS_PENDING , \PDO ::PARAM_INT );
122+ $ stmt ->bindValue (':limit ' , self ::REBALANCE_LIMIT , \PDO ::PARAM_INT );
123+ $ stmt ->bindValue (':ts_created ' , time () + self ::REBALANCE_TIME_IN_FUTURE , \PDO ::PARAM_INT );
124+
125+ $ stmt ->execute ();
126+
127+ return $ stmt ->fetchAll (\PDO ::FETCH_COLUMN );
128+ }
129+
103130 private function getIdentifier ()
104131 {
105132 if ($ this ->identifier === null ) {
@@ -157,7 +184,6 @@ public function addBulk($tasks)
157184 $ sql .= implode (', ' , $ insertQuery );
158185
159186 $ stmt = $ this ->pdo ->prepare ($ sql );
160- $ stmt ->bindValue (':mudo ' , Consts::TASKS_TABLE_NAME );
161187 $ this ->execute ($ stmt ,$ insertData );
162188 }
163189
@@ -193,6 +219,27 @@ public function updateStatus($status, Task ...$tasks)
193219 );
194220 }
195221
222+ /**
223+ * @param string$identifier
224+ * @param array $taskIds
225+ * @return void
226+ */
227+ public function updateIdentifier ($ identifier , array $ taskIds )
228+ {
229+ if (count ($ taskIds ) === 0 ) {
230+ return ;
231+ }
232+
233+ $ query = sprintf (
234+ 'UPDATE %s SET identifier="%s" WHERE task_id IN (%s) ' ,
235+ Consts::TASKS_TABLE_NAME ,
236+ $ identifier ,
237+ implode (', ' , $ taskIds )
238+ );
239+
240+ $ this ->pdo ->exec ($ query );
241+ }
242+
196243 /**
197244 * @param \PDOStatement $stmt
198245 * @param Task $task
@@ -228,4 +275,4 @@ private function execute(\PDOStatement $stmt, $data = null)
228275 }
229276 return $ res ;
230277 }
231- }
278+ }
0 commit comments