bottleneck.d.ts.ejs 25.1 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588
declare module "bottleneck" {
    namespace Bottleneck {
        type ConstructorOptions = {
            /**
             * How many jobs can be running at the same time.
             */
            readonly maxConcurrent?: number | null;
            /**
             * How long to wait after launching a job before launching another one.
             */
            readonly minTime?: number | null;
            /**
             * How long can the queue get? When the queue length exceeds that value, the selected `strategy` is executed to shed the load.
             */
            readonly highWater?: number | null;
            /**
             * Which strategy to use if the queue gets longer than the high water mark.
             */
            readonly strategy?: Bottleneck.Strategy | null;
            /**
             * The `penalty` value used by the `Bottleneck.strategy.BLOCK` strategy.
             */
            readonly penalty?: number | null;
            /**
             * How many jobs can be executed before the limiter stops executing jobs. If `reservoir` reaches `0`, no jobs will be executed until it is no longer `0`.
             */
            readonly reservoir?: number | null;
            /**
             * Every `reservoirRefreshInterval` milliseconds, the `reservoir` value will be automatically reset to `reservoirRefreshAmount`.
             */
            readonly reservoirRefreshInterval?: number | null;
            /**
             * The value to reset `reservoir` to when `reservoirRefreshInterval` is in use.
             */
            readonly reservoirRefreshAmount?: number | null;
            /**
             * The increment applied to `reservoir` when `reservoirIncreaseInterval` is in use.
             */
            readonly reservoirIncreaseAmount?: number | null;
            /**
             * Every `reservoirIncreaseInterval` milliseconds, the `reservoir` value will be automatically incremented by `reservoirIncreaseAmount`.
             */
            readonly reservoirIncreaseInterval?: number | null;
            /**
             * The maximum value that `reservoir` can reach when `reservoirIncreaseInterval` is in use.
             */
            readonly reservoirIncreaseMaximum?: number | null;
            /**
             * Optional identifier
             */
            readonly id?: string | null;
            /**
             * Set to true to leave your failed jobs hanging instead of failing them.
             */
            readonly rejectOnDrop?: boolean | null;
            /**
             * Set to true to keep track of done jobs with counts() and jobStatus(). Uses more memory.
             */
            readonly trackDoneStatus?: boolean | null;
            /**
             * Where the limiter stores its internal state. The default (`local`) keeps the state in the limiter itself. Set it to `redis` to enable Clustering.
             */
            readonly datastore?: string | null;
            /**
             * Override the Promise library used by Bottleneck.
             */
            readonly Promise?: any;
            /**
             * This object is passed directly to the redis client library you've selected.
             */
            readonly clientOptions?: any;
            /**
             * **ioredis only.** When `clusterNodes` is not null, the client will be instantiated by calling `new Redis.Cluster(clusterNodes, clientOptions)`.
             */
            readonly clusterNodes?: any;
            /**
             * An existing Bottleneck.RedisConnection or Bottleneck.IORedisConnection object to use.
             * If using, `datastore`, `clientOptions` and `clusterNodes` will be ignored.
             */
            /**
             * Optional Redis/IORedis library from `require('ioredis')` or equivalent. If not, Bottleneck will attempt to require Redis/IORedis at runtime.
             */
            readonly Redis?: any;
            /**
             * Bottleneck connection object created from `new Bottleneck.RedisConnection` or `new Bottleneck.IORedisConnection`.
             */
            readonly connection?: Bottleneck.RedisConnection | Bottleneck.IORedisConnection | null;
            /**
             * When set to `true`, on initial startup, the limiter will wipe any existing Bottleneck state data on the Redis db.
             */
            readonly clearDatastore?: boolean | null;
            /**
             * The Redis TTL in milliseconds for the keys created by the limiter. When `timeout` is set, the limiter's state will be automatically removed from Redis after timeout milliseconds of inactivity. Note: timeout is 300000 (5 minutes) by default when using a Group.
             */
             readonly timeout?: number | null;

            [propName: string]: any;
        };
        type JobOptions = {
            /**
             * A priority between `0` and `9`. A job with a priority of `4` will _always_ be executed before a job with a priority of `5`.
             */
            readonly priority?: number | null;
            /**
             * Must be an integer equal to or higher than `0`. The `weight` is what increases the number of running jobs (up to `maxConcurrent`, if using) and decreases the `reservoir` value (if using).
             */
            readonly weight?: number | null;
            /**
             * The number milliseconds a job has to finish. Jobs that take longer than their `expiration` will be failed with a `BottleneckError`.
             */
            readonly expiration?: number | null;
            /**
             * Optional identifier, helps with debug output.
             */
            readonly id?: string | null;
        };
        type StopOptions = {
            /**
             * When `true`, drop all the RECEIVED, QUEUED and RUNNING jobs. When `false`, allow those jobs to complete before resolving the Promise returned by this method.
             */
            readonly dropWaitingJobs?: boolean | null;
            /**
             * The error message used to drop jobs when `dropWaitingJobs` is `true`.
             */
            readonly dropErrorMessage?: string | null;
            /**
             * The error message used to reject a job added to the limiter after `stop()` has been called.
             */
            readonly enqueueErrorMessage?: string | null;
        };
        type Callback<T> = (err: any, result: T) => void;
        type ClientsList = { client?: any; subscriber?: any };
        type GroupLimiterPair = { key: string; limiter: Bottleneck };
        interface Strategy {}

