Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Block communication in client class when rate limited #147

Merged
merged 2 commits into from
Jul 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,9 @@ See [`src/example.ts`](./src/example.ts).
* Add Tests

## Changelog:
### __WORK IN PROGRESS__
* Block communication in client class when rate limited according to Daikin response

### 2.1.1 (2024-07-05)
* Expose the Rate limit error retryAfter time in the error object

Expand Down
22 changes: 20 additions & 2 deletions src/onecta/oidc-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,17 @@ import {
import { startOnectaOIDCCallbackServer } from './oidc-callback-server.js';
import { RateLimitedError } from "../index";

type RequestParameters = Parameters<typeof BaseClient.prototype.requestResource>[2] & {
ignoreRateLimit?: boolean;
}

export class OnectaClient {
#config: OnectaClientConfig;
#client: BaseClient;
#tokenSet: TokenSet | null;
#emitter: EventEmitter;
#getTokenSetQueue: { resolve: (set: TokenSet) => any, reject: (err: Error) => any }[];
#blockedUntil: number = 0;

constructor(config: OnectaClientConfig, emitter: EventEmitter) {
this.#config = config;
Expand All @@ -39,6 +44,10 @@ export class OnectaClient {
}
}

get blockedUntil(): number {
return this.#blockedUntil;
}

async #authorize(): Promise<TokenSet> {
const redirectUri = this.#config.oidcCallbackServerBaseUrl;
const reqState = randomBytes(32).toString('hex');
Expand Down Expand Up @@ -140,10 +149,16 @@ export class OnectaClient {
};
}

async requestResource(path: string, opts?: Parameters<typeof BaseClient.prototype.requestResource>[2]): Promise<any> {
async requestResource(path: string, opts?: RequestParameters): Promise<any> {
if (!opts?.ignoreRateLimit && this.#blockedUntil > Date.now()) {
const retryAfter = Math.ceil((this.#blockedUntil - Date.now()) / 1000);
throw new RateLimitedError(`API request still rate-limited, retry after ${retryAfter} seconds`, retryAfter);
}
const reqOpts = { ...opts };
delete reqOpts.ignoreRateLimit;
const tokenSet = await this.#getTokenSetQueued();
const url = `${OnectaAPIBaseUrl.prod}${path}`;
const res = await this.#client.requestResource(url, tokenSet, opts);
const res = await this.#client.requestResource(url, tokenSet, reqOpts);
RESOLVED.then(() => this.#emitter.emit('rate_limit_status', this.#getRateLimitStatus(res)));
switch (res.statusCode) {
case 200:
Expand All @@ -160,6 +175,9 @@ export class OnectaClient {
case 429: {
// See "Rate limitation" at https://developer.cloud.daikineurope.com/docs/b0dffcaa-7b51-428a-bdff-a7c8a64195c0/general_api_guidelines
const retryAfter = maybeParseInt(res.headers['retry-after']);
if (retryAfter !== undefined) {
this.#blockedUntil = Date.now() + retryAfter * 1000;
jacoscaz marked this conversation as resolved.
Show resolved Hide resolved
}
throw new RateLimitedError(`API request rate-limited, retry after ${retryAfter} seconds`, retryAfter);
}
case 500:
Expand Down
Loading