13
13
// limitations under the License.
14
14
//
15
15
16
- import { getEmbeddedLabel , IntlString , PlatformError , unknownError } from '@hcengineering/platform'
16
+ import { getEmbeddedLabel , IntlString } from '@hcengineering/platform'
17
17
import { deepEqual } from 'fast-equals'
18
- import { DOMAIN_BENCHMARK } from './benchmark'
19
18
import {
20
19
Account ,
21
20
AccountRole ,
@@ -47,6 +46,7 @@ import { TxOperations } from './operations'
47
46
import { isPredicate } from './predicate'
48
47
import { DocumentQuery , FindResult } from './storage'
49
48
import { DOMAIN_TX } from './tx'
49
+ import { DOMAIN_BENCHMARK } from './benchmark'
50
50
51
51
function toHex ( value : number , chars : number ) : string {
52
52
const result = value . toString ( 16 )
@@ -355,6 +355,7 @@ export class DocManager<T extends Doc> implements IDocManager<T> {
355
355
356
356
export class RateLimiter {
357
357
idCounter : number = 0
358
+ processingQueue = new Map < number , Promise < void > > ( )
358
359
last : number = 0
359
360
rate : number
360
361
@@ -365,21 +366,21 @@ export class RateLimiter {
365
366
}
366
367
367
368
notify : ( ( ) => void ) [ ] = [ ]
368
- finished : boolean = false
369
369
370
370
async exec < T , B extends Record < string , any > = any > ( op : ( args ?: B ) => Promise < T > , args ?: B ) : Promise < T > {
371
- if ( this . finished ) {
372
- throw new PlatformError ( unknownError ( 'No Possible to add/exec on finished queue' ) )
373
- }
374
- while ( this . notify . length >= this . rate ) {
371
+ const processingId = this . idCounter ++
372
+
373
+ while ( this . processingQueue . size >= this . rate ) {
375
374
await new Promise < void > ( ( resolve ) => {
376
375
this . notify . push ( resolve )
377
376
} )
378
377
}
379
378
try {
380
379
const p = op ( args )
380
+ this . processingQueue . set ( processingId , p as Promise < void > )
381
381
return await p
382
382
} finally {
383
+ this . processingQueue . delete ( processingId )
383
384
const n = this . notify . shift ( )
384
385
if ( n !== undefined ) {
385
386
n ( )
@@ -388,20 +389,15 @@ export class RateLimiter {
388
389
}
389
390
390
391
async add < T , B extends Record < string , any > = any > ( op : ( args ?: B ) => Promise < T > , args ?: B ) : Promise < void > {
391
- if ( this . notify . length < this . rate ) {
392
+ if ( this . processingQueue . size < this . rate ) {
392
393
void this . exec ( op , args )
393
394
} else {
394
395
await this . exec ( op , args )
395
396
}
396
397
}
397
398
398
399
async waitProcessing ( ) : Promise < void > {
399
- this . finished = true
400
- while ( this . notify . length > 0 ) {
401
- await new Promise < void > ( ( resolve ) => {
402
- this . notify . push ( resolve )
403
- } )
404
- }
400
+ await Promise . all ( this . processingQueue . values ( ) )
405
401
}
406
402
}
407
403
0 commit comments