        type EventInfo = {
            readonly args: any[];
            readonly options: {
                readonly id: string;
                readonly priority: number;
                readonly weight: number;
                readonly expiration?: number;
            };
        };
        type EventInfoDropped = EventInfo & {
            readonly task: Function;
            readonly promise: Promise<any>;
        };
        type EventInfoQueued = EventInfo & {
            readonly reachedHWM: boolean;
            readonly blocked: boolean;
        };
        type EventInfoRetryable = EventInfo & { readonly retryCount: number; };

        enum Status {
            RECEIVED = "RECEIVED",
            QUEUED = "QUEUED",
            RUNNING = "RUNNING",
            EXECUTING = "EXECUTING",
            DONE = "DONE"
        }
        type Counts = {
            RECEIVED: number,
            QUEUED: number,
            RUNNING: number,
            EXECUTING: number,
            DONE?: number
        };

        type RedisConnectionOptions = {
            /**
             * This object is passed directly to NodeRedis' createClient() method.
             */
            readonly clientOptions?: any;
            /**
             * An existing NodeRedis client to use. If using, `clientOptions` will be ignored.
             */
            readonly client?: any;
            /**
             * Optional Redis library from `require('redis')` or equivalent. If not, Bottleneck will attempt to require Redis at runtime.
             */
            readonly Redis?: any;
        };

        type IORedisConnectionOptions = {
            /**
             * This object is passed directly to ioredis' constructor method.
             */
            readonly clientOptions?: any;
            /**
             * When `clusterNodes` is not null, the client will be instantiated by calling `new Redis.Cluster(clusterNodes, clientOptions)`.
             */
            readonly clusterNodes?: any;
            /**
             * An existing ioredis client to use. If using, `clientOptions` and `clusterNodes` will be ignored.
             */
            readonly client?: any;
            /**
             * Optional IORedis library from `require('ioredis')` or equivalent. If not, Bottleneck will attempt to require IORedis at runtime.
             */
            readonly Redis?: any;
        };

        type BatcherOptions = {
            /**
             * Maximum acceptable time (in milliseconds) a request can have to wait before being flushed to the `"batch"` event.
             */
            readonly maxTime?: number | null;
            /**
             * Maximum number of requests in a batch.
             */
            readonly maxSize?: number | null;
        };

        class BottleneckError extends Error {
        }

        class RedisConnection {
            constructor(options?: Bottleneck.RedisConnectionOptions);

            /**
             * Register an event listener.
             * @param name - The event name.
             * @param fn - The callback function.
             */
            on(name: "error", fn: (error: any) => void): void;

            /**
             * Register an event listener for one event only.
             * @param name - The event name.
             * @param fn - The callback function.
             */
            once(name: "error", fn: (error: any) => void): void;

            /**
             * Waits until the connection is ready and returns the raw Node_Redis clients.
             */
            ready(): Promise<ClientsList>;

            /**
             * Close the redis clients.
             * @param flush - Write transient data before closing.
             */
            disconnect(flush?: boolean): Promise<void>;
        }

        class IORedisConnection {
            constructor(options?: Bottleneck.IORedisConnectionOptions);

            /**
             * Register an event listener.
             * @param name - The event name.
             * @param fn - The callback function.
             */
            on(name: "error", fn: (error: any) => void): void;

            /**
             * Register an event listener for one event only.
             * @param name - The event name.
             * @param fn - The callback function.
             */
            once(name: "error", fn: (error: any) => void): void;

