ofsc-utility 1.0.40 → 1.0.43

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1,13 @@
1
- export declare function getOAuthToken(clientId: string, clientSecret: string, instanceUrl: string): Promise<any>;
1
+ interface OAuthTokenOptions {
2
+ /** Max retry attempts for transient (5xx) failures. Default: 2 */
3
+ maxRetries?: number;
4
+ /** Base delay in ms between retries (exponential backoff). Default: 1000 */
5
+ retryDelayMs?: number;
6
+ /** Request timeout in ms. Default: 10000 */
7
+ timeoutMs?: number;
8
+ }
9
+ /**
10
+ * Fetches an OAuth access token from OFSC.
11
+ */
12
+ export declare function getOAuthToken(clientId: string, clientSecret: string, instanceUrl: string, options?: OAuthTokenOptions): Promise<string>;
13
+ export {};
@@ -1,30 +1,63 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.getOAuthToken = getOAuthToken;
4
- async function getOAuthToken(clientId, clientSecret, instanceUrl) {
4
+ /**
5
+ * Fetches an OAuth access token from OFSC.
6
+ */
7
+ async function getOAuthToken(clientId, clientSecret, instanceUrl, options = {}) {
8
+ const { maxRetries = 3, retryDelayMs = 1000, timeoutMs = 10000 } = options;
5
9
  const url = `https://${instanceUrl}.fs.ocs.oraclecloud.com/rest/oauthTokenService/v2/token`;
6
10
  const credentials = btoa(`${clientId}@${instanceUrl}:${clientSecret}`);
7
11
  const headers = {
8
12
  'Content-Type': 'application/x-www-form-urlencoded',
9
- 'Authorization': `Basic ${credentials}`
13
+ 'Authorization': `Basic ${credentials}`,
10
14
  };
11
- const body = new URLSearchParams({
12
- 'grant_type': 'client_credentials'
13
- });
14
- try {
15
- const response = await fetch(url, {
16
- method: 'POST',
17
- headers: headers,
18
- body: body
19
- });
20
- if (!response.ok) {
21
- throw new Error(`HTTP error! status: ${response.status}`);
15
+ const body = new URLSearchParams({ grant_type: 'client_credentials' });
16
+ let lastError;
17
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
18
+ //AbortController is a built-in browser/Node API for cancelling async operations
19
+ // controller.signal & controller.abort() are used to cancel the fetch request if it takes too long
20
+ const controller = new AbortController();
21
+ const timeout = setTimeout(() => controller.abort(), timeoutMs);
22
+ try {
23
+ const response = await fetch(url, {
24
+ method: 'POST',
25
+ headers,
26
+ body,
27
+ signal: controller.signal,
28
+ });
29
+ clearTimeout(timeout);
30
+ if (response.ok) {
31
+ const data = (await response.json());
32
+ if (!data.access_token) {
33
+ throw new Error('OAuth response did not contain an access_token');
34
+ }
35
+ return data.access_token;
36
+ }
37
+ // Retry only on server-side / transient errors
38
+ if (response.status >= 500 && response.status < 600 && attempt < maxRetries) {
39
+ lastError = new Error(`OAuth token request failed with status ${response.status}`);
40
+ await delay(retryDelayMs * 2 ** attempt);
41
+ continue;
42
+ }
43
+ // Non-retriable (4xx) or out of retries — fail fast
44
+ const bodyText = await response.text().catch(() => '');
45
+ throw new Error(`OAuth token request failed: ${response.status} ${response.statusText}${bodyText ? ` - ${bodyText}` : ''}`);
46
+ }
47
+ catch (error) {
48
+ clearTimeout(timeout);
49
+ lastError = error;
50
+ const isAbort = error instanceof Error && error.name === 'AbortError';
51
+ const isNetworkError = error instanceof TypeError;
52
+ if ((isAbort || isNetworkError) && attempt < maxRetries) {
53
+ await delay(retryDelayMs * 2 ** attempt);
54
+ continue;
55
+ }
56
+ throw new Error(`Failed to fetch OAuth token after ${attempt + 1} attempt(s): ${error instanceof Error ? error.message : String(error)}`);
22
57
  }
23
- const data = await response.json();
24
- return data.access_token;
25
- }
26
- catch (error) {
27
- console.error('Error fetching OAuth token:', error);
28
- throw error;
29
58
  }
59
+ throw lastError instanceof Error ? lastError : new Error('Failed to fetch OAuth token');
60
+ }
61
+ function delay(ms) {
62
+ return new Promise((resolve) => setTimeout(resolve, ms));
30
63
  }
@@ -78,7 +78,7 @@ const fetchWithRetry = async (url, clientId, clientSecret, instanceUrl, token, r
78
78
  res = await doFetch(token);
79
79
  }
80
80
  /* ---------- 429: retry with backoff ---------- */
81
- if ((res.status === 429 || res.status === 400) && retries > 0) {
81
+ if ((res.status === 429 || res.status === 502 || res.status === 503 || res.status === 504) && retries > 0) {
82
82
  const retryAfter = res.headers.get("Retry-After");
83
83
  console.log("⚠️ 429 received. Retrying...", retryAfter);
84
84
  const delay = retryAfter ? Number(retryAfter) * 1000 : baseDelay;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ofsc-utility",
3
- "version": "1.0.40",
3
+ "version": "1.0.43",
4
4
  "description": "TypeScript helpers for Oracle Field Service Cloud (OFSC): events, resources, inventories, metadata and CSV/Excel utilities.",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
package/readme.md CHANGED
@@ -9,10 +9,29 @@ This package exposes grouped API helpers for common OFSC operations, including:
9
9
  - inventory and activity records
10
10
  - metadata file generation
11
11
 
12
+ ### Built-in resilience for OFSC's server errors
13
+
14
+ OFSC's REST API sits behind Oracle's gateway infrastructure, which means calls can occasionally fail with transient errors that have nothing to do with your request — the gateway losing its connection to the backend, a brief service restart, or normal rate limiting under load. This package handles those cases automatically so your integration doesn't fail on a blip that would have succeeded a second later.
15
+
16
+ ### Exponential backoff
17
+
18
+ Retries don't hammer the API at a fixed interval — each attempt waits longer than the last (starting at a small base delay and doubling each time), unless OFSC explicitly tells us how long to wait via Retry-After. This gives Oracle's backend room to recover instead of adding to the load that likely caused the error in the first place.
19
+
20
+ ### Why this matters for OFSC specifically
21
+
22
+ OFSC's gateway is known to return 503s and connection resets during normal operation — not just outages — especially under sustained polling or bulk export workloads (events, activities, inventory).Handling these
23
+ transparently means:
24
+
25
+ - Scheduled jobs don't die on a single flaky response and require manual re-runs
26
+ - Token expiry mid-session is handled without the caller needing to track token lifetimes
27
+ - You get clear, real error messages (with the response body attached) for
28
+ genuine failures, instead of noisy retries on errors that were never going
29
+ to succeed
30
+
12
31
  ## Installation
13
32
 
14
33
  ```bash
15
- npm install ofsc-utility
34
+ npm install ofsc-utility@latest
16
35
  ```
17
36
 
18
37
  ## Getting Started