@@ -36,7 +36,9 @@ export default function Home({ baseUrl, submissionPredictions }) {
36
36
const response = await fetch ( `/api/submissions/${ seed } ` , {
37
37
method : "GET" ,
38
38
} ) ;
39
- submissionPredictions = await response . json ( ) ;
39
+ if ( response . ok ) {
40
+ submissionPredictions = await response . json ( ) ;
41
+ }
40
42
setPredictions ( submissionPredictions ) ;
41
43
42
44
// get the model names from the predictions, and update which ones are checked
@@ -151,17 +153,36 @@ export default function Home({ baseUrl, submissionPredictions }) {
151
153
throw new Error ( prediction . detail ) ;
152
154
}
153
155
156
+ // Add incremental backoff for polling requests.
157
+ const backoff = [ 250 , 500 , 500 , 750 , 1000 , 1500 , 3000 , 5000 , 10000 , 15000 , 30000 ] ;
158
+
154
159
while (
155
160
prediction . status !== "succeeded" &&
156
161
prediction . status !== "failed"
157
162
) {
158
- await sleep ( 500 ) ;
163
+ const jitter = random ( 0 , 100 ) ; // Don't make all requests at the same time.
164
+ const delay = backoff . shift ( ) ;
165
+ if ( ! delay ) {
166
+ // We've exceeded our timeout.
167
+ // TODO: Better user facing messaging here.
168
+ break ;
169
+ }
170
+
171
+ await sleep ( delay + jitter ) ;
159
172
const response = await fetch ( "/api/predictions/" + prediction . id ) ;
160
- prediction = await response . json ( ) ;
161
- console . log ( prediction ) ;
173
+
174
+ // Handle Rate Limiting
175
+ if ( response . status === 429 ) {
176
+ const reset = response . headers . get ( 'X-Ratelimit-Reset' ) ?? Date . now ( ) + 10_000 ;
177
+ const wait = reset - Date . now ( ) ;
178
+ await sleep ( wait )
179
+ continue ;
180
+ }
181
+
162
182
if ( response . status !== 200 ) {
163
183
throw new Error ( prediction . detail ) ;
164
184
}
185
+ prediction = await response . json ( ) ;
165
186
}
166
187
167
188
prediction . model = model . name ;
@@ -551,3 +572,7 @@ export async function getServerSideProps({ req }) {
551
572
552
573
return { props : { baseUrl, submissionPredictions } } ;
553
574
}
575
+
576
+ function random ( min , max ) {
577
+ return Math . floor ( Math . random ( ) * ( max - min + 1 ) + min )
578
+ }
0 commit comments