            /**
             * Waits until the connection is ready and returns the raw ioredis clients.
             */
            ready(): Promise<ClientsList>;

            /**
             * Close the redis clients.
             * @param flush - Write transient data before closing.
             */
            disconnect(flush?: boolean): Promise<void>;
        }

        class Batcher {
            constructor(options?: Bottleneck.BatcherOptions);

            /**
             * Register an event listener.
             * @param name - The event name.
             * @param fn - The callback function.
             */
            on(name: string, fn: Function): void;
            on(name: "error", fn: (error: any) => void): void;
            on(name: "batch", fn: (batch: any[]) => void): void;

            /**
             * Register an event listener for one event only.
             * @param name - The event name.
             * @param fn - The callback function.
             */
            once(name: string, fn: Function): void;
            once(name: "error", fn: (error: any) => void): void;
            once(name: "batch", fn: (batch: any[]) => void): void;

            /**
             * Add a request to the Batcher. Batches are flushed to the "batch" event.
             */
            add(data: any): Promise<void>;
        }

        class Group {
            constructor(options?: Bottleneck.ConstructorOptions);

            id: string;
            datastore: string;
            connection?: Bottleneck.RedisConnection | Bottleneck.IORedisConnection;

            /**
             * Returns the limiter for the specified key.
             * @param str - The limiter key.
             */
            key(str: string): Bottleneck;

            /**
             * Register an event listener.
             * @param name - The event name.
             * @param fn - The callback function.
             */
            on(name: string, fn: Function): void;
            on(name: "error", fn: (error: any) => void): void;
            on(name: "created", fn: (limiter: Bottleneck, key: string) => void): void;

            /**
             * Register an event listener for one event only.
             * @param name - The event name.
             * @param fn - The callback function.
             */
            once(name: string, fn: Function): void;
            once(name: "error", fn: (error: any) => void): void;
            once(name: "created", fn: (limiter: Bottleneck, key: string) => void): void;

            /**
             * Removes all registered event listeners.
             * @param name - The optional event name to remove listeners from.
             */
            removeAllListeners(name?: string): void;

            /**
             * Updates the group settings.
             * @param options - The new settings.
             */
            updateSettings(options: Bottleneck.ConstructorOptions): void;

            /**
             * Deletes the limiter for the given key.
             * Returns true if a key was deleted.
             * @param str - The key
             */
            deleteKey(str: string): Promise<boolean>;

            /**
             * Disconnects the underlying redis clients, unless the Group was created with the `connection` option.
             * @param flush - Write transient data before closing.
             */
            disconnect(flush?: boolean): Promise<void>;

            /**
             * Returns all the key-limiter pairs.
             */
            limiters(): Bottleneck.GroupLimiterPair[];

            /**
             * Returns all Group keys in the local instance
             */
            keys(): string[];

            /**
             * Returns all Group keys in the Cluster
             */
            clusterKeys(): Promise<string[]>;
        }

        class Events {
            constructor(object: Object);

            /**
             * Returns the number of limiters for the event name
             * @param name - The event name.
             */
            listenerCount(name: string): number;

            /**
             * Returns a promise with the first non-null/non-undefined result from a listener
             * @param name - The event name.
             * @param args - The arguments to pass to the event listeners.
             */
            trigger(name: string, ...args: any[]): Promise<any>;
        }
    }

    class Bottleneck {
        public static readonly strategy: {
            /**
             * When adding a new job to a limiter, if the queue length reaches `highWater`, drop the oldest job with the lowest priority. This is useful when jobs that have been waiting for too long are not important anymore. If all the queued jobs are more important (based on their `priority` value) than the one being added, it will not be added.
             */
            readonly LEAK: Bottleneck.Strategy;
            /**
             * Same as `LEAK`, except it will only drop jobs that are less important than the one being added. If all the queued jobs are as or more important than the new one, it will not be added.
             */
            readonly OVERFLOW_PRIORITY: Bottleneck.Strategy;
            /**
             * When adding a new job to a limiter, if the queue length reaches `highWater`, do not add the new job. This strategy totally ignores priority levels.
             */
            readonly OVERFLOW: Bottleneck.Strategy;
            /**
             * When adding a new job to a limiter, if the queue length reaches `highWater`, the limiter falls into "blocked mode". All queued jobs are dropped and no new jobs will be accepted until the limiter unblocks. It will unblock after `penalty` milliseconds have passed without receiving a new job. `penalty` is equal to `15 * minTime` (or `5000` if `minTime` is `0`) by default and can be changed by calling `changePenalty()`. This strategy is ideal when bruteforce attacks are to be expected. This strategy totally ignores priority levels.
             */
            readonly BLOCK: Bottleneck.Strategy;
        };

        constructor(options?: Bottleneck.ConstructorOptions);

        id: string;
        datastore: string;
        connection?: Bottleneck.RedisConnection | Bottleneck.IORedisConnection;

        /**
         * Returns a promise which will be resolved once the limiter is ready to accept jobs
         * or rejected if it fails to start up.
         */
        ready(): Promise<any>;

        /**
         * Returns a datastore-specific object of redis clients.
         */
        clients(): Bottleneck.ClientsList;

        /**
         * Returns the name of the Redis pubsub channel used for this limiter
         */
        channel(): string;

        /**
         * Disconnects the underlying redis clients, unless the limiter was created with the `connection` option.
         * @param flush - Write transient data before closing.
         */
        disconnect(flush?: boolean): Promise<void>;

        /**
         * Broadcast a string to every limiter in the Cluster.
         */
        publish(message: string): Promise<void>;

        /**
         * Returns an object with the current number of jobs per status.
         */
        counts(): Bottleneck.Counts;

        /**
         * Returns the status of the job with the provided job id.
         */
        jobStatus(id: string): Bottleneck.Status;

        /**
         * Returns the status of the job with the provided job id.
         */
        jobs(status?: Bottleneck.Status): string[];

        /**
         * Returns the number of requests queued.
         * @param priority - Returns the number of requests queued with the specified priority.
         */
        queued(priority?: number): number;

        /**
         * Returns the number of requests queued across the Cluster.
         */
        clusterQueued(): Promise<number>;

        /**
         * Returns whether there are any jobs currently in the queue or in the process of being added to the queue.
         */
        empty(): boolean;

        /**
         * Returns the total weight of jobs in a RUNNING or EXECUTING state in the Cluster.
         */
        running(): Promise<number>;

        /**
         * Returns the total weight of jobs in a DONE state in the Cluster.
         */
        done(): Promise<number>;

        /**
         * If a request was added right now, would it be run immediately?
         * @param weight - The weight of the request
         */
        check(weight?: number): Promise<boolean>;

        /**
         * Register an event listener.
         * @param name - The event name.
         * @param fn - The callback function.
         */
        on(name: "error",     fn: (error: any) => void): void;
        on(name: "empty",     fn: () => void): void;
        on(name: "idle",      fn: () => void): void;
        on(name: "depleted",  fn: (empty: boolean) => void): void;
        on(name: "message",   fn: (message: string) => void): void;
        on(name: "debug",     fn: (message: string, info: any) => void): void;
        on(name: "dropped",   fn: (dropped: Bottleneck.EventInfoDropped) => void): void;
        on(name: "received",  fn: (info: Bottleneck.EventInfo) => void): void;
        on(name: "queued",    fn: (info: Bottleneck.EventInfoQueued) => void): void;
        on(name: "scheduled", fn: (info: Bottleneck.EventInfo) => void): void;
        on(name: "executing", fn: (info: Bottleneck.EventInfoRetryable) => void): void;
        on(name: "failed",    fn: (error: any, info: Bottleneck.EventInfoRetryable) => Promise<number | void | null> | number | void | null): void;
        on(name: "retry",     fn: (message: string, info: Bottleneck.EventInfoRetryable) => void): void;
        on(name: "done",      fn: (info: Bottleneck.EventInfoRetryable) => void): void;

        /**
         * Register an event listener for one event only.
         * @param name - The event name.
         * @param fn - The callback function.
         */
        once(name: "error",     fn: (error: any) => void): void;
        once(name: "empty",     fn: () => void): void;
        once(name: "idle",      fn: () => void): void;
        once(name: "depleted",  fn: (empty: boolean) => void): void;
        once(name: "message",   fn: (message: string) => void): void;
        once(name: "debug",     fn: (message: string, info: any) => void): void;
        once(name: "dropped",   fn: (dropped: Bottleneck.EventInfoDropped) => void): void;
        once(name: "received",  fn: (info: Bottleneck.EventInfo) => void): void;
        once(name: "queued",    fn: (info: Bottleneck.EventInfoQueued) => void): void;
        once(name: "scheduled", fn: (info: Bottleneck.EventInfo) => void): void;
        once(name: "executing", fn: (info: Bottleneck.EventInfoRetryable) => void): void;
        once(name: "failed",    fn: (error: any, info: Bottleneck.EventInfoRetryable) => Promise<number | void | null> | number | void | null): void;
        once(name: "retry",     fn: (message: string, info: Bottleneck.EventInfoRetryable) => void): void;
        once(name: "done",      fn: (info: Bottleneck.EventInfoRetryable) => void): void;

        /**
         * Removes all registered event listeners.
         * @param name - The optional event name to remove listeners from.
         */
        removeAllListeners(name?: string): void;

        /**
         * Changes the settings for future requests.
         * @param options - The new settings.
         */
        updateSettings(options?: Bottleneck.ConstructorOptions): Bottleneck;

        /**
         * Adds to the reservoir count and returns the new value.
         */
        incrementReservoir(incrementBy: number): Promise<number>;

        /**
         * The `stop()` method is used to safely shutdown a limiter. It prevents any new jobs from being added to the limiter and waits for all Executing jobs to complete.
         */
        stop(options?: Bottleneck.StopOptions): Promise<void>;

        /**
         * Returns the current reservoir count, if any.
         */
        currentReservoir(): Promise<number | null>;

        /**
         * Chain this limiter to another.
         * @param limiter - The limiter that requests to this limiter must also follow.
         */
        chain(limiter?: Bottleneck): Bottleneck;

        <%_ for (var count of [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) { _%>
        wrap<R<%_ for (var idx = 1; idx <= count; idx++) { _%>, A<%= idx %><%_ } _%>>(fn: (<%= Array.apply(null, Array(count)).map((e, i) => i+1).map(i => `arg${i}: A${i}`).join(", ") %>) => PromiseLike<R>): ((<%_ for (var idx = 1; idx <= count; idx++) { _%><%_ if (idx > 1) { %>, <% } %>arg<%= idx %>: A<%= idx %><%_ } _%>) => Promise<R>) & { withOptions: (options: Bottleneck.JobOptions<%_ for (var idx = 1; idx <= count; idx++) { _%>, arg<%= idx %>: A<%= idx %><%_ } _%>) => Promise<R>; };
        <%_ } _%>

        <%_ for (var count of [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) { _%>
        submit<R<%_ for (var idx = 1; idx <= count; idx++) { _%>, A<%= idx %><%_ } _%>>(fn: (<%_ for (var idx = 1; idx <= count; idx++) { _%>arg<%= idx %>: A<%= idx %>, <% } _%>callback: Bottleneck.Callback<R>) => void<%_ for (var idx = 1; idx <= count; idx++) { _%>, arg<%= idx %>: A<%= idx %><%_ } _%>, callback: Bottleneck.Callback<R>): void;
        <%_ } _%>

        <%_ for (var count of [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) { _%>
        submit<R<%_ for (var idx = 1; idx <= count; idx++) { _%>, A<%= idx %><%_ } _%>>(options: Bottleneck.JobOptions, fn: (<%_ for (var idx = 1; idx <= count; idx++) { _%>arg<%= idx %>: A<%= idx %>, <% } _%>callback: Bottleneck.Callback<R>) => void<%_ for (var idx = 1; idx <= count; idx++) { _%>, arg<%= idx %>: A<%= idx %><%_ } _%>, callback: Bottleneck.Callback<R>): void;
        <%_ } _%>

        <%_ for (var count of [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) { _%>
        schedule<R<%_ for (var idx = 1; idx <= count; idx++) { _%>, A<%= idx %><%_ } _%>>(fn: (<%= Array.apply(null, Array(count)).map((e, i) => i+1).map(i => `arg${i}: A${i}`).join(", ") %>) => PromiseLike<R><%_ for (var idx = 1; idx <= count; idx++) { _%>, arg<%= idx %>: A<%= idx %><%_ } _%>): Promise<R>;
        <%_ } _%>

        <%_ for (var count of [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) { _%>
        schedule<R<%_ for (var idx = 1; idx <= count; idx++) { _%>, A<%= idx %><%_ } _%>>(options: Bottleneck.JobOptions, fn: (<%= Array.apply(null, Array(count)).map((e, i) => i+1).map(i => `arg${i}: A${i}`).join(", ") %>) => PromiseLike<R><%_ for (var idx = 1; idx <= count; idx++) { _%>, arg<%= idx %>: A<%= idx %><%_ } _%>): Promise<R>;
        <%_ } _%>
    }

    export default Bottleneck;